Search code examples
javajavacc

How to parse a function with a variable argument number?


Until now my parser is able to parse functions with a known parameter number using expressions such as this

<FUNCTION><OPENPAR> son=expression() <COMMA> son1=expression() <CLOSEPAR>

Also, optional parameters can also easily be handled

<FUNCTION><OPENPAR> son=expression() <COMMA> son1=expression() [<COMMA> son2=expression()] <CLOSEPAR>

However, I haven't been able to find documentation regarding the possibility of capturing an unknown number of parameters. My guess is something like this

<FUNCTION><OPENPAR> son=expression() <COMMA> son1=expression() [<COMMA> son2=expression()]+ <CLOSEPAR>

But in this case I don't know how to capture of these multiple parameters should be done.

Any ideas or examples? (or if anyone knows that this is impossible)


Solution

  • Let's say at least one parameter is required. Then, you would need something like:

    private X myFunction():
    {
      X result = new X();
    }
    {
    
      <FUNCTION>
        <OPENPAR> 
                      son=expression() { result.params.add(son); }
           (  <COMMA> son=expression() { result.params.add(son); } )*
        <CLOSEPAR>
        { return result; }
    }
    

    To sum up, my approach is to:

    1. Create result Java class X and use it as you would in plain Java.
    2. Initialize what's required at the beginning.
    3. Return filled object.

    If you still need working example, you may find this useful.