我想用PEG Parser解析输入字符串并输出格式化的字符串。
类似于 2x 是 2 * x , 我想添加能够编写“ someString” 的功能,该功能默认情况下会调用我的javascript函数 newOperator(newVariable(“ name”),“ =”,“ newText(someString))
示例:
Tech & region = europe
// should mean
name=tech & region=europe
// and call
newOperator(newOperator(newVariable("name"),"=",newText("Tech")),
"&",
newOperator(newVariable("region"),"=",newText("europe")))
我目前的PEG语法:
表达式:
TopExpression
= head:ExpressionIV tail:(_ ("&" / "|") _ ExpressionIV)* {
tail = tail.myClean();
return tail.trippleReduce(newOperator,head);
}
ExpressionIII
= head:ExpressionIII tail:(_ ("=" / ">" / "<") _ ExpressionIII)* {
tail = tail.myClean();
return tail.trippleReduce(newOperator,head);
}
ExpressionII
= head:ExpressionII tail:(_ ("+" / "-") _ ExpressionII)* {a
tail = tail.myClean();
return tail.trippleReduce(newOperator,head);
}
ExpressionI
= head:Atom tail:(_ ("*" / "/") _ Atom)* {
tail = tail.myClean();
return tail.trippleReduce(newOperator,head);
}
原子:
Atom
= "(" _ e:TopExpression _ ")" {return e;}
/ variableAtom
/ numericAtom
/ textAtom
variableAtom
= v:("name" / "isin" / "region" / "rendite24") {return newVariable(v)};
numericAtom
= n:number {return newNumeric(n);}
textAtom
= t:$[a-zA-Z]+ {return newText(t);}
基本知识:
word = $[a-zA-Z]+
number = $[0-9]+
_ "whitespace" = [ \t\n\r]* {return;}
我认为以下是我的解决方案,但是它停止了解析器使用除&和 | 之外的运算符解析任何输入。为什么会这样,什么是正确的解决方案?
ExpressionIII
= t:textAtom {return newOperator(newVariable("name"),"=",t);}
/ head:ExpressionIII tail:(_ ("=" / ">" / "<") _ ExpressionIII)* {
tail = tail.myClean();
return tail.trippleReduce(newOperator,head);
}