[antlr-interest] C# Question: cannot convert from 'method group' to 'antlr.collections.AST

Bryan Ewbank ewbank at gmail.com
Thu Mar 2 05:23:24 PST 2006


>  variable :     ID
>          ( componentSelection )?
>          { #variable=
>              #(
>                   [VARIABLE,"VARIABLE"],
>                   ID,
>                   componentSelection
>              );
>          }
>      ;
>
>  This is the C# code that was generated from that grammar:
>  variable_AST=
>                      (AST)
> astFactory.make(astFactory.create(VARIABLE,"VARIABLE"), tmp93_AST,
> componentSelection);

There are two problems with this code; one is a code generation
problem - that's the one reporting the error - and one a logic error
that you will have to clear up on your own.

The problem in code generation is that componentSelection, inside the
#(...) expression, is not being recognized as a reference to a tree. 
Instead, it's just the bare rulename - which is a method function.  My
workaround is to (1) always name rule elements, and (2) always use the
"#" prefix, even within #(...) expressions.  Probably overkill, but I
don't have code-generation failures when I use this technique.

Your rule would end up looking like this (note that ## means "tree of
this rule"):

  variable :     id:ID
          ( cs:componentSelection )?
          { ## =
              #(
                   #[VARIABLE,"VARIABLE"],
                   #id,
                   #cs
              );
          }
      ;

The other problem (the logic problem) is that you are using the result
of componentSelection even if that rule has not been called.  At the
risk of someone accusing me of always using the same solution :-), you
could do this to avoid the logic problem:

   variable
   :     ID
           ( componentSelection )?
           { ## = #( [VARIABLE,"VARIABLE"], ## ); }
   ;

It is a more standard idiom for adding nodes to a tree, and avoids the
question of whether componentSelection was recognized.  The problem,
in this case, is that you can end up with VARIABLE nodes with either
one or two children.  I say "problem" here because it causes problems
in subsequent tree parsers; however, if you don't need to worry about
falling off of the tree, you can accept this.

There's an example in the antlrman.pdf that discusses this tree-shape
problem in the context of the "-" operator being either a minus, or a
unary negation operator.

Hope this helps,
- Bryan


More information about the antlr-interest mailing list