エンジニアのソフトウェア的愛情

または私は如何にして心配するのを止めてプログラムを・愛する・ようになったか

C/C++スタイルのコメントの除去 by Haskell

以前C++で書いたものHaskellのParsecで。
まだテストしてないので間違えてるかもしれない。

(2010/02/03追記:やっぱり間違えてた。quoteStringエスケープしたダブルコーテーションをきちんと処理できない。修正版は後日)

import Text.ParserCombinators.Parsec

quoteString = do
  char '\"'
  s <- many ( noneOf "\"" <|> char '\\' <|> do { char '\\'; char '\"' } )
  char '\"'
  return $ "\"" ++ s ++ "\""

cStyleComment = do
  string "/*"
  manyTill anyChar (try (string "*/"))
  return " "

cxxStyleComment = do
  string "//"
  manyTill anyChar (try newline)
  return "\n"

removeComment = many (try quoteString <|> try cStyleComment <|> try cxxStyleComment <|> do { c <- noneOf "\""; return [c] } )

main = do
  contents <- getContents
  case (parse removeComment "" contents) of
    Right result -> putStrLn $ concat result
    Left  err    -> print err