I do not see how to handle the error of a ANTLR grammar:
****************error message*********
Decision can match input such as "{'+', '-'} IDENT" using multiple alternatives: 1, 2
As a result, alternative(s) 2 were disabled for that input
|---> add: mult (('+'|'-') mult)*;
***************************************
This is mostly copied from the example of Scott, but I do not see why his works well but mine got stuck and how to get out of it?
—————following Sample.g—————-
grammar Sample;
options {
language = Java;
}
program
: 'program' IDENT '='
(constant| variable)*
'begin'
(statement)*
'end' IDENT '.'
;
constant:
'constant' IDENT ':' type ':=' expression ';'
;
type: 'integer';
variable: 'var' IDENT (',' IDENT)* ':' type ';';
statement: 'var' IDENT ':=' INTEGER ';' ;
//expression
term: IDENT |'(' expression ')'|INTEGER;
negation: 'not'* term;
unary: ('+'|'-')* negation;
mult: unary (('*'|'/'|'mod') unary)*;
[XXX Errorfor the following line]
add: mult (('+'|'-') mult)*;
relation: add (('='|'/='|'<'|'<=') add)*;
expression: (relation ('and'|'or') relation)*;
END : 'end';
CONSTANT : 'constant';
INTEGER: '0'| (('1'..'9') ('0'..'9')*);
IDENT: ('a'..'z'|'A'..'Z')('a'..'z'|'A'..'Z'|'0'..'9')*;
WS: ('\n'|' '|'\t'|'r'|'\f')+ {$channel=HIDDEN;};
You’ve misplaced a parenthesis in:
making your grammar ambiguous: the parser cannot decide when it sees a
- IDENTif it should be a part of anadd– orunary-rule.For example, your rule
expressionnow matches this:i.e., two
relationrules directly placed after each other. If the parser now stumbles upon input like this:the parser “sees” two possibilities to parse this input:
1 (unary expression & unary expression)
2 (unary & add expression)
It should be:
instead, so the there can never be 2 successive expressions (and no ambiguity!).