如何解析单个文件使用Python绑定到Clang? [英] How to parse single file using Python bindings to Clang?

查看:432
本文介绍了如何解析单个文件使用Python绑定到Clang?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am writing a simple tool to help with refactoring the source code of our application. I would like to parse C++ code based on wxWidgets library, which defines GUI and produce XML .ui file to use with Qt. I need to get all function calls and value of arguments.

目前我使用Python绑定到Clang,使用下面的示例代码,我获得令牌及其种类和位置,但游标类型总是 CursorKind.INVALID_FILE

Currently I am toying with Python bindings to Clang, using the example code below I get the tokens and their kind and location, but the cursor kind is always 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)

光标种类?

我找不到任何文档,除了几个博客文章,但他们已过时或不覆盖这个主题。

I couldn't find any documentation except few blog posts, but they were outdated or not covering this topic. I was neither unable to work it out from examples that came with Clang .

推荐答案

对于游标对象,它应该是确定的使用cursor.kind。也许问题是你走的是令牌,而不是子游标对象(不确定)。
而不是get_tokens,你可以使用get_children来走AST。

For cursor objects, it should be ok to just use cursor.kind. Maybe the problem is that you're walking tokens instead of child cursor objects (Not sure about that). Instead of get_tokens, you can use get_children to walk the AST.

为了看看AST的样子,当我想写一个AST走函数,我使用此脚本: https://gist.github.com/2503232
这只是显示cursor.kind,并在我的系统上给出合理的输出。否 CursorKind.INVALID_FILE。

In order to see how the AST looks like, when I want to write an AST walking function, I use this script: https://gist.github.com/2503232. This just shows cursor.kind, and gives sensible outputs, on my system. No CursorKind.INVALID_FILE.

这篇关于如何解析单个文件使用Python绑定到Clang?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆