[antlr-interest] if statement troubles

Juancarlo Añez apalala at gmail.com
Thu Sep 6 05:10:16 PDT 2012


Guus,

Just my humble opinion...

You've obfuscated the grammar with tree-construction and other actions
beyond the point of understanding. I'be been there, and done that.

With the speed of modern computers, there's no need to try to build a one
pass parser/compiler. And if you did want to build such a beast, the clear
way to do it is through delegation to phase-specific grammars.

If I remember correctly, the grammar for parsing LISP-like languages takes
less than a dozen lines of ANTLR. A tree grammar that can stract semantics
out of the AST take about the same, and you still have one pass.

My advice would be to go back to the drawing board with the aim of making
things simpler.

This code transforms an ANTLR AST into a Python list of lists:

def tree_to_list(tree):
    name = tree.getText()
    if not tree.children:
        children = []
    else:
        children = [tree_to_list(c) for c in tree.children]
    return [name] + children


The interpreter dispatches execution based on the first value of each list
using getattr().

FWIW, It doesn't have to hurt.

-- Juanca


On Thu, Sep 6, 2012 at 4:28 AM, Guus Bonnema <gbonnema at xs4all.nl> wrote:

>
> Hi All,
>
> When interpreting an if-statement for a simple language I found that my
> approach for executing the statement block had weird results. When
> debugging in Netscape I found that input.index() always returns zero. I
> am probably doing something wrong. My intention is to parse the
> if-statement first and interprete the statement block according to the
> condition.
>
> Could anyone point me in the right direction? What am I doing wrong?
>
> The source copied below is part of a tree grammar that reads the
> following tree:
>
> (X (SLIST (VAR int i = (UNAIR - 1)) (if (> 2 0) (SLIST (= i 1)))))
>
> <QUOTE>
> if_statement    // options {backtrack=true;}
>         @init {int s_index=0; int el_index=0;}
> :               ^(IF b=boolexpr {s_index = input.index();} s=.
>                              {el_index = input.index();} el=.?)
> {       int next = input.index();
>         if ($b.value) {
>            input.seek(s_index);
>            statement_block();
>         } else if ($el!=null) {
>            input.seek(el_index);
>            statement_block();
>         }
>         input.seek(next);
> }
> ;
> </QUOTE>
>
> P.S. I copied this solution from somewhere in Markmail, but must have
> missed something.
>
> Kind regards, Guus Bonnema.
>
> List: http://www.antlr.org/mailman/listinfo/antlr-interest
> Unsubscribe:
> http://www.antlr.org/mailman/options/antlr-interest/your-email-address
>



-- 
Juancarlo *Añez*


More information about the antlr-interest mailing list