[antlr-interest] How to implement an IF

Joerg.Werner at qimonda.com Joerg.Werner at qimonda.com
Mon Dec 11 11:42:43 PST 2006


Hi all, 

>Ok, I just figured out. we need a new method on the CommonTreeNodeStream that pushes the
>current location a stack and jumps to a new index in the stream.  The only trick then is to map 
>nodes of interest to the correct index.  In reality, what happens is that the recognition of 
>the functions in your language will create a hash table entry that maps the function name to 
>the index in the stream:
>
>funcDef
>@init {int i = input.index();}
>	:	'void' ID '(' ')' -> ^(FUNCDEF ID)
>		{functions.put($ID.text, i);}
>	;

Yes, this will work nicely for functions. What I do not like is that we use "input" directly, this makes us implementation/language dependent. Maybe we should go for $input instead?

And what about if-else constructs? It is hard to keep track of those, because they typically have no unique ID. My solution for if-then constructs would be along these lines (in the TreeParser):

  ^(IF_TOKEN t=boolean_expression {int thenIndex = input.index();} thenAst:. {int elseIndex = input.index();} elseAst:.)
     {
        input.jumpTo(t ? thenIndex : elseIndex); 
        val = expression(); 
     }

Though I think this litters the code quite a lot. Much nicer would be if thenAst and elseAst would have attributes which would point to the correct position in the CommonTreeNodeStream, something like:

  ^(IF_TOKEN t=boolean_expression thenAst:. elseAst:.)
     {
        input.jumpTo(t ? $thenAst.TreeNodePos : $elseAst.TreeNodePos); 
        val = expression(); 
     }

What do you think about this?

>something like that. If you get that to work, let us know.

I'll try to implement something like the index() and jumpTo() methods in CommonTreeNodeStream. Will let you know when I'm done.


>I should also note that I don't think that I have finished backtracking for the tree node 
>stream.  Comments on the market and rewind methods should indicate that.

>Ter

Regards,

Jörg


More information about the antlr-interest mailing list