[antlr-interest] FW: Repeating Group of Statements

Craig Main craig at palantir.co.za
Sat Jun 18 23:48:20 PDT 2005


Hi,

I was hoping for a little assistance with my AST.
In the past I have always used antlr without the AST trees, and am now
trying to incorporate a tree in my expression parser.

The attached grammar is a simple expression parser.
My problem with the simple example is that the AST refuses to recognise more
than one line of input, and I cannot figure out why.

When I parse 'statement' I get the following.

For the following input:
const R = 1900;
BOB = (45+900);

I get the following tree. I cannot work out why the next line (BOB = ...) is
ignored.
( = const R 1900 )


The following grammar is a simple calculator

options {
	language = "CSharp";
}

class CalcLexer extends Lexer;


WS      : ( ' ' | '\t' | '\n' { newline(); }
        | '\r' ) { $setType(Token.SKIP); }
        ;

LPAREN  : '(' ;
RPAREN  : ')' ;
STAR    : '*' ;
SLASH   : '/' ;
DASH    : '^' ;
PLUS    : '+' ;
MINUS   : '-' ;
SEMI    : ';' ;
ASSIGN  : '=' ;

protected
DIGIT   : '0'..'9'|'.' ;

NUM     
options {
   paraphrase = "a numeric value";
}
        : (DIGIT)+ ;

ID
options {
  testLiterals = true;
  paraphrase = "an identifer";
}
        :	('a'..'z'|'A'..'Z'|'_') ('a'..'z'|'A'..'Z'|'_'|'0'..'9')*
;

class CalcParser extends Parser;
options { buildAST = true; }

statement      : (assignment SEMI! | const_decl SEMI!)* ;
assignment     : ID ASSIGN^ expression ;
const_decl     : "const" ID ASSIGN^ NUM;

expression     : mexpr ((PLUS^|MINUS^) mexpr)* ;
mexpr          : dexpr ((STAR^|SLASH^) dexpr)* ;
dexpr          : atom (DASH^ atom)* ;
atom           : NUM
               | LPAREN! expression RPAREN!
               | ID
               ;

class CalcTreeParser extends TreeParser;

statement
        : (assignment | const_decl)*
        ;

assignment : #(ASSIGN expression) ;
const_decl : #("const" ID ASSIGN NUM) ;

expression returns [double r] { double a, b; r = 0; }
        : #(PLUS a=expression b=expression ) {r=a+b;}
        | #(MINUS a=expression b=expression ) {r=a-b;}
        | #(DASH a=expression b=expression ) {r=System.Math.Pow(a,b);}
        | #(STAR a=expression b=expression ) {r=a*b;}
        | #(SLASH a=expression b=expression ) {r=a/b;}
        | n:NUM {r=(double)double.Parse(n.getText());}
        | i:ID {r = 0;}
        ;






More information about the antlr-interest mailing list