简体   繁体   English

使用Eclipse JDT从变量声明中提取所有变量名

[英]Extracting all variable names from Variable declarations using Eclipse JDT

I have been working on analyzing source code using Eclipse JDT. 我一直在使用Eclipse JDT分析源代码。 Currently, I have a program that is able to get some code, convert it to an AST and then make some annotations. 目前,我有一个程序能够获取一些代码,将其转换为AST然后进行一些注释。

Now, what I want to do is, for each variable declaration, get all the variables involved. 现在,我想要做的是,对于每个变量声明,获取所涉及的所有变量。 For example: 例如:

int  a = 10;

Its easy, just variable a 它很容易,只是变量a

But in the following case : 但是在以下情况下:

int a = b +c ;

I need to analyze the right part and extract each variable. 我需要分析正确的部分并提取每个变量。 What I have until now is this : 我到现在所拥有的是:

For each variable declaration: 对于每个变量声明:

//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);
}                                                                       

So, Im able to get the name of the variable and the expression which is assigned to it. 因此,我能够获取变量的名称和分配给它的表达式。 Now, here is my question: 现在,这是我的问题:

How can I analyze using JDT the expression being assigned to the variable, For example in 如何使用JDT分析分配给变量的表达式,例如

int a = b + c ;

I want to get b and c . 我想得到bc I know that I can get the "b+c" string and apply a manual parsing based on the operator, but Im wondering if there is a more automated way using JDT 我知道我可以获取“ b + c”字符串并根据运算符应用手动解析,但是我想知道是否有使用JDT的自动化方式

Thanks! 谢谢!

Essentially you are looking for 'org.eclipse.jdt.core.dom.SimpleName' nodes which have an 'org.eclipse.jdt.core.dom.IVariableBinding'. 基本上,您正在寻找具有'org.eclipse.jdt.core.dom.IVariableBinding'的'org.eclipse.jdt.core.dom.SimpleName'节点。 You should create an 'org.eclipse.jdt.core.dom.ASTVisitor' and override 'org.eclipse.jdt.core.dom.ASTVisitor.visit(SimpleName)'. 您应该创建一个'org.eclipse.jdt.core.dom.ASTVisitor'并覆盖'org.eclipse.jdt.core.dom.ASTVisitor.visit(SimpleName)'。 Using the ASTVisitor you should then analyse the right hand side expression of a variable declaration. 然后使用ASTVisitor分析变量声明的右侧表达式。

You may find the 'How to find an AST Node' section of this article useful. 您可能会发现的“如何找到一个AST节点”部分这篇文章有用。 You may also find the AST View plugin useful. 您可能还会发现AST View插件很有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM