python使用pycparser库将c语言程序转变为抽象语法树(ast)
pycparser库github地址: https://github.com/eliben/pycparser
封装方法
from __future__ import print_function
from pycparser.c_ast import *
from util.remove_zs import rm_emptyline, rm_includeline, rmCommentsInCFile
sys.path.extend(['.', '..'])
from pycparser import c_parser
def translate_to_c(filename):
with open(filename, encoding='utf-8') as f:
txt = f.read()
txt = rmCommentsInCFile(txt)
txt = rm_emptyline(txt)
txt = rm_includeline(txt)
ast = c_parser.CParser().parse(txt)
return txt, ast
def translate_to_c_txt(txt):
txt = rmCommentsInCFile(txt)
txt = rm_emptyline(txt)
txt = rm_includeline(txt)
ast = c_parser.CParser().parse(txt)
return txt, ast
if __name__ == "__main__":
filename = 'D:/desktop/t1.c'
txt, ast = translate_to_c(filename)
ast.show()
print(ast)
|