3

我有这么多:

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到达时的注释。我需要一些帮助来找到正确的组合器,我需要在所有可能的情况下吃掉所有的评论。

4

2 回答 2

3

也许使用类似eof的东西?

comment :: GenParser Char st ()
comment =
    (string "--" >> manyTill anyChar newline >> spaces >> return ()) <|>
    (string "/*" >> manyTill anyChar ((try (string "*/") >> return ()) <|> eof) >> spaces >> return ())
于 2012-10-17T18:21:48.010 回答
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
于 2012-10-17T19:09:09.623 回答