Applying the Parsing Function Using FParsec Using OperatorPrecedenceParser?

The question is similar to this , but I want to FParsec expression using the application application using OperatorPrecedenceParser in FParsec .

Here is my AST:

 type Expression = | Float of float | Variable of VarIdentifier | BinaryOperation of Operator * Expression * Expression | FunctionCall of VarIdentifier (*fun name*) * Expression list (*arguments*) 

I have the following input:

 boardโ†’create_obstacle(4, 4, 450, 0, fric) 

And here is the parser code:

 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))) 

My problem is that function arguments are also expressions (they can include operators, variables, etc.), and I don't know how to extend the expr parser to parse the list of arguments as a list of expressions. I created a parser here, but I donโ€™t know how to combine it with an existing parser:

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

Currently, I have the following output from my parsing:

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

I want to get the following:

  Success: Expression (BinaryOperation (Arrow, Variable "board", Function (VarIdentifier "create_obstacle", [Float 4, Float 4, Float 450, Float 0, Variable "fric"])) 
+6
source share
1 answer

You can parse the argument list as an optional postfix identifier expression

 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)) 

and then define expr as

 let expr = (number |>> Float) <|> identWithOptArgs 
+6
source

Source: https://habr.com/ru/post/907965/


All Articles