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

。_饼干妹妹 提交于 2019-12-23 19:58:30

问题


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.


回答1:


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 ())



回答2:


I hit on this which seems to work. But please feel free to critique:

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

notComment = manyTill anyChar (lookAhead (comment <|> eof))

eatComments :: GenParser Char st String
eatComments = do
  optional comment
  xs <- sepBy notComment comment
  optional comment
  return $ intercalate "" xs


来源:https://stackoverflow.com/questions/12940490/how-would-i-strip-out-comments-from-a-file-with-parsec

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!