0

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?

E.g. 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.

Rahn
  • 4,787
  • 4
  • 31
  • 57

1 Answers1

0

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)

mitch_
  • 1,048
  • 5
  • 14
  • This is all I got. I don't have access to the complete code. – Rahn Jul 14 '22 at 07:14
  • In that case your 'complete code' is not valid in the first place. If you don't even have a function prototype, no compiler would accept the code. There's no way to disambiguate something like `thing->foo()` from an indirect function pointer call, a member method call, or an `operator()` call, so Clang cannot give you an answer. As proof, try including the proposed `struct` in your example code, see that it works, then try replacing it with `struct Thing { std::function DoSomething; }` and note that your output changes as a consequence. – mitch_ Jul 14 '22 at 07:17