2012-02-15 113 views
1

我一直在使用Eclipse JDT来分析源代码。 目前,我有一个程序能够得到一些代码,将其转换为AST,然后做一些注释。使用Eclipse从变量声明中提取所有变量名称JDT

现在,我想要做的是,对于每个变量声明,获取所有涉及的变量。例如:

int a = 10; 

它很容易,只是变a

但在下列情况下:

int a = b +c ; 

我需要分析的右侧部分,提取每个变量。 什么我到现在为止是这样的:

对于每个变量声明:

//get the fragment         
List<VariableDeclarationFragment> ff = vds_p.fragments(); 

//foreach fragment, get the name of the variable and the value associated 
for(VariableDeclarationFragment f_p : ff){ 
    SimpleName name = f_p.getName(); 
    Expression exp = f_p.getInitializer(); 
    ChildPropertyDescriptor exp_prop = f_p.getInitializerProperty(); 

    System.out.println("name: "+name); 
    System.out.println("expression: "+exp); 
}                  

因此,林能得到变量的名称,并分配给它的表达。 现在,这里是我的问题:

如何分析利用JDT的表达被赋值给变量,例如,在

int a = b + c ; 

我想bc。 我知道我可以得到“b + c”字符串并应用基于操作员的手动解析,但是我想知道是否有更加自动化的方式使用JDT

谢谢!

+0

我会在eclipse.org的JDT论坛上发布这个问题。 JDT提交者在那里并将回答它。 – 2012-02-15 16:15:08

回答

3

本质上你正在寻找'org.eclipse.jdt.core.dom.SimpleName'有一个'org.eclipse.jdt.core.dom.IVariableBinding'节点。您应该创建一个'org.eclipse.jdt.core.dom.ASTVisitor'并重写'org.eclipse.jdt.core.dom.ASTVisitor.visit(SimpleName)'。然后使用ASTVisitor分析变量声明的右侧表达式。

您可能会发现this article的'如何找到AST节点'部分有用。您也可以找到有用的AST View plugin