[英]Ambiguous grammar when parsing boolean expressions with Peg.js
我正在編寫一個從布爾表達式生成抽象語法樹的解析器。
我有以下支持^
和∨
Peg.js語法,分別為&
和|
分別:
start
= operation
// optional whitespace
_ = [ \t\r\n]*
operation "operation"
= "("? _ left:(operand / operation) _ operator:operator _ right:(operand / operation) _ ")"?
{
return {
operation: operator,
between: [ left, right ]
};
}
operator "operator"
= operator:["&"|"|"]
{
return operator;
}
operand "operand"
= operand:[a-z]
{
return { operand: operand };
}
它可以成功解析a & b
和a & (b | c)
之類的表達式,但是如果該表達式以一個運算符開頭,則會失敗:
(a | b) & c
Line 1, column 8: Expected end of input but " " found.
如果使用括號將表達式正確解析,則可以:
((a | b) & c)
我的猜測是Peg.js僅將(a | b)
作為操作,而不是父操作的操作數,因此在看到& c
時失敗。
我想念什么?
您的操作規則說,方括號是可選的,但沒有一個方括號會強制使用另一個方括號。 例如, (a & b
已成功解析。
您需要將其分解成較小的部分。 and
和or
的單獨規則允許運算符優先級發揮作用。
嘗試這個:
start
= sentence
sentence
= orSentence
orSentence
= lhs:andSentence __ '|' __ rhs:orSentence { return { operation: '|', between: [lhs, rhs] }; }
/ andSentence
andSentence
= lhs:primarySentence __ '&' __ rhs:andSentence { return { operation: '&', between: [lhs, rhs] }; }
/ primarySentence
primarySentence
= '(' _ sentence:sentence _ ')' { return sentence; }
/ operand
operand
= operand:[a-z] { return { operand: operand }; }
_ "optionalWhiteSpace"
= whiteSpace *
__ "mandatoryWhiteSpace"
= whiteSpace +
whiteSpace
= [ \t\n\r]+
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.