Is there any convenient way to say "multiple options in any order" in ANTLR 4?

46 views Asked by At

I just ran across this rather messy declaration in an ANTLR 4 grammar:

func_arg
    : arg_class  param_name? func_type
    | param_name arg_class?  func_type
    |                        func_type
    ;

If you look at that and think about it for a second, the idea it's really trying to get across is (pseudocode):

func_arg
    : MULTIPLE_IN_ANY_ORDER(arg_class?, param_name?) func_type
    ;

If there are more than two options, declaring it in this style could lead to a combinatorial explosion of sub-rules. Is there any simpler way to declare the concept of "multiple options in any order"?

2

There are 2 answers

0
Bart Kiers On

Is there any simpler way to declare the concept of "multiple options in any order"?

No, there is not.

Of course, you can make it a bit more readable by doing something like this:

func_arg
 : arg_class_param_name? func_type
 ;

arg_class_param_name
 : arg_class  param_name?
 | param_name arg_class?
 ;

But there is no ANTLR syntax for "optionally match either A or B only once, in no particular order".

3
cschneid On

One way to deal with this situation is to code...

func_arg
    : func_arg_opts* func_type
    ;

func_arg_opts
    : arg_class
    | param_name
    ;

...which scales up for many options in func_arg_opts but introduces the possibility of any one option being specified more than once, which may not be desired. You could code an action in func_arg to check for this situation, but again, that may not be desired.