[antlr-interest] How do you implement conditional blocks in tree grammars?

Terence Parr parrt at cs.usfca.edu
Wed Sep 17 16:44:15 PDT 2008


Hi Kurt,Here are two simple rules:

ifstat
     :   ^('if' c=expr s=. e=.?) // ^('if' expr stat stat?)
         {interp.ifstat(this, (Boolean)$c.value, $s, $e);}
     ;

whilestat
     :   ^('while' c=. s=.) // ^('while' expr stat)
         {interp.whilestat(this, $c, $s);}
     ;

and here is the ifstat in the interpreter core:

     public void ifstat(Eval evaluator, Boolean condition, SLAST stat,  
SLAST elsestat)
         throws RecognitionException
     {
         nodes.push(nodes.index());
         if ( condition.booleanValue() ) {
             nodes.seek(stat.streamIndex);
             evaluator.stat();
         }
         else if ( elsestat!=null ) {
             nodes.seek(elsestat.streamIndex);
             evaluator.stat();
         }
         nodes.pop(); // start after IF
     }

Slick, no? :)

Ter
On Sep 17, 2008, at 4:38 PM, Kurt Otte wrote:

> So would the expected model be:
>
> ^((CONDITIONAL exp=expression
>    {($exp.bool)}?=>  ^(IF ^(BLOCK statement+) )
>    {(!$exp.bool)}?=>  ^(IF ^(BLOCK .) )
>  )
>
> So if the expression is true, the statements are processed as
> statements, and if the expression is false they are slurped up through
> a wildcard?
>
> Do you recommend using a predicate (like shown above) to do the
> switching or what is the best plan?  Is there a code snippet or
> example you could point me to?
>
> Thanks so much for your help and quick responses,
>
> Kurt
>
>
> On Wed, Sep 17, 2008 at 5:18 PM, Terence Parr <parrt at cs.usfca.edu>  
> wrote:
>> Oh,I did that in a tree grammar so it should work for complete
>> subtrees. At least, I did that in an interpreter of mine.
>> T
>>
>> List: http://www.antlr.org/mailman/listinfo/antlr-interest
>> Unsubscribe: http://www.antlr.org/mailman/options/antlr-interest/your-email-address
>>
>>
>
> List: http://www.antlr.org/mailman/listinfo/antlr-interest
> Unsubscribe: http://www.antlr.org/mailman/options/antlr-interest/your-email-address
>



More information about the antlr-interest mailing list