Search code examples
haskellparsec

How would I strip out comments from a file with Parsec?


I have this much:

comment :: GenParser Char st ()
comment =
    (string "--" >> manyTill anyChar newline >> spaces >> return ()) <|>
    (string "/*" >> manyTill anyChar (string "*/") >> spaces >> return ())

eatComments :: GenParser Char st String
eatComments = do
  xs <- many (do
          optional comment
          x <- manyTill anyChar (try comment)
          return x)
  return $ intercalate " " xs

This works if the input ends with a comment, but it fails if it ends with something else. In that case the error message is like

No match (line 13, column 1):
unexpected end of input
expecting "--" or "/*"

So the parser is looking for a comment by the time eof arrives. I need some help finding the right combinators I need to eat up all the comments in all possible cases.


Solution

  • Maybe use something like eof ?

    comment :: GenParser Char st ()
    comment =
        (string "--" >> manyTill anyChar newline >> spaces >> return ()) <|>
        (string "/*" >> manyTill anyChar ((try (string "*/") >> return ()) <|> eof) >> spaces >> return ())