[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
[news.eclipse.tools.jdt] Re: Analyzing IF statements using Eclipse ASTParser

Fayezin Islam wrote:
Hi,

I want to differentiate between the two if statements by parsing using Eclipse ASTParser.

The if statements are -
if (c==1)
if (a<10 && b>0)

Using the visitor pattern I am able to identify both statements as "ifstatement"s...

Now, I also need to count "how many" conditions/branches are inside the statement.

For example, in the 1st if statement above, there is 1 condition (c==1) and in the second if statement above there are two conditions (a<10 and b>0).

Please advice how can I find how many branches are inside the ifstatement.

A reply with a small example will be very appreciated as I am a newbie to the ASTParser.

Thanks for your help in advance.

Regards,

Fayezin


I'd recommend downloading the ASTView plug-in from http://www.eclipse.org/jdt/ui/astview/index.php; then you can examine the AST view of various snippets of code and see exactly what the AST representation is. This will allow you to distinguish between the cases above, or any others.

To answer your specific question, in both cases the IfStatement contains an expression (an InfixExpression). You can examine either the operands or the operator to distinguish the two:

In the first example (c==1), the operator is '==', the left operand is a SimpleName, and the right operand is a NumberLiteral.

In the second example, the operator is &&, and both the left and right operands are InfixExpressions (which you can dive deeper into).

So if you're just trying to distinguish simple expressions from compound expressions, you could look at the operand types and see if they are instances of Expressions, or of simple types.

I think you might want to do something like clear a counter at your IfStatement visitor, and then have an InfixExpression visitor that increments the counter, if your primary requirement is just to find the number of conditions being tested.

Hope that helps,
Mike