[antlr-interest] How does one handle variable number of function parameters?

Bryan Ewbank ewbank at gmail.com
Tue Nov 29 17:51:03 PST 2005


Hi Rob,

Don't give up.  You're very close to groking ANTLR.  I think you tried
to merge what several people suggested, but there were not really
meant to work together.  They were more ideas bouncing around.

If you are lost, then we failed in our attempt to assimilate you into
the uber-ANTLR collective, and we must try again :-)

The lexer appears okay (even to the "evil DOS" comment!).  I don't use
ANTLR for lexing (I roll my own), so I just gave it a cursory
glance...

The parser and the tree parser both look "correct", but they don't
play well together.

The parser you have written produces trees (from the "expression"
production) that look like this:
    // Read "#( e1 e2 ... eN )" as "the tree with root e1, and children e2..eN".
    #( LPAREN IDENTIFIER #( ARGLIST expr expr ... ) )
    NUMBER

The tree parser (looking just at "expression") will only accept trees
that look like this:
    NUMBER
    IDENTIFIER
    // there's also the argList production which matches trees like this:
    //      #( ARGLIST expr expr expr ... )

The crux of the problem is that the tree parser is not eating the
function-call tree that is produced by the parser - it's only looking
for NUMBER or IDENTIFIER, but the parser will never produce
IDENTIFIER.

To get the tree parser to match the parser, it should look something like this:

expression
returns [double value = 0]
:
    ( n:NUMBER
        { ... as your example ... }
    | #( LPAREN i:IDENTIFIER a:argList )
        { ... #a contains the argument list; #i is the function to call... }
    )
;

argList
{ double v; }
:
    #( ARGLIST
        (
            v=arg:expression
            {
                System.out.println("expression = " + v);
                ... need to do something with the value, v ...
            }
        )*
    )
;


More information about the antlr-interest mailing list