[Haskell-cafe] Poor Parsec error message

Lyle Kopnicky lists at qseep.net
Thu Jul 10 03:39:21 EDT 2008


Hi folks,

I'm using Parsec to parse a stream of tokens. The token primitive takes, 
among other arguments, a function to print tokens. However, this 
function is not always applied. Try the code below:

---------
import Text.ParserCombinators.Parsec
import Text.ParserCombinators.Parsec.Pos(newPos)

mytoken :: (Eq t, Show t) => t -> GenParser (SourcePos,t) () t
mytoken x = token showTok posFromTok testTok where
   showTok (pos,t) = "<" ++ show t ++ ">"
   posFromTok (pos,t) = pos
   testTok (pos,t) = if (x == t) then Just t else Nothing

main = do
   putStrLn ""
   case parse the123Parser "" [(newPos "" 1 n, n) | n <- [1,2,3,4]] of
       (Left err) -> putStrLn (show err)
       (Right _) -> putStrLn "parsed correctly"
   putStrLn ""
   case parse the123Parser "" [(newPos "" 1 n, n) | n <- [1,3,4]] of
       (Left err) -> putStrLn (show err)
       (Right _) -> putStrLn "parsed correctly"

the123Parser = do
   mytoken 1
   mytoken 2
   mytoken 3
   eof
   return 123
-------

The output I get looks like this:

(line 1, column 4):
unexpected [((line 1, column 4),4)]
expecting end of input

(line 1, column 3):
unexpected <3>

In the second parse case, it correctly uses my showTok function to show 
the token. But in the first case, it just uses the regular show method. 
I guess that's because the eof parser doesn't know anything about how to 
show the token it sees. Any ideas on how I can get the error message in 
the first case to look more like the second case?

Thanks,
Lyle


More information about the Haskell-Cafe mailing list