我的同事 PaulS 问了我以下问题:
我正在为现有语言(SystemVerilog - IEEE 标准)编写一个解析器,并且该规范中有一条结构与此类似的规则:
cover_point
=
[[data_type] identifier ':' ] 'coverpoint' identifier ';'
;
data_type
=
'int' | 'float' | identifier
;
identifier
=
?/\w+/?
;
问题是在解析以下合法字符串时:
anIdentifier: coverpoint another_identifier;
anIdentifier
与 匹配data_type
(通过其标识符选项)成功,这意味着 Grako 正在寻找其后的另一个标识符,然后失败。然后它不会尝试在没有 data_type 部分的情况下进行解析。
我可以将规则重写如下,
cover_point_rewrite
=
[data_type identifier ':' | identifier ':' ] 'coverpoint' identifier ';'
;
但我想知道是否:
- 这是故意的并且
- 是否有更好的语法?
这是一般 PEG 问题还是工具(Grako)问题?
It says here在 PEG 中,选择运算符是ordered通过使用第一个匹配来避免 CFG 歧义。
在你的第一个例子中
[data_type]
succeeds parsing id, so it fails when it finds
:
instead of another identifier.
That may be because
[data_type]
behaves like
(data_type | ε)
so it will always parse
data_type
with the first id.
In
[data_type identifier ':' | identifier ':' ]
the first choice fails when there is no second id, so the parser backtracks and tries with the second choice.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)