How to print a syntax tree using Javac

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

It detects the object as an identifier, but cannot determine YYY as an identifier. However, when I have System.out.println (YYY); then visitIdentifier will visit YYY .

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

How can I visit YYY at object.YYY ?

In the org.eclipse.jdt.core.dom class, we have FieldAccess , which is called in both cases above for YYY , but it looks like TreeScanner in Javac does not have a similar method.

+5
source share
1 answer

The visitIdentifier method visitIdentifier called in the Identifier notes in the AST, which are created when the identifier is used as an expression. However, the syntax for selecting a member in Java is <expression>.<identifier> , not <expression>.<expression> , which means that YYY in object.YYY not a sub-expression and therefore does not get its own subtree. Instead, MemberSelectTree for object.YYY just contains YYY as Name directly, accessible via getIdentifier() . There TreeScanner no TreeScanner method in visitName , so the only way to get to YYY here would be to do this directly from visitMemberSelect .

Here you can print object.YYY with 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()); } 
+1
source

Source: https://habr.com/ru/post/1210553/


All Articles