antlr4语法如何以任意顺序指定参数

huangapple go评论55阅读模式
英文:

antlr4 grammar how to specify parameters in any order

问题

假设我想要实现一个调用函数的功能,该函数可以接受多种不同的参数:

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

在这个例子中,有4个参数,通过变量名(style、theme、x、y)进行标识。
如果我想编写一个antlr4语法来接受这个输入,我可以这样写:

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

这将接受任何顺序的参数。但是,这也允许多次指定它们。有没有一种简单的方法来指定语法中只能使用每个参数一次,而不是标记它们为已使用并拒绝重复使用?

此外,假设我有两种类型的图表。线图是一个2D图表,需要x和y,而曲面图是3D图表,需要x、y和z,而Gapminder图表支持x、y、color和size。

我唯一想到的方法是非常重复的,基本上是一个巨大的OR操作,将每个规则组合在一起。有没有一种方法可以说明所有图表都需要x和y,而曲面图需要z,而Gapminder图表需要size和color?同时允许以任何顺序进行指定?

英文:

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?

答案1

得分: 1

ANTLR4中不存在允许仅指定一次多个替代项的语法。这个限制不是句法上的,而是语义上的。解析过程中的这些部分应在第二阶段进行处理(通常称为语义阶段,与确定输入结构的句法阶段相对应)。

在这个语义阶段,您可以通过使用树遍历器轻松检查每个参数是否仅指定了一次,并在未指定时创建解析错误。

英文:

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.

huangapple
  • 本文由 发表于 2023年7月7日 06:02:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/76632775.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定