ANTLR4 parsing error: no viable alternative at input

5.6k views Asked by At

I have a grammar which is obviously erroneous as parsing a simple file generates strange error messages.

I simplified the following grammar as much as I could without altering the error (if you remove 'this' the tree gui output of ANTLRWorks colors the token int of the sample file differently although the structure seems to be equal).

grammar DepClsJ_no_java_debug;

module   : ( methodDecl )* ;

methodDecl   : pathType Identifier '()' block ;

pathType   : Identifier | 'this' ;

block   : '{'
    ( localDecl ';'  )*
    ( statement  )*
    ( expr  )?
    '}'   ;

localDecl   : pathType Identifier ( '=' expr )?;

statement   : block | expr ';' ;

expr   : dotExpr ( '=' dotExpr  )* ;    dotExpr   : Identifier ( '.' Identifier )* ;

Identifier   : ('a'..'z'|'A'..'Z'|'_') ('a'..'z'|'A'..'Z'|'0'..'9'|'_')* ;

Demo code:

void main() {
    a = c;
    int b;
}

ANTLRWorks 2 gives me the following error messages:

line 3:8 no viable alternative at input 'intb'
line 3:9 mismatched input ';' expecting '()'
1

There are 1 answers

1
Sam Harwell On BEST ANSWER

int b; is a localDecl, which according to the block rule in your grammar cannot appear after the first statement. If you had instead relaxed your grammar by using the following, then you could have used a parse tree listener to produce a meaningful error message after the parse completed successfully.

block
  : '{'
    (localDecl ';' | statement)*
    expr?
    '}'
  ;