【发布时间】:2021-02-27 10:15:22
【问题描述】:
我想创建一个 raku 语法,可用于解析缩减的 markdown 语法。这种简化的 markdown 语法必须满足以下条件:
- markdown 中的标头必须以“#”开头,后跟一个空格,或者必须用“-”序列(至少 2 个)加下划线。
- 文本不能独立存在。它必须以标题开头。
为了解析这个语法,我创建了以下脚本:
#!/usr/bin/perl6
use v6;
grammar gram {
token TOP {
<text>
}
token text {
[ <section> ]+
}
token section {
<headline> <textline>*
}
token headline {
^^ [<hashheadline> | <underlineheadline>] $$
}
token hashheadline {
<hashprefix> <headlinecontent>
}
token hashprefix {
[\#] <space>
}
token underlineheadline {
<headlinecontent> [\n] <underline>
}
token underline {
[\-]**2..*
}
token headlinecontent {
[\N]+
}
token textline {
^^ (<[\N]-[\#]> (<[\N]-[\ ]> [\N]*)? )? [\n] <!before [\-][\-]>
}
}
my @tests = "", #should not match and doesn't match - OK
"test1", #should not match and doesn't match - OK
"test2\n", #should not match and doesn't match - OK
"test3\nnewline", #should not match and doesn't match - OK
"test4\n----", #should match and does match - OK
"test5\n----\nnewline", #should match but doesn't match - NOK
"#test6\nnewline", #should not match and doesn't match - OK
"# test7\nnewline", #should match but doesn't match - NOK
"# test8", #should match and does match - OK
"test9\n----\nnewline\nanother\nnew line", #should match but doesn't match - NOK
"# test10\nnewline\nhead\n---\nanother", #should match but doesn't match - NOK
;
for @tests -> $test {
say gram.parse($test).perl;
}
但我的语法有问题:正如测试数组的 cmets 中所述,语法有问题,但我不知道是什么。
【问题讨论】:
-
您是否尝试过生成minimal reproducible example?
-
在我看来,这已经是一个最小的工作示例。因为我说我需要解析降价的部分,所以我想保留标题的两种变体。在我的具体示例中,我有一个额外的动作类来帮助处理语法中的内容。在这个问题中,我删除了解析器的其他内容以及这个动作类。因此,它已经减少了很多。唯一不需要的是测试字符串数组。但我想保留它,因为这是我通过测试的绝对要求。
-
"已经减少了很多。"谢谢! “唯一不需要的是测试字符串数组”我认为测试是必要的,如果你把它们排除在外,你的问题会更糟。 “这已经是一个最小的工作示例。”我说的是minimal reproducible example 页面上描述的内容,这意味着您可以从回答者的 POV 中查看它。虽然您可能已尝试仔细遵循该页面的建议,但您的
token textline是识别错误所需的全部内容,这也是解决您问题的任何人都必须将其减少到的内容。我的回答解释了我认为最好的方法。 YMMV。
标签: raku