Python libclang如何使用编译数据库



这个问题已经被问了两次了,其中一个答案似乎很受欢迎:

如何将compile_commands.json与clang python绑定一起使用?

另一个没有那么多:如何将compile_commands.json与llvm clang(7.0.1版(python绑定一起使用?

然而,这两种解决方案似乎都不起作用。如果你尝试最流行的解决方案,即如果你这样做:

index = clang.cindex.Index.create()
compdb = clang.cindex.CompilationDatabase.fromDirectory('/home/makogan/neverengine_personal/build/')
file_args = compdb.getCompileCommands(path)
translation_unit = index.parse(path, file_args)

你会得到这个错误:

Traceback (most recent call last):
File "/home/makogan/neverengine_personal/Source/../Scripts/notebook_generator.py", line 178, in <module>
main()
File "/home/makogan/neverengine_personal/Source/../Scripts/notebook_generator.py", line 175, in main
CreateNotebookFromHeader(args.path, args.out_path)
File "/home/makogan/neverengine_personal/Source/../Scripts/notebook_generator.py", line 165, in CreateNotebookFromHeader
nb['cells'] = GetHeaderCellPrototypes(path)
File "/home/makogan/neverengine_personal/Source/../Scripts/notebook_generator.py", line 148, in GetHeaderCellPrototypes
tokens = ExtractTokensOfInterest(path)
File "/home/makogan/neverengine_personal/Source/../Scripts/notebook_generator.py", line 54, in ExtractTokensOfInterest
translation_unit = index.parse(path, file_args)
File "/home/makogan/.local/lib/python3.9/site-packages/clang/cindex.py", line 2688, in parse
return TranslationUnit.from_source(path, args, unsaved_files, options,
File "/home/makogan/.local/lib/python3.9/site-packages/clang/cindex.py", line 2783, in from_source
args_array = (c_char_p * len(args))(*[b(x) for x in args])
File "/home/makogan/.local/lib/python3.9/site-packages/clang/cindex.py", line 2783, in <listcomp>
args_array = (c_char_p * len(args))(*[b(x) for x in args])
File "/home/makogan/.local/lib/python3.9/site-packages/clang/cindex.py", line 109, in b
return x.encode('utf8')
AttributeError: 'CompileCommand' object has no attribute 'encode'

如果你尝试第二种选择:

即:

print( list(iter(file_args).next().arguments))

你得到这个错误:

AttributeError: 'iterator' object has no attribute 'next'

人们是如何获得第一个解决方案来为他们工作的?

正确的方法似乎是:

index = clang.cindex.Index.create()
token_dict = {}
compdb = clang.cindex.CompilationDatabase.fromDirectory('/home/makogan/neverengine_personal/build/')
commands = compdb.getCompileCommands(path)
file_args = []
for command in commands:
for argument in command.arguments:
file_args.append(argument)
translation_unit = index.parse(path, file_args)

最新更新