[antlr-interest] Re: I'm stuck with my parser tree generator ..

kozchris csnyder at alumni.ncsu.edu
Mon Oct 11 14:38:41 PDT 2004



Adding this should work:

expr {
  // tree construction rule here?
   ##=#(#[EXPR, "EXPR"],##);
} 

Chris
--- In antlr-interest at yahoogroups.com, "whaefelinger"
<ora.et.labora at w...> wrote:
> 
> 
> I do not get the picture about this parser trees and how to utilitze 
> them. Here's my very simple problem: 
> 
> My parser should accept a list of (simple) expressions, for
> example:
> 
>  5+4 ; 3*2; 
> 
> My parser should then further evaluate each expression in the
> list and summarize  them up. So my input 5+4 ;3*2; should end
> up in printing 15.
> 
> Here's my Parser:
> 
>  class CalcParser extends Parser;
>   options { buildAST = true; }
> 
>   tokens { EXPR; }
> 
>   stmts
>     :  ( 
>             expr {
>                 // tree construction rule here?
>             } 
>             ";"!
>         )+ 
>     ;
> 
>   expr
>     :	INT ((PLUS^|MULT^) INT)*
>     ;
> 
> 
> and this is my tree parser:
> 
>  class CalcTreeWalker extends TreeParser;
> 
>  stmts returns [float r]
>  { 
>     float a = 0;
>     r = 0; 
>  }
>     : #(EXPR a=expr) { r+=a ; } 
>     ;
> 
>  expr returns [float r]
>  {
> 	float a,b;
> 	r=0;
>  }
>     :	#(PLUS  a=expr b=expr) { r = a+b; }
>     |   #(MULT  a=expr b=expr) { r = a*b; }
>     |	i:INT	{r = (float)Integer.parseInt(i.getText());}
>     ;
> 
> In my main function I do then basically this:
> 
>   public static void main(String[] args)
>   {
>      ...
>      // Parse the input expression
>      parser.stmts();
>      CommonAST t = (CommonAST)parser.getAST();
>      // Print the resulting tree out in LISP notation
>      System.out.println(t.toStringTree());
>      CalcTreeWalker walker = new CalcTreeWalker();
>      // Traverse the tree created by the parser
>      float sum = walker.stmts(t);
>      System.out.println("*sum => " + sum);
>      ...
>    }
> 
> When I run my parser on input "5+4 ; 3*2;" I do get this
> output (line numbering by me):
> 
> 001  /opt/jdk32/142_03/bin/java antlr.Tool calc.g
> 002  ANTLR Parser Generator   Version 2.7.4   1989-2004 jGuru.com
> 003  ( + 5 4 )
> 004  <AST>:0:0: expecting EXPR, found '+'
> 005  *sum => 0.0
> 
> The error message in 004 is what I (more or less) expected as
> there is no 'EXPR' node. But how would I construct it?
> 
> Please be aware that I deliberatly do not want to "summarize"
> in the 'expr' rule of my parser tree. 
> 
> I wonder whether someone can give me some help?





 
Yahoo! Groups Links

<*> To visit your group on the web, go to:
    http://groups.yahoo.com/group/antlr-interest/

<*> To unsubscribe from this group, send an email to:
    antlr-interest-unsubscribe at yahoogroups.com

<*> Your use of Yahoo! Groups is subject to:
    http://docs.yahoo.com/info/terms/
 





More information about the antlr-interest mailing list