为什么 __ 不匹配时 pegjs 不匹配表达式?程序 = __/表达式

Why pegjs not match Expression when __ not matched? Program = __/Expression

示例代码:

Program = __/Expression

Expression = .*

__ = [ \t\r\n]*
test is

2 * (3 + 4)
hahah hahhah
def hahah

在我看来,pegjs while match Expression when __ 不匹配? 但这会出错

第 1 行,第 1 列: 应为 [ \t\r\n] 或输入结尾,但已找到 "2"。 预期行为:

我想知道为什么它不起作用。 我想知道是否有可能让 js 中的所有函数调用者都使用 pegjs?

实际行为: 解析错误:第 1 行,第 1 列:预期 [ \t\r\n] 或输入结束但找到 "2"

这是因为您规则 __ 始终匹配,因为它匹配空输入。你可以认为,你的语法在内部重写如下(这是完全有效的语法,你可以在 pegjs 在线输入它):

start = Program EOF

Program = __/Expression

Expression = .*

__ = [ \t\r\n]*
// EOF is ephemeral rule that match end of input, i.e. when nothing left in input
EOF = !.

因此您的输入解析为:

<'__' matched>
<'Program' matched>
<'EOF' not matched
  =>backtrack to 'start'
  =>nothing alternatives on 'start'
  =>error
>2 * (3 + 4)