parsing - 在 EOS(字符串结束)处停止 Raku 语法
问题描述
在将一种音乐语言翻译成另一种音乐语言(ABC 到 Alda)作为学习 Raku DSL 能力的借口的过程中,我注意到似乎没有办法终止.parse
! 这是我缩短的演示代码:
#!/home/hsmyers/rakudo741/bin/perl6
use v6d;
# use Grammar::Debugger;
use Grammar::Tracer;
my $test-n01 = q:to/EOS/;
a b c d e f g
A B C D E F G
EOS
grammar test {
token TOP { <score>+ }
token score {
<.ws>?
[
| <uc>
| <lc>
]+
<.ws>?
}
token uc { <[A..G]> }
token lc { <[a..g]> }
}
test.parse($test-n01).say;
这是 Grammer::Tracer 显示的最后一部分,它展示了我的问题。
| score
| | uc
| | * MATCH "G"
| * MATCH "G\n"
| score
| * FAIL
* MATCH "a b c d e f g\nA B C D E F G\n"
「a b c d e f g
A B C D E F G
」
在倒数第二行,FAIL 这个词告诉我 .parse 运行无法退出。我想知道这是否正确?.say 显示所有内容,所以我不清楚 FAIL 有多真实?问题仍然存在,“我如何正确编写解析多行而没有错误的语法?”
解决方案
当你使用语法调试器时,它可以让你准确地看到引擎是如何解析字符串的——失败是正常的,也是意料之中的。例如,考虑a+b*
与字符串匹配aab
。您应该为 'a' 获得两个匹配项,然后是一个失败(因为b
is not a
),但随后它将重试b
并成功匹配。
如果您与||
(强制执行顺序)进行交替,这可能会更容易看到。如果你有
token TOP { I have a <fruit> }
token fruit { apple || orange || kiwi }
然后你解析句子“I have a kiwi”,你会看到它首先匹配“I have a”,然后是两个失败的“apple”和“orange”,最后一个匹配“kiwi”。
现在让我们看看你的情况:
TOP # Trying to match top (need >1 match of score)
| score # Trying to match score (need >1 match of lc/uc)
| | lc # Trying to match lc
| | * MATCH "a" # lc had a successful match! ("a")
| * MATCH "a " # and as a result so did score! ("a ")
| score # Trying to match score again (because <score>+)
| | lc # Trying to match lc
| | * MATCH "b" # lc had a successful match! ("b")
| * MATCH "b " # and as a result so did score! ("b ")
…………… # …so forth and so on until…
| score # Trying to match score again (because <score>+)
| | uc # Trying to match uc
| | * MATCH "G" # uc had a successful match! ("G")
| * MATCH "G\n" # and as a result, so did score! ("G\n")
| score # Trying to match *score* again (because <score>+)
| * FAIL # failed to match score, because no lc/uc.
|
| # <-------------- At this point, the question is, did TOP match?
| # Remember, TOP is <score>+, so we match TOP if there
| # was at least one <score> token that matched, there was so...
|
* MATCH "a b c d e f g\nA B C D E F G\n" # this is the TOP match
这里的失败是正常的:在某些时候我们会用完<score>
令牌,所以失败是不可避免的。发生这种情况时,语法引擎可以继续处理语法中的任何内容<score>+
。由于没有任何内容,因此失败实际上会导致整个字符串的匹配(因为TOP
与 implicit 匹配/^…$/
)。
此外,您可能会考虑使用自动插入 <.ws>* 的规则重写您的语法(除非它只是一个空格很重要):
grammar test {
rule TOP { <score>+ }
token score {
[
| <uc>
| <lc>
]+
}
token uc { <[A..G]> }
token lc { <[a..g]> }
}
此外,在 IME 中,您可能还想为 uc/lc 添加一个 proto 令牌,因为当您拥有它们时[ <foo> | <bar> ]
,其中一个总是未定义的,这会使在动作类中处理它们有点烦人。你可以试试:
grammar test {
rule TOP { <score> + }
token score { <letter> + }
proto token letter { * }
token letter:uc { <[A..G]> }
token letter:lc { <[a..g]> }
}
$<letter>
将始终以这种方式定义。
推荐阅读
- javascript - JS:使用下拉绑定切换到功能
- r - 使用混合十进制和分组数字整理财务数据
- javascript - 如何将动态数据从 json 文件部署到 html 表中?
- ios - 使用 match 创建的代码签名证书不会显示在 XCode 10.3 中
- c++ - 如何使用 CTRL+C 停止从用户那里获取输入?
- function - 如何在颤振中将函数注入其他类
- php - 货运现场的功能表格?
- python - 从 Pandas 列中分解 dict
- amazon-cognito - Cognito:了解 LimitExceededException
- angular - 本地存储中的 Angular 缓存 http