ANTLR4: Extraneous Input error

2019-05-21 03:41发布

问题:

I'm following the "Definitive ANTLR4 Reference" book, and decided to add a couple of keywords to their calculator grammar to help clear memory. Building the grammar and compiling the resulting java code works fine, but when I execute the visitor code, I get the error: "line 6:0 extraneous input '$rem' expecting {<EOF>, '(', ID, INT, NEWLINE}" and the same for '$clearmem' on line 8:0.

Here is my grammar file:

grammar LabeledExpr;

//Parser rules================================= 
prog: kword+
    | stat+ 
    ;

stat: expr endl             # printExpr
    | ID '=' expr endl      # assign
    | NEWLINE               # blank
    ;

expr: expr op=('*'|'/') expr    # MulDiv
    | expr op=('+'|'-') expr    # AddSub
    | INT                       # int
    | ID                        # id
    | '(' expr ')'              # parens
    ;

kword: '$clearmem' endl     #clearMem
    | '$rem' ID endl        #remVar
    ;

endl: NEWLINE
    | EOF
    ;

//Lexer rules==================================
ID: [a-zA-Z]+ ;
INT: [0-9]+ ;
NEWLINE: '\r'? '\n' ;
WS: [ \t]+ -> skip;

MUL: '*' ;
DIV: '/' ;
ADD: '+' ;
SUB: '-' ;

And the .expr file with the code to parse:

193
a = 5
b = 6
a
b 
$rem a
a
$clearmem

I just started on ANTLR4 last night so I really don't know much of what to look for error-wise, but from what I can tell nothing is wrong with either file.

I'm sure that I am missing something pretty simple, but I can find it, so I would appreciate help from anyone who is more familiar with ANTLR4.

Thanks.

回答1:

The problem is your prog rule:

prog: kword+
  | stat+ 
  ;

This rule states that the program consists of one or more kword rules or one or more stat rules. There is no program that includes both a kword and stat. What you probably meant to write is the following, which allows any sequence of kword or stat rules. Note that I changed + to * to allow an empty program. Even if your compiler shouldn't allow the program to be empty, this error is better left for validation in a visitor or listener.

prog
  : ( kword
    | stat
    )*
  ;