[antlr-interest] How to implement an IF

Terence Parr parrt at cs.usfca.edu
Mon Dec 11 15:44:59 PST 2006


On Dec 11, 2006, at 11:42 AM, <Joerg.Werner at qimonda.com>  
<Joerg.Werner at qimonda.com> wrote:

> 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?

Well, the functions.put($ID.text, i) will be language specific  
anyway, won't it?

> And what about if-else constructs? It is hard to keep track of  
> those, because they typically have no unique ID.

There index in the input stream is effectively their virtual machine  
address I guess.

> 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:.)
>      {

don't forget that we have to actually call a rule in 3.0; can't use  
'.' to jump over a subtree (yet?)

>         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?

Actually, we have $thenAST.start, which is the tree node...damn, we  
don't have the stream index! Crap.  I guess we could add $index but  
that would force us to add that as a variable to the tree node I  
guess unless you called a rule that set a return value.  Not sure  
what to do here...

>> 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.

Great.  Use seek() for jumpTo() to be consistent; should already exist.

Ter


More information about the antlr-interest mailing list