[antlr-interest] Examples from the antlr book, (p 54) simple expressions
Jim Idle
jimi at temporal-wave.com
Sun Mar 15 08:19:12 PDT 2009
Berlin Brown wrote:
> I am trying to run the examples from the book (or any examples for
> that matter) and getting NullPointerException errors.
>
> With antrl 3.1.2:
> Java 1.6
>
> grammar Adder;
>
> @header {
> import java.util.HashMap;
> }
>
> @members {
> HashMap memory = new HashMap();
> }
>
> prog: stat+ ;
>
> // START: stat
> stat: // Evaluate expr and emit result
> expr NEWLINE { System.out.println($expr.value); }
>
> // Match assignment and stored value
> | ID '=' expr NEWLINE { memory.put($ID.text, new
> Integer($expr.value)); }
> | NEWLINE
> ;
> // END: stat
>
> expr returns [int value]
> : e = multExpr { $value = $e.value; }
> ( '+' e = multExpr { $value += $e.value; }
> | '-' e = multExpr { $value -= $e.value; }
> )*
> ;
> // END: expr
>
> multExpr returns [int value]
> : e.atom { $value = $e.value; } ('*' e.atom { $value *= $e.value; } )*
> ;
>
First thing is that this should be e=atom in both cases.
Once I fixed that, then the grammar works as advertised with the current
version of ANTLR, so perhaps what you are trying to compile isn't quite
what you posted here?
> I am trying to run the grammar above.
>
> I get the following error:
>
> ntlr:
> [java] warning(200):
> /usr/local/projects/light_edit/src/antlr/Adder.g:14:5: Decision can
> match input such as "NEWLINE" using multiple alternatives: 1, 3
> [java] As a result, alternative(s) 3 were disabled for that input
> [java] error(201):
> /usr/local/projects/light_edit/src/antlr/Adder.g:14:5: The following
> alternatives can never be matched: 3
> [java]
> [java] Java Result: 1
>
Try this:
prog: (stat? NEWLINE)+ ;
// START: stat
stat: // Evaluate expr and emit result
expr { System.out.println($expr.value); }
// Match assignment and stored value
| ID '=' expr { memory.put($ID.text, new Integer($expr.value)); }
;
// END: stat
Although, as I say, you should not be getting that error anyway :-(
JIm
More information about the antlr-interest
mailing list