gpt4 book ai didi

haskell - 如何编写一个不占用空间的解析器?

转载 作者:行者123 更新时间:2023-12-02 01:12:09 25 4
gpt4 key购买 nike

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

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

data Identifier = Identifier String String

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

如何为 Identifier 编写解析器?

最佳答案

我最终编写了 parseLexeme,以替换 this tutorial 中的词素

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

关于haskell - 如何编写一个不占用空间的解析器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44841659/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com