[英]define statement only works if followed by an assignment in Lark grammar
I am creating a parser with Lark.我正在用 Lark 创建一个解析器。 The parser works fine for most of the tests I ran, but failed with the define keyword.对于我运行的大多数测试,解析器工作正常,但因 define 关键字而失败。 It only works if it is followed by an assignement.只有在它后面有一个赋值时它才有效。 define a = 10
works just fine, but define b
is not treated as a define statement. define a = 10
工作正常,但define b
不被视为 define 语句。
Here is the Lark parser:这是 Lark 解析器:
import lark
# ...
parser = lark.Lark("""
?start: statements
?statements: ((expr (";" | NEWLINE) | NEWLINE ) )* expr?
?expr: identifier | number | functioncall | define | assignment | function
?functioncall: identifier "(" arguments? ")"
?arguments: expr ("," expr)*
?define: "define" identifier ("=" expr)?
?assignment: identifier "=" expr
?function: "function" "(" parameters? ")" "->" identifier block
?parameters: identifier ("," identifier)*
?block: "{" statements "}"
?identifier: NAME -> identifier
?number: NUMBER -> number
%import common.NEWLINE
%import common.CNAME -> NAME
%import common.NUMBER
%import common.WS_INLINE
%ignore WS_INLINE
COMMENT: "/*" /(.|\n)+/x "*/" | "//" /.+/ NEWLINE?
%ignore COMMENT
""")
My tests:我的测试:
tree = parser.parse("define a = 10")
assert(tree.data == "define") # OK
tree = parser.parse("define b")
assert(tree.data == "define") # NOT OK - tree.data is "identifier"
Specifically, parser.parse("define b")
and parser.parse("b")
give the exact same result.具体来说, parser.parse("define b")
和parser.parse("b")
给出完全相同的结果。 I would expect parser.parse("define b")
to give a tree beginning with the define
rule, but instead I have an identifier
.我希望parser.parse("define b")
给出一个以define
规则开头的树,但我有一个identifier
。
Sometime Lark parser doesn't clearly identifies a rule, for instance, define b
and b
gives Tree(identifier, [Token(NAME, 'b')])
.有时 Lark 解析器没有明确识别规则,例如, define b
和b
给出Tree(identifier, [Token(NAME, 'b')])
。 To be able to distinguish the two, you need to force Lark to add a name to the rule, this can be done by adding -> name_of_rule
at the end of a line in the parser definition.为了能够区分两者,您需要强制 Lark 为规则添加名称,这可以通过在解析器定义的一行末尾添加-> name_of_rule
来完成。 So for instance, the definition of the ?define
rule should become:因此,例如, ?define
规则的定义应该变成:
?define: "define" identifier ( "=" expr )? -> define
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.