ANTLR grammar for defining/calling multi-parameter functions
Asked Answered
P

1

6

I have a grammar that I'd like to include multi-parameter functions in (like f(x,y)). I'm using AST output with my own tree parser. Right now my parameter list production is

paramdefs: (ID COMMA)* ID ;

This works fine, but the AST output for

z(x,y)=expression

is

(FUNC (z)(x)(,)(y)(expression))

(i.e. it's very flat).

The FUNC CommonTree's children, in the general case, are {function name, parameter, comma, parameter, defined expression}, for any number of parameters. I'd like the parameter list to be a single child and not have commas (this would make it easier to walk the tree).

Ideally, this is what the tree would look like:

(FUNC (z)((x)(y))(expression))

(note the absence of the comma element and the grouping of x and y.

Relevant associated areas of the grammar:

funcdef: ID  '(' paramdefs ')' '=' expr -> ^(FUNC ID paramdefs expr) ;

paramdefs: (ID COMMA)* ID ;
Pasteurism answered 11/7, 2011 at 0:57 Comment(0)
N
8

To create a tree like this:

enter image description here

for the input z(x,y)=expr, do the following:

grammar ...

...

tokens {
  FUNC;
  PARAMS;
}

...

funcdef
  :  ID  '(' paramdefs ')' '=' expr   -> ^(FUNC ID paramdefs expr) 
  ;

paramdefs
  :  (ID COMMA)* ID                   -> ^(PARAMS ID+)
  ;
Nedry answered 11/7, 2011 at 6:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.