问题类似于this one https://stackoverflow.com/questions/7199589/parsing-method-arguments-with-fparsec,但我想使用函数应用程序来解析表达式OperatorPrecedenceParser
in FParsec
.
这是我的 AST:
type Expression =
| Float of float
| Variable of VarIdentifier
| BinaryOperation of Operator * Expression * Expression
| FunctionCall of VarIdentifier (*fun name*) * Expression list (*arguments*)
我有以下输入:
board→create_obstacle(4, 4, 450, 0, fric)
这是解析器代码:
let expr = (number |>> Float) <|> (ident |>> Variable)
let parenexpr = between (str_ws "(") (str_ws ")") expr
let opp = new OperatorPrecedenceParser<_,_,_>()
opp.TermParser <- expr <|> parenexpr
opp.AddOperator(InfixOperator("→", ws,
10, Associativity.Right,
fun left right -> BinaryOperation(Arrow, left, right)))
我的问题是函数参数也是表达式(它们可以包括运算符、变量等),我不知道如何扩展我的expr
解析器将参数列表解析为表达式列表。我在这里构建了一个解析器,但我不知道如何将它与我现有的解析器结合起来:
let primitive = expr <|> parenexpr
let argList = sepBy primitive (str_ws ",")
let fcall = tuple2 ident (between (str_ws "(") (str_ws ")") argList)
我的解析器目前有以下输出:
Success: Expression (BinaryOperation
(Arrow,Variable "board",Variable "create_obstacle"))
我想要的是得到以下内容:
Success: Expression
(BinaryOperation
(Arrow,
Variable "board",
Function (VarIdentifier "create_obstacle",
[Float 4, Float 4, Float 450, Float 0, Variable "fric"]))