1

I am using Megaparsec to get tree representation of the code, which is later evaluated by separated functions. I would like to add to the nodes of the tree representation the parsec function with the current context to format the error.

Why? Eg. the syntax might be okey, but some variable from the code might not exist which will be found out only by later separeted functions processing the tree. The functions will have to throw error, that variable don't exist and I would be glad, if I could use Megaparsec nicely formatted errors for this (with line number, context,...).

Is there some way how to do this please?

Thanks.

Přemysl Šťastný
  • 1,676
  • 2
  • 18
  • 39

1 Answers1

1

I believe you can get the current position via getSourcePos. For example, in the open-recursion style of tree generation, you might write

data Annotated f = Annotated
    { start :: SourcePos
    , term :: f (Annotated f)
    , end :: SourcePos
    }

annotated :: (MonadParser e s m, TraversableStream s) =>
    m (f (Annotated f)) -> m (Annotated f)
annotated p = liftA3 Annotated getSourcePos p getSourcePos

(N.B. I haven't tried it or even type-checked it; only done my best to interpret megaparsec's documentation with an expert eye. Caveat lector.)

Daniel Wagner
  • 145,880
  • 9
  • 220
  • 380
  • Thanks. I know about this method, but I am still missing the method to get from source position ParseError, which can be easily processed by parseErrorPretty – Přemysl Šťastný Feb 15 '22 at 20:12
  • My read of the [source of `parseErrorPretty`](https://hackage.haskell.org/package/megaparsec-9.2.0/docs/src/Text.Megaparsec.Error.html#parseErrorPretty) suggests it doesn't format this kind of error with line number or context as requested in the question, only index into the stream and, in case of some errors, alternative inputs it would know how to handle. But if that's what you want, then... what's stopping you from creating a `ParseError`? All the relevant constructors seem to be exposed. – Daniel Wagner Feb 15 '22 at 20:20
  • Yes. You are right. It is a possible solution to the problem. - When I wrote this question, I hoped, there is some easy way, how to get String -> String function from the monad to generate error message, which I am missing. – Přemysl Šťastný Feb 15 '22 at 20:27