Search code examples
haskelltext-parsingparsecmegaparsec

Getting current context error formatting function


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.


Solution

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