我回到探索pegjs,显然还没有掌握核心概念。我试图解析查询语言"以谓词开头,然后是操作数列表(可能包含另一个谓词)。所以一个简单的例子就是:
OR(
"string1"
"string2"
)
我希望将上述内容转化为:
{
predicate: "OR",
operands: [
{
type: "STRING",
value: "string1"
},
{
type: "STRING",
value: "string2"
}
]
}
此查询:
OR(
"string1"
"string2"
AND (
"string4"
"string5"
)
"string3"
)
将成为这个AST:
{
predicate: "OR",
operands: [
{
type: "STRING",
value: "string1"
},
{
type: "STRING",
value: "string2"
},
{
predicate: "AND"
operands: [
{
type: "STRING",
value: "string4"
},
{
type: "STRING",
value: "string5"
}
]
},
{
type: "STRING",
value: "string3"
}
]
}
我的语法很接近,但有几个问题。这是目前的PEGJS语法。它可以直接粘贴到在线pegjs解析器(http://pegjs.majda.cz/online)。
start =
or_predicate
or_predicate
= ws* "OR" ws* "(" ws* operands:or_predicate ws* ")" ws*
{ if(Array.isArray(operands)) {
return {predicate: "OR", operands: operands}
} else {
return {predicate: "OR", operands: [operands] }
}
}
/ and_predicate
and_predicate
= ws* "AND" ws* "(" operands:and_predicate ")"
{ if(Array.isArray(operands)) {
return {predicate: "AND", operands: operands}
} else {
return {predicate: "AND", operands: [operands] }
}
}
/ operands
operands
= ws* values:operand+ { return values; }
operand =
string
/ ws or_predicate:or_predicate { return or_predicate; }
string =
ws* "\"" value:valid_variable_characters "\""
{ return { type: "STRING", value: value.join("")}}
// List of valid characters for string variables
valid_variable_characters =
[a-zA-Z0-9 _]+
ws =
[ \t\n]
上面的语法处理了我给出的两个例子,但我发现了两个问题,这引出了以下三个问题。
1.语法在这个看似简单的输入上失败(关键是嵌套的OR紧跟在父OR之后,"字符串"在最后):
OR(
OR (
"string1"
)
"string2"
)
我不确定导致此问题的原因或解决方法。
2.语法目前对operand
规则有这个愚蠢的行:
operand =
string
/ ws or_predicate:or_predicate { return or_predicate; }
注意or_predicate
之前第三行的前导空格(ws)。如果没有那个空格,我会收到错误'超出最大调用堆栈大小'。我认为这与左递归有关,但对此没有积极意义。理想情况下,我希望能够没有必要的' ws'那么没有像这样的空格的查询就可以了:
OR("string1"OR("string2")"string3")
现在你必须人为地添加一些像这样的额外空格:
OR("string1" OR("string2") "string3")
3.我完全错误地接近这个语法?这只是我尝试的第二个,第一个基于pegjs算术示例,所以我意识到我可能会完全错误,这可能就是我遇到这些问题的原因。
感谢您的帮助和时间!
最诚挚的问候,
版
答案 0 :(得分:4)
我对PEG也很陌生,但在主要关注examples而不是阅读文档之后,你就掌握了它。
尝试将您的版本与此版本进行比较:
start
= ws* predicate:predicate ws* { return predicate; }
predicate
= "OR" ws* "(" operands:operand+ ")" { return { predicate: 'OR', operands: operands }; }
/ "AND" ws* "(" operands:operand+ ")" { return { predicate: 'AND', operands: operands }; }
operand
= ws* predicate:predicate ws* { return predicate; }
/ ws* string:string ws* { return string; }
string
= "\"" chars:valid_variable_characters+ "\"" { return { type: "STRING", value: chars.join("")}}
valid_variable_characters = [a-zA-Z0-9 _]
ws = [ \t\n]
空白是可选的。
OR("str1"OR("str2""str3"AND("str4""str5"))"str6")
给出:
{
"predicate": "OR",
"operands": [
{
"type": "STRING",
"value": "str1"
},
{
"predicate": "OR",
"operands": [
{
"type": "STRING",
"value": "str2"
},
{
"type": "STRING",
"value": "str3"
},
{
"predicate": "AND",
"operands": [
{
"type": "STRING",
"value": "str4"
},
{
"type": "STRING",
"value": "str5"
}
]
}
]
},
{
"type": "STRING",
"value": "str6"
}
]
}