如果我在某些 C++ 代码中有以下宏:
_Foo(arg1, arg2)
我想使用 Python 使用 Clang 和 cindex.py 提供的 Python 绑定来查找该宏的所有实例和范围。我不想直接在代码上使用 Python 中的正则表达式,因为这让我达到了 99%,但不是 100%。在我看来,要达到 100%,您需要使用真正的 C++ 解析器(如 Clang)来处理人们执行语法正确和编译但对正则表达式没有意义的愚蠢事情的所有情况。我需要处理 100% 的情况,并且由于我们使用 Clang 作为我们的编译器之一,因此将它用作此任务的解析器也是有意义的。
鉴于以下 Python 代码,我能够找到 Clang python 绑定知道的似乎是预定义类型,但不是宏:
def find_typerefs(node):
ref_node = clang.cindex.Cursor_ref(node)
if ref_node:
print 'Found %s Type %s DATA %s Extent %s [line=%s, col=%s]' % (
ref_node.spelling, ref_node.kind, node.data, node.extent, node.location.line, node.location.column)
# Recurse for children of this node
for c in node.get_children():
find_typerefs(c)
index = clang.cindex.Index.create()
tu = index.parse(sys.argv[1])
find_typerefs(tu.cursor)
我想我正在寻找的是一种将原始 AST 解析为我的宏名称的方法_FOO()
,但我不确定。有人可以提供一些代码让我以宏的名称传递并从 Clang 取回范围或数据吗?