14

如果我在某些 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 取回范围或数据吗?

4

2 回答 2

10

您需要将适当的options标志传递给Index.parse

tu = index.parse(sys.argv[1], options=clang.cindex.TranslationUnit.PARSE_DETAILED_PROCESSING_RECORD)

光标访问者的其余部分可能如下所示:

def visit(node):
    if node.kind in (clang.cindex.CursorKind.MACRO_INSTANTIATION, clang.cindex.CursorKind.MACRO_DEFINITION):
        print 'Found %s Type %s DATA %s Extent %s [line=%s, col=%s]' % (node.displayname, node.kind, node.data, node.extent, node.location.line, node.location.column)
    for c in node.get_children():
        visit(c)
于 2013-06-28T20:44:02.263 回答
0

我曾经写了一个脚本来漂亮地打印你从 libclang 获得的整个 AST,以便查看在哪里可以找到哪些信息。

这是:https ://gist.github.com/2503232

于 2013-02-25T19:09:08.400 回答