I am trying to find (line and column position) all the references of a specific function declaration when parsing a C++ source file via libclang in Python.
For example:
#include <iostream>
using namespace std;
int addition (int a, int b)
{
int r;
r=a+b;
return r;
}
int main ()
{
int z, q;
z = addition (5,3);
q = addition (5,5);
cout << "The first result is " << z;
cout << "The second result is " << q;
}
So, for the source file above, I would like for the function declaration for addition
in line 5, I would like the find_all_function_decl_references
(see below) to return the references of addition
at lines 15 and 16.
I have tried this (adapted from here)
import clang.cindex
import ccsyspath
index = clang.cindex.Index.create()
translation_unit = index.parse(filename, args=args)
for node in translation_unit.cursor.walk_preorder():
node_definition = node.get_definition()
if node.location.file is None:
continue
if node.location.file.name != sourcefile:
continue
if node_def is None:
pass
if node.kind.name == 'FUNCTION_DECL':
if node.kind.is_reference():
find_all_function_decl_references(node_definition.displayname) # TODO
Another approach could be to store all the function declarations found on a list and run the find_all_function_decl_references
method on each.
Does anyone has any idea of how to approach this? How this find_all_function_decl_references
method would be? (I am very new with libclang
and Python.)
I have seen this where the def find_typerefs
is finding all references to some type but I am not sure how to implement it for my needs.
Ideally, I would like to be able to fetch all references for any declaration; not only functions but variable declarations, parameter declarations (e.g. the a
and b
in the example above in line 7), class declarations etc.
EDIT Following Andrew's comment, here are some details regarding my setup specifications:
- LLVM 3.8.0-win64
- libclang-py3 3.8.1
- Python3.5.1 (in Windows, I assume CPython)
- For the
args
, I tried both the ones suggested in the answer here and the ones from another answer.
*Please note, given my small programming experience I could appreciate an answer with a brief explanation of how it works.