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 : experimental
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 -- First order parsers
71 -- | Parsers chained in series, if one parser terminates the composition
74 -- | Grab a sequence of input elements without inspecting them
76 -- , take -- takeBetween 0 n
77 , takeEQ -- takeBetween n n
78 , takeGE -- takeBetween n maxBound
80 -- Grab a sequence of input elements by inspecting them
100 -- , prefixOf -- match any prefix of a given string
101 -- , suffixOf -- match any suffix of a given string
102 -- , infixOf -- match any substring of a given string
105 -- Second order parsers (parsers using parsers)
106 -- * Binary Combinators
108 -- ** Sequential Applicative
112 -- ** Parallel Applicatives
116 -- , teeTill -- like manyTill but parallel
118 -- ** Sequential Interleaving
119 -- Use two folds, run a primary parser, its rejected values go to the
123 -- ** Sequential Alternative
126 -- ** Parallel Alternatives
131 -- * N-ary Combinators
132 -- ** Sequential Collection
136 -- ** Sequential Repetition
148 -- | TODO: traditional implmentations of these may be of limited use. For
149 -- example, consider parsing lines separated by @\\r\\n@. The main parser
150 -- will have to detect and exclude the sequence @\\r\\n@ anyway so that we
151 -- can apply the "sep" parser.
153 -- We can instead implement these as special cases of deintercalate.
166 -- | A simple and stupid impl would be to just convert the stream to an
167 -- array and give the array reference to all consumers. The array can be
168 -- grown on demand by any consumer and truncated when nonbody needs it.
170 -- ** Distribute to collection
171 -- ** Distribute to repetition
173 -- ** Interleaved collection
180 -- ** Collection of Alternatives
186 -- , fastestN -- first N successful in time
187 -- , choiceN -- first N successful in position
189 , choice -- first successful in position
191 -- ** Repeated Alternatives
198import Control.Monad.Catch (MonadCatch)
200 hiding (any, all, take, takeWhile, sequence, concatMap, maybe, either)
202import Streamly.Internal.Data.Fold.Types (Fold(..))
203import Streamly.Internal.Data.Parser.ParserK.Types (Parser)
205import qualified Streamly.Internal.Data.Fold as FL
206import qualified Streamly.Internal.Data.Parser.ParserD as D
207import qualified Streamly.Internal.Data.Parser.ParserK.Types as K
209-------------------------------------------------------------------------------
210-- Upgrade folds to parses
211-------------------------------------------------------------------------------
213-- | Make a 'Parser' from a 'Fold'.
217{-# INLINE fromFold #-}
218fromFold :: MonadCatch m => Fold m a b -> Parser m a b
219fromFold = K.toParserK . D.fromFold
221-------------------------------------------------------------------------------
222-- Terminating but not failing folds
223-------------------------------------------------------------------------------
225-- This is the dual of stream "yield".
227-- | A parser that always yields a pure value without consuming any input.
231{-# INLINE [3] yield #-}
232yield :: MonadCatch m => b -> Parser m a b
233yield = K.toParserK . D.yield
234{-# RULES "yield fallback to CPS" [2]
235 forall a. K.toParserK (D.yield a) = K.yield a #-}
237-- This is the dual of stream "yieldM".
239-- | A parser that always yields the result of an effectful action without
240-- consuming any input.
245yieldM :: MonadCatch m => m b -> Parser m a b
246yieldM = K.yieldM -- K.toParserK . D.yieldM
248-- This is the dual of "nil".
250-- | A parser that always fails with an error message without consuming
255{-# INLINE [3] die #-}
256die :: MonadCatch m => String -> Parser m a b
257die = K.toParserK . D.die
258{-# RULES "die fallback to CPS" [2]
259 forall a. K.toParserK (D.die a) = K.die a #-}
261-- This is the dual of "nilM".
263-- | A parser that always fails with an effectful error message and without
264-- consuming any input.
269dieM :: MonadCatch m => m String -> Parser m a b
270dieM = K.toParserK . D.dieM
272-------------------------------------------------------------------------------
274-------------------------------------------------------------------------------
276-- | Peek the head element of a stream, without consuming it. Fails if it
277-- encounters end of input.
279-- >>> S.parse ((,) <$> PR.peek <*> PR.satisfy (> 0)) $ S.fromList [1]
283-- peek = lookAhead (satisfy True)
289peek :: MonadCatch m => Parser m a a
290peek = K.toParserK D.peek
292-- | Succeeds if we are at the end of input, fails otherwise.
294-- >>> S.parse ((,) <$> PR.satisfy (> 0) <*> PR.eof) $ S.fromList [1]
300eof :: MonadCatch m => Parser m a ()
301eof = K.toParserK D.eof
303-- | Returns the next element if it passes the predicate, fails otherwise.
305-- >>> S.parse (PR.satisfy (== 1)) $ S.fromList [1,0,1]
310{-# INLINE satisfy #-}
311satisfy :: MonadCatch m => (a -> Bool) -> Parser m a a
312satisfy = K.toParserK . D.satisfy
314-- | Map a 'Maybe' returning function on the next element in the stream. The
315-- parser fails if the function returns 'Nothing' otherwise returns the 'Just'
321maybe :: MonadCatch m => (a -> Maybe b) -> Parser m a b
322maybe = K.toParserK . D.maybe
324-- | Map an 'Either' returning function on the next element in the stream. If
325-- the function returns 'Left err', the parser fails with the error message
326-- @err@ otherwise returns the 'Right' value.
331either :: MonadCatch m => (a -> Either String b) -> Parser m a b
332either = K.toParserK . D.either
334-------------------------------------------------------------------------------
336-------------------------------------------------------------------------------
338-- | @takeBetween m n@ takes a minimum of @m@ and a maximum of @n@ input
339-- elements and folds them using the supplied fold.
341-- Stops after @n@ elements.
342-- Fails if the stream ends before @m@ elements could be taken.
347-- takeBetween' low high ls = S.parse prsr (S.fromList ls)
348-- where prsr = P.takeBetween low high FL.toList
351-- >>> takeBetween' 2 4 [1, 2, 3, 4, 5]
354-- >>> takeBetween' 2 4 [1, 2]
357-- >>> takeBetween' 2 4 [1]
358-- > ParseError "takeBetween: Expecting alteast 2 elements, got 1"
360-- >>> takeBetween' 0 0 [1, 2]
363-- >>> takeBetween' 0 1 []
366-- @takeBetween@ is the most general take operation, other take operations can
367-- be defined in terms of takeBetween. For example:
370-- take = takeBetween 0 n -- equivalent of takeLE
371-- take1 = takeBetween 1 n -- equivalent of takeLE1
372-- takeEQ = takeBetween n n
373-- takeGE = takeBetween n maxBound
378{-# INLINE takeBetween #-}
379takeBetween :: MonadCatch m =>
380 Int -> Int -> Fold m a b -> Parser m a b
381takeBetween m n = K.toParserK . D.takeBetween m n
383-- | Stops after taking exactly @n@ input elements.
385-- * Stops - after consuming @n@ elements.
386-- * Fails - if the stream or the collecting fold ends before it can collect
387-- exactly @n@ elements.
389-- >>> S.parse (PR.takeEQ 4 FL.toList) $ S.fromList [1,0,1]
390-- > "takeEQ: Expecting exactly 4 elements, got 3"
395takeEQ :: MonadCatch m => Int -> Fold m a b -> Parser m a b
396takeEQ n = K.toParserK . D.takeEQ n
398-- | Take at least @n@ input elements, but can collect more.
400-- * Stops - when the collecting fold stops.
401-- * Fails - if the stream or the collecting fold ends before producing @n@
404-- >>> S.parse (PR.takeGE 4 FL.toList) $ S.fromList [1,0,1]
405-- > "takeGE: Expecting at least 4 elements, got only 3"
407-- >>> S.parse (PR.takeGE 4 FL.toList) $ S.fromList [1,0,1,0,1]
413takeGE :: MonadCatch m => Int -> Fold m a b -> Parser m a b
414takeGE n = K.toParserK . D.takeGE n
417-- Note: This is called @takeWhileP@ and @munch@ in some parser libraries.
419-- | Like 'takeWhile' but uses a 'Parser' instead of a 'Fold' to collect the
420-- input. The combinator stops when the condition fails or if the collecting
423-- This is a generalized version of takeWhile, for example 'takeWhile1' can be
424-- implemented in terms of this:
427-- takeWhile1 cond p = takeWhile cond (takeBetween 1 maxBound p)
430-- Stops: when the condition fails or the collecting parser stops.
431-- Fails: when the collecting parser fails.
435{-# INLINE takeWhileP #-}
436takeWhileP :: -- MonadCatch m =>
437 (a -> Bool) -> Parser m a b -> Parser m a b
438takeWhileP _cond = undefined -- K.toParserK . D.takeWhileP cond
440-- | Collect stream elements until an element fails the predicate. The element
441-- on which the predicate fails is returned back to the input stream.
443-- * Stops - when the predicate fails or the collecting fold stops.
446-- >>> S.parse (PR.takeWhile (== 0) FL.toList) $ S.fromList [0,0,1,0,1]
449-- We can implement a @breakOn@ using 'takeWhile':
452-- breakOn p = takeWhile (not p)
457{-# INLINE takeWhile #-}
458takeWhile :: MonadCatch m => (a -> Bool) -> Fold m a b -> Parser m a b
459takeWhile cond = K.toParserK . D.takeWhile cond
461-- | Like 'takeWhile' but takes at least one element otherwise fails.
465{-# INLINE takeWhile1 #-}
466takeWhile1 :: MonadCatch m => (a -> Bool) -> Fold m a b -> Parser m a b
467takeWhile1 cond = K.toParserK . D.takeWhile1 cond
469-- | Drain the input as long as the predicate succeeds, running the effects and
470-- discarding the results.
472-- This is also called @skipWhile@ in some parsing libraries.
476{-# INLINE drainWhile #-}
477drainWhile :: MonadCatch m => (a -> Bool) -> Parser m a ()
478drainWhile p = takeWhile p FL.drain
480-- | @sliceSepByP cond parser@ parses a slice of the input using @parser@ until
481-- @cond@ succeeds or the parser stops.
483-- This is a generalized slicing parser which can be used to implement other
487-- sliceSepByMax cond n p = sliceSepByP cond (take n p)
488-- sliceSepByBetween cond m n p = sliceSepByP cond (takeBetween m n p)
493{-# INLINABLE sliceSepByP #-}
496 (a -> Bool) -> Parser m a b -> Parser m a b
497sliceSepByP cond = K.toParserK . D.sliceSepByP cond . K.fromParserK
499-- | Like 'sliceSepBy' but does not drop the separator element, instead
500-- separator is emitted as a separate element in the output.
503{-# INLINABLE sliceSepWith #-}
504sliceSepWith :: -- MonadCatch m =>
505 (a -> Bool) -> Fold m a b -> Parser m a b
506sliceSepWith _cond = undefined -- K.toParserK . D.sliceSepBy cond
508-- | Collect stream elements until an elements passes the predicate, return the
509-- last element on which the predicate succeeded back to the input stream. If
510-- the predicate succeeds on the first element itself then the parser does not
511-- terminate there. The succeeding element in the leading position
512-- is treated as a prefix separator which is kept in the output segment.
514-- * Stops - when the predicate succeeds in non-leading position.
517-- S.splitWithPrefix pred f = S.parseMany (PR.sliceBeginWith pred f)
522-- sliceBeginWithOdd ls = S.parse prsr (S.fromList ls)
523-- where prsr = P.sliceBeginWith odd FL.toList
526-- >>> sliceBeginWithOdd [2, 4, 6, 3]
529-- >>> sliceBeginWithOdd [3, 5, 7, 4]
532-- >>> sliceBeginWithOdd [3, 4, 6, 8, 5]
535-- >>> sliceBeginWithOdd []
540{-# INLINABLE sliceBeginWith #-}
543 (a -> Bool) -> Fold m a b -> Parser m a b
544sliceBeginWith cond = K.toParserK . D.sliceBeginWith cond
546-- | Like 'sliceSepBy' but the separator elements can be escaped using an
547-- escape char determined by the second predicate.
550{-# INLINABLE escapedSliceSepBy #-}
551escapedSliceSepBy :: -- MonadCatch m =>
552 (a -> Bool) -> (a -> Bool) -> Fold m a b -> Parser m a b
553escapedSliceSepBy _cond _esc = undefined
554 -- K.toParserK . D.escapedSliceSepBy cond esc
556-- | @escapedFrameBy begin end escape@ parses a string framed using @begin@ and
557-- @end@ as the frame begin and end marker elements and @escape@ as an escaping
558-- element to escape the occurrence of the framing elements within the frame.
559-- Nested frames are allowed, but nesting is removed when parsing.
563-- >>> escapedFrameBy (== '{') (== '}') (== '\\') S.toList $ S.fromList "{hello}"
566-- >>> escapedFrameBy (== '{') (== '}') (== '\\') S.toList $ S.fromList "{hello {world}}"
569-- >>> escapedFrameBy (== '{') (== '}') (== '\\') S.toList $ S.fromList "{hello \\{world\\}}"
572-- >>> escapedFrameBy (== '{') (== '}') (== '\\') S.toList $ S.fromList "{hello {world}"
573-- > ParseError "Unterminated '{'"
576{-# INLINABLE escapedFrameBy #-}
577escapedFrameBy :: -- MonadCatch m =>
578 (a -> Bool) -> (a -> Bool) -> (a -> Bool) -> Fold m a b -> Parser m a b
579escapedFrameBy _begin _end _escape _p = undefined
580 -- K.toParserK . D.frameBy begin end escape p
582-- | Like 'splitOn' but strips leading, trailing, and repeated separators.
583-- Therefore, @".a..b."@ having '.' as the separator would be parsed as
584-- @["a","b"]@. In other words, its like parsing words from whitespace
587-- * Stops - when it finds a word separator after a non-word element
591-- S.wordsBy pred f = S.parseMany (PR.wordBy pred f)
595wordBy :: MonadCatch m => (a -> Bool) -> Fold m a b -> Parser m a b
596wordBy f = K.toParserK . D.wordBy f
598-- | Given an input stream @[a,b,c,...]@ and a comparison function @cmp@, the
599-- parser assigns the element @a@ to the first group, then if @a \`cmp` b@ is
600-- 'True' @b@ is also assigned to the same group. If @a \`cmp` c@ is 'True'
601-- then @c@ is also assigned to the same group and so on. When the comparison
602-- fails the parser is terminated. Each group is folded using the 'Fold' @f@ and
603-- the result of the fold is the result of the parser.
605-- * Stops - when the comparison fails.
610-- > . Stream.parseMany (groupBy eq Fold.toList)
611-- > . Stream.fromList
613-- >>> runGroupsBy (<) []
616-- >>> runGroupsBy (<) [1]
619-- >>> runGroupsBy (<) [3, 5, 4, 1, 2, 0]
620-- [[3, 5, 4], [1, 2], [0]]
624{-# INLINABLE groupBy #-}
625groupBy :: MonadCatch m => (a -> a -> Bool) -> Fold m a b -> Parser m a b
626groupBy eq = K.toParserK . D.groupBy eq
628-- | Unlike 'groupBy' this combinator performs a rolling comparison of two
629-- successive elements in the input stream. Assuming the input stream to the
630-- parser is @[a,b,c,...]@ and the comparison function is @cmp@, the parser
631-- first assigns the element @a@ to the first group, then if @a \`cmp` b@ is
632-- 'True' @b@ is also assigned to the same group. If @b \`cmp` c@ is 'True'
633-- then @c@ is also assigned to the same group and so on. When the comparison
634-- fails the parser is terminated. Each group is folded using the 'Fold' @f@ and
635-- the result of the fold is the result of the parser.
637-- * Stops - when the comparison fails.
640-- > runGroupsByRolling eq =
642-- > . Stream.parseMany (groupByRolling eq Fold.toList)
643-- > . Stream.fromList
645-- >>> runGroupsByRolling (<) []
648-- >>> runGroupsByRolling (<) [1]
651-- >>> runGroupsByRolling (<) [3, 5, 4, 1, 2, 0]
652-- [[3, 5], [4], [1, 2], [0]]
656{-# INLINABLE groupByRolling #-}
657groupByRolling :: MonadCatch m => (a -> a -> Bool) -> Fold m a b -> Parser m a b
658groupByRolling eq = K.toParserK . D.groupByRolling eq
660-- | Match the given sequence of elements using the given comparison function.
662-- >>> S.parse $ S.eqBy (==) "string" $ S.fromList "string"
664-- >>> S.parse $ S.eqBy (==) "mismatch" $ S.fromList "match"
665-- > *** Exception: ParseError "eqBy: failed, yet to match 7 elements"
670eqBy :: MonadCatch m => (a -> a -> Bool) -> [a] -> Parser m a ()
671eqBy cmp = K.toParserK . D.eqBy cmp
673-------------------------------------------------------------------------------
675-------------------------------------------------------------------------------
677-- | Sequential parser application. Apply two parsers sequentially to an input
678-- stream. The input is provided to the first parser, when it is done the
679-- remaining input is provided to the second parser. If both the parsers
680-- succeed their outputs are combined using the supplied function. The
681-- operation fails if any of the parsers fail.
683-- Note: This is a parsing dual of appending streams using
684-- 'Streamly.Prelude.serial', it splits the streams using two parsers and zips
687-- This implementation is strict in the second argument, therefore, the
688-- following will fail:
690-- >>> S.parse (PR.splitWith const (PR.satisfy (> 0)) undefined) $ S.fromList [1]
692-- Compare with 'Applicative' instance method '<*>'. This implementation allows
693-- stream fusion but has quadratic complexity. This can fuse with other
694-- operations and can be faster than 'Applicative' instance for small number
695-- (less than 8) of compositions.
699{-# INLINE splitWith #-}
700splitWith :: MonadCatch m
701 => (a -> b -> c) -> Parser m x a -> Parser m x b -> Parser m x c
703 K.toParserK $ D.splitWith f (K.fromParserK p1) (K.fromParserK p2)
705-- | Sequential parser application ignoring the output of the first parser.
706-- Apply two parsers sequentially to an input stream. The input is provided to
707-- the first parser, when it is done the remaining input is provided to the
708-- second parser. The output of the parser is the output of the second parser.
709-- The operation fails if any of the parsers fail.
711-- This implementation is strict in the second argument, therefore, the
712-- following will fail:
714-- >>> S.parse (split_ (PR.satisfy (> 0)) undefined) $ S.fromList [1]
716-- Compare with 'Applicative' instance method '*>'. This implementation allows
717-- stream fusion but has quadratic complexity. This can fuse with other
718-- operations, and can be faster than 'Applicative' instance for small
719-- number (less than 8) of compositions.
724split_ :: MonadCatch m => Parser m x a -> Parser m x b -> Parser m x b
725split_ p1 p2 = K.toParserK $ D.split_ (K.fromParserK p1) (K.fromParserK p2)
727-- | @teeWith f p1 p2@ distributes its input to both @p1@ and @p2@ until both
728-- of them succeed or anyone of them fails and combines their output using @f@.
729-- The parser succeeds if both the parsers succeed.
733{-# INLINE teeWith #-}
734teeWith :: MonadCatch m
735 => (a -> b -> c) -> Parser m x a -> Parser m x b -> Parser m x c
737 K.toParserK $ D.teeWith f (K.fromParserK p1) (K.fromParserK p2)
739-- | Like 'teeWith' but ends parsing and zips the results, if available,
740-- whenever the first parser ends.
744{-# INLINE teeWithFst #-}
745teeWithFst :: MonadCatch m
746 => (a -> b -> c) -> Parser m x a -> Parser m x b -> Parser m x c
748 K.toParserK $ D.teeWithFst f (K.fromParserK p1) (K.fromParserK p2)
750-- | Like 'teeWith' but ends parsing and zips the results, if available,
751-- whenever any of the parsers ends or fails.
755{-# INLINE teeWithMin #-}
756teeWithMin :: MonadCatch m
757 => (a -> b -> c) -> Parser m x a -> Parser m x b -> Parser m x c
759 K.toParserK $ D.teeWithMin f (K.fromParserK p1) (K.fromParserK p2)
761-- | Sequential alternative. Apply the input to the first parser and return the
762-- result if the parser succeeds. If the first parser fails then backtrack and
763-- apply the same input to the second parser and return the result.
765-- Note: This implementation is not lazy in the second argument. The following
768-- >>> S.parse (PR.satisfy (> 0) `PR.alt` undefined) $ S.fromList [1..10]
770-- Compare with 'Alternative' instance method '<|>'. This implementation allows
771-- stream fusion but has quadratic complexity. This can fuse with other
772-- operations and can be much faster than 'Alternative' instance for small
773-- number (less than 8) of alternatives.
778alt :: MonadCatch m => Parser m x a -> Parser m x a -> Parser m x a
779alt p1 p2 = K.toParserK $ D.alt (K.fromParserK p1) (K.fromParserK p2)
781-- | Shortest alternative. Apply both parsers in parallel but choose the result
782-- from the one which consumed least input i.e. take the shortest succeeding
787{-# INLINE shortest #-}
788shortest :: MonadCatch m
789 => Parser m x a -> Parser m x a -> Parser m x a
790shortest p1 p2 = K.toParserK $ D.shortest (K.fromParserK p1) (K.fromParserK p2)
792-- | Longest alternative. Apply both parsers in parallel but choose the result
793-- from the one which consumed more input i.e. take the longest succeeding
798{-# INLINE longest #-}
799longest :: MonadCatch m
800 => Parser m x a -> Parser m x a -> Parser m x a
801longest p1 p2 = K.toParserK $ D.longest (K.fromParserK p1) (K.fromParserK p2)
803-- | Run a parser without consuming the input.
807{-# INLINE lookAhead #-}
808lookAhead :: MonadCatch m => Parser m a b -> Parser m a b
809lookAhead p = K.toParserK $ D.lookAhead $ K.fromParserK p
811-------------------------------------------------------------------------------
813-------------------------------------------------------------------------------
815-- To deinterleave we can chain two parsers one behind the other. The input is
816-- given to the first parser and the input definitively rejected by the first
817-- parser is given to the second parser.
819-- We can either have the parsers themselves buffer the input or use the shared
820-- global buffer to hold it until none of the parsers need it. When the first
821-- parser returns Skip (i.e. rewind) we let the second parser consume the
822-- rejected input and when it is done we move the cursor forward to the first
823-- parser again. This will require a "move forward" command as well.
825-- To implement grep we can use three parsers, one to find the pattern, one
826-- to store the context behind the pattern and one to store the context in
827-- front of the pattern. When a match occurs we need to emit the accumulator of
828-- all the three parsers. One parser can count the line numbers to provide the
831-- | Apply two parsers alternately to an input stream. The input stream is
832-- considered an interleaving of two patterns. The two parsers represent the
835-- This undoes a "gintercalate" of two streams.
839{-# INLINE deintercalate #-}
842 Fold m a y -> Parser m x a
843 -> Fold m b z -> Parser m x b
845deintercalate = undefined
847-------------------------------------------------------------------------------
848-- Sequential Collection
849-------------------------------------------------------------------------------
851-- | @concatSequence f t@ collects sequential parses of parsers in the
852-- container @t@ using the fold @f@. Fails if the input ends or any of the
855-- This is same as 'Data.Traversable.sequence' but more efficient.
859{-# INLINE concatSequence #-}
862 Fold m b c -> t (Parser m a b) -> Parser m a c
863concatSequence _f _p = undefined
865-- | Map a 'Parser' returning function on the result of a 'Parser'.
867-- Compare with 'Monad' instance method '>>='. This implementation allows
868-- stream fusion but has quadratic complexity. This can fuse with other
869-- operations and can be much faster than 'Monad' instance for small number
870-- (less than 8) of compositions.
874{-# INLINE concatMap #-}
875concatMap :: MonadCatch m
876 => (b -> Parser m a c) -> Parser m a b -> Parser m a c
877concatMap f p = K.toParserK $ D.concatMap (K.fromParserK . f) (K.fromParserK p)
879-------------------------------------------------------------------------------
880-- Alternative Collection
881-------------------------------------------------------------------------------
883-- | @choice parsers@ applies the @parsers@ in order and returns the first
886-- This is same as 'asum' but more efficient.
893 t (Parser m a b) -> Parser m a b
894choice _ps = undefined
896-------------------------------------------------------------------------------
897-- Sequential Repetition
898-------------------------------------------------------------------------------
901-- TODO "many" is essentially a Fold because it cannot fail. So it can be
902-- downgraded to a Fold. Or we can make the return type a Fold instead and
903-- upgrade that to a parser when needed.
905-- | Like 'many' but uses a 'Parser' instead of a 'Fold' to collect the
906-- results. Parsing stops or fails if the collecting parser stops or fails.
911manyP :: -- MonadCatch m =>
912 Parser m b c -> Parser m a b -> Parser m a c
913manyP _f _p = undefined -- K.toParserK $ D.manyP f (K.fromParserK p)
915-- | Collect zero or more parses. Apply the supplied parser repeatedly on the
916-- input stream and push the parse results to a downstream fold.
918-- Stops: when the downstream fold stops or the parser fails.
919-- Fails: never, produces zero or more results.
921-- Compare with 'Control.Applicative.many'.
926many :: MonadCatch m => Fold m b c -> Parser m a b -> Parser m a c
927many f p = K.toParserK $ D.many f (K.fromParserK p)
928-- many = countBetween 0 maxBound
930-- Note: many1 would perhaps be a better name for this and consistent with
931-- other names like takeWhile1. But we retain the name "some" for
934-- | Collect one or more parses. Apply the supplied parser repeatedly on the
935-- input stream and push the parse results to a downstream fold.
937-- Stops: when the downstream fold stops or the parser fails.
938-- Fails: if it stops without producing a single result.
940-- @some fld parser = manyP (takeGE 1 fld) parser@
942-- Compare with 'Control.Applicative.some'.
947some :: MonadCatch m => Fold m b c -> Parser m a b -> Parser m a c
948some f p = K.toParserK $ D.some f (K.fromParserK p)
949-- some f p = manyP (takeGE 1 f) p
950-- many = countBetween 1 maxBound
952-- | @countBetween m n f p@ collects between @m@ and @n@ sequential parses of
953-- parser @p@ using the fold @f@. Stop after collecting @n@ results. Fails if
954-- the input ends or the parser fails before @m@ results are collected.
958{-# INLINE countBetween #-}
961 Int -> Int -> Fold m b c -> Parser m a b -> Parser m a c
962countBetween _m _n _f = undefined
963-- countBetween m n f p = manyP (takeBetween m n f) p
965-- | @count n f p@ collects exactly @n@ sequential parses of parser @p@ using
966-- the fold @f@. Fails if the input ends or the parser fails before @n@
967-- results are collected.
974 Int -> Fold m b c -> Parser m a b -> Parser m a c
975count n = countBetween n n
976-- count n f p = manyP (takeEQ n f) p
978-- | Like 'manyTill' but uses a 'Parser' to collect the results instead of a
979-- 'Fold'. Parsing stops or fails if the collecting parser stops or fails.
981-- We can implemnent parsers like the following using 'manyTillP':
984-- countBetweenTill m n f p = manyTillP (takeBetween m n f) p
989{-# INLINE manyTillP #-}
990manyTillP :: -- MonadCatch m =>
991 Parser m b c -> Parser m a b -> Parser m a x -> Parser m a c
992manyTillP _f _p1 _p2 = undefined
993 -- K.toParserK $ D.manyTillP f (K.fromParserK p1) (K.fromParserK p2)
995-- | @manyTill f collect test@ tries the parser @test@ on the input, if @test@
996-- fails it backtracks and tries @collect@, after @collect@ succeeds @test@ is
997-- tried again and so on. The parser stops when @test@ succeeds. The output of
998-- @test@ is discarded and the output of @collect@ is accumulated by the
999-- supplied fold. The parser fails if @collect@ fails.
1001-- Stops when the fold @f@ stops.
1005{-# INLINE manyTill #-}
1006manyTill :: MonadCatch m
1007 => Fold m b c -> Parser m a b -> Parser m a x -> Parser m a c
1009 K.toParserK $ D.manyTill f (K.fromParserK p1) (K.fromParserK p2)
1011-- | @manyThen f collect recover@ repeats the parser @collect@ on the input and
1012-- collects the output in the supplied fold. If the the parser @collect@ fails,
1013-- parser @recover@ is run until it stops and then we start repeating the
1014-- parser @collect@ again. The parser fails if the recovery parser fails.
1016-- For example, this can be used to find a key frame in a video stream after an
1021{-# INLINE manyThen #-}
1022manyThen :: -- (Foldable t, MonadCatch m) =>
1023 Fold m b c -> Parser m a b -> Parser m a x -> Parser m a c
1024manyThen _f _parser _recover = undefined
1026-------------------------------------------------------------------------------
1027-- Interleaving a collection of parsers
1028-------------------------------------------------------------------------------
1030-- | Apply a collection of parsers to an input stream in a round robin fashion.
1031-- Each parser is applied until it stops and then we repeat starting with the
1032-- the first parser again.
1036{-# INLINE roundRobin #-}
1037roundRobin :: -- (Foldable t, MonadCatch m) =>
1038 Fold m b c -> t (Parser m a b) -> Parser m a c
1039roundRobin _f _ps = undefined
1041-------------------------------------------------------------------------------
1042-- Repeated Alternatives
1043-------------------------------------------------------------------------------
1045-- | Keep trying a parser up to a maximum of @n@ failures. When the parser
1046-- fails the input consumed till now is dropped and the new instance is tried
1047-- on the fresh input.
1051{-# INLINE retryMaxTotal #-}
1052retryMaxTotal :: -- (MonadCatch m) =>
1053 Int -> Fold m b c -> Parser m a b -> Parser m a c
1054retryMaxTotal _n _f _p = undefined
1056-- | Like 'retryMaxTotal' but aborts after @n@ successive failures.
1060{-# INLINE retryMaxSuccessive #-}
1061retryMaxSuccessive :: -- (MonadCatch m) =>
1062 Int -> Fold m b c -> Parser m a b -> Parser m a c
1063retryMaxSuccessive _n _f _p = undefined
1065-- | Keep trying a parser until it succeeds. When the parser fails the input
1066-- consumed till now is dropped and the new instance is tried on the fresh
1072retry :: -- (MonadCatch m) =>
1073 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