on e4e1d25 help sign in
1074 lines 35 kB history raw
1{-# OPTIONS_GHC -Wno-orphans #-}
3-- |
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
9-- Portability : GHC
10--
11-- Fast backtracking parsers with stream fusion and native streaming
12-- capability.
13--
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:
20--
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.
27--
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.
32--
33-- = Errors
34--
35-- Failing parsers in this module throw the 'D.ParseError' exception.
36--
37-- = Naming
38--
39-- As far as possible, try that the names of the combinators in this module are
40-- consistent with:
41--
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
49 (
50 K.Parser (..)
51 , D.ParseError (..)
52 , D.Step (..)
54 -- First order parsers
55 -- * Accumulators
56 , fromFold
57 , yield
58 , yieldM
59 , die
60 , dieM
62 -- * Element parsers
63 , peek
64 , eof
65 , satisfy
66 , maybe
67 , either
69 -- * Sequence parsers
70 --
71 -- | Parsers chained in series, if one parser terminates the composition
72 -- terminates.
74 -- | Grab a sequence of input elements without inspecting them
75 , takeBetween
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
81 , lookAhead
82 , takeWhileP
83 , takeWhile
84 -- $takeWhile
85 , takeWhile1
86 , drainWhile
88 , sliceSepByP
89 , sliceBeginWith
90 , sliceSepWith
91 , escapedSliceSepBy
92 , escapedFrameBy
93 , wordBy
94 , groupBy
95 , groupByRolling
96 , eqBy
97 -- | Unimplemented
98 --
99 -- @
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
103 -- @
105 -- Second order parsers (parsers using parsers)
106 -- * Binary Combinators
108 -- ** Sequential Applicative
109 , splitWith
110 , split_
112 -- ** Parallel Applicatives
113 , teeWith
114 , teeWithFst
115 , teeWithMin
116 -- , teeTill -- like manyTill but parallel
118 -- ** Sequential Interleaving
119 -- Use two folds, run a primary parser, its rejected values go to the
120 -- secondary parser.
121 , deintercalate
123 -- ** Sequential Alternative
124 , alt
126 -- ** Parallel Alternatives
127 , shortest
128 , longest
129 -- , fastest
131 -- * N-ary Combinators
132 -- ** Sequential Collection
133 , concatSequence
134 , concatMap
136 -- ** Sequential Repetition
137 , count
138 , countBetween
140 , manyP
141 , many
142 , some
143 , manyTillP
144 , manyTill
145 , manyThen
147 -- ** Special cases
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.
152 --
153 -- We can instead implement these as special cases of deintercalate.
154 --
155 -- @
156 -- , endBy
157 -- , sepBy
158 -- , sepEndBy
159 -- , beginBy
160 -- , sepBeginBy
161 -- , sepAroundBy
162 -- @
164 -- * Distribution
165 --
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
174 -- |
175 --
176 -- 1. Round robin
177 -- 2. Priority based
178 , roundRobin
180 -- ** Collection of Alternatives
181 -- | Unimplemented
182 --
183 -- @
184 -- , shortestN
185 -- , longestN
186 -- , fastestN -- first N successful in time
187 -- , choiceN -- first N successful in position
188 -- @
189 , choice -- first successful in position
191 -- ** Repeated Alternatives
192 , retryMaxTotal
193 , retryMaxSuccessive
194 , retry
195 )
196where
198import Control.Monad.Catch (MonadCatch)
199import Prelude
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-------------------------------------------------------------------------------
212--
213-- | Make a 'Parser' from a 'Fold'.
214--
215-- /Internal/
216--
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-------------------------------------------------------------------------------
224--
225-- This is the dual of stream "yield".
226--
227-- | A parser that always yields a pure value without consuming any input.
228--
229-- /Internal/
230--
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".
238--
239-- | A parser that always yields the result of an effectful action without
240-- consuming any input.
241--
242-- /Internal/
243--
244{-# INLINE yieldM #-}
245yieldM :: MonadCatch m => m b -> Parser m a b
246yieldM = K.yieldM -- K.toParserK . D.yieldM
248-- This is the dual of "nil".
249--
250-- | A parser that always fails with an error message without consuming
251-- any input.
252--
253-- /Internal/
254--
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".
262--
263-- | A parser that always fails with an effectful error message and without
264-- consuming any input.
265--
266-- /Internal/
267--
268{-# INLINE dieM #-}
269dieM :: MonadCatch m => m String -> Parser m a b
270dieM = K.toParserK . D.dieM
272-------------------------------------------------------------------------------
273-- Failing Parsers
274-------------------------------------------------------------------------------
276-- | Peek the head element of a stream, without consuming it. Fails if it
277-- encounters end of input.
278--
279-- >>> S.parse ((,) <$> PR.peek <*> PR.satisfy (> 0)) $ S.fromList [1]
280-- (1,1)
281--
282-- @
283-- peek = lookAhead (satisfy True)
284-- @
285--
286-- /Internal/
287--
288{-# INLINE peek #-}
289peek :: MonadCatch m => Parser m a a
290peek = K.toParserK D.peek
292-- | Succeeds if we are at the end of input, fails otherwise.
293--
294-- >>> S.parse ((,) <$> PR.satisfy (> 0) <*> PR.eof) $ S.fromList [1]
295-- > (1,())
296--
297-- /Internal/
298--
299{-# INLINE eof #-}
300eof :: MonadCatch m => Parser m a ()
301eof = K.toParserK D.eof
303-- | Returns the next element if it passes the predicate, fails otherwise.
304--
305-- >>> S.parse (PR.satisfy (== 1)) $ S.fromList [1,0,1]
306-- > 1
307--
308-- /Internal/
309--
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'
316-- value.
317--
318-- /Internal/
319--
320{-# INLINE maybe #-}
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.
327--
328-- /Internal/
329--
330{-# INLINE either #-}
331either :: MonadCatch m => (a -> Either String b) -> Parser m a b
332either = K.toParserK . D.either
334-------------------------------------------------------------------------------
335-- Taking elements
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.
340--
341-- Stops after @n@ elements.
342-- Fails if the stream ends before @m@ elements could be taken.
343--
344-- Examples: -
345--
346-- @
347-- takeBetween' low high ls = S.parse prsr (S.fromList ls)
348-- where prsr = P.takeBetween low high FL.toList
349-- @
350--
351-- >>> takeBetween' 2 4 [1, 2, 3, 4, 5]
352-- > [1,2,3,4]
353--
354-- >>> takeBetween' 2 4 [1, 2]
355-- > [1,2]
356--
357-- >>> takeBetween' 2 4 [1]
358-- > ParseError "takeBetween: Expecting alteast 2 elements, got 1"
359--
360-- >>> takeBetween' 0 0 [1, 2]
361-- > []
362--
363-- >>> takeBetween' 0 1 []
364-- > []
365--
366-- @takeBetween@ is the most general take operation, other take operations can
367-- be defined in terms of takeBetween. For example:
368--
369-- @
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
374-- @
375--
376-- /Internal/
377--
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.
384--
385-- * Stops - after consuming @n@ elements.
386-- * Fails - if the stream or the collecting fold ends before it can collect
387-- exactly @n@ elements.
388--
389-- >>> S.parse (PR.takeEQ 4 FL.toList) $ S.fromList [1,0,1]
390-- > "takeEQ: Expecting exactly 4 elements, got 3"
391--
392-- /Internal/
393--
394{-# INLINE takeEQ #-}
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.
399--
400-- * Stops - when the collecting fold stops.
401-- * Fails - if the stream or the collecting fold ends before producing @n@
402-- elements.
403--
404-- >>> S.parse (PR.takeGE 4 FL.toList) $ S.fromList [1,0,1]
405-- > "takeGE: Expecting at least 4 elements, got only 3"
406--
407-- >>> S.parse (PR.takeGE 4 FL.toList) $ S.fromList [1,0,1,0,1]
408-- > [1,0,1,0,1]
409--
410-- /Internal/
411--
412{-# INLINE takeGE #-}
413takeGE :: MonadCatch m => Int -> Fold m a b -> Parser m a b
414takeGE n = K.toParserK . D.takeGE n
416-- $takeWhile
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
421-- parser stops.
422--
423-- This is a generalized version of takeWhile, for example 'takeWhile1' can be
424-- implemented in terms of this:
425--
426-- @
427-- takeWhile1 cond p = takeWhile cond (takeBetween 1 maxBound p)
428-- @
429--
430-- Stops: when the condition fails or the collecting parser stops.
431-- Fails: when the collecting parser fails.
432--
433-- /Unimplemented/
434--
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.
442--
443-- * Stops - when the predicate fails or the collecting fold stops.
444-- * Fails - never.
445--
446-- >>> S.parse (PR.takeWhile (== 0) FL.toList) $ S.fromList [0,0,1,0,1]
447-- > [0,0]
448--
449-- We can implement a @breakOn@ using 'takeWhile':
450--
451-- @
452-- breakOn p = takeWhile (not p)
453-- @
454--
455-- /Internal/
456--
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.
462--
463-- /Internal/
464--
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.
471--
472-- This is also called @skipWhile@ in some parsing libraries.
473--
474-- /Internal/
475--
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.
482--
483-- This is a generalized slicing parser which can be used to implement other
484-- parsers e.g.:
485--
486-- @
487-- sliceSepByMax cond n p = sliceSepByP cond (take n p)
488-- sliceSepByBetween cond m n p = sliceSepByP cond (takeBetween m n p)
489-- @
490--
491-- /Internal/
492--
493{-# INLINABLE sliceSepByP #-}
494sliceSepByP ::
495 MonadCatch m =>
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.
501--
502-- /Unimplemented/
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.
513--
514-- * Stops - when the predicate succeeds in non-leading position.
515-- * Fails - never.
516--
517-- S.splitWithPrefix pred f = S.parseMany (PR.sliceBeginWith pred f)
518--
519-- Examples: -
520--
521-- @
522-- sliceBeginWithOdd ls = S.parse prsr (S.fromList ls)
523-- where prsr = P.sliceBeginWith odd FL.toList
524-- @
525--
526-- >>> sliceBeginWithOdd [2, 4, 6, 3]
527-- > [2,4,6]
528--
529-- >>> sliceBeginWithOdd [3, 5, 7, 4]
530-- > [3]
531--
532-- >>> sliceBeginWithOdd [3, 4, 6, 8, 5]
533-- > [3,4,6,8]
534--
535-- >>> sliceBeginWithOdd []
536-- > []
537--
538-- /Internal/
539--
540{-# INLINABLE sliceBeginWith #-}
541sliceBeginWith ::
542 MonadCatch m =>
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.
548--
549-- /Unimplemented/
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.
560--
561-- For example,
562--
563-- >>> escapedFrameBy (== '{') (== '}') (== '\\') S.toList $ S.fromList "{hello}"
564-- > "hello"
565--
566-- >>> escapedFrameBy (== '{') (== '}') (== '\\') S.toList $ S.fromList "{hello {world}}"
567-- > "hello world"
568--
569-- >>> escapedFrameBy (== '{') (== '}') (== '\\') S.toList $ S.fromList "{hello \\{world\\}}"
570-- > "hello {world}"
571--
572-- >>> escapedFrameBy (== '{') (== '}') (== '\\') S.toList $ S.fromList "{hello {world}"
573-- > ParseError "Unterminated '{'"
574--
575-- /Unimplemented/
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
585-- separated text.
586--
587-- * Stops - when it finds a word separator after a non-word element
588-- * Fails - never.
589--
590-- @
591-- S.wordsBy pred f = S.parseMany (PR.wordBy pred f)
592-- @
593--
594{-# INLINE wordBy #-}
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.
604--
605-- * Stops - when the comparison fails.
606-- * Fails - never.
607--
608-- > runGroupsBy eq =
609-- > Stream.toList
610-- > . Stream.parseMany (groupBy eq Fold.toList)
611-- > . Stream.fromList
612--
613-- >>> runGroupsBy (<) []
614-- []
615--
616-- >>> runGroupsBy (<) [1]
617-- [[1]]
618--
619-- >>> runGroupsBy (<) [3, 5, 4, 1, 2, 0]
620-- [[3, 5, 4], [1, 2], [0]]
621--
622-- /Internal/
623--
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.
636--
637-- * Stops - when the comparison fails.
638-- * Fails - never.
639--
640-- > runGroupsByRolling eq =
641-- > Stream.toList
642-- > . Stream.parseMany (groupByRolling eq Fold.toList)
643-- > . Stream.fromList
644--
645-- >>> runGroupsByRolling (<) []
646-- []
647--
648-- >>> runGroupsByRolling (<) [1]
649-- [[1]]
650--
651-- >>> runGroupsByRolling (<) [3, 5, 4, 1, 2, 0]
652-- [[3, 5], [4], [1, 2], [0]]
653--
654-- /Internal/
655--
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.
661--
662-- >>> S.parse $ S.eqBy (==) "string" $ S.fromList "string"
663--
664-- >>> S.parse $ S.eqBy (==) "mismatch" $ S.fromList "match"
665-- > *** Exception: ParseError "eqBy: failed, yet to match 7 elements"
666--
667-- /Internal/
668--
669{-# INLINE eqBy #-}
670eqBy :: MonadCatch m => (a -> a -> Bool) -> [a] -> Parser m a ()
671eqBy cmp = K.toParserK . D.eqBy cmp
673-------------------------------------------------------------------------------
674-- nested parsers
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.
682--
683-- Note: This is a parsing dual of appending streams using
684-- 'Streamly.Prelude.serial', it splits the streams using two parsers and zips
685-- the results.
686--
687-- This implementation is strict in the second argument, therefore, the
688-- following will fail:
689--
690-- >>> S.parse (PR.splitWith const (PR.satisfy (> 0)) undefined) $ S.fromList [1]
691--
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.
696--
697-- /Internal/
698--
699{-# INLINE splitWith #-}
700splitWith :: MonadCatch m
701 => (a -> b -> c) -> Parser m x a -> Parser m x b -> Parser m x c
702splitWith f p1 p2 =
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.
710--
711-- This implementation is strict in the second argument, therefore, the
712-- following will fail:
713--
714-- >>> S.parse (split_ (PR.satisfy (> 0)) undefined) $ S.fromList [1]
715--
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.
720--
721-- /Internal/
722--
723{-# INLINE split_ #-}
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.
730--
731-- /Internal/
732--
733{-# INLINE teeWith #-}
734teeWith :: MonadCatch m
735 => (a -> b -> c) -> Parser m x a -> Parser m x b -> Parser m x c
736teeWith f p1 p2 =
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.
741--
742-- /Internal/
743--
744{-# INLINE teeWithFst #-}
745teeWithFst :: MonadCatch m
746 => (a -> b -> c) -> Parser m x a -> Parser m x b -> Parser m x c
747teeWithFst f p1 p2 =
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.
752--
753-- /Unimplemented/
754--
755{-# INLINE teeWithMin #-}
756teeWithMin :: MonadCatch m
757 => (a -> b -> c) -> Parser m x a -> Parser m x b -> Parser m x c
758teeWithMin f p1 p2 =
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.
764--
765-- Note: This implementation is not lazy in the second argument. The following
766-- will fail:
767--
768-- >>> S.parse (PR.satisfy (> 0) `PR.alt` undefined) $ S.fromList [1..10]
769--
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.
774--
775-- /Internal/
776--
777{-# INLINE alt #-}
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
783-- parse.
784--
785-- /Internal/
786--
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
794-- parse.
795--
796-- /Internal/
797--
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.
804--
805-- /Internal/
806--
807{-# INLINE lookAhead #-}
808lookAhead :: MonadCatch m => Parser m a b -> Parser m a b
809lookAhead p = K.toParserK $ D.lookAhead $ K.fromParserK p
811-------------------------------------------------------------------------------
812-- Interleaving
813-------------------------------------------------------------------------------
814--
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.
818--
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.
824--
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
829-- line number info.
830--
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
833-- two patterns.
834--
835-- This undoes a "gintercalate" of two streams.
836--
837-- /Unimplemented/
838--
839{-# INLINE deintercalate #-}
840deintercalate ::
841 -- Monad m =>
842 Fold m a y -> Parser m x a
843 -> Fold m b z -> Parser m x b
844 -> Parser m x (y, z)
845deintercalate = undefined
847-------------------------------------------------------------------------------
848-- Sequential Collection
849-------------------------------------------------------------------------------
850--
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
853-- parsers fail.
854--
855-- This is same as 'Data.Traversable.sequence' but more efficient.
856--
857-- /Unimplemented/
858--
859{-# INLINE concatSequence #-}
860concatSequence ::
861 -- Foldable t =>
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'.
866--
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.
871--
872-- /Internal/
873--
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-------------------------------------------------------------------------------
882--
883-- | @choice parsers@ applies the @parsers@ in order and returns the first
884-- successful parse.
885--
886-- This is same as 'asum' but more efficient.
887--
888-- /Unimplemented/
889--
890{-# INLINE choice #-}
891choice ::
892 -- Foldable t =>
893 t (Parser m a b) -> Parser m a b
894choice _ps = undefined
896-------------------------------------------------------------------------------
897-- Sequential Repetition
898-------------------------------------------------------------------------------
899--
900-- $many
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.
907--
908-- /Unimplemented/
909--
910{-# INLINE manyP #-}
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.
917--
918-- Stops: when the downstream fold stops or the parser fails.
919-- Fails: never, produces zero or more results.
920--
921-- Compare with 'Control.Applicative.many'.
922--
923-- /Internal/
924--
925{-# INLINE 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
932-- compatibility.
933--
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.
936--
937-- Stops: when the downstream fold stops or the parser fails.
938-- Fails: if it stops without producing a single result.
939--
940-- @some fld parser = many (takeGE 1 fld) parser@
941--
942-- Compare with 'Control.Applicative.some'.
943--
944-- /Internal/
945--
946{-# INLINE 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.
955--
956-- /Unimplemented/
957--
958{-# INLINE countBetween #-}
959countBetween ::
960 -- MonadCatch m =>
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.
968--
969-- /Unimplemented/
970--
971{-# INLINE count #-}
972count ::
973 -- MonadCatch m =>
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.
980--
981-- We can implemnent parsers like the following using 'manyTillP':
982--
983-- @
984-- countBetweenTill m n f p = manyTillP (takeBetween m n f) p
985-- @
986--
987-- /Unimplemented/
988--
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.
1003-- /Internal/
1005{-# INLINE manyTill #-}
1006manyTill :: MonadCatch m
1007 => Fold m b c -> Parser m a b -> Parser m a x -> Parser m a c
1008manyTill f p1 p2 =
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
1017-- error.
1019-- /Unimplemented/
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.
1034-- /Unimplemented/
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.
1049-- /Unimplemented/
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.
1058-- /Unimplemented/
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
1067-- input.
1069-- /Unimplemented/
1071{-# INLINE retry #-}
1072retry :: -- (MonadCatch m) =>
1073 Parser m a b -> Parser m a b
1074retry _p = undefined