【发布时间】:2016-09-08 17:57:50
【问题描述】:
在 Python 中通过 libclang 解析 C++ 源文件时,我试图查找(行和列位置)特定函数声明的所有引用。
例如:
#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;
}
因此,对于上面的源文件,我希望在第 5 行中为 addition 的函数声明,我希望 find_all_function_decl_references(见下文)在第 15 行和第 16 行返回 addition 的引用.
我试过这个(改编自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
另一种方法是存储在列表中找到的所有函数声明,并在每个函数上运行find_all_function_decl_references 方法。
有没有人知道如何解决这个问题?这个find_all_function_decl_references 方法会怎么样? (我是 libclang 和 Python 的新手。)
我已经看到this def find_typerefs 在其中找到对某种类型的所有引用,但我不确定如何根据我的需要实现它。
理想情况下,我希望能够获取任何声明的所有引用;不仅是函数,还有变量声明、参数声明(例如上面第 7 行示例中的 a 和 b)、类声明等。
编辑 在Andrew's 评论之后,这里有一些关于我的设置规范的详细信息:
- LLVM 3.8.0-win64
- libclang-py3 3.8.1
- Python3.5.1(在 Windows 中,我假设是 CPython)
- 对于
args,我尝试了答案here 中建议的方法和another 答案中建议的方法。
*请注意,鉴于我的编程经验很少,我希望能得到一个简单解释其工作原理的答案。
【问题讨论】:
-
不适用于 clang/python,但请参阅 stackoverflow.com/a/37149988/120163 了解有关如何“查找对特定符号/运算符的所有引用”的另一种变体
-
@IraBaxter 感谢您的链接,但我只对通过
libclang实现这一目标感兴趣。