I am attempting to print out all the AST nodes in a given C++ file. And i provide a valid C++ file that has a compile_commands.json file in its parent directory. All steps just like How to use compile_commands.json with clang python bindings? and my clang version is: "clang version 7.0.1 (tags/RELEASE_701/final) Target: x86_64-pc-windows-msvc Thread model: posix InstalledDir: C:\Program Files\LLVM\bin". OS is windows10, python version is 2.7. However, when i run this script below.
enter code here
import clang.cindex
from clang.cindex import *
libclang_path = r'C:\Program Files\LLVM\bin\libclang.dll'
if Config.loaded == True:
pass
else:
Config.set_library_file(libclang_path)
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():
compilation_database_path = 'C:/Users/liqiu/Desktop/md/gn/build/win/x64'
source_file_path = 'C:/Users/liqiu/Desktop/md/.../video_camera_source.cpp'
index = clang.cindex.Index.create()
compdb = clang.cindex.CompilationDatabase.fromDirectory(compilation_database_path)
try:
file_args = compdb.getCompileCommands(source_file_path)
translation_unit = index.parse(source_file_path, file_args)
file_nodes = get_nodes_in_file(translation_unit.cursor, source_file_path)
print [p.spelling for p in file_nodes]
except clang.cindex.CompilationDatabaseError:
print 'Could not load compilation flags for', source_file_path
if __name__ == '__main__':
main()
There are some errors like the following. I think the reason for this error is "file_args = compdb. GetCompileCommands (source_file_path)" this line returns a CompileCommand instance rather than string or integer type, so the index.parse()can not directly accept this instance as a parameter. But this seems to have returned some string type of "Commands" in older versions of libclang. This caused me to be confused now.
D:\Python27\python.exe C:/Users/liqiu/Desktop/libclang_parse/parser.py
Traceback (most recent call last):
File "C:/Users/liqiu/Desktop/libclang_parse/parser.py", line 51, in <module>
main()
File "C:/Users/liqiu/Desktop/libclang_parse/parser.py", line 43, in main
translation_unit = index.parse(source_file_path, file_args)
File "C:\Users\liqiu\Desktop\libclang_parse\clang\cindex.py", line 2689, in parse
self)
File "C:\Users\liqiu\Desktop\libclang_parse\clang\cindex.py", line 2783, in from_source
args_array = (c_char_p * len(args))(*[b(x) for x in args])
TypeError: string or integer address expected instead of CompileCommand instance
Process finished with exit code 1