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 it is kept in the
511-- stream and we continue collecting. The succeeding element is treated as a
512-- prefix separator which is kept in the output segement.
514-- * Stops - when the predicate succeeds in non-leading position.
517-- S.splitWithPrefix pred f = S.parseMany (PR.sliceBeginWith pred f)
521{-# INLINABLE sliceBeginWith #-}
524 (a -> Bool) -> Fold m a b -> Parser m a b
525sliceBeginWith = undefined
527-- | Like 'sliceSepBy' but the separator elements can be escaped using an
528-- escape char determined by the second predicate.
531{-# INLINABLE escapedSliceSepBy #-}
532escapedSliceSepBy :: -- MonadCatch m =>
533 (a -> Bool) -> (a -> Bool) -> Fold m a b -> Parser m a b
534escapedSliceSepBy _cond _esc = undefined
535 -- K.toParserK . D.escapedSliceSepBy cond esc
537-- | @escapedFrameBy begin end escape@ parses a string framed using @begin@ and
538-- @end@ as the frame begin and end marker elements and @escape@ as an escaping
539-- element to escape the occurrence of the framing elements within the frame.
540-- Nested frames are allowed, but nesting is removed when parsing.
544-- >>> escapedFrameBy (== '{') (== '}') (== '\\') S.toList $ S.fromList "{hello}"
547-- >>> escapedFrameBy (== '{') (== '}') (== '\\') S.toList $ S.fromList "{hello {world}}"
550-- >>> escapedFrameBy (== '{') (== '}') (== '\\') S.toList $ S.fromList "{hello \\{world\\}}"
553-- >>> escapedFrameBy (== '{') (== '}') (== '\\') S.toList $ S.fromList "{hello {world}"
554-- > ParseError "Unterminated '{'"
557{-# INLINABLE escapedFrameBy #-}
558escapedFrameBy :: -- MonadCatch m =>
559 (a -> Bool) -> (a -> Bool) -> (a -> Bool) -> Fold m a b -> Parser m a b
560escapedFrameBy _begin _end _escape _p = undefined
561 -- K.toParserK . D.frameBy begin end escape p
563-- | Like 'splitOn' but strips leading, trailing, and repeated separators.
564-- Therefore, @".a..b."@ having '.' as the separator would be parsed as
565-- @["a","b"]@. In other words, its like parsing words from whitespace
568-- * Stops - when it finds a word separator after a non-word element
572-- S.wordsBy pred f = S.parseMany (PR.wordBy pred f)
576wordBy :: MonadCatch m => (a -> Bool) -> Fold m a b -> Parser m a b
577wordBy f = K.toParserK . D.wordBy f
579-- | Given an input stream @[a,b,c,...]@ and a comparison function @cmp@, the
580-- parser assigns the element @a@ to the first group, then if @a \`cmp` b@ is
581-- 'True' @b@ is also assigned to the same group. If @a \`cmp` c@ is 'True'
582-- then @c@ is also assigned to the same group and so on. When the comparison
583-- fails the parser is terminated. Each group is folded using the 'Fold' @f@ and
584-- the result of the fold is the result of the parser.
586-- * Stops - when the comparison fails.
591-- > . Stream.parseMany (groupBy eq Fold.toList)
592-- > . Stream.fromList
594-- >>> runGroupsBy (<) []
597-- >>> runGroupsBy (<) [1]
600-- >>> runGroupsBy (<) [3, 5, 4, 1, 2, 0]
601-- [[3, 5, 4], [1, 2], [0]]
605{-# INLINABLE groupBy #-}
606groupBy :: MonadCatch m => (a -> a -> Bool) -> Fold m a b -> Parser m a b
607groupBy eq = K.toParserK . D.groupBy eq
609-- | Unlike 'groupBy' this combinator performs a rolling comparison of two
610-- successive elements in the input stream. Assuming the input stream to the
611-- parser is @[a,b,c,...]@ and the comparison function is @cmp@, the parser
612-- first assigns the element @a@ to the first group, then if @a \`cmp` b@ is
613-- 'True' @b@ is also assigned to the same group. If @b \`cmp` c@ is 'True'
614-- then @c@ is also assigned to the same group and so on. When the comparison
615-- fails the parser is terminated. Each group is folded using the 'Fold' @f@ and
616-- the result of the fold is the result of the parser.
618-- * Stops - when the comparison fails.
621-- > runGroupsByRolling eq =
623-- > . Stream.parseMany (groupByRolling eq Fold.toList)
624-- > . Stream.fromList
626-- >>> runGroupsByRolling (<) []
629-- >>> runGroupsByRolling (<) [1]
632-- >>> runGroupsByRolling (<) [3, 5, 4, 1, 2, 0]
633-- [[3, 5], [4], [1, 2], [0]]
637{-# INLINABLE groupByRolling #-}
638groupByRolling :: MonadCatch m => (a -> a -> Bool) -> Fold m a b -> Parser m a b
639groupByRolling eq = K.toParserK . D.groupByRolling eq
641-- | Match the given sequence of elements using the given comparison function.
643-- >>> S.parse $ S.eqBy (==) "string" $ S.fromList "string"
645-- >>> S.parse $ S.eqBy (==) "mismatch" $ S.fromList "match"
646-- > *** Exception: ParseError "eqBy: failed, yet to match 7 elements"
651eqBy :: MonadCatch m => (a -> a -> Bool) -> [a] -> Parser m a ()
652eqBy cmp = K.toParserK . D.eqBy cmp
654-------------------------------------------------------------------------------
656-------------------------------------------------------------------------------
658-- | Sequential parser application. Apply two parsers sequentially to an input
659-- stream. The input is provided to the first parser, when it is done the
660-- remaining input is provided to the second parser. If both the parsers
661-- succeed their outputs are combined using the supplied function. The
662-- operation fails if any of the parsers fail.
664-- Note: This is a parsing dual of appending streams using
665-- 'Streamly.Prelude.serial', it splits the streams using two parsers and zips
668-- This implementation is strict in the second argument, therefore, the
669-- following will fail:
671-- >>> S.parse (PR.splitWith const (PR.satisfy (> 0)) undefined) $ S.fromList [1]
673-- Compare with 'Applicative' instance method '<*>'. This implementation allows
674-- stream fusion but has quadratic complexity. This can fuse with other
675-- operations and can be faster than 'Applicative' instance for small number
676-- (less than 8) of compositions.
680{-# INLINE splitWith #-}
681splitWith :: MonadCatch m
682 => (a -> b -> c) -> Parser m x a -> Parser m x b -> Parser m x c
684 K.toParserK $ D.splitWith f (K.fromParserK p1) (K.fromParserK p2)
686-- | Sequential parser application ignoring the output of the first parser.
687-- Apply two parsers sequentially to an input stream. The input is provided to
688-- the first parser, when it is done the remaining input is provided to the
689-- second parser. The output of the parser is the output of the second parser.
690-- The operation fails if any of the parsers fail.
692-- This implementation is strict in the second argument, therefore, the
693-- following will fail:
695-- >>> S.parse (split_ (PR.satisfy (> 0)) undefined) $ S.fromList [1]
697-- Compare with 'Applicative' instance method '*>'. This implementation allows
698-- stream fusion but has quadratic complexity. This can fuse with other
699-- operations, and can be faster than 'Applicative' instance for small
700-- number (less than 8) of compositions.
705split_ :: MonadCatch m => Parser m x a -> Parser m x b -> Parser m x b
706split_ p1 p2 = K.toParserK $ D.split_ (K.fromParserK p1) (K.fromParserK p2)
708-- | @teeWith f p1 p2@ distributes its input to both @p1@ and @p2@ until both
709-- of them succeed or anyone of them fails and combines their output using @f@.
710-- The parser succeeds if both the parsers succeed.
714{-# INLINE teeWith #-}
715teeWith :: MonadCatch m
716 => (a -> b -> c) -> Parser m x a -> Parser m x b -> Parser m x c
718 K.toParserK $ D.teeWith f (K.fromParserK p1) (K.fromParserK p2)
720-- | Like 'teeWith' but ends parsing and zips the results, if available,
721-- whenever the first parser ends.
725{-# INLINE teeWithFst #-}
726teeWithFst :: MonadCatch m
727 => (a -> b -> c) -> Parser m x a -> Parser m x b -> Parser m x c
729 K.toParserK $ D.teeWithFst f (K.fromParserK p1) (K.fromParserK p2)
731-- | Like 'teeWith' but ends parsing and zips the results, if available,
732-- whenever any of the parsers ends or fails.
736{-# INLINE teeWithMin #-}
737teeWithMin :: MonadCatch m
738 => (a -> b -> c) -> Parser m x a -> Parser m x b -> Parser m x c
740 K.toParserK $ D.teeWithMin f (K.fromParserK p1) (K.fromParserK p2)
742-- | Sequential alternative. Apply the input to the first parser and return the
743-- result if the parser succeeds. If the first parser fails then backtrack and
744-- apply the same input to the second parser and return the result.
746-- Note: This implementation is not lazy in the second argument. The following
749-- >>> S.parse (PR.satisfy (> 0) `PR.alt` undefined) $ S.fromList [1..10]
751-- Compare with 'Alternative' instance method '<|>'. This implementation allows
752-- stream fusion but has quadratic complexity. This can fuse with other
753-- operations and can be much faster than 'Alternative' instance for small
754-- number (less than 8) of alternatives.
759alt :: MonadCatch m => Parser m x a -> Parser m x a -> Parser m x a
760alt p1 p2 = K.toParserK $ D.alt (K.fromParserK p1) (K.fromParserK p2)
762-- | Shortest alternative. Apply both parsers in parallel but choose the result
763-- from the one which consumed least input i.e. take the shortest succeeding
768{-# INLINE shortest #-}
769shortest :: MonadCatch m
770 => Parser m x a -> Parser m x a -> Parser m x a
771shortest p1 p2 = K.toParserK $ D.shortest (K.fromParserK p1) (K.fromParserK p2)
773-- | Longest alternative. Apply both parsers in parallel but choose the result
774-- from the one which consumed more input i.e. take the longest succeeding
779{-# INLINE longest #-}
780longest :: MonadCatch m
781 => Parser m x a -> Parser m x a -> Parser m x a
782longest p1 p2 = K.toParserK $ D.longest (K.fromParserK p1) (K.fromParserK p2)
784-- | Run a parser without consuming the input.
788{-# INLINE lookAhead #-}
789lookAhead :: MonadCatch m => Parser m a b -> Parser m a b
790lookAhead p = K.toParserK $ D.lookAhead $ K.fromParserK p
792-------------------------------------------------------------------------------
794-------------------------------------------------------------------------------
796-- To deinterleave we can chain two parsers one behind the other. The input is
797-- given to the first parser and the input definitively rejected by the first
798-- parser is given to the second parser.
800-- We can either have the parsers themselves buffer the input or use the shared
801-- global buffer to hold it until none of the parsers need it. When the first
802-- parser returns Skip (i.e. rewind) we let the second parser consume the
803-- rejected input and when it is done we move the cursor forward to the first
804-- parser again. This will require a "move forward" command as well.
806-- To implement grep we can use three parsers, one to find the pattern, one
807-- to store the context behind the pattern and one to store the context in
808-- front of the pattern. When a match occurs we need to emit the accumulator of
809-- all the three parsers. One parser can count the line numbers to provide the
812-- | Apply two parsers alternately to an input stream. The input stream is
813-- considered an interleaving of two patterns. The two parsers represent the
816-- This undoes a "gintercalate" of two streams.
820{-# INLINE deintercalate #-}
823 Fold m a y -> Parser m x a
824 -> Fold m b z -> Parser m x b
826deintercalate = undefined
828-------------------------------------------------------------------------------
829-- Sequential Collection
830-------------------------------------------------------------------------------
832-- | @concatSequence f t@ collects sequential parses of parsers in the
833-- container @t@ using the fold @f@. Fails if the input ends or any of the
836-- This is same as 'Data.Traversable.sequence' but more efficient.
840{-# INLINE concatSequence #-}
843 Fold m b c -> t (Parser m a b) -> Parser m a c
844concatSequence _f _p = undefined
846-- | Map a 'Parser' returning function on the result of a 'Parser'.
848-- Compare with 'Monad' instance method '>>='. This implementation allows
849-- stream fusion but has quadratic complexity. This can fuse with other
850-- operations and can be much faster than 'Monad' instance for small number
851-- (less than 8) of compositions.
855{-# INLINE concatMap #-}
856concatMap :: MonadCatch m
857 => (b -> Parser m a c) -> Parser m a b -> Parser m a c
858concatMap f p = K.toParserK $ D.concatMap (K.fromParserK . f) (K.fromParserK p)
860-------------------------------------------------------------------------------
861-- Alternative Collection
862-------------------------------------------------------------------------------
864-- | @choice parsers@ applies the @parsers@ in order and returns the first
867-- This is same as 'asum' but more efficient.
874 t (Parser m a b) -> Parser m a b
875choice _ps = undefined
877-------------------------------------------------------------------------------
878-- Sequential Repetition
879-------------------------------------------------------------------------------
882-- TODO "many" is essentially a Fold because it cannot fail. So it can be
883-- downgraded to a Fold. Or we can make the return type a Fold instead and
884-- upgrade that to a parser when needed.
886-- | Like 'many' but uses a 'Parser' instead of a 'Fold' to collect the
887-- results. Parsing stops or fails if the collecting parser stops or fails.
892manyP :: -- MonadCatch m =>
893 Parser m b c -> Parser m a b -> Parser m a c
894manyP _f _p = undefined -- K.toParserK $ D.manyP f (K.fromParserK p)
896-- | Collect zero or more parses. Apply the supplied parser repeatedly on the
897-- input stream and push the parse results to a downstream fold.
899-- Stops: when the downstream fold stops or the parser fails.
900-- Fails: never, produces zero or more results.
902-- Compare with 'Control.Applicative.many'.
907many :: MonadCatch m => Fold m b c -> Parser m a b -> Parser m a c
908many f p = K.toParserK $ D.many f (K.fromParserK p)
909-- many = countBetween 0 maxBound
911-- Note: many1 would perhaps be a better name for this and consistent with
912-- other names like takeWhile1. But we retain the name "some" for
915-- | Collect one 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: if it stops without producing a single result.
921-- @some fld parser = many (takeGE 1 fld) parser@
923-- Compare with 'Control.Applicative.some'.
928some :: MonadCatch m => Fold m b c -> Parser m a b -> Parser m a c
929some f p = K.toParserK $ D.some f (K.fromParserK p)
930-- some f p = manyP (takeGE 1 f) p
931-- many = countBetween 1 maxBound
933-- | @countBetween m n f p@ collects between @m@ and @n@ sequential parses of
934-- parser @p@ using the fold @f@. Stop after collecting @n@ results. Fails if
935-- the input ends or the parser fails before @m@ results are collected.
939{-# INLINE countBetween #-}
942 Int -> Int -> Fold m b c -> Parser m a b -> Parser m a c
943countBetween _m _n _f = undefined
944-- countBetween m n f p = manyP (takeBetween m n f) p
946-- | @count n f p@ collects exactly @n@ sequential parses of parser @p@ using
947-- the fold @f@. Fails if the input ends or the parser fails before @n@
948-- results are collected.
955 Int -> Fold m b c -> Parser m a b -> Parser m a c
956count n = countBetween n n
957-- count n f p = manyP (takeEQ n f) p
959-- | Like 'manyTill' but uses a 'Parser' to collect the results instead of a
960-- 'Fold'. Parsing stops or fails if the collecting parser stops or fails.
962-- We can implemnent parsers like the following using 'manyTillP':
965-- countBetweenTill m n f p = manyTillP (takeBetween m n f) p
970{-# INLINE manyTillP #-}
971manyTillP :: -- MonadCatch m =>
972 Parser m b c -> Parser m a b -> Parser m a x -> Parser m a c
973manyTillP _f _p1 _p2 = undefined
974 -- K.toParserK $ D.manyTillP f (K.fromParserK p1) (K.fromParserK p2)
976-- | @manyTill f collect test@ tries the parser @test@ on the input, if @test@
977-- fails it backtracks and tries @collect@, after @collect@ succeeds @test@ is
978-- tried again and so on. The parser stops when @test@ succeeds. The output of
979-- @test@ is discarded and the output of @collect@ is accumulated by the
980-- supplied fold. The parser fails if @collect@ fails.
982-- Stops when the fold @f@ stops.
986{-# INLINE manyTill #-}
987manyTill :: MonadCatch m
988 => Fold m b c -> Parser m a b -> Parser m a x -> Parser m a c
990 K.toParserK $ D.manyTill f (K.fromParserK p1) (K.fromParserK p2)
992-- | @manyThen f collect recover@ repeats the parser @collect@ on the input and
993-- collects the output in the supplied fold. If the the parser @collect@ fails,
994-- parser @recover@ is run until it stops and then we start repeating the
995-- parser @collect@ again. The parser fails if the recovery parser fails.
997-- For example, this can be used to find a key frame in a video stream after an
1002{-# INLINE manyThen #-}
1003manyThen :: -- (Foldable t, MonadCatch m) =>
1004 Fold m b c -> Parser m a b -> Parser m a x -> Parser m a c
1005manyThen _f _parser _recover = undefined
1007-------------------------------------------------------------------------------
1008-- Interleaving a collection of parsers
1009-------------------------------------------------------------------------------
1011-- | Apply a collection of parsers to an input stream in a round robin fashion.
1012-- Each parser is applied until it stops and then we repeat starting with the
1013-- the first parser again.
1017{-# INLINE roundRobin #-}
1018roundRobin :: -- (Foldable t, MonadCatch m) =>
1019 Fold m b c -> t (Parser m a b) -> Parser m a c
1020roundRobin _f _ps = undefined
1022-------------------------------------------------------------------------------
1023-- Repeated Alternatives
1024-------------------------------------------------------------------------------
1026-- | Keep trying a parser up to a maximum of @n@ failures. When the parser
1027-- fails the input consumed till now is dropped and the new instance is tried
1028-- on the fresh input.
1032{-# INLINE retryMaxTotal #-}
1033retryMaxTotal :: -- (MonadCatch m) =>
1034 Int -> Fold m b c -> Parser m a b -> Parser m a c
1035retryMaxTotal _n _f _p = undefined
1037-- | Like 'retryMaxTotal' but aborts after @n@ successive failures.
1041{-# INLINE retryMaxSuccessive #-}
1042retryMaxSuccessive :: -- (MonadCatch m) =>
1043 Int -> Fold m b c -> Parser m a b -> Parser m a c
1044retryMaxSuccessive _n _f _p = undefined
1046-- | Keep trying a parser until it succeeds. When the parser fails the input
1047-- consumed till now is dropped and the new instance is tried on the fresh
1053retry :: -- (MonadCatch m) =>
1054 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