我正在尝试在一个大的c文件中查找所有的除法运算符。我看到了Python代码的这个example。
我试着在我的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'
那么,对于如何在代码中使用此example,您有什么想法吗?或者一般情况下如何在ast文件上循环?
发布于 2021-03-11 01:05:11
使用Python的内置ast
库和使用pycparser
是非常不同的。一个是Python AST,另一个是将C解析成ASTs。它们是来自不同库的不同类型--你不能期望一个人的方法(如walk
)能神奇地为另一个人工作!
我建议您从pycparser的示例开始:https://github.com/eliben/pycparser/tree/master/examples
例如,this examples查找C代码中的所有函数调用。查找所有除法运算符应该很容易进行调整。explore_ast示例向您展示了如何在AST中摸索。
https://stackoverflow.com/questions/66565355
复制相似问题