[antlr-interest] Trying to get started with ANTLR; two problems
Niemeijer, R.A.
r.a.niemeijer at tue.nl
Thu Jul 24 06:31:21 PDT 2008
Hello everyone,
I'm trying to get started with ANTLR but I'm having two slight problems.
I'm undoubtedly doing something wrong but I can't figure out what.
Let's start with the program code:
static void Main(string[] args)
{
var input = new ANTLRStringStream("2*3=1+5");
var lexer = new TestLexer(input);
var tokens = new CommonTokenStream(lexer);
var parser = new TestParser(tokens);
var tree = parser.stat().Tree as CommonTree;
Console.WriteLine(tree.ToStringTree());
var val = parser.stat().val;
Console.WriteLine(val);
}
Nothing too complex. First I create the tree and print it, then I print
the evaluated result.
The generated output:
(= (* 2 3) (+ 1 5))
line 0:-1 no viable alternative at input '<EOF>'
False
The tree generation and printing goes without a hitch, but the
evaluation gives an error message and the wrong result. Time for the
grammar code:
grammar Test;
options
{
language = CSharp;
output = AST;
}
// LEXER --------------------------------------
INT : '0'..'9'+ ;
PLUS : '+';
MINUS : '-';
TIMES : '*';
DIV : '/';
EQ : '=';
// PARSER--------------------------------------
stat returns [bool val]
: a=exprL3 EOF!
{ $val = $a.val; }
;
exprL3 returns [bool val]
: a=exprL2 EQ^ b=exprL2
{ $val = true; }
;
exprL2 returns [int result]
: a=exprL1
(
(TIMES^ b=exprL1)
|
(DIV^ b=exprL1)
)*
;
exprL1 returns [int result]
: a=atom
(
(PLUS^ b=atom)
|
(MINUS^ b=atom)
)*
;
atom returns [int result]
: a=INT
| '(' exprL2 ')'
;
Since I have defined stat as "exprL3 EOF!", which seems to be the common
method in the examples I could find, I don't quite understand why it's
complaining about the lack of a viable alternative.
As for the evaluation value: if I change stat to say "$val = true" it
indeed returns true. If however I defer this to exprL3 it doesn't work
anymore.
Can anyone tell me what I'm doing wrong?
Thanks in advance.
Regards,
R.A. Niemeijer
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.antlr.org/pipermail/antlr-interest/attachments/20080724/50cca34f/attachment.html
More information about the antlr-interest
mailing list