如何使用Python绑定解析单个文件到Clang?

use*_*083 6 c++ python parsing clang

我正在编写一个简单的工具来帮助重构我们的应用程序的源代码.我想解析基于wxWidgets库的C++代码,它定义了GUI并生成.ui用于Qt的XML 文件.我需要获取所有函数调用和参数值.

目前我正在使用Python绑定到Clang,使用下面的示例代码我得到了令牌及其种类和位置,但光标种类总是如此CursorKind.INVALID_FILE.

import sys
import clang.cindex

def find_typerefs(node):
    """ Find all references to the type named 'typename'
    """

    for t in node.get_tokens():
        if not node.location.file != sys.argv[1]:
            continue
        if t.kind.value != 0 and t.kind.value != 1 and t.kind.value != 4:
            print t.spelling
            print t.location
            print t.cursor.kind
            print t.kind
            print "\n"

index = clang.cindex.Index.create()
tu = index.parse(sys.argv[1])
print 'Translation unit:', tu.spelling
find_typerefs(tu.cursor)
Run Code Online (Sandbox Code Playgroud)

确定光标种类的正确方法是什么?

除了很少的博客文章,我找不到任何文档,但它们已经过时或者没有涵盖这个主题.我无法从Clang附带的例子中解决这个问题.

Seb*_*ian 5

对于游标对象,只使用cursor.kind应该没问题。也许问题在于您正在遍历令牌而不是子光标对象(对此不确定)。代替get_tokens,可以使用get_children进行AST。

为了查看AST的外观,当我想编写AST步行功能时,我使用以下脚本:https : //gist.github.com/2503232。这只显示了我系统上的cursor.kind,并提供了有意义的输出。没有CursorKind.INVALID_FILE.