Parsec-Haskell formatting parsing errors

I am developing a simple calculator that takes a single line of input, parse it using parsec and then process it.

I want parsec-parse-error messages to be smaller. These include location information that is not needed to enter a single line. I tried using <?>, but it doesn’t quite do what I want.

An attempt to extract the cause of the parsing error did not yield good results.

Some way to indicate errors for inconsistent parentheses or just a message syntax errorwould be nice.

+4
source share
1 answer

You may receive an error message and an initial position error using the functions errorMessages, messageString, errorPosand sourceColumnof Text.Parsec.Error.

Here is an example taken from this blog post . It demonstrates the use <?>and use of the above functions to customize error handling:

import Text.ParserCombinators.Parsec
import Text.ParserCombinators.Parsec.Expr
import Text.Parsec.Error

expr :: Parser Integer
expr = buildExpressionParser table factor <?> "expression"

table :: [[ Operator Char st Integer ]]
table = [
    [ op "*" (*) AssocLeft, op "/" div AssocLeft ],
    [ op "+" (+) AssocLeft, op "-" (-) AssocLeft ]
    ]
  where
    op s f assoc = Infix (do { string s ; return f }) assoc

factor = do { char '(' ; x <- expr ; char ')' ; return x }
   <|> number
   <?> "simple expression"

number :: Parser Integer
number = do { ds <- many1 digit; return (read ds) } <?> "number"

doit str =
  case parse expr "blah" str of
    Left e -> do let msgs = filter (not.null) $ map messageString (errorMessages e)
                 let col = sourceColumn (errorPos e)
                 putStrLn $ "error at column " ++ show col ++ ": " ++ show msgs
    Right x -> putStrLn $ "ok - got: " ++ show x

main = do
  doit "3+5"
  doit "5-"
  doit "("
+2
source

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


All Articles