[antlr-interest] newbie help with treewalker

Ric Klaren ric.klaren at gmail.com
Tue Jan 4 07:24:06 PST 2005


On Thu, 30 Dec 2004 04:28:25 +0000 (UTC), jmcclain
<jmcclain1 at surewest.net> wrote:
> I am parsing expressions of the form:
> left(f1("a", "b", "c"+f2(f3()), ""), 5) + mid(f1("a", "b", "c"+f2(f3()), ""),
> 5,5)
> I have built the lexer and parser grammar. The parser grammar is setup to
> build an AST where each node is the function name, logical operator or logical
> comparator, and each child is a parameter of said node. What I want to do is
> associate an action with each node that calls the associated function or
> operator. I.E., each node will execute its action that will execute a function
> passing in the child nodes as parameters. 

This very much sounds like a recursive tree walk e.g. it would look
like the calc example. E.g. you recurse down the tree until you get to
the places where you have actual values (the leaves of the tree),
return the value to the level above and there the values of the
children are added/etc.

class CalcTreeWalker extends TreeParser;
expr returns [float r]
  float a,b;
  r = 0;
:   #(PLUS a=expr b=expr)   {r = a+b;}
|   #(STAR a=expr b=expr)   {r = a*b;}
|   i:INT                               {r = (float)Integer.parseInt(i.getText()

> The result of the function should overwrite the node. What I want is to treewalk the ast, 
> overwriting the ast nodes, until you get to the root, which will hold the final value of the
> expression.

Overwriting AST nodes is not supported you can only build a new tree
when walking or set attributes in the AST nodes.



More information about the antlr-interest mailing list