[antlr-interest] TreeWalker algorithm for a for loop (C style)

Christian Pontesegger christian.pontesegger at web.de
Fri Feb 26 06:31:09 PST 2010


The next step for my grammar is to implement a tree walker for loops. I
guess the hardest one is the for loop. The syntax should be almost the
same as for C:

for (int $i = 0; $i < 4; $i++) {
    print($i)
}

my parser creates a nice tree like this:

(for (VARDECL int i 0) (CONDITION (< i 4)) (ITERATE (POSTFIX ++ i))
(BLOCK (FUNCALL print i)))



Treegrammar looks like this:

forStatement
    :    ^('for'
            variableDefinition?
            condition?
            iteration?
            block
        )
    ;

condition returns [boolean result]
    :    ^(CONDITION expression)        { $result =
$expression.value.getBoolean(); }
    ;
   
iteration
    :    ^(ITERATE expression)
    ;



I figured out how to move around within the tree with push() & pop() on
the CommonTreeNodeStream.
Initially I wanted to do it that way:


    :    ^(
            'for'
            variableDefinition?        {    markCondition = input.mark(); }
            cond=condition?            {    markIteration = input.mark(); }
            iter=iteration?            {    markBody = input.mark(); }
            .
        )
                {  loop logic: do some evaluation and re-run the body if
necessary }

Problem is, that iteration is executed before the first time the loop
body is executed. I need to postpone this until the body has been
executed the first time.
Secondly iter seems not to be set to something. How can I find out if a
condition is there?

I find tree walking rather complicated, especially if you need to jump
around between tree nodes. Is there some tutorial on this. The ANTLR
reference seems to have no topic on this.

Christian


More information about the antlr-interest mailing list