如何从Parsec中删除文件中的注释?

时间:2012-10-17 18:02:17

标签: haskell parsec

我有这么多:

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

如果输入以注释结束,则此方法有效,但如果以其他方式结束,则会失败。在这种情况下,错误消息就像

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

因此解析器在eof到达时查找评论。我需要一些帮助来找到合适的组合器,我需要在所有可能的情况下吃掉所有评论。

2 个答案:

答案 0 :(得分:3)

也许使用类似eof的内容?

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

答案 1 :(得分:0)

我点击这个似乎有效。但请随意批评:

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