[antlr-interest] Loop and input.rewind()

Łukasz Antoniak lukasz.antoniak at gmail.com
Sun Apr 5 22:40:55 PDT 2009


Welcome!

I am new to ANTLR and trying to create a simple mini-C interpreter. I wanted
to interpret all the language actions in the parser action section. I'm
trying not to process the AST etc. I have managed to implement conditional
statements, but still have one problem with loops. I'm trying to rewind the
input stream like in the following example (I know that the loop counter is
static etc. - I wanted only to test rewinding input stream):

(for full grammar see: miniC.g)

scope CScope {
    String name;
    List symbols;
}

@members {
   int loopCounter = 5;
}

loop
@init {
    int start = -1;
}
@after {
    if (--loopCounter > 0) {
       System.out.println("rewinding: " + loopCounter);
       input.rewind(start);
    }
}
     : 'for' val=ID 'in' set=ID
     {start = input.mark(); System.out.println("start: " + start);}
     block
     {if (--loopCounter > 0) {System.out.println("rewinding: " +
loopCounter); input.rewind(start);}}
     ;

block
scope CScope;
@init {
    // initialize a scope for this code block
    $CScope::symbols = new ArrayList();
    $CScope::name = "level "+$CScope.size();
}
}
    :   '{' block_content* '}' //decl* stat+ loop* cond* '}'
    ;

block_content
    :    decl
    |    stat
    |    loop
    |    '{' block_content* '}'
    ;

decl:   'int' ID {if (evaluate) { $CScope::symbols.add($ID.text);
System.out.println("Decalred variable: " + $ID.text);}} ';'
    ;

stat:   ID '=' INT ';'
        {
        if ( !isDefined($ID.text) ) {
            System.err.println("undefined variable level "+
                $CScope.size()+": "+$ID.text);
        }
        }

Example file:
void g()
{
    for a in set
    {
        int x;
        x = 10;
    }

I'll be gratefull for any suggestions.

Regards,
Lukasz
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.antlr.org/pipermail/antlr-interest/attachments/20090406/286a9a9b/attachment.html 
-------------- next part --------------
A non-text attachment was scrubbed...
Name: miniC.g
Type: application/octet-stream
Size: 4047 bytes
Desc: not available
Url : http://www.antlr.org/pipermail/antlr-interest/attachments/20090406/286a9a9b/attachment.obj 


More information about the antlr-interest mailing list