@@ -1901,14 +1901,79 @@ sepBy
19011901-------------------------------------------------------------------------------
19021902--
19031903-- | See 'Streamly.Internal.Data.Parser.sequence'.
1904−--
1905−-- /Unimplemented/
1906−--
19071904{-# INLINE sequence #-}
1908−sequence ::
1909− -- Foldable t =>
1910− Fold m b c -> t (Parser m a b) -> Parser m a c
1911−sequence _f _p = undefined
1905+sequence :: MonadThrow m =>
1906+ Fold m b c -> D.Stream m (Parser m a b) -> Parser m a c
1907+sequence (Fold fstep finitial fextract) (D.Stream sstep sstate) =
1908+ Parser step initial extract
1909+
1910+ where
1911+
1912+ initial = do
1913+ fres <- finitial
1914+ case fres of
1915+ FL.Partial fs -> return $ IPartial (Nothing', sstate, fs)
1916+ FL.Done c -> return $ IDone c
1917+
1918+ -- state does not contain any parser
1919+ -- yield a new parser from the stream
1920+ step (Nothing', ss, fs) _ = do
1921+ sres <- sstep defState ss
1922+ case sres of
1923+ D.Yield p ss1 -> return $ Continue 1 (Just' p, ss1, fs)
1924+ D.Stop -> do
1925+ c <- fextract fs
1926+ return $ Done 1 c
1927+ D.Skip ss1 -> return $ Continue 1 (Nothing', ss1, fs)
1928+
1929+ -- state holds a parser that may or may not have been
1930+ -- initialized. pinit holds the initial parser state
1931+ -- or modified parser state respectively
1932+ step (Just' (Parser pstep pinit pextr), ss, fs) a = do
1933+ ps <- pinit
1934+ case ps of
1935+ IPartial ps1 -> do
1936+ pres <- pstep ps1 a
1937+ case pres of
1938+ Partial n ps2 ->
1939+ let newP =
1940+ Just' $ Parser pstep (return $ IPartial ps2) pextr
1941+ in return $ Partial n (newP, ss, fs)
1942+ Continue n ps2 ->
1943+ let newP =
1944+ Just' $ Parser pstep (return $ IPartial ps2) pextr
1945+ in return $ Continue n (newP, ss, fs)
1946+ Done n b -> do
1947+ fres <- fstep fs b
1948+ case fres of
1949+ FL.Partial fs1 ->
1950+ return $ Partial n (Nothing', ss, fs1)
1951+ FL.Done c -> return $ Done n c
1952+ Error msg -> return $ Error msg
1953+ IDone b -> do
1954+ fres <- fstep fs b
1955+ case fres of
1956+ FL.Partial fs1 ->
1957+ return $ Partial 1 (Nothing', ss, fs1)
1958+ FL.Done c -> return $ Done 1 c
1959+ IError err -> return $ Error err
1960+
1961+ extract (Nothing', _, fs) = fextract fs
1962+ extract (Just' (Parser _ pinit pextr), _, fs) = do
1963+ ps <- pinit
1964+ case ps of
1965+ IPartial ps1 -> do
1966+ b <- pextr ps1
1967+ fres <- fstep fs b
1968+ case fres of
1969+ FL.Partial fs1 -> fextract fs1
1970+ FL.Done c -> return c
1971+ IDone b -> do
1972+ fres <- fstep fs b
1973+ case fres of
1974+ FL.Partial fs1 -> fextract fs1
1975+ FL.Done c -> return c
1976+ IError err -> throwM $ ParseError err
19121977
19131978-------------------------------------------------------------------------------
19141979-- Alternative Collection