parsec icon indicating copy to clipboard operation
parsec copied to clipboard

"unexpected end of input, expecting end of input"

Open samuela opened this issue 4 years ago • 4 comments

Weird error message coming from parsec...

#!/usr/bin/env stack
-- stack runghc --package parsec

import Data.Map (fromList)
import Text.Parsec

sepBy1Try p sep = do
  x <- p
  xs <- many (try $ sep *> p)
  return (x : xs)

key =
  try (string "byr")
    <|> try (string "cid")
    <|> try (string "eyr")
    <|> try (string "ecl")
    <|> try (string "hgt")
    <|> try (string "hcl")
    <|> try (string "iyr")
    <|> try (string "pid")

passportKV = try $ do
  k <- key
  char ':'
  v <- many1 (try alphaNum <|> try (char '#'))
  return (k, v)

passportLine = sepBy1Try passportKV space

passport = do
  lines <- sepBy1Try passportLine endOfLine
  return $ fromList [kv | line <- lines, kv <- line]

passports = sepBy1 passport (endOfLine *> ((try endOfLine *> pure ()) <|> eof))

main = do
  raw <- readFile "input.txt"
  print $ parse passports "(poop)" raw

and here's the input file: input.txt

Here's what I get:

❯ ./day4.hs
Left "(poop)" (line 1134, column 1):
unexpected end of input
expecting new-line, end of input, "byr", "cid", "eyr", "ecl", "hgt", "hcl", "iyr" or "pid"

which seems... highly counter-intuitive!

samuela avatar Dec 23 '20 06:12 samuela

Here's another way to trigger this:

passports = sepBy1 passport (try (endOfLine *> endOfLine *> pure ()) <|> (endOfLine *> eof *> pure ()))

which gets rid of the new-line option:

❯ ./day4.hs
Left "(poop)" (line 1134, column 1):
unexpected end of input
expecting end of input, "byr", "cid", "eyr", "ecl", "hgt", "hcl", "iyr" or "pid"

samuela avatar Dec 23 '20 06:12 samuela

Read http://blog.ezyang.com/2014/05/parsec-try-a-or-b-considered-harmful/

By trying too much you make parsecs life harder.

phadej avatar Jan 04 '22 11:01 phadej

In particular, removing try from sepBy1Try seems to fix the problem and not break the parser.

phadej avatar Jan 04 '22 12:01 phadej

That's fair, but it feels like this error message falls into the category of things that "should never happen".

samuela avatar Jan 05 '22 07:01 samuela