我正在尝试使用clang及其python绑定来处理C / C ++代码的AST。
我有以下测试C ++代码:
#include <stdio.h>
class myclass {
public:
void mymethod() {
printf("method\n");
}
};
void testfunc() {
myclass var;
var.mymethod();
}
并且我编写了以下python代码(简化和缩短)以进行遍历:
#! /usr/bin/python
import clang.cindex
import sys
def walk(node):
if node.kind == clang.cindex.CursorKind.CALL_EXPR:
print 'name: %s, type: %s' % (node.spelling or node.displayname, node.type.spelling)
for c in node.get_children():
walk(c)
index = clang.cindex.Index.create()
walk(index.parse(sys.argv[1]).cursor)
现在,当我的代码在testfunc中到达var.mymethod()时,它将显示“ mymethod”和“ void”。不是我所期望的。我正在尝试检索调用mymethod的类类型,而不是方法的返回类型。
如上面的注释所述,您将获得函数的返回类型。这不是从中mymethod
调用变量的类型。
查看AST输出(使用clang -Xclang -ast-dump -fno-diagnostics-color),这是 testfunc
`-FunctionDecl 0x5e14080 <line:9:1, line:12:1> line:9:6 testfunc 'void ()'
`-CompoundStmt 0x5e14750 <col:17, line:12:1>
|-DeclStmt 0x5e146b0 <line:10:9, col:20>
| `-VarDecl 0x5e14130 <col:9, col:17> col:17 used var 'myclass' callinit
| `-CXXConstructExpr 0x5e14680 <col:17> 'myclass' 'void () noexcept'
`-CXXMemberCallExpr 0x5e14728 <line:11:9, col:22> 'void'
`-MemberExpr 0x5e146f0 <col:9, col:13> '<bound member function type>' .mymethod 0x5e13dd0
`-DeclRefExpr 0x5e146c8 <col:9> 'myclass' lvalue Var 0x5e14130 'var' 'myclass'
然后,您可以看到里面CXXMemberCallExpr
的MemberExpr
,里面有和,里面的aDeclRefExpr
指代了var
它的类型myclass
。我不确定您是如何用Python编写的,但是通过从CALL_EXPR条目中转储一些内部结构来弄清楚它并不难。
使用上面的代码,我将其修改为如下所示:
#! /usr/bin/python
import clang.cindex
import sys
def find_decl_ref_expr(node):
for c in node.get_children():
if c.kind == clang.cindex.CursorKind.DECL_REF_EXPR:
print "Member function call via", c.type.spelling, c.displayname
else:
find_decl_ref_expr(c)
def called_from(node):
for c in node.get_children():
if c.kind == clang.cindex.CursorKind.MEMBER_REF_EXPR:
find_decl_ref_expr(c);
def walk(node):
if node.kind == clang.cindex.CursorKind.CALL_EXPR:
print 'name: %s, type: %s' % (node.spelling or node.displayname, node.type.spelling)
called_from(node)
for c in node.get_children():
walk(c)
index = clang.cindex.Index.create()
walk(index.parse(sys.argv[1]).cursor)
这是可行的,但绝对不是一个完整的解决方案。例如,添加通过数组使用的指针也会打印用于进入数组的索引。为了完全理解复杂的代码,我不确定您实际需要执行什么操作(例如,如果myclass
一个类中的多层包含各种指针和索引操作)。
我还发布了一些我用来检查每个节点中内容的代码:
def dump_children(node):
for c in node.get_children():
print c.kind, c.type.spelling
dump_children(c)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句