需要一个工具来检测C代码中的变量类型

时间:2012-12-30 08:12:35

标签: python c compiler-construction

我正在开发一个特定的源到源编译器的项目。在这个阶段,我需要在C源代码中找到变量的类型。例如,如果代码为c[i]=j*f[k]+p;,我应该找到cijfk和{的类型{1}}变量(pint*以及源中定义的任何其他类型。有没有工具可以这样做?如果有多个工具,我更喜欢基于python的工具。

谢谢你。

2 个答案:

答案 0 :(得分:4)

您可以使用pycparser编写自己的解析器,您可以找到更多示例here

from pycparser import c_parser
parser = c_parser.CParser()
text = 'int x; int y; float z;'
ast = parser.parse(text, filename='<none>')
ast.show()
FileAST: 
  Decl: x, [], [], []
    TypeDecl: x, []
      IdentifierType: ['int']
  Decl: y, [], [], []
    TypeDecl: y, []
      IdentifierType: ['int']
  Decl: z, [], [], []
    TypeDecl: z, []
      IdentifierType: ['float']

答案 1 :(得分:2)

您应该能够使用llvm-tools从源代码创建AST,然后分析AST。除了你的任务是编写像llvm-tools这样的东西:)

这是一个如何使用llvm绑定python来分析c文件的示例:

http://www.mdevan.org/llvm-py/examples.html