3

I have the need to generate errors while parsing operators using FParsec's OperatorPrecedenceParsers, specifically during the mapping phase. Suppose I have the following code:

let pOperatorExpr : ExpressionParser =
    let opp = new OperatorPrecedenceParser<MyType, unit, unit>()
    let arithmeticOperator a b ->
        if someOperation a b then
            // Fatal error! Abort!
        else foobar a b

    opp.AddOperator(InfixOperator("+", spaces, 1, Associativity.Left, arithmeticOperator)
    opp.ExpressionParser

What should I do to generate an error in that particular position?

1 Answers1

2

There is no direct support for triggering an error in the mapping function of the operator.

In the "More uses of the after‐string‐parser" section of the OPP reference you can find an example for how to get hold of the precise text location of the binary operator. You could also have your term parser include the text position in its result value. Once you have the locations, you could construct an "error node" in your AST and then manually generate an error later.

Stephan Tolksdorf
  • 3,062
  • 21
  • 28
  • The problem with this strategy is that it does not integrate well into my existing architecture: my plan is to _not_ build an AST if an error is detected at parse-time, but the error can only be detected after _both_ of the operator sides are parsed, and then checked, and therein lies the rub: I can not generate an error in the mapping phase... – Francesco Bertolaccini Aug 29 '17 at 10:30
  • 1
    What exactly do you want to happen when an error is detected? If you want to cancel all parsing, you could just use an exception. If you want to allow backtracking, you could build an error AST node and then make your expression parser check for such an error node and generate a suitable FParsec error if necessary (so that no error node can end up in the final AST). – Stephan Tolksdorf Aug 29 '17 at 13:31
  • My original idea was to just "reply" a fatal error, in which case the parser, once run, would have returned a failure. Using the tactic you suggest, I could indeed build an ad-hoc data structure which either contains a valid node or an error. Seems reasonable: I will try it as soon as I can – Francesco Bertolaccini Aug 29 '17 at 13:36