I'm learning to parse some C++ source file with python-libclang
, so far I have a script that can partially achieve what I hope:
import clang.cindex
idx = clang.cindex.Index.create()
tu = idx.parse('example.cpp', args='-xc++ --std=c++11'.split())
for cursor in tu.cursor.walk_preorder():
print("`{}` --> {}".format(cursor.spelling, cursor.kind))
This script can parse a example.cpp
// example.cpp
// I know this is incomplete but this is all I got: some incomplete files
int main()
{
Thing *thing = new Thing();
thing->DoSomething();
return 0;
}
and print out:
`example.cpp` --> CursorKind.TRANSLATION_UNIT
`main` --> CursorKind.FUNCTION_DECL
`` --> CursorKind.COMPOUND_STMT
`` --> CursorKind.DECL_STMT
`thing` --> CursorKind.VAR_DECL
`` --> CursorKind.RETURN_STMT
`` --> CursorKind.INTEGER_LITERAL
Yet there is no information about function DoSomething()
. How do I locate all function calls (and hopefully their fully-qualified names) from a source file?
Eg how do I get a Thing::DoSomething
, or at least a DoSomething
?
I have read and tried examples from
but none of them get what I want.
Recommendation to any other SIMPLE tools to parse C++ source files is welcomed.
Your code does not work as you expect since Thing
is lacking a definition, or even a declaration. Clang is not parsing this as a function call, since as far as it's concerned, the code is not well formed. To see, try adding a declaration like
struct Thing { void DoSomething(); };
and you will see your missing function calls appear like:
`Thing` --> CursorKind.TYPE_REF
`DoSomething` --> CursorKind.CALL_EXPR
`DoSomething` --> CursorKind.MEMBER_REF_EXPR
(tested with LLVM 14)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.