2010年8月18日 星期三

Lex & Yacc case study @ PLY

除了用 Perl/Python 做簡單的 regular expression 外,最常用到的就是 Lex && Yacc摟... Lex : Lexical Analyzar Yacc : Yet Another Compiler Compiler Lex Yacc 簡易介紹 Lex Yacc Lex && Yacc flow 詳細請參考 A COMPACT GUIDE TO LEX & YACC 底下用 open source 的 Project 來完成我們要的Parser. 請先安裝 PLY (Python Lex-Yacc) input part
int main(){
a=1;
b=3;
c=a+b;

printf("%d\n",c);
return 0;
}
analysis part
import sys



# This is not required if you've installed pycparser into

# your site-packages/ with setup.py

#

sys.path.insert(0, '..')



from pycparser import c_parser, c_ast, parse_file

from pycparser.portability import printme





# A simple visitor for FuncDef nodes that prints the names and 

# locations of function definitions.

#



def show_func_defs(filename):

    # Note that cpp is used. Provide a path to your own cpp or 

    # make sure one exists in PATH.

    #
    ast = parse_file(filename, use_cpp=True)    

    ast.show()





if __name__ == "__main__":

    if len(sys.argv) > 1:

        filename  = sys.argv[1]

    else:

        filename = 'c_files/test.c'



    show_func_defs(filename)


output part
FileAST: 
  FuncDef: 
    Decl: main, [], []
      FuncDecl: 
        TypeDecl: main, []
          IdentifierType: ['int']
    Compound: 
      Assignment: =
        ID: a
        Constant: int, 1
      Assignment: =
        ID: b
        Constant: int, 3
      Assignment: =
        ID: c
        BinaryOp: +
          ID: a
          ID: b
      FuncCall: 
        ID: printf
        ExprList: 
          Constant: string, "%d\n"
          ID: c
      Return: 
        Constant: int, 0
main at ./c_files/test.c:3

Refs: C Parser (Front End) Introducing the Boost parser framework Spirit Parser Framework Lex and YACC primer/HOWTO Simple Top-Down Parsing in Python Parse::Eyapp::datagenerationtut @ Perl 2.2. Parse::Yapp Lex && Yacc Example

沒有留言:

張貼留言