如何跳过子树在AST遍历使用python绑定libclang [英] How to skip subtrees in AST traversal using python bindings for libclang

查看:424
本文介绍了如何跳过子树在AST遍历使用python绑定libclang的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始使用 libclang 通过python绑定。我知道我可以遍历整个语法树(AST)使用 get_children ,但我还没有能够找到一个 get_next_sibling()(或任何可能被称为)函数,以便我可以跳过不感兴趣的子树。这样的函数是否存在?

I have just started using libclang via python bindings. I understand that I can traverse the entire syntax tree (AST) using get_children, but I have not been able to find a get_next_sibling() (or whatever it might be called) function so that I can skip subtrees that are not of interest. Does such a function exist?

推荐答案

正如francesco指出的,可以跳过元素。
由于最新的cindex.py修订版本的更改,已修饰的代码示例不再工作。

As francesco pointed out it is possible to skip elements. The mentoined code example though is not working anymore due to changes in latest cindex.py revision.

以下是从AST获取特定节点的最小示例。

Below is a minimal example to get specific nodes from AST.

example.cpp档案:

example.cpp file:

int i; 
char var[10]; 
double tmp;

int add (int a, int b)
{
  int r;
  r=a+b;
  return (r);
}

示例python代码:

example python code:

import sys
from clang.cindex import *

index = Index.create()
tu = index.parse('example.cpp')

root_node = tu.cursor

#for further working with children nodes i tend to save them in a seperate list
#wanted nodes in extra list "result"
wanted_nodes = ['var', 'tmp']
result = []
node_list= []

for i in node.get_children():
    node_list.append(i)

for i in node_list:
    if i.spelling in wanted_nodes:
        result.append(i)

#now result contains the two nodes "var" and "add"

#print the name
for i in result:
    print i.spelling

#print the type
for i in result:
    print i.type.kind

######OUTPUT#######
>>> var
>>> add
>>> TypeKind.CONSTANTARRAY
>>> TypeKind.DOUBLE

如果你想要数组的每个元素的类型u通过: / p>

if you want furthermore the type of each element of the array u get it through:

result[1].type.element_type.kind

#######OUTPUT######
>>> TypeKind.CHAR_S

因为modul cindex.py 有很好的文档,应该很难找到如何获得您需要的信息。

since the modul cindex.py is well documented it shouldnt be hard to find how to get the information that you need.

这篇关于如何跳过子树在AST遍历使用python绑定libclang的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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