当您使用语法调试器时,它可以让您准确地看到引擎是如何解析字符串的——失败是正常的,也是意料之中的。例如,考虑将a+b* 与字符串aab 匹配。您应该得到两个匹配 'a',然后是失败(因为 b 不是 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 与隐式 /^…$/ 匹配)。
另外,您可以考虑使用自动插入 <.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> 将始终以这种方式定义。