我正在尝试使用 Trifecta 来解析具有类似 Haskell 布局语法的非常简单的函数式语言。我正在研究 Haddock 文档和我在 Parsec 方面的经验,因为我找不到关于 Trifecta 本身的任何介绍性材料。
我遇到的问题是使用布局的东西,因为即使是 Haddock 文档也没有多大帮助。
给定以下代码:
import Text.Trifecta
import Text.Trifecta.Parser.Token.Style
import Text.Trifecta.Parser.Identifier.Style
import Text.Trifecta.Layout.Combinators
import Text.Trifecta.Language.Prim
import Control.Applicative
import Control.Monad.Trans
import Data.Maybe (fromMaybe)
import Data.HashSet as HashSet
import Data.ByteString.UTF8 as UTF8
-- Copypasta from Text.Trifecta.Parser.Identifier.Style
set :: [String] -> HashSet ByteString
set = HashSet.fromList . fmap UTF8.fromString
lang :: MonadParser m => LanguageDef m
lang = LanguageDef{ languageCommentStyle = haskellCommentStyle
, languageIdentifierStyle = emptyIdents{ styleReserved = set keywords }
, languageOperatorStyle = emptyOps{ styleReserved = set ops }
}
where
keywords = ["where"]
ops = ["="]
data Def = Def ByteString [ByteString] [ByteString] [Def]
deriving Show
instance MonadLanguage m => MonadLanguage (Layout m) where
askLanguage = fmap liftLanguageDef $ lift askLanguage
def :: (MonadParser m) => Layout (Language m) Def
def = Def <$> identifier <*> vars <* reservedOp "=" <*> vars <*> laidout locals
where
vars = many identifier
locals = fromMaybe [] <$> optional (reserved "where" *> defs)
defs :: (MonadParser m) => Layout (Language m) [Def]
defs = laidout (many def)
test :: String -> IO ()
test = parseTest $ run $ defs <* eof
where
run p = runLanguage (fst <$> runLayout p defaultLayoutState) lang
我正在尝试解析以下文本test
:
f x = x y a b c -- 1
where -- 2
y = d -- 3
g x = z -- 4
但它因解析错误而失败:
(interactive):4:2: error: expected: "=",
identifier, letter or digit
g x = z -- 4
^
但如果我注释掉第 2 行和第 3 行,它会起作用。
那么,即使包含第 2 行和第 3 行,我如何让它解析呢?