我正在用golang开发一个玩具解析器,只是为了学习这门语言。我添加了一个测试用例,其语法涵盖以下情况:
Valid:
a, ab, aba, ababababababa, ababababab
b, ba, bab, babababababab, bababababa
Invalid:
abb, baa
a总是跟在后面,b反之亦然。
现在我的解析器中的语法看起来像这样(为简洁起见,我省略了周围的代码):
"expr": Or(Ref("A"), Ref("B")),
"A": And(
a,
Optional(
And(
b,
Optional(Ref("A"))))),
"B": And(
b,
Optional(Ref("A")))
在哪里
a - exact match for "a" character
b - exact match for "b" character
"A", "B", "expr" - names of the parts of the grammar that can be referred
later with Ref("A")
And - consume sequence of expressions
Or - consume any of the expressions
Ref - refer to other expression (allows recursion)
Optional - make the expression non-obligatory
我想这不是描述这种语法的最简洁的方式。如何让它更紧凑?
当年话下
相关分类