module Data.Attoparsec.Text.Lazy
(
Result(..)
, module Data.Attoparsec.Text
, parse
, parseTest
, maybeResult
, eitherResult
) where
import Control.DeepSeq (NFData(rnf))
import Data.Text.Lazy.Internal (Text(..), chunk)
import qualified Data.Attoparsec.Internal.Types as T
import qualified Data.Attoparsec.Text as A
import qualified Data.Text as T
import Data.Attoparsec.Text hiding (IResult(..), Result, eitherResult,
maybeResult, parse, parseWith, parseTest)
data Result r = Fail Text [String] String
| Done Text r
instance Show r => Show (Result r) where
show (Fail bs stk msg) =
"Fail " ++ show bs ++ " " ++ show stk ++ " " ++ show msg
show (Done bs r) = "Done " ++ show bs ++ " " ++ show r
instance NFData r => NFData (Result r) where
rnf (Fail bs ctxs msg) = rnf bs `seq` rnf ctxs `seq` rnf msg
rnf (Done bs r) = rnf bs `seq` rnf r
fmapR :: (a -> b) -> Result a -> Result b
fmapR _ (Fail st stk msg) = Fail st stk msg
fmapR f (Done bs r) = Done bs (f r)
instance Functor Result where
fmap = fmapR
parse :: A.Parser a -> Text -> Result a
parse p s = case s of
Chunk x xs -> go (A.parse p x) xs
empty -> go (A.parse p T.empty) empty
where
go (T.Fail x stk msg) ys = Fail (chunk x ys) stk msg
go (T.Done x r) ys = Done (chunk x ys) r
go (T.Partial k) (Chunk y ys) = go (k y) ys
go (T.Partial k) empty = go (k T.empty) empty
parseTest :: (Show a) => A.Parser a -> Text -> IO ()
parseTest p s = print (parse p s)
maybeResult :: Result r -> Maybe r
maybeResult (Done _ r) = Just r
maybeResult _ = Nothing
eitherResult :: Result r -> Either String r
eitherResult (Done _ r) = Right r
eitherResult (Fail _ _ msg) = Left msg