Search code examples
antlr4grammar

antlr4 grammar how to specify parameters in any order


Suppose I wish to implement a call to a function that can take a number of different parameters:

graph(style=line, theme=dark, x=time, y=height)

In this example there are 4 parameters, identified by variable name (style, theme, x,y) If I wish to write an antlr4 grammar to accept this I could write:

graphcall: 'graph' '(' (style_spec | theme_spec | x | y) + ')' ;

which would accept the parameters in any order. However, it would also allow specifying them multiple times. Is there any easy way to specify that one can only use each one once in the grammar, as opposed to marking them as used and refusing to repeat?

Furthermore, suppose I have two kinds of graphs. A line graph is a 2d graph requiring x,y, and a surface graph is 3d requiring x,y,z, and a gapminder graph supports x,y,color and size.

The only way I can think of to do these is extremely repetitive, basically a huge OR combining each rule specified. Is there any way to state that all graphs require x and y, while a surface graph requires z, and a gapminder graph requires size and color? All while allowing the specification in any order?


Solution

  • No syntax exists for ANTLR4 that allows to specify only one occurrence of a number of alternatives. This constraint is not a syntactic one, but semantical. Such parts of the parse process should be handled in a second phase (often called the semantic phase, in contrast to the syntactic phase where the structure of input is determined).

    In that semantic phase you can easily check that each parameter is specified only once by using a tree walker and create a parse error, if not.