java - ANTLR4 controlling current node execution -
i'm building java ruby source code translator, i'm using listeners, far have extended baselistener, i'm using java.g4 , i'm trying output "else" after if, has matched right, i've got this:
@override public void enterstatement(javaparser.statementcontext ctx) { ident(); if(ctx.getchild(0).gettext().compareto("if") == 0){ // has else clause if(ctx.getchildcount() > 3){ // changes java "if( x > 5)" ruby "if x > 5" system.out.println("if "+ctx.getchild(1).getchild(1).gettext()); // how ho put else after execution of statement? } else system.out.println("if "+ctx.getchild(1).getchild(1).gettext()); } }
something this: image.png
one way better plan use of enter/exit methods. includes using labeled alternatives create automatically distinguishable contexts.
to implement, change 'statement' rule
| 'if' parexpression statement ('else' statement)?
to
| 'if' parexpression statement elsestatement? # ifstmt
and define new rule
elsestatement: 'else' statement ;
in enterifstmt
listener method, print if. no need test if in if statement -- context ensures are. in enterelsestatement
method, likewise print else.
use enter , exit methods of parexpression , statement print content, delegating printing of content of elements elements own enter/exit methods.
Comments
Post a Comment