4

我正在编写一个程序来修改源代码文件。我需要解析文件(例如使用 megaparsec),修改其抽象语法树 AST(例如使用 Uniplate),并尽可能少地重新生成文件(例如保留空格、注释等)。

因此,AST 应该包含空格,例如:

data Identifier = Identifier String String

其中第一个字符串是标识符的名称,第二个是它后面的空格。这同样适用于语言中的任何符号。

如何为 Identifier 编写解析器?

4

1 回答 1

2

我最终编写了 parseLexeme,以替换本教程中的词素

data Lexeme a = Lexeme a String -- String contains the spaces after the lexeme

whites :: Parser String
whites = many spaceChar

parseLexeme :: Parser a -> Parser (Lexeme a)
parseLexeme p = do
  value <- p
  w <- whites
  return $ Lexeme value w

instance PPrint a => PPrint (Lexeme a) where
  pprint (Lexeme value w) = (pprint value) ++ w

标识符的解析器变为:

data Identifier = Identifier (Lexeme String)

parseIdentifier :: Parser Identifier
parseIdentifier = do
  v <- parseLexeme $ (:) <$> letterChar <*> many (alphaNumChar <|> char '_')
  return $ Identifier v

instance PPrint Identifier where
  pprint (Identifier l) = pprint l
于 2017-06-30T10:15:43.230 回答