Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How print syntax tree using Javac

I implemented a program TreeScanner, to print information about all nodes in AST. The program supports all types (all visit methods are implemented). However, the problem is that for the statement, System.out.println(object.YYY); the program does not visit field reference YYY.

It detects object as identifier, but can not detect YYY as identifier. However, when I have System.out.println(YYY); then visitIdentifier will visit YYY.

Please let me know what is the difference between the both above lines, while in one YYY is visited by visitidentifier, in the another case it is not visited.

How can I visit YYY in object.YYY?

In class org.eclipse.jdt.core.dom we have FieldAccess which is called in both above cases for YYY, but seems TreeScanner in Javac has no similar method.

like image 620
Nihamata Fashoti Avatar asked Nov 09 '22 20:11

Nihamata Fashoti


1 Answers

The visitIdentifier method gets called on Identifier notes in the AST, which are created when an identifier is used as an expression. However the syntax for member selection in Java is <expression>.<identifier>, not <expression>.<expression>, meaning the YYY in object.YYY is not a sub-expression and thus doesn't get its own subtree. Instead the MemberSelectTree for object.YYY simply contains YYY as a Name directly, accessible via getIdentifier(). There is no visitName method in TreeScanner, so the only way to get at YYY here would be to do so from visitMemberSelect directly.

Here's how you'd print object.YYY using visitMemberSelect:

Void visitMemberSelect(MemberSelectTree memberSelect, Void p) {
    // Print the object
    memberSelect.getExpression().accept(this, p);
    System.out.print(".");
    // Print the name of the member
    System.out.print(memberSelect.getIdentifier());
}
like image 114
sepp2k Avatar answered Nov 14 '22 23:11

sepp2k