How to parse single file using Python bindings to

2019-06-21 22:35发布

问题:

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.

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)

What is the correct way to determine the cursor kind?

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 .

回答1:

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.

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.