Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

haskell

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.

like image 666
dan Avatar asked Dec 04 '25 19:12

dan


1 Answers

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 ())
like image 110
Marius Danila Avatar answered Dec 08 '25 00:12

Marius Danila