查找C文件中的除法运算符实例



我试图在一个大的c文件中找到所有的除法运算符。我看到了一个Python代码的例子。

和我试图使用它为我的c文件。因此,我使用pycparser将c文件解析为ast,如下所示:

from pycparser import parse_file, c_parser, c_generator
def translate_to_c(filename):
ast = parse_file(filename, use_cpp=True)
ast.show()
translate_to_c('source.c')

然后我尝试通过修改translate_to_c来使用示例,如下所示:

def translate_to_c(filename):
ast = parse_file(filename, use_cpp=True)
ast.show()
last_lineno = None
for node in ast.walk(ast):
# Not all nodes in the AST have line numbers, remember latest one
if hasattr(node, "lineno"):
last_lineno = node.lineno
# If this is a division expression, then show the latest line number
if isinstance(node, ast.Div):
print(last_lineno)

我得到以下错误:

line 25, in translate_to_c
for node in ast.walk(ast):
AttributeError: 'FileAST' object has no attribute 'walk'

关于如何在我的代码中使用这个例子,有什么想法吗?或How to loop on ast file in general ?

使用Python内置的ast库和pycparser是非常不同的。一个是Python AST,另一个将C解析为C AST。它们是来自不同库的不同类型-你不能期望一个方法(如walk)只是神奇地为另一个工作!

我建议您从pycparser的示例开始:https://github.com/eliben/pycparser/tree/master/examples

例如,这个例子查找C代码中的所有函数调用。查找所有除法运算符应该很容易调整。explore_ast示例向您展示了如何感知AST。

最新更新