ANTLR4 controlling current node execution

73 views Asked by At

I'm building a Java to Ruby source code translator, I'm using listeners, so far I have extended the BaseListener, I'm using Java.g4 and I'm trying to output the "else" after the if, but it has to be matched right, I've got this:

@Override public void enterStatement(JavaParser.StatementContext ctx) {
    ident();
    if(ctx.getChild(0).getText().compareTo("if") == 0){
        // has a else clause
        if(ctx.getChildCount() > 3){
            // this just changes java "if( x > 5)" to ruby "if x > 5"
            System.out.println("if "+ctx.getChild(1).getChild(1).getText());
            // how ho I put the else after the execution of this statement?
        }
        else
            System.out.println("if "+ctx.getChild(1).getChild(1).getText());
        }
    }

Something like this: Image.png

1

There are 1 answers

0
GRosenberg On BEST ANSWER

One way to do this is to better plan for use of the enter/exit methods. This includes using labeled alternatives to create automatically distinguishable contexts.

To implement, change the 'statement' rule from

| 'if' parExpression statement ('else' statement)?

to

| 'if' parExpression statement elseStatement?  # ifStmt

and define a new rule

elseStatement: 'else' statement ;

In the enterIfStmt listener method, just print the IF. No need to test if you are in an IF statement -- the context ensures that you are. In the enterElseStatement method, likewise just print the ELSE.

Use the enter and exit methods of parExpression and statement to print their content, delegating the printing of the content of their elements to the elements own enter/exit methods.