Search code examples
antlrantlr3antlrworks

ANTLR3 NoViableAltException


This is the part of my grammar that make error:

expr : func_name '(' constant (',' constant)* ')' ;

constant
    :    '"' (~'"')* '"';

WS      :      (' '|'\t')+ {skip();} ;

And the error is about this part of text:

"w9ygS99Qp_", "vuPfq6YcbX"

The interpreter of ANTLRWorks give me the next leaves, which have a node constant as parent:

"
w9ygS99Qp_",
"

Then it is an NoViableAltException error.

Normally, it should have this leaves:

"
w9ygS99Qp_
"

Apparently, the problem is the _ before the ", because I tried to suppress the _, but the same error appears when te parser meet the next _"


Solution

  • Your constant should be a lexer rule, not a parser rule. Inside a parser rule, ~'"' matches any token other than a double quote-token. It does not match any charatcer except the double quote-char.

    Do it like this instead:

    expr : func_name '(' Constant (',' Constant)* ')' ;
    
    Constant
        :    '"' (~'"')* '"';
    

    OK, thus I have to compile the grammar in Java, and then test it in Java, if I understood well?

    Yes, or use ANTLRWorks' debugger instead. The debugger works like a charm.

    To test in plain Java, do something like this:

    import org.antlr.runtime.*;
    
    public class Main {
      public static void main(String[] args) throws Exception {
        TLexer lexer = new TLexer(new ANTLRStringStream("name(\"w9ygS99Qp_\", \"vuPfq6YcbX\")"));
        TParser parser = new TParser(new CommonTokenStream(lexer));
        parser.expr();
      }
    }
    

    Maybe should I use ANTLR4, to be able to use ANTLRWorks correctly?

    If you have a choice to use either ANTLR3 or ANTLR4, then go for ANTLR4. Note that there's a new (rewritten) version of ANTLRWorks for ANTLR4 grammars: http://tunnelvisionlabs.com/products/demo/antlrworks