7

質問はこれに似ていますが、 OperatorPrecedenceParserinを使用して関数適用で式を解析したいと思います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 に答える