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

How to parse single file using Python bindings to Clang?

本文关键字:单个 文件 Clang 何使用 Python 绑定      更新时间:2023-10-16

我正在编写一个简单的工具,以帮助重构我们应用程序的源代码。我想基于WXWIDGETS库来解析C 代码,该库定义GUI并产生XML .ui文件以与QT一起使用。我需要获取所有函数调用和参数的价值。

目前,我正在使用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)

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

我找不到任何文档,除了少数几篇博客文章,但是它们已经过时或没有涵盖此主题。我既不能从Clang随附的示例中解决这个问题。

对于光标对象,应该只使用光标。也许问题是您正在走上代币而不是儿童光标对象(对此不确定)。您可以使用get_children而不是get_tokens来行走AST。

为了查看AST的外观,当我想编写AST步行功能时,我使用此脚本:https://gist.github.com/2503232。这只是显示了光标,并在我的系统上提供明智的输出。无CursorKind.INVALID_FILE.