ANTLR 4 Parsing Problems: Works with TestRig But Not in Java

Viewed 70

I'm writing a lambda calculus interpreter in Java using ANTLR 4.8. Parsing works as expected when using the TestRun tool. However, inside my Java code, I end up with empty parsing lists whenever I parse lambda expressions with the abstractionExpr rule in them. I don't understand the discrepancy between TestRun and my Java code.

Here is an example using TestRun:

$ grun LambdaExpr lexpr -tree
^x.y
(lexpr ^ x . (lexpr y))

And here is the output of my Java program when parsing the same expression:

$ java LambdaCalculusInterpreter
Parse tree output: []

Below is my grammar:

grammar LambdaExpr;

Var         : [a-z]+ ;

WS          : [ \t\r\n]+ -> skip ;


lexpr       : Var                   # varExpr
            | '^' Var '.' lexpr     # abstractionExpr
            | '(' lexpr lexpr ')'   # applicationExpr
            ;

Below is my Java code:

import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.tree.*;

public class LambdaCalculusInterpreter {
    public static void main(String[] args) {
    CharStream inputStream = CharStreams.fromString("^x.y");
    LambdaExprLexer lexer = new LambdaExprLexer(inputStream);
    CommonTokenStream commonTokenStream = new CommonTokenStream(lexer);
    LambdaExprParser parser = new LambdaExprParser(commonTokenStream);

    ParseTree tree = parser.lexpr();
    System.out.println("Parse tree output: " + tree.toString());
}

1 Answers

The toString is inherited from org.antlr.v4.runtime.RuleContext, which has a different implementation than you expect. You'll want to call toStringTree(...):

ParseTree tree = parser.lexpr();
System.out.println("Parse tree output: " + tree.toStringTree(parser));

which prints:

Parse tree output: (lexpr ^ x . (lexpr y))

Also make sure you're using org.antlr.v4.runtime.tree.ParseTree, not some other ParseTree class that happens to be present in your classpath (which might not be the case).

Related