[antlr-interest] loops and syntax-directed interpreter ?

Roy Metzger antlrmen at yahoo.com
Thu Jul 7 06:57:41 PDT 2011


Hello everyone and good day,

I'm following Mr. Parr's tutorial on syntax-directed interpreter for Pie language
(link: http://www.antlr.org/wiki/display/ANTLR3/Pie ). So, for this one  I'm not interested
into building tree's and such.

Now, the problem. I'm using code provided with the tutorial with minimal tweaks. My issue is with the while loop.
It looks like this:

while[boolean defer]:
'while' e=expr [defer]
s=statement[defer]+
'stop' 'loop'
{if (!defer) interp.allWhile($e.start, $s.start);} ;


My issue is with starting location of the statements passed(token index).For example this works:

while(true)
print 1 //print unlimited number of 1's
stop loop


However, whenever I use multiple statements, only last one is executed, for example:
while(true)
print 1
print 2
print 3
stop loop

This will print non-stop 3's, and  not 1,2,3,1,2,3 as I would want etc.

If there are multiple statements in the while loop, while function in the interpreter always rewinds input to
the last statement in the while clasue(print 3 in above example, while I would like to rewind input to print 1).

In the interpreter, callWhile function is not changed from the tutorial(aside statements instead of slist):

 public void callWhile(Token condStart, Token codeStart) 

{
       Boolean c = (Boolean)exec("expr", condStart.getTokenIndex());

        while ( c ) 

{
            exec("statement", codeStart.getTokenIndex());
            c = (Boolean)exec("expr", condStart.getTokenIndex());
   }
   }



Also, exec is not changed from the tutorial:

 public Object exec(String rule, int tokenIndex) 

{
        Object rv = null;
        try 

{
            int oldPosition = parser.input.index(); // save current location
            parser.input.seek(tokenIndex); // seek to place to start execution
            try { // which rule are we executing?
                if ( rule.equals("expr") ) { rv = parser.expr(false).value; }
                else if ( rule.equals("statement") ) { parser.statement(false); }
                else listener.error("error: can't start at "+rule);
    }
            finally { parser.input.seek(oldPosition); }// restore location
       }
        catch (Exception e) {
            listener.error("can't exec code @ index "+tokenIndex, e);
       }
        return rv;
   }

Now, I would really appreciate if someone could point me out why is this happening and
how it can be fixed? Also, I've noticed that even code from the tutorial has similar issues.

I would really appreciate any help, hints or tricks to help solve this problem.
Thanks,
Lee


More information about the antlr-interest mailing list