1{-# OPTIONS_GHC -Wno-orphans #-}
4-- Module : Streamly.Internal.Data.Parser
5-- Copyright : (c) 2020 Composewell Technologies
6-- License : BSD-3-Clause
7-- Maintainer : streamly@composewell.com
8-- Stability : pre-release
11-- Fast backtracking parsers with stream fusion and native streaming
14-- 'Applicative' and 'Control.Applicative.Alternative' type class based
15-- combinators from the
16-- <http://hackage.haskell.org/package/parser-combinators parser-combinators>
17-- package can also be used with the 'Parser' type. However, there are two
18-- important differences between @parser-combinators@ and the equivalent ones
19-- provided in this module in terms of performance:
21-- 1) @parser-combinators@ use plain Haskell lists to collect the results, in a
22-- strict Monad like IO, the results are necessarily buffered before they can
23-- be consumed. This may not perform optimally in streaming applications
24-- processing large amounts of data. Equivalent combinators in this module can
25-- consume the results of parsing using a 'Fold', thus providing a scalability
26-- and a composable consumer.
28-- 2) Several combinators in this module can be many times faster because of
29-- stream fusion. For example, 'Streamly.Internal.Data.Parser.many' combinator
30-- in this module is much faster than the 'Control.Applicative.many' combinator
31-- of 'Control.Applicative.Alternative' type class.
35-- Failing parsers in this module throw the 'D.ParseError' exception.
39-- As far as possible, try that the names of the combinators in this module are
42-- * <https://hackage.haskell.org/package/base/docs/Text-ParserCombinators-ReadP.html base/Text.ParserCombinators.ReadP>
43-- * <http://hackage.haskell.org/package/parser-combinators parser-combinators>
44-- * <http://hackage.haskell.org/package/megaparsec megaparsec>
45-- * <http://hackage.haskell.org/package/attoparsec attoparsec>
46-- * <http://hackage.haskell.org/package/parsec parsec>
48module Streamly.Internal.Data.Parser
54 -- * Downgrade to Fold
57 -- First order parsers
77 -- All of these can be expressed in terms of either
88 -- * Sequence parsers (tokenizers)
90 -- | Parsers chained in series, if one parser terminates the composition
96 -- | Grab a sequence of input elements without inspecting them
98 -- , take -- takeBetween 0 n
99 , takeEQ -- takeBetween n n
100 , takeGE -- takeBetween n maxBound
103 -- Grab a sequence of input elements by inspecting them
130 , groupByRollingEither
136 , takeFramedByGeneric
143 -- , prefixOf -- match any prefix of a given string
144 -- , suffixOf -- match any suffix of a given string
145 -- , infixOf -- match any substring of a given string
148 -- Second order parsers (parsers using parsers)
149 -- * Binary Combinators
151 -- ** Sequential Applicative
156 -- ** Parallel Applicatives
160 -- , teeTill -- like manyTill but parallel
163 -- ** Sequential Interleaving
164 -- Use two folds, run a primary parser, its rejected values go to the
167 -- , deintercalatePrefix
168 -- , deintercalateSuffix
171 -- | TODO: traditional implmentations of these may be of limited use. For
172 -- example, consider parsing lines separated by @\\r\\n@. The main parser
173 -- will have to detect and exclude the sequence @\\r\\n@ anyway so that we
174 -- can apply the "sep" parser.
176 -- We can instead implement these as special cases of deintercalate.
188 -- ** Sequential Alternative
192 -- ** Parallel Alternatives
198 -- * N-ary Combinators
199 -- ** Sequential Collection
203 -- ** Sequential Repetition
216 -- | A simple and stupid impl would be to just convert the stream to an
217 -- array and give the array reference to all consumers. The array can be
218 -- grown on demand by any consumer and truncated when nonbody needs it.
220 -- ** Distribute to collection
221 -- ** Distribute to repetition
223 -- ** Interleaved collection
230 -- ** Collection of Alternatives
236 -- , fastestN -- first N successful in time
237 -- , choiceN -- first N successful in position
239 -- , choice -- first successful in position
241 -- ** Repeated Alternatives
251import Streamly.Internal.Data.Fold.Type (Fold(..))
252import Streamly.Internal.Data.Parser.ParserK.Type (Parser)
253import Streamly.Internal.Data.Stream.Type (Stream)
255import qualified Streamly.Internal.Data.Fold.Type as FL
256import qualified Streamly.Internal.Data.Parser.ParserD as D
257import qualified Streamly.Internal.Data.Parser.ParserK.Type as K
258import qualified Streamly.Internal.Data.Stream.Type as Stream
261 ( any, all, dropWhile, take, takeWhile, sequence, concatMap, maybe, either
267-- >>> import Prelude hiding (any, all, dropWhile, take, takeWhile, sequence, concatMap, maybe, either, filter)
268-- >>> import Control.Applicative ((<|>))
269-- >>> import Data.Char (isSpace)
270-- >>> import qualified Data.Maybe as Maybe
271-- >>> import qualified Streamly.Data.Stream as Stream
272-- >>> import qualified Streamly.Internal.Data.Stream as Stream (parse, parseMany)
273-- >>> import qualified Streamly.Internal.Data.Fold as Fold
274-- >>> import qualified Streamly.Internal.Data.Parser as Parser
276-------------------------------------------------------------------------------
277-- Downgrade a parser to a Fold
278-------------------------------------------------------------------------------
280-- | Make a 'Fold' from a 'Parser'. The fold just throws an exception if the
281-- parser fails or tries to backtrack.
283-- This can be useful in combinators that accept a Fold and we know that a
284-- Parser cannot fail or failure exception is acceptable as there is no way to
290toFold :: Monad m => Parser m a b -> Fold m a b
291toFold p = D.toFold $ D.fromParserK p
293-------------------------------------------------------------------------------
294-- Upgrade folds to parses
295-------------------------------------------------------------------------------
297-- | Make a 'Parser' from a 'Fold'.
299{-# INLINE fromFold #-}
300fromFold :: Monad m => Fold m a b -> Parser m a b
301fromFold = D.toParserK . D.fromFold
303-- | Convert a Maybe returning fold to an error returning parser. The first
304-- argument is the error message that the parser would return when the fold
309{-# INLINE fromFoldMaybe #-}
310fromFoldMaybe :: Monad m => String -> Fold m a (Maybe b) -> Parser m a b
311fromFoldMaybe err = D.toParserK . D.fromFoldMaybe err
313-------------------------------------------------------------------------------
314-- Terminating but not failing folds
315-------------------------------------------------------------------------------
317-- This is the dual of stream "fromPure".
319-- | A parser that always yields a pure value without consuming any input.
321{-# INLINE [3] fromPure #-}
322fromPure :: Monad m => b -> Parser m a b
323fromPure = D.toParserK . D.fromPure
324{-# RULES "fromPure fallback to CPS" [2]
325 forall a. D.toParserK (D.fromPure a) = K.fromPure a #-}
327-- This is the dual of stream "fromEffect".
329-- | A parser that always yields the result of an effectful action without
330-- consuming any input.
332{-# INLINE fromEffect #-}
333fromEffect :: Monad m => m b -> Parser m a b
334fromEffect = K.fromEffect -- D.toParserK . D.fromEffect
336-- This is the dual of "nil".
338-- | A parser that always fails with an error message without consuming
341{-# INLINE [3] die #-}
342die :: Monad m => String -> Parser m a b
343die = D.toParserK . D.die
344{-# RULES "die fallback to CPS" [2]
345 forall a. D.toParserK (D.die a) = K.die a #-}
347-- This is the dual of "nilM".
349-- | A parser that always fails with an effectful error message and without
350-- consuming any input.
355dieM :: Monad m => m String -> Parser m a b
356dieM = D.toParserK . D.dieM
358-------------------------------------------------------------------------------
360-------------------------------------------------------------------------------
362-- | @lmap f parser@ maps the function @f@ on the input of the parser.
364-- >>> Stream.parse (Parser.lmap (\x -> x * x) (Parser.fromFold Fold.sum)) (Stream.enumerateFromTo 1 100)
367-- > lmap = Parser.lmapM return
370lmap :: Monad m => (a -> b) -> Parser m b r -> Parser m a r
371lmap f p = D.toParserK $ D.lmap f $ D.fromParserK p
373-- | @lmapM f parser@ maps the monadic function @f@ on the input of the parser.
376lmapM :: Monad m => (a -> m b) -> Parser m b r -> Parser m a r
377lmapM f p = D.toParserK $ D.lmapM f $ D.fromParserK p
379-- | @rmapM f parser@ maps the monadic function @f@ on the output of the parser.
382rmapM :: Monad m => (b -> m c) -> Parser m a b -> Parser m a c
383rmapM f p = D.toParserK $ D.rmapM f $ D.fromParserK p
385-- | Include only those elements that pass a predicate.
387-- >>> Stream.parse (Parser.filter (> 5) (Parser.fromFold Fold.sum)) $ Stream.fromList [1..10]
391filter :: Monad m => (a -> Bool) -> Parser m a b -> Parser m a b
392filter f p = D.toParserK $ D.filter f $ D.fromParserK p
394-------------------------------------------------------------------------------
396-------------------------------------------------------------------------------
398-- | Peek the head element of a stream, without consuming it. Fails if it
399-- encounters end of input.
401-- >>> Stream.parse ((,) <$> Parser.peek <*> Parser.satisfy (> 0)) $ Stream.fromList [1]
405-- peek = lookAhead (satisfy True)
409peek :: Monad m => Parser m a a
410peek = D.toParserK D.peek
412-- | Succeeds if we are at the end of input, fails otherwise.
414-- >>> Stream.parse ((,) <$> Parser.satisfy (> 0) <*> Parser.eof) $ Stream.fromList [1]
418eof :: Monad m => Parser m a ()
419eof = D.toParserK D.eof
421-- | Returns the next element if it passes the predicate, fails otherwise.
423-- >>> Stream.parse (Parser.satisfy (== 1)) $ Stream.fromList [1,0,1]
426-- >>> toMaybe f x = if f x then Just x else Nothing
427-- >>> satisfy f = Parser.maybe (toMaybe f)
429{-# INLINE satisfy #-}
430satisfy :: Monad m => (a -> Bool) -> Parser m a a
431satisfy = D.toParserK . D.satisfy
433-- | Consume one element from the head of the stream. Fails if it encounters
436-- >>> one = Parser.satisfy $ const True
439one :: Monad m => Parser m a a
440one = satisfy $ const True
442-- | Match a specific element.
444-- >>> oneEq x = Parser.satisfy (== x)
447oneEq :: (Monad m, Eq a) => a -> Parser m a a
448oneEq x = satisfy (== x)
450-- | Match anything other than the supplied element.
452-- >>> oneNotEq x = Parser.satisfy (/= x)
454{-# INLINE oneNotEq #-}
455oneNotEq :: (Monad m, Eq a) => a -> Parser m a a
456oneNotEq x = satisfy (/= x)
458-- | Match any one of the elements in the supplied list.
460-- >>> oneOf xs = Parser.satisfy (`elem` xs)
462-- When performance matters a pattern matching predicate could be more
463-- efficient than a list:
474-- GHC may use a binary search instead of linear search in the list.
475-- Alternatively, you can also use an array instead of list for storage and
479oneOf :: (Monad m, Eq a) => [a] -> Parser m a a
480oneOf xs = satisfy (`elem` xs)
482-- | See performance notes in 'oneOf'.
484-- >>> noneOf xs = Parser.satisfy (`notElem` xs)
487noneOf :: (Monad m, Eq a) => [a] -> Parser m a a
488noneOf xs = satisfy (`notElem` xs)
490-- | Return the next element of the input. Returns 'Nothing'
491-- on end of input. Also known as 'head'.
495{-# DEPRECATED next "Please use \"fromFold Fold.one\" instead" #-}
497next :: Monad m => Parser m a (Maybe a)
498next = D.toParserK D.next
500-- | Map a 'Maybe' returning function on the next element in the stream. The
501-- parser fails if the function returns 'Nothing' otherwise returns the 'Just'
504-- >>> toEither = Maybe.maybe (Left "maybe: predicate failed") Right
505-- >>> maybe f = Parser.either (toEither . f)
507-- >>> maybe f = Parser.fromFoldMaybe "maybe: predicate failed" (Fold.maybe f)
512maybe :: Monad m => (a -> Maybe b) -> Parser m a b
513maybe = D.toParserK . D.maybe
515-- | Map an 'Either' returning function on the next element in the stream. If
516-- the function returns 'Left err', the parser fails with the error message
517-- @err@ otherwise returns the 'Right' value.
522either :: Monad m => (a -> Either String b) -> Parser m a b
523either = D.toParserK . D.either
525-------------------------------------------------------------------------------
527-------------------------------------------------------------------------------
529-- | @takeBetween m n@ takes a minimum of @m@ and a maximum of @n@ input
530-- elements and folds them using the supplied fold.
532-- Stops after @n@ elements.
533-- Fails if the stream ends before @m@ elements could be taken.
539-- takeBetween' low high ls = Stream.parse prsr (Stream.fromList ls)
540-- where prsr = Parser.takeBetween low high Fold.toList
545-- >>> takeBetween' 2 4 [1, 2, 3, 4, 5]
548-- >>> takeBetween' 2 4 [1, 2]
551-- >>> takeBetween' 2 4 [1]
552-- *** Exception: ParseError "takeBetween: Expecting alteast 2 elements, got 1"
554-- >>> takeBetween' 0 0 [1, 2]
557-- >>> takeBetween' 0 1 []
560-- @takeBetween@ is the most general take operation, other take operations can
561-- be defined in terms of takeBetween. For example:
563-- >>> take n = Parser.takeBetween 0 n
564-- >>> takeEQ n = Parser.takeBetween n n
565-- >>> takeGE n = Parser.takeBetween n maxBound
569{-# INLINE takeBetween #-}
570takeBetween :: Monad m =>
571 Int -> Int -> Fold m a b -> Parser m a b
572takeBetween m n = D.toParserK . D.takeBetween m n
574-- | Stops after taking exactly @n@ input elements.
576-- * Stops - after consuming @n@ elements.
577-- * Fails - if the stream or the collecting fold ends before it can collect
578-- exactly @n@ elements.
580-- >>> Stream.parse (Parser.takeEQ 4 Fold.toList) $ Stream.fromList [1,0,1]
581-- *** Exception: ParseError "takeEQ: Expecting exactly 4 elements, input terminated on 3"
584takeEQ :: Monad m => Int -> Fold m a b -> Parser m a b
585takeEQ n = D.toParserK . D.takeEQ n
587-- | Take at least @n@ input elements, but can collect more.
589-- * Stops - when the collecting fold stops.
590-- * Fails - if the stream or the collecting fold ends before producing @n@
593-- >>> Stream.parse (Parser.takeGE 4 Fold.toList) $ Stream.fromList [1,0,1]
594-- *** Exception: ParseError "takeGE: Expecting at least 4 elements, input terminated on 3"
596-- >>> Stream.parse (Parser.takeGE 4 Fold.toList) $ Stream.fromList [1,0,1,0,1]
602takeGE :: Monad m => Int -> Fold m a b -> Parser m a b
603takeGE n = D.toParserK . D.takeGE n
605-------------------------------------------------------------------------------
606-- Take until a condition
607-------------------------------------------------------------------------------
610-- Note: This is called @takeWhileP@ and @munch@ in some parser libraries.
612-- XXX We should perhaps use only takeWhileP and rename it to takeWhile.
614-- | Like 'takeWhile' but uses a 'Parser' instead of a 'Fold' to collect the
615-- input. The combinator stops when the condition fails or if the collecting
618-- Other interesting parsers can be implemented in terms of this parser:
620-- >>> takeWhile1 cond p = Parser.takeWhileP cond (Parser.takeBetween 1 maxBound p)
621-- >>> takeWhileBetween cond m n p = Parser.takeWhileP cond (Parser.takeBetween m n p)
623-- Stops: when the condition fails or the collecting parser stops.
624-- Fails: when the collecting parser fails.
628{-# INLINE takeWhileP #-}
629takeWhileP :: Monad m => (a -> Bool) -> Parser m a b -> Parser m a b
630takeWhileP cond p = D.toParserK $ D.takeWhileP cond (D.fromParserK p)
632-- | Collect stream elements until an element fails the predicate. The element
633-- on which the predicate fails is returned back to the input stream.
635-- * Stops - when the predicate fails or the collecting fold stops.
638-- >>> Stream.parse (Parser.takeWhile (== 0) Fold.toList) $ Stream.fromList [0,0,1,0,1]
641-- >>> takeWhile cond f = Parser.takeWhileP cond (Parser.fromFold f)
643-- We can implement a @breakOn@ using 'takeWhile':
646-- breakOn p = takeWhile (not p)
649{-# INLINE takeWhile #-}
650takeWhile :: Monad m => (a -> Bool) -> Fold m a b -> Parser m a b
651takeWhile cond = D.toParserK . D.takeWhile cond
652-- takeWhile cond f = takeWhileP cond (fromFold f)
654-- | Like 'takeWhile' but takes at least one element otherwise fails.
656-- >>> takeWhile1 cond p = Parser.takeWhileP cond (Parser.takeBetween 1 maxBound p)
658{-# INLINE takeWhile1 #-}
659takeWhile1 :: Monad m => (a -> Bool) -> Fold m a b -> Parser m a b
660takeWhile1 cond = D.toParserK . D.takeWhile1 cond
661-- takeWhile1 cond f = takeWhileP cond (takeBetween 1 maxBound f)
663-- | Drain the input as long as the predicate succeeds, running the effects and
664-- discarding the results.
666-- This is also called @skipWhile@ in some parsing libraries.
668-- >>> dropWhile p = Parser.takeWhile p Fold.drain
670{-# INLINE dropWhile #-}
671dropWhile :: Monad m => (a -> Bool) -> Parser m a ()
672dropWhile p = takeWhile p FL.drain
674-------------------------------------------------------------------------------
676-------------------------------------------------------------------------------
678-- XXX We can remove Maybe from esc
679{-# INLINE takeFramedByGeneric #-}
680takeFramedByGeneric :: Monad m =>
686takeFramedByGeneric esc begin end f =
687 D.toParserK $ D.takeFramedByGeneric esc begin end f
689-- | @takeEndBy cond parser@ parses a token that ends by a separator chosen by
690-- the supplied predicate. The separator is also taken with the token.
692-- This can be combined with other parsers to implement other interesting
693-- parsers as follows:
695-- >>> takeEndByLE cond n p = Parser.takeEndBy cond (Parser.fromFold $ Fold.take n p)
696-- >>> takeEndByBetween cond m n p = Parser.takeEndBy cond (Parser.takeBetween m n p)
698-- >>> takeEndBy = Parser.takeEndByEsc (const False)
700-- See also "Streamly.Data.Fold.takeEndBy". Unlike the fold, the collecting
701-- parser in the takeEndBy parser can decide whether to fail or not if the
702-- stream does not end with separator.
706{-# INLINE takeEndBy #-}
707takeEndBy :: Monad m => (a -> Bool) -> Parser m a b -> Parser m a b
708takeEndBy cond = D.toParserK . D.takeEndBy cond . D.fromParserK
709-- takeEndBy = takeEndByEsc (const False)
711-- | Like 'takeEndBy' but the separator is dropped.
713-- See also "Streamly.Data.Fold.takeEndBy_".
717{-# INLINE takeEndBy_ #-}
718takeEndBy_ :: Monad m => (a -> Bool) -> Parser m a b -> Parser m a b
719takeEndBy_ cond = D.toParserK . D.takeEndBy_ cond . D.fromParserK
722 takeFramedByGeneric Nothing Nothing (Just isEnd) (toFold p)
725-- | Take either the separator or the token. Separator is a Left value and
726-- token is Right value.
729{-# INLINE takeEitherSepBy #-}
730takeEitherSepBy :: -- Monad m =>
731 (a -> Bool) -> Fold m (Either a b) c -> Parser m a c
732takeEitherSepBy _cond = undefined -- D.toParserK . D.takeEitherSepBy cond
734-- | Parse a token that starts with an element chosen by the predicate. The
735-- parser fails if the input does not start with the selected element.
737-- * Stops - when the predicate succeeds in non-leading position.
738-- * Fails - when the predicate fails in the leading position.
740-- >>> splitWithPrefix p f = Stream.parseMany (Parser.takeStartBy p f)
744-- >>> p = Parser.takeStartBy (== ',') Fold.toList
745-- >>> leadingComma = Stream.parse p . Stream.fromList
746-- >>> leadingComma "a,b"
747-- *** Exception: ParseError "takeStartBy: missing frame start"
749-- >>> leadingComma ",,"
751-- >>> leadingComma ",a,b"
753-- >>> leadingComma ""
758{-# INLINE takeStartBy #-}
759takeStartBy :: Monad m => (a -> Bool) -> Fold m a b -> Parser m a b
760takeStartBy cond = D.toParserK . D.takeStartBy cond
762-- | Like 'takeStartBy' but drops the separator.
764-- >>> takeStartBy_ isBegin = Parser.takeFramedByGeneric Nothing (Just isBegin) Nothing
766{-# INLINE takeStartBy_ #-}
767takeStartBy_ :: Monad m => (a -> Bool) -> Fold m a b -> Parser m a b
768takeStartBy_ isBegin = takeFramedByGeneric Nothing (Just isBegin) Nothing
770-------------------------------------------------------------------------------
771-- Quoting and Escaping
772-------------------------------------------------------------------------------
774-- | Like 'takeEndBy' but the separator elements can be escaped using an
775-- escape char determined by the first predicate. The escape characters are
779{-# INLINE takeEndByEsc #-}
780takeEndByEsc :: Monad m =>
781 (a -> Bool) -> (a -> Bool) -> Parser m a b -> Parser m a b
782takeEndByEsc isEsc isEnd p =
783 D.toParserK $ D.takeEndByEsc isEsc isEnd (D.fromParserK p)
785-- | @takeFramedByEsc_ isEsc isBegin isEnd fold@ parses a token framed using a
786-- begin and end predicate, and an escape character. The frame begin and end
787-- characters lose their special meaning if preceded by the escape character.
789-- Nested frames are allowed if begin and end markers are different, nested
790-- frames must be balanced unless escaped, nested frame markers are emitted as
795-- >>> p = Parser.takeFramedByEsc_ (== '\\') (== '{') (== '}') Fold.toList
796-- >>> Stream.parse p $ Stream.fromList "{hello}"
798-- >>> Stream.parse p $ Stream.fromList "{hello {world}}"
800-- >>> Stream.parse p $ Stream.fromList "{hello \\{world}"
802-- >>> Stream.parse p $ Stream.fromList "{hello {world}"
803-- *** Exception: ParseError "takeFramedByEsc_: missing frame end"
806{-# INLINE takeFramedByEsc_ #-}
807takeFramedByEsc_ :: Monad m =>
808 (a -> Bool) -> (a -> Bool) -> (a -> Bool) -> Fold m a b -> Parser m a b
809takeFramedByEsc_ isEsc isBegin isEnd f =
810 D.toParserK $ D.takeFramedByEsc_ isEsc isBegin isEnd f
811-- takeEndByEsc_ isEsc isEnd p =
812-- takeFramedByGeneric (Just isEsc) Nothing (Just isEnd) (toFold p)
814-- | @takeFramedBy_ isBegin isEnd fold@ parses a token framed by a begin and an
817-- >>> takeFramedBy_ = Parser.takeFramedByEsc_ (const False)
819{-# INLINE takeFramedBy_ #-}
820takeFramedBy_ :: Monad m =>
821 (a -> Bool) -> (a -> Bool) -> Fold m a b -> Parser m a b
822takeFramedBy_ isBegin isEnd f = D.toParserK $ D.takeFramedBy_ isBegin isEnd f
823-- takeFramedBy_ isBegin isEnd =
824-- takeFramedByGeneric (Just (const False)) (Just isBegin) (Just isEnd)
826-------------------------------------------------------------------------------
828-------------------------------------------------------------------------------
830-- Note we can also get words using something like:
831-- sepBy FL.toList (takeWhile (not . p) Fold.toList) (dropWhile p)
833-- But that won't be as efficient and ergonomic.
835-- | Like 'splitOn' but strips leading, trailing, and repeated separators.
836-- Therefore, @".a..b."@ having '.' as the separator would be parsed as
837-- @["a","b"]@. In other words, its like parsing words from whitespace
840-- * Stops - when it finds a word separator after a non-word element
843-- >>> wordBy = Parser.wordFramedBy (const False) (const False) (const False)
846-- S.wordsBy pred f = S.parseMany (PR.wordBy pred f)
850wordBy :: Monad m => (a -> Bool) -> Fold m a b -> Parser m a b
851wordBy f = D.toParserK . D.wordBy f
853-- | Like 'wordBy' but treats anything inside a pair of quotes as a single
854-- word, the quotes can be escaped by an escape character. Recursive quotes
855-- are possible if quote begin and end characters are different, quotes must be
856-- balanced. Outermost quotes are stripped.
858-- >>> braces = Parser.wordFramedBy (== '\\') (== '{') (== '}') isSpace Fold.toList
859-- >>> Stream.parse braces $ Stream.fromList "{ab} cd"
861-- >>> Stream.parse braces $ Stream.fromList "{ab}{cd}"
863-- >>> Stream.parse braces $ Stream.fromList "a{b} cd"
865-- >>> Stream.parse braces $ Stream.fromList "a{{b}} cd"
868-- >>> quotes = Parser.wordFramedBy (== '\\') (== '"') (== '"') isSpace Fold.toList
869-- >>> Stream.parse quotes $ Stream.fromList "\"a\"\"b\""
872{-# INLINE wordFramedBy #-}
873wordFramedBy :: Monad m =>
874 (a -> Bool) -- ^ Escape
875 -> (a -> Bool) -- ^ left quote
876 -> (a -> Bool) -- ^ right quote
877 -> (a -> Bool) -- ^ word seperator
880wordFramedBy isEsc isBegin isEnd isSpc =
881 D.toParserK . D.wordFramedBy isEsc isBegin isEnd isSpc
883-- | Like 'wordFramedBy' but the closing quote is determined by the opening
884-- quote. The first quote begin starts a quote that is closed by its
885-- corresponding closing quote.
887-- 'wordFramedBy' and 'wordQuotedBy' both allow multiple quote characters based
888-- on the predicates but 'wordQuotedBy' always fixes the quote at the first
889-- occurrence and then it is closed only by the corresponding closing quote.
890-- Therefore, other quoting characters can be embedded inside it as normal
891-- characters. On the other hand, 'wordFramedBy' would close the quote as soon
892-- as it encounters any of the closing quotes.
894-- >>> q = (`elem` ['"', '\''])
895-- >>> p kQ = Parser.wordQuotedBy kQ (== '\\') q q id isSpace Fold.toList
897-- >>> Stream.parse (p False) $ Stream.fromList "a\"b'c\";'d\"e'f ghi"
900-- >>> Stream.parse (p True) $ Stream.fromList "a\"b'c\";'d\"e'f ghi"
903{-# INLINE wordQuotedBy #-}
904wordQuotedBy :: (Monad m, Eq a) =>
905 Bool -- ^ keep the quotes in the output
906 -> (a -> Bool) -- ^ Escape
907 -> (a -> Bool) -- ^ left quote
908 -> (a -> Bool) -- ^ right quote
909 -> (a -> a) -- ^ get right quote from left quote
910 -> (a -> Bool) -- ^ word seperator
913wordQuotedBy keepQuotes isEsc isBegin isEnd toRight isSpc =
914 D.toParserK . D.wordQuotedBy keepQuotes isEsc isBegin isEnd toRight isSpc
916-- | Given an input stream @[a,b,c,...]@ and a comparison function @cmp@, the
917-- parser assigns the element @a@ to the first group, then if @a \`cmp` b@ is
918-- 'True' @b@ is also assigned to the same group. If @a \`cmp` c@ is 'True'
919-- then @c@ is also assigned to the same group and so on. When the comparison
920-- fails the parser is terminated. Each group is folded using the 'Fold' @f@ and
921-- the result of the fold is the result of the parser.
923-- * Stops - when the comparison fails.
928-- Stream.fold Fold.toList
929-- . Stream.parseMany (Parser.groupBy eq Fold.toList)
933-- >>> runGroupsBy (<) []
936-- >>> runGroupsBy (<) [1]
939-- >>> runGroupsBy (<) [3, 5, 4, 1, 2, 0]
940-- [[3,5,4],[1,2],[0]]
942{-# INLINE groupBy #-}
943groupBy :: Monad m => (a -> a -> Bool) -> Fold m a b -> Parser m a b
944groupBy eq = D.toParserK . D.groupBy eq
946-- | Unlike 'groupBy' this combinator performs a rolling comparison of two
947-- successive elements in the input stream. Assuming the input stream
948-- is @[a,b,c,...]@ and the comparison function is @cmp@, the parser
949-- first assigns the element @a@ to the first group, then if @a \`cmp` b@ is
950-- 'True' @b@ is also assigned to the same group. If @b \`cmp` c@ is 'True'
951-- then @c@ is also assigned to the same group and so on. When the comparison
952-- fails the parser is terminated. Each group is folded using the 'Fold' @f@ and
953-- the result of the fold is the result of the parser.
955-- * Stops - when the comparison fails.
959-- runGroupsByRolling eq =
960-- Stream.fold Fold.toList
961-- . Stream.parseMany (Parser.groupByRolling eq Fold.toList)
965-- >>> runGroupsByRolling (<) []
968-- >>> runGroupsByRolling (<) [1]
971-- >>> runGroupsByRolling (<) [3, 5, 4, 1, 2, 0]
972-- [[3,5],[4],[1,2],[0]]
976{-# INLINE groupByRolling #-}
977groupByRolling :: Monad m => (a -> a -> Bool) -> Fold m a b -> Parser m a b
978groupByRolling eq = D.toParserK . D.groupByRolling eq
980-- | Like 'groupByRolling', but if the predicate is 'True' then collects using
981-- the first fold as long as the predicate holds 'True', if the predicate is
982-- 'False' collects using the second fold as long as it remains 'False'.
983-- Returns 'Left' for the first case and 'Right' for the second case.
985-- For example, if we want to detect sorted sequences in a stream, both
986-- ascending and descending cases we can use 'groupByRollingEither (<=)
987-- Fold.toList Fold.toList'.
990{-# INLINE groupByRollingEither #-}
991groupByRollingEither :: Monad m =>
992 (a -> a -> Bool) -> Fold m a b -> Fold m a c -> Parser m a (Either b c)
993groupByRollingEither eq f1 = D.toParserK . D.groupByRollingEither eq f1
995-- | Match the given sequence of elements using the given comparison function.
996-- Returns the original sequence if successful.
998-- >>> Stream.parse (Parser.listEqBy (==) "string") $ Stream.fromList "string"
1001-- >>> Stream.parse (Parser.listEqBy (==) "mismatch") $ Stream.fromList "match"
1002-- *** Exception: ParseError "listEqBy: failed, yet to match 7 elements"
1004{-# INLINE listEqBy #-}
1005listEqBy :: Monad m => (a -> a -> Bool) -> [a] -> Parser m a [a]
1006listEqBy cmp xs = D.toParserK (D.listEqBy cmp xs)
1008-- | Like 'listEqBy' but uses a stream instead of a list and does not return
1012eqBy :: Monad m => (a -> a -> Bool) -> Stream m a -> Parser m a ()
1013eqBy cmp = D.toParserK . D.eqBy cmp . Stream.toStreamD
1015-- | Match the input sequence with the supplied list and return it if
1018-- >>> listEq = Parser.listEqBy (==)
1020{-# INLINE listEq #-}
1021listEq :: (Monad m, Eq a) => [a] -> Parser m a [a]
1022listEq = listEqBy (==)
1024-------------------------------------------------------------------------------
1026-------------------------------------------------------------------------------
1028-- | Sequential parser application. Apply two parsers sequentially to an input
1029-- stream. The input is provided to the first parser, when it is done the
1030-- remaining input is provided to the second parser. If both the parsers
1031-- succeed their outputs are combined using the supplied function. The
1032-- operation fails if any of the parsers fail.
1034-- Note: This is a parsing dual of appending streams using
1035-- 'Streamly.Prelude.serial', it splits the streams using two parsers and zips
1038-- This implementation is strict in the second argument, therefore, the
1039-- following will fail:
1041-- >>> Stream.parse (Parser.serialWith const (Parser.satisfy (> 0)) undefined) $ Stream.fromList [1]
1042-- *** Exception: Prelude.undefined
1045-- Compare with 'Applicative' instance method '<*>'. This implementation allows
1046-- stream fusion but has quadratic complexity. This can fuse with other
1047-- operations and can be faster than 'Applicative' instance for small number
1048-- (less than 8) of compositions.
1050-- Many combinators can be expressed using @serialWith@ and other parser
1051-- primitives. Some common idioms are described below,
1054-- span :: (a -> Bool) -> Fold m a b -> Fold m a b -> Parser m a b
1055-- span pred f1 f2 = serialWith (,) ('takeWhile' pred f1) ('fromFold' f2)
1059-- spanBy :: (a -> a -> Bool) -> Fold m a b -> Fold m a b -> Parser m a b
1060-- spanBy eq f1 f2 = serialWith (,) ('groupBy' eq f1) ('fromFold' f2)
1064-- spanByRolling :: (a -> a -> Bool) -> Fold m a b -> Fold m a b -> Parser m a b
1065-- spanByRolling eq f1 f2 = serialWith (,) ('groupByRolling' eq f1) ('fromFold' f2)
1070{-# INLINE serialWith #-}
1071serialWith :: Monad m
1072 => (a -> b -> c) -> Parser m x a -> Parser m x b -> Parser m x c
1074 D.toParserK $ D.serialWith f (D.fromParserK p1) (D.fromParserK p2)
1076-- | Sequential parser application ignoring the output of the first parser.
1077-- Apply two parsers sequentially to an input stream. The input is provided to
1078-- the first parser, when it is done the remaining input is provided to the
1079-- second parser. The output of the parser is the output of the second parser.
1080-- The operation fails if any of the parsers fail.
1082-- This implementation is strict in the second argument, therefore, the
1083-- following will fail:
1085-- >>> Stream.parse (Parser.split_ (Parser.satisfy (> 0)) undefined) $ Stream.fromList [1]
1086-- *** Exception: Prelude.undefined
1089-- Compare with 'Applicative' instance method '*>'. This implementation allows
1090-- stream fusion but has quadratic complexity. This can fuse with other
1091-- operations, and can be faster than 'Applicative' instance for small
1092-- number (less than 8) of compositions.
1096{-# INLINE split_ #-}
1097split_ :: Monad m => Parser m x a -> Parser m x b -> Parser m x b
1098split_ p1 p2 = D.toParserK $ D.split_ (D.fromParserK p1) (D.fromParserK p2)
1101-- | @teeWith f p1 p2@ distributes its input to both @p1@ and @p2@ until both
1102-- of them succeed or anyone of them fails and combines their output using @f@.
1103-- The parser succeeds if both the parsers succeed.
1107{-# INLINE teeWith #-}
1109 => (a -> b -> c) -> Parser m x a -> Parser m x b -> Parser m x c
1111 D.toParserK $ D.teeWith f (D.fromParserK p1) (D.fromParserK p2)
1113-- | Like 'teeWith' but ends parsing and zips the results, if available,
1114-- whenever the first parser ends.
1118{-# INLINE teeWithFst #-}
1119teeWithFst :: Monad m
1120 => (a -> b -> c) -> Parser m x a -> Parser m x b -> Parser m x c
1122 D.toParserK $ D.teeWithFst f (D.fromParserK p1) (D.fromParserK p2)
1124-- | Like 'teeWith' but ends parsing and zips the results, if available,
1125-- whenever any of the parsers ends or fails.
1129{-# INLINE teeWithMin #-}
1130teeWithMin :: Monad m
1131 => (a -> b -> c) -> Parser m x a -> Parser m x b -> Parser m x c
1133 D.toParserK $ D.teeWithMin f (D.fromParserK p1) (D.fromParserK p2)
1136-- | Sequential alternative. Apply the input to the first parser and return the
1137-- result if the parser succeeds. If the first parser fails then backtrack and
1138-- apply the same input to the second parser and return the result.
1140-- Note: This implementation is not lazy in the second argument. The following
1143-- >>> Stream.parse (Parser.satisfy (> 0) `Parser.alt` undefined) $ Stream.fromList [1..10]
1146-- Compare with 'Alternative' instance method '<|>'. This implementation allows
1147-- stream fusion but has quadratic complexity. This can fuse with other
1148-- operations and can be much faster than 'Alternative' instance for small
1149-- number (less than 8) of alternatives.
1154alt :: Monad m => Parser m x a -> Parser m x a -> Parser m x a
1155alt p1 p2 = D.toParserK $ D.alt (D.fromParserK p1) (D.fromParserK p2)
1158-- | Shortest alternative. Apply both parsers in parallel but choose the result
1159-- from the one which consumed least input i.e. take the shortest succeeding
1164{-# INLINE shortest #-}
1166 => Parser m x a -> Parser m x a -> Parser m x a
1167shortest p1 p2 = D.toParserK $ D.shortest (D.fromParserK p1) (D.fromParserK p2)
1169-- | Longest alternative. Apply both parsers in parallel but choose the result
1170-- from the one which consumed more input i.e. take the longest succeeding
1175{-# INLINE longest #-}
1177 => Parser m x a -> Parser m x a -> Parser m x a
1178longest p1 p2 = D.toParserK $ D.longest (D.fromParserK p1) (D.fromParserK p2)
1181-- | Run a parser without consuming the input.
1183{-# INLINE lookAhead #-}
1184lookAhead :: Monad m => Parser m a b -> Parser m a b
1185lookAhead p = D.toParserK $ D.lookAhead $ D.fromParserK p
1187-- | Takes at-most @n@ input elements.
1189-- * Stops - when the collecting parser stops.
1190-- * Fails - when the collecting parser fails.
1192-- >>> Stream.parse (Parser.takeP 4 (Parser.takeEQ 2 Fold.toList)) $ Stream.fromList [1, 2, 3, 4, 5]
1195-- >>> Stream.parse (Parser.takeP 4 (Parser.takeEQ 5 Fold.toList)) $ Stream.fromList [1, 2, 3, 4, 5]
1196-- *** Exception: ParseError "takeEQ: Expecting exactly 5 elements, input terminated on 4"
1200takeP :: Monad m => Int -> Parser m a b -> Parser m a b
1201takeP i p = D.toParserK $ D.takeP i $ D.fromParserK p
1203-------------------------------------------------------------------------------
1204-- Sequential Collection
1205-------------------------------------------------------------------------------
1207-- | @concatSequence f p@ collects sequential parses of parsers in a
1208-- serial stream @p@ using the fold @f@. Fails if the input ends or any
1209-- of the parsers fail.
1211-- An even more efficient implementation can use ParserD type Parser in
1216{-# INLINE concatSequence #-}
1219 Fold m b c -> Stream m (Parser m a b) -> Parser m a c
1221 let sp = fmap D.fromParserK $ Stream.toStreamD p
1222 in D.toParserK $ D.sequence sp f
1224-- | Map a 'Parser' returning function on the result of a 'Parser'.
1226-- Compare with 'Monad' instance method '>>='. This implementation allows
1227-- stream fusion but has quadratic complexity. This can fuse with other
1228-- operations and can be much faster than 'Monad' instance for small number
1229-- (less than 8) of compositions.
1233{-# INLINE concatMap #-}
1235 => (b -> Parser m a c) -> Parser m a b -> Parser m a c
1236concatMap f p = D.toParserK $ D.concatMap (D.fromParserK . f) (D.fromParserK p)
1239-------------------------------------------------------------------------------
1240-- Alternative Collection
1241-------------------------------------------------------------------------------
1243-- | @choice parsers@ applies the @parsers@ in order and returns the first
1246-- This is same as 'asum' but more efficient.
1250{-# INLINE choice #-}
1252 (Functor t, Foldable t, Monad m) => t (Parser m a b) -> Parser m a b
1253choice ps = D.toParserK $ D.choice $ D.fromParserK <$> ps
1256-------------------------------------------------------------------------------
1257-- Sequential Repetition
1258-------------------------------------------------------------------------------
1260-- | Like 'many' but uses a 'Parser' instead of a 'Fold' to collect the
1261-- results. Parsing stops or fails if the collecting parser stops or fails.
1266manyP :: -- Monad m =>
1267 Parser m a b -> Parser m b c -> Parser m a c
1268manyP _p _f = undefined -- D.toParserK $ D.manyP (D.fromParserK p) f
1270-- | Collect zero or more parses. Apply the supplied parser repeatedly on the
1271-- input stream and push the parse results to a downstream fold.
1273-- Stops: when the downstream fold stops or the parser fails.
1274-- Fails: never, produces zero or more results.
1276-- >>> many = Parser.countBetween 0 maxBound
1278-- Compare with 'Control.Applicative.many'.
1281many :: Monad m => Parser m a b -> Fold m b c -> Parser m a c
1282many p f = D.toParserK $ D.many (D.fromParserK p) f
1284-- Note: many1 would perhaps be a better name for this and consistent with
1285-- other names like takeWhile1. But we retain the name "some" for
1288-- | Collect one or more parses. Apply the supplied parser repeatedly on the
1289-- input stream and push the parse results to a downstream fold.
1291-- Stops: when the downstream fold stops or the parser fails.
1292-- Fails: if it stops without producing a single result.
1294-- >>> some p f = Parser.manyP p (Parser.takeGE 1 f)
1295-- >>> some = Parser.countBetween 1 maxBound
1297-- Compare with 'Control.Applicative.some'.
1300some :: Monad m => Parser m a b -> Fold m b c -> Parser m a c
1301some p f = D.toParserK $ D.some (D.fromParserK p) f
1302-- some p f = manyP p (takeGE 1 f)
1303-- some = countBetween 1 maxBound
1305-- | @countBetween m n f p@ collects between @m@ and @n@ sequential parses of
1306-- parser @p@ using the fold @f@. Stop after collecting @n@ results. Fails if
1307-- the input ends or the parser fails before @m@ results are collected.
1309-- >>> countBetween m n p f = Parser.manyP p (Parser.takeBetween m n f)
1313{-# INLINE countBetween #-}
1314countBetween :: -- Monad m =>
1315 Int -> Int -> Parser m a b -> Fold m b c -> Parser m a c
1316countBetween _m _n _p = undefined
1317-- countBetween m n p f = manyP p (takeBetween m n f)
1319-- | @count n f p@ collects exactly @n@ sequential parses of parser @p@ using
1320-- the fold @f@. Fails if the input ends or the parser fails before @n@
1321-- results are collected.
1323-- >>> count n = Parser.countBetween n n
1324-- >>> count n p f = Parser.manyP p (Parser.takeEQ n f)
1329count :: -- Monad m =>
1330 Int -> Parser m a b -> Fold m b c -> Parser m a c
1331count n = countBetween n n
1332-- count n p f = manyP p (takeEQ n f)
1334-- | Like 'manyTill' but uses a 'Parser' to collect the results instead of a
1335-- 'Fold'. Parsing stops or fails if the collecting parser stops or fails.
1337-- We can implemnent parsers like the following using 'manyTillP':
1340-- countBetweenTill m n f p = manyTillP (takeBetween m n f) p
1345{-# INLINE manyTillP #-}
1346manyTillP :: -- Monad m =>
1347 Parser m a b -> Parser m a x -> Parser m b c -> Parser m a c
1348manyTillP _p1 _p2 _f = undefined
1349 -- D.toParserK $ D.manyTillP (D.fromParserK p1) (D.fromParserK p2) f
1351-- | @manyTill collect test f@ tries the parser @test@ on the input, if @test@
1352-- fails it backtracks and tries @collect@, after @collect@ succeeds @test@ is
1353-- tried again and so on. The parser stops when @test@ succeeds. The output of
1354-- @test@ is discarded and the output of @collect@ is accumulated by the
1355-- supplied fold. The parser fails if @collect@ fails.
1357-- Stops when the fold @f@ stops.
1359{-# INLINE manyTill #-}
1361 => Parser m a b -> Parser m a x -> Fold m b c -> Parser m a c
1362manyTill collect test f =
1363 D.toParserK $ D.manyTill (D.fromParserK collect) (D.fromParserK test) f
1365-- | @manyThen f collect recover@ repeats the parser @collect@ on the input and
1366-- collects the output in the supplied fold. If the the parser @collect@ fails,
1367-- parser @recover@ is run until it stops and then we start repeating the
1368-- parser @collect@ again. The parser fails if the recovery parser fails.
1370-- For example, this can be used to find a key frame in a video stream after an
1375{-# INLINE manyThen #-}
1376manyThen :: -- (Foldable t, Monad m) =>
1377 Parser m a b -> Parser m a x -> Fold m b c -> Parser m a c
1378manyThen _parser _recover _f = undefined
1380-------------------------------------------------------------------------------
1382-------------------------------------------------------------------------------
1384-- To deinterleave we can chain two parsers one behind the other. The input is
1385-- given to the first parser and the input definitively rejected by the first
1386-- parser is given to the second parser.
1388-- We can either have the parsers themselves buffer the input or use the shared
1389-- global buffer to hold it until none of the parsers need it. When the first
1390-- parser returns Skip (i.e. rewind) we let the second parser consume the
1391-- rejected input and when it is done we move the cursor forward to the first
1392-- parser again. This will require a "move forward" command as well.
1394-- To implement grep we can use three parsers, one to find the pattern, one
1395-- to store the context behind the pattern and one to store the context in
1396-- front of the pattern. When a match occurs we need to emit the accumulator of
1397-- all the three parsers. One parser can count the line numbers to provide the
1400-- XXX rename this to intercalate
1401-- | Apply two parsers alternately to an input stream. The input stream is
1402-- considered an interleaving of two patterns. The two parsers represent the
1405-- This undoes a "gintercalate" of two streams.
1407{-# INLINE deintercalate #-}
1408deintercalate :: Monad m =>
1411 -> Fold m (Either x y) z
1413deintercalate contentL contentR sink =
1416 (D.fromParserK contentL) (D.fromParserK contentR) sink
1418-- | Parse items separated by a separator parsed by the supplied parser. At
1419-- least one item must be present for the parser to succeed.
1421-- Note that this can go in infinite loop if both the parsers fail on some
1422-- input. Detection of that would make the implementation more complex.
1424{-# INLINE sepBy1 #-}
1426 Fold m b c -> Parser m a b -> Parser m a x -> Parser m a c
1427sepBy1 sink p sep = do
1429 f <- fromEffect $ FL.initialize sink
1430 f1 <- fromEffect $ FL.snoc f x
1433-- | Run the content parser first, when it is done, the separator parser is
1434-- run, when it is done content parser is run again and so on. If none of the
1435-- parsers consumes an input then parser returns a failure.
1437-- >>> sepBy sink p1 p2 = Parser.deintercalate p1 p2 (Fold.lefts sink)
1438-- >>> sepBy sink content sep = Parser.sepBy1 sink content sep <|> return mempty
1442 Parser m a b -> Parser m a x -> Fold m b c -> Parser m a c
1443sepBy content sep sink =
1444 D.toParserK $ D.sepBy (D.fromParserK content) (D.fromParserK sep) sink
1445-- sepBy sink = deintercalate (FL.lefts sink)
1447-------------------------------------------------------------------------------
1448-- Interleaving a collection of parsers
1449-------------------------------------------------------------------------------
1451-- | Apply a collection of parsers to an input stream in a round robin fashion.
1452-- Each parser is applied until it stops and then we repeat starting with the
1453-- the first parser again.
1457{-# INLINE roundRobin #-}
1458roundRobin :: -- (Foldable t, Monad m) =>
1459 t (Parser m a b) -> Fold m b c -> Parser m a c
1460roundRobin _ps _f = undefined
1462-------------------------------------------------------------------------------
1463-- Repeated Alternatives
1464-------------------------------------------------------------------------------
1466-- | Keep trying a parser up to a maximum of @n@ failures. When the parser
1467-- fails the input consumed till now is dropped and the new instance is tried
1468-- on the fresh input.
1472{-# INLINE retryMaxTotal #-}
1473retryMaxTotal :: -- (Monad m) =>
1474 Int -> Parser m a b -> Fold m b c -> Parser m a c
1475retryMaxTotal _n _p _f = undefined
1477-- | Like 'retryMaxTotal' but aborts after @n@ successive failures.
1481{-# INLINE retryMaxSuccessive #-}
1482retryMaxSuccessive :: -- (Monad m) =>
1483 Int -> Parser m a b -> Fold m b c -> Parser m a c
1484retryMaxSuccessive _n _p _f = undefined
1486-- | Keep trying a parser until it succeeds. When the parser fails the input
1487-- consumed till now is dropped and the new instance is tried on the fresh
1493retry :: -- (Monad m) =>
1494 Parser m a b -> Parser m a b
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list