Why do I get an “unexpected end to input” when my parser explicitly searches for it?

import Control.Applicative hiding (many)
import Text.Parsec
import Text.Parsec.String

lexeme :: Parser a -> Parser a
lexeme p = many (oneOf " \n\r") *> p

identifier :: Parser String
identifier = lexeme $ many1 $ oneOf (['a'..'z'] ++ ['A'..'Z'])

operator :: String -> Parser String
operator = lexeme . string

field :: Parser (String, String)
field = (,) <$> identifier <* operator ":" <*> identifier <* operator ";"

fields :: Parser [(String, String)]
fields = many (try field) <* eof

testInput :: String
testInput = unlines
    [ "    FCheckErrors         : Boolean            ;"
    , "    FAcl                 : TStrings           ;"
    ]

main :: IO ()
main = parseTest fields testInput

At startup, this gives:

parse error in (row 3, column 1): unexpected end of input

When I remove the explicit eof mapping, there is no such parsing error:

fields = many (try field)

I also tried try field `manyTill` eof, but this will lead to the same behavior as the source code.

I want to make sure that the parser consumes all the input, how can I do this?

+4
source share
1 answer

The problem is that before eof(inserted unlines), there is a new line.

So, eofshould be done through lexeme.

fields = many (try field) <* lexeme eof

Otherwise, Parsec tries to start the parser fieldsin a new line.

+6
source

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


All Articles