2012-02-15 107 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