Search code examples
parsinghaskellhappy

Show custom errors while parsing Happy Haskell


I'm writing a monadic parser using Alex and Happy in Haskell.

My error function is defined like this:

parseError :: Token -> Alex a
parseError _ = alexError "error occurred"

How can I send custom errors (like incorrect type while trying to add a string to a number) during parsing?


UPDATE

The parser doesn't need to do the type checking, I'm doing it inside the production since I keep track of the operands type. As said in a comment, I cannot use the parseError, so is there a way to print an error and stop the parser?


Solution

  • I've solved it by implementing this function:

    fatalError :: (Show a1, Show a) => [Char] -> a -> a1 -> t
    fatalError s l c = error ("Error at line " ++ (show l) ++ " column " ++ (show c) ++ ": " ++ s)
    

    and I call it from the production when an error is detected