使用clang遍历C ++

时间:2018-06-05 14:32:03

标签: python c++ clang

目前我正在尝试使用python绑定遍历clang生成的ast。当我只涉及一些原始类型时,python脚本工作正常。

#! /usr/bin/python

import clang.cindex
import sys

def get_class(node):
    if node.kind == clang.cindex.CursorKind.CLASS_DECL:
        print 'class name: ' , node.type.spelling

def walk(node):
    get_class(node)#
    if node.kind == clang.cindex.CursorKind.CXX_METHOD :
        print 'method name: %s, type: %s, access: %s' % (node.spelling or node.displayname, node.type.spelling, node.access_specifier)
        args = node.type.argument_types()
        if len(args) != 0:
            print 'arg type: %s' % (args[0].kind.spelling)
    for c in node.get_children():
        walk(c)

index = clang.cindex.Index.create()
walk(index.parse(sys.argv[1]).cursor)

然而,当涉及STL时,事情变得复杂......

#include <stdio.h>
#include <vector>

class myclass {

    public:
        void method1(std::vector<int>& t){
        printf("%s\n", 'a');
        }
        int method2(int a){
            a = 2;
    }
};

包含的向量头也是ast的一部分(虽然根本没有被调用),它产生大量关于std :: vector公共成员函数的信息。

是否有可能丢弃此类信息或以任何可能的方式将其隐藏到以下部分?

class name:  myclass
method name: method1, type: void (std::vector<int> &), 
access:AccessSpecifier.PUBLIC
arg type: LValueReference

我已经检查了clang / bindings / python / tests / cindex / test_translation_unit.py是否有标题排除,但未能获得进一步的通知。

关于参数类型的“displayname”还有一个小问题:无论argument_types()返回什么,它没有displayname字段,拼写字段显示“LValueReference”而不是“std :: vector”,或者我错过了一些除了“args [0] .kind.spelling”之外的其他方式?

0 个答案:

没有答案