使用OperatorPrecedenceParser使用FParsec解析函数应用程序? [英] Parsing function application with FParsec using OperatorPrecedenceParser?

查看:87
本文介绍了使用OperatorPrecedenceParser使用FParsec解析函数应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题类似于这个问题,但我想解析一个表达式使用FParsec中的OperatorPrecedenceParser进行功能应用程序.

The question is similar to this one, but I want to parse an expression with function application using the 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解析器以将参数列表解析为表达式列表.我在这里构建了一个解析器,但是我不知道如何将其与我现有的解析器结合起来:

My problem here is that the function arguments are expressions as well (they can include operators, variables etc) and I don't know how to extend my expr parser to parse the argument list as a list of expression. I built a parser here, but I don't know how to combine it with my existing parser:

let primitive = expr <|> parenexpr
let argList = sepBy primitive (str_ws ",")
let fcall = tuple2 ident (between (str_ws "(") (str_ws ")") argList)

我目前从解析器中得到以下输出:

I currently have the following output from my parser:

Success: Expression (BinaryOperation 
     (Arrow,Variable "board",Variable "create_obstacle"))

我想要得到的是以下内容:

What I want is to get the following:

 Success: Expression 
      (BinaryOperation 
            (Arrow,
                Variable "board",
                Function (VarIdentifier "create_obstacle",
                          [Float 4, Float 4, Float 450, Float 0, Variable "fric"]))

推荐答案

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

You could parse the argument list as an optional postfix expression of an identifier

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

这篇关于使用OperatorPrecedenceParser使用FParsec解析函数应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆