我遇到了同样的问题。我的情境是需要以JSON格式解析AST,我想摆脱所有的头文件和不必要的文件。我尝试复制@textshell的答案(
https://dev59.com/rF4c5IYBdhLWcg3wVo9I#69150479),但我注意到CLANG在我的情况下表现不同。我正在使用的CLANG版本是:
$ clang --version
Debian clang version 13.0.1-+rc1-1~exp4
Target: x86_64-pc-linux-gnu
Thread model: posix
为了解释我的情况,让我们考虑以下例子:
![enter image description here](https://istack.dev59.com/6XajW.webp)
“my_function”和“main”都是来自同一源文件(function_definition_invocation.c)的函数。然而,在“my_function”的FunctionDecl节点中才有这个信息。我猜测这是因为两个函数都属于同一文件,CLANG仅在属于该文件的节点中打印文件位置。
一旦找到主文件的第一个出现,每个连续的节点都应添加到结果过滤后的JSON文件中。我使用的代码是:
def filter_ast_only_source_file(source_file, json_ast):
new_inner = []
first_occurrence_of_main_file = False
for entry in json_ast['inner']:
if not first_occurrence_of_main_file:
if entry.get('isImplicit', False):
continue
file_name = None
loc = entry.get('loc', {})
if 'file' in loc:
file_name = loc['file']
if 'expansionLoc' in loc:
if 'file' in loc['expansionLoc']:
file_name = loc['expansionLoc']['file']
if file_name != source_file:
continue
new_inner.append(entry)
first_occurrence_of_main_file = True
else:
new_inner.append(entry)
json_ast['inner'] = new_inner
"我是这样称呼它的:"
generated_ast = subprocess.run(["clang", "-Xclang", "-ast-dump=json", source_file], capture_output=True)
json_ast = json.loads(generated_ast.stdout)
filter_ast_only_source_file(source_file, json_ast)
到目前为止,它似乎正在起作用。