我有以下脚本尝试打印给定 C++ 文件中的所有 AST 节点。当在具有简单包含的简单文件(同一目录中的头文件等)上使用它时,效果很好。
#!/usr/bin/env python
from argparse import ArgumentParser, FileType
from clang import cindex
def node_info(node):
return {'kind': node.kind,
'usr': node.get_usr(),
'spelling': node.spelling,
'location': node.location,
'file': node.location.file.name,
'extent.start': node.extent.start,
'extent.end': node.extent.end,
'is_definition': node.is_definition()
}
def get_nodes_in_file(node, filename, ls=None):
ls = ls if ls is not None else []
for n in node.get_children():
if n.location.file is not None and n.location.file.name == filename:
ls.append(n)
get_nodes_in_file(n, filename, ls)
return ls
def main():
arg_parser = ArgumentParser()
arg_parser.add_argument('source_file', type=FileType('r+'),
help='C++ source file to parse.')
arg_parser.add_argument('compilation_database', type=FileType('r+'),
help='The compile_commands.json to use to parse the source file.')
args = arg_parser.parse_args()
compilation_database_path = args.compilation_database.name
source_file_path = args.source_file.name
clang_args = ['-x', 'c++', '-std=c++11', '-p', compilation_database_path]
index = cindex.Index.create()
translation_unit = index.parse(source_file_path, clang_args)
file_nodes = get_nodes_in_file(translation_unit.cursor, source_file_path)
print [p.spelling for p in file_nodes]
if __name__ == '__main__':
main()
但是,我得到了clang.cindex.TranslationUnitLoadError: Error parsing translation unit.
当我运行脚本并提供一个有效的 C++ 文件时,该文件的父目录中有一个compile_commands.json 文件。这段代码使用 CMake 和 clang 可以正常运行和构建,但我似乎无法弄清楚如何正确传递指向compile_commands.json的参数。
我也很难在 clang 文档中找到这个选项,并且无法得到-ast-dump
上班。然而,clang-check 只需传递文件路径就可以正常工作!