[英]Collision in between “END” and “END IF” in BASIC grammar, using Lark
[英]Priority in grammar using Lark
我的語法有一個優先問題,我沒有任何想法來解決它。
我正在使用Lark
這是事情(我盡可能地簡化了問題):
from lark import Lark
parser = Lark(r"""
start: set | set_mul
set_mul: [nb] set
set: [nb] "foo"
nb: INT "x"
%import common.INT
%import common.WS
%ignore WS
""", start='start')
input = "3xfoo"
p = parser.parse(input)
print(p.pretty())
輸出是:
start
set_mul
set
nb 3
但我想要的是:
start
set_mul
nb 3
set
我試圖優先考慮我的規則,但它不起作用。
你知道我需要改變什么來使它工作嗎?
謝謝
一個簡單的解決方案可能是重寫你的語法以消除歧義。
parser = Lark(r"""
start: set | set_mul
set_mul: nb | nb set | nb nb_set
set: "foo"
nb_set: nb set
nb: INT "x"
%import common.INT
%import common.WS
%ignore WS
""", start='start')
這樣,以下每個輸入只有一種可能的解釋:
input = "3xfoo"
p = parser.parse(input)
print(p.pretty())
input = "3x4xfoo"
p = parser.parse(input)
print(p.pretty())
結果:
start
set_mul
nb 3
set
start
set_mul
nb 3
nb_set
nb 4
set
這不是一個完整的答案,但讓你分道揚鋸。 你的問題是你的語法含糊不清,你使用的例子正面臨着這種模糊性。 Lark選擇為你消除歧義,你就得到了結果。 看到。
通過添加ambiguity='explicit'
,讓Lark不要消除歧義:
import lark
parser = lark.Lark(r"""
start: set | set_mul
set_mul: [nb] set
set: [nb] "foo"
nb: INT "x"
%import common.INT
%import common.WS
%ignore WS
""", start='start',ambiguity='explicit')
input = "3xfoo"
p = parser.parse(input)
print(p.pretty())
你得到的輸出包括你想要的輸出:
_ambig
start
set
nb 3
start
set_mul
set
nb 3
start
set_mul
nb 3
set
你怎么能鼓勵Lark消除你喜歡的歧視? 好問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.