7

这个问题与这个问题类似,但我想使用 in 解析一个带有函数应用程序的OperatorPrecedenceParser表达式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"]))
4

1 回答 1

6

您可以将参数列表解析为标识符的可选后缀表达式

let argListInParens = between (str_ws "(") (str_ws ")") argList
let identWithOptArgs = 
    pipe2 ident (opt argListInParens) 
          (fun id optArgs -> match optArgs with
                             | Some args -> FunctionCall(id, args)
                             | None -> Variable(id))

然后定义expr

let expr = (number |>> Float) <|> identWithOptArgs
于 2012-02-08T18:19:01.103 回答