on 03218ad help sign in
1118 lines 36 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 , fromPure
58 , fromEffect
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 , serialWith
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.Type (Fold(..))
203import Streamly.Internal.Data.Parser.ParserK.Type (Parser)
205import qualified Streamly.Internal.Data.Fold.Type as FL
206import qualified Streamly.Internal.Data.Parser.ParserD as D
207import qualified Streamly.Internal.Data.Parser.ParserK.Type as K
209--
210-- $setup
211-- >>> :m
212-- >>> import Prelude hiding (any, all, take, takeWhile, sequence, concatMap, maybe, either)
213-- >>> import qualified Streamly.Prelude as Stream
214-- >>> import qualified Streamly.Internal.Data.Stream.IsStream as Stream (parse, parseMany)
215-- >>> import qualified Streamly.Data.Fold as Fold
216-- >>> import qualified Streamly.Internal.Data.Parser as Parser
218-------------------------------------------------------------------------------
219-- Upgrade folds to parses
220-------------------------------------------------------------------------------
221--
222-- | Make a 'Parser' from a 'Fold'.
223--
224-- /Pre-release/
225--
226{-# INLINE fromFold #-}
227fromFold :: MonadCatch m => Fold m a b -> Parser m a b
228fromFold = K.toParserK . D.fromFold
230-------------------------------------------------------------------------------
231-- Terminating but not failing folds
232-------------------------------------------------------------------------------
233--
234-- This is the dual of stream "fromPure".
235--
236-- | A parser that always yields a pure value without consuming any input.
237--
238-- /Pre-release/
239--
240{-# INLINE [3] fromPure #-}
241fromPure :: MonadCatch m => b -> Parser m a b
242fromPure = K.toParserK . D.fromPure
243{-# RULES "fromPure fallback to CPS" [2]
244 forall a. K.toParserK (D.fromPure a) = K.fromPure a #-}
246-- This is the dual of stream "fromEffect".
247--
248-- | A parser that always yields the result of an effectful action without
249-- consuming any input.
250--
251-- /Pre-release/
252--
253{-# INLINE fromEffect #-}
254fromEffect :: MonadCatch m => m b -> Parser m a b
255fromEffect = K.fromEffect -- K.toParserK . D.fromEffect
257-- This is the dual of "nil".
258--
259-- | A parser that always fails with an error message without consuming
260-- any input.
261--
262-- /Pre-release/
263--
264{-# INLINE [3] die #-}
265die :: MonadCatch m => String -> Parser m a b
266die = K.toParserK . D.die
267{-# RULES "die fallback to CPS" [2]
268 forall a. K.toParserK (D.die a) = K.die a #-}
270-- This is the dual of "nilM".
271--
272-- | A parser that always fails with an effectful error message and without
273-- consuming any input.
274--
275-- /Pre-release/
276--
277{-# INLINE dieM #-}
278dieM :: MonadCatch m => m String -> Parser m a b
279dieM = K.toParserK . D.dieM
281-------------------------------------------------------------------------------
282-- Failing Parsers
283-------------------------------------------------------------------------------
285-- | Peek the head element of a stream, without consuming it. Fails if it
286-- encounters end of input.
287--
288-- >>> Stream.parse ((,) <$> Parser.peek <*> Parser.satisfy (> 0)) $ Stream.fromList [1]
289-- (1,1)
290--
291-- @
292-- peek = lookAhead (satisfy True)
293-- @
294--
295-- /Pre-release/
296--
297{-# INLINE peek #-}
298peek :: MonadCatch m => Parser m a a
299peek = K.toParserK D.peek
301-- | Succeeds if we are at the end of input, fails otherwise.
302--
303-- >>> Stream.parse ((,) <$> Parser.satisfy (> 0) <*> Parser.eof) $ Stream.fromList [1]
304-- (1,())
305--
306-- /Pre-release/
307--
308{-# INLINE eof #-}
309eof :: MonadCatch m => Parser m a ()
310eof = K.toParserK D.eof
312-- | Returns the next element if it passes the predicate, fails otherwise.
313--
314-- >>> Stream.parse (Parser.satisfy (== 1)) $ Stream.fromList [1,0,1]
315-- 1
316--
317-- /Pre-release/
318--
319{-# INLINE satisfy #-}
320satisfy :: MonadCatch m => (a -> Bool) -> Parser m a a
321satisfy = K.toParserK . D.satisfy
323-- | Map a 'Maybe' returning function on the next element in the stream. The
324-- parser fails if the function returns 'Nothing' otherwise returns the 'Just'
325-- value.
326--
327-- /Pre-release/
328--
329{-# INLINE maybe #-}
330maybe :: MonadCatch m => (a -> Maybe b) -> Parser m a b
331maybe = K.toParserK . D.maybe
333-- | Map an 'Either' returning function on the next element in the stream. If
334-- the function returns 'Left err', the parser fails with the error message
335-- @err@ otherwise returns the 'Right' value.
336--
337-- /Pre-release/
338--
339{-# INLINE either #-}
340either :: MonadCatch m => (a -> Either String b) -> Parser m a b
341either = K.toParserK . D.either
343-------------------------------------------------------------------------------
344-- Taking elements
345-------------------------------------------------------------------------------
347-- | @takeBetween m n@ takes a minimum of @m@ and a maximum of @n@ input
348-- elements and folds them using the supplied fold.
349--
350-- Stops after @n@ elements.
351-- Fails if the stream ends before @m@ elements could be taken.
352--
353-- Examples: -
354--
355-- @
356-- >>> :{
357-- takeBetween' low high ls = Stream.parse prsr (Stream.fromList ls)
358-- where prsr = Parser.takeBetween low high Fold.toList
359-- :}
360--
361-- @
362--
363-- >>> takeBetween' 2 4 [1, 2, 3, 4, 5]
364-- [1,2,3,4]
365--
366-- >>> takeBetween' 2 4 [1, 2]
367-- [1,2]
368--
369-- >>> takeBetween' 2 4 [1]
370-- *** Exception: ParseError "takeBetween: Expecting alteast 2 elements, got 1"
371--
372-- >>> takeBetween' 0 0 [1, 2]
373-- []
374--
375-- >>> takeBetween' 0 1 []
376-- []
377--
378-- @takeBetween@ is the most general take operation, other take operations can
379-- be defined in terms of takeBetween. For example:
380--
381-- @
382-- take = takeBetween 0 n -- equivalent of take
383-- take1 = takeBetween 1 n -- equivalent of takeLE1
384-- takeEQ = takeBetween n n
385-- takeGE = takeBetween n maxBound
386-- @
387--
388-- /Pre-release/
389--
390{-# INLINE takeBetween #-}
391takeBetween :: MonadCatch m =>
392 Int -> Int -> Fold m a b -> Parser m a b
393takeBetween m n = K.toParserK . D.takeBetween m n
395-- | Stops after taking exactly @n@ input elements.
396--
397-- * Stops - after consuming @n@ elements.
398-- * Fails - if the stream or the collecting fold ends before it can collect
399-- exactly @n@ elements.
400--
401-- >>> Stream.parse (Parser.takeEQ 4 Fold.toList) $ Stream.fromList [1,0,1]
402-- *** Exception: ParseError "takeEQ: Expecting exactly 4 elements, input terminated on 3"
403--
404-- /Pre-release/
405--
406{-# INLINE takeEQ #-}
407takeEQ :: MonadCatch m => Int -> Fold m a b -> Parser m a b
408takeEQ n = K.toParserK . D.takeEQ n
410-- | Take at least @n@ input elements, but can collect more.
411--
412-- * Stops - when the collecting fold stops.
413-- * Fails - if the stream or the collecting fold ends before producing @n@
414-- elements.
415--
416-- >>> Stream.parse (Parser.takeGE 4 Fold.toList) $ Stream.fromList [1,0,1]
417-- *** Exception: ParseError "takeGE: Expecting at least 4 elements, input terminated on 3"
418--
419-- >>> Stream.parse (Parser.takeGE 4 Fold.toList) $ Stream.fromList [1,0,1,0,1]
420-- [1,0,1,0,1]
421--
422-- /Pre-release/
423--
424{-# INLINE takeGE #-}
425takeGE :: MonadCatch m => Int -> Fold m a b -> Parser m a b
426takeGE n = K.toParserK . D.takeGE n
428-- $takeWhile
429-- Note: This is called @takeWhileP@ and @munch@ in some parser libraries.
431-- | Like 'takeWhile' but uses a 'Parser' instead of a 'Fold' to collect the
432-- input. The combinator stops when the condition fails or if the collecting
433-- parser stops.
434--
435-- This is a generalized version of takeWhile, for example 'takeWhile1' can be
436-- implemented in terms of this:
437--
438-- @
439-- takeWhile1 cond p = takeWhile cond (takeBetween 1 maxBound p)
440-- @
441--
442-- Stops: when the condition fails or the collecting parser stops.
443-- Fails: when the collecting parser fails.
444--
445-- /Unimplemented/
446--
447{-# INLINE takeWhileP #-}
448takeWhileP :: -- MonadCatch m =>
449 (a -> Bool) -> Parser m a b -> Parser m a b
450takeWhileP _cond = undefined -- K.toParserK . D.takeWhileP cond
452-- | Collect stream elements until an element fails the predicate. The element
453-- on which the predicate fails is returned back to the input stream.
454--
455-- * Stops - when the predicate fails or the collecting fold stops.
456-- * Fails - never.
457--
458-- >>> Stream.parse (Parser.takeWhile (== 0) Fold.toList) $ Stream.fromList [0,0,1,0,1]
459-- [0,0]
460--
461-- We can implement a @breakOn@ using 'takeWhile':
462--
463-- @
464-- breakOn p = takeWhile (not p)
465-- @
466--
467-- /Pre-release/
468--
469{-# INLINE takeWhile #-}
470takeWhile :: MonadCatch m => (a -> Bool) -> Fold m a b -> Parser m a b
471takeWhile cond = K.toParserK . D.takeWhile cond
473-- | Like 'takeWhile' but takes at least one element otherwise fails.
474--
475-- /Pre-release/
476--
477{-# INLINE takeWhile1 #-}
478takeWhile1 :: MonadCatch m => (a -> Bool) -> Fold m a b -> Parser m a b
479takeWhile1 cond = K.toParserK . D.takeWhile1 cond
481-- | Drain the input as long as the predicate succeeds, running the effects and
482-- discarding the results.
483--
484-- This is also called @skipWhile@ in some parsing libraries.
485--
486-- /Pre-release/
487--
488{-# INLINE drainWhile #-}
489drainWhile :: MonadCatch m => (a -> Bool) -> Parser m a ()
490drainWhile p = takeWhile p FL.drain
492-- | @sliceSepByP cond parser@ parses a slice of the input using @parser@ until
493-- @cond@ succeeds or the parser stops.
494--
495-- This is a generalized slicing parser which can be used to implement other
496-- parsers e.g.:
497--
498-- @
499-- sliceSepByMax cond n p = sliceSepByP cond (take n p)
500-- sliceSepByBetween cond m n p = sliceSepByP cond (takeBetween m n p)
501-- @
502--
503-- /Pre-release/
504--
505{-# INLINABLE sliceSepByP #-}
506sliceSepByP ::
507 MonadCatch m =>
508 (a -> Bool) -> Parser m a b -> Parser m a b
509sliceSepByP cond = K.toParserK . D.sliceSepByP cond . K.fromParserK
511-- | Like 'sliceSepBy' but does not drop the separator element, instead
512-- separator is emitted as a separate element in the output.
513--
514-- /Unimplemented/
515{-# INLINABLE sliceSepWith #-}
516sliceSepWith :: -- MonadCatch m =>
517 (a -> Bool) -> Fold m a b -> Parser m a b
518sliceSepWith _cond = undefined -- K.toParserK . D.sliceSepBy cond
520-- | Collect stream elements until an elements passes the predicate, return the
521-- last element on which the predicate succeeded back to the input stream. If
522-- the predicate succeeds on the first element itself then the parser does not
523-- terminate there. The succeeding element in the leading position
524-- is treated as a prefix separator which is kept in the output segment.
525--
526-- * Stops - when the predicate succeeds in non-leading position.
527-- * Fails - never.
528--
529-- S.splitWithPrefix pred f = S.parseMany (PR.sliceBeginWith pred f)
530--
531-- Examples: -
532--
533-- >>> :{
534-- sliceBeginWithOdd ls = Stream.parse prsr (Stream.fromList ls)
535-- where prsr = Parser.sliceBeginWith odd Fold.toList
536-- :}
537--
538--
539-- >>> sliceBeginWithOdd [2, 4, 6, 3]
540-- *** Exception: sliceBeginWith : slice begins with an element which fails the predicate
541-- ...
542--
543-- >>> sliceBeginWithOdd [3, 5, 7, 4]
544-- [3]
545--
546-- >>> sliceBeginWithOdd [3, 4, 6, 8, 5]
547-- [3,4,6,8]
548--
549-- >>> sliceBeginWithOdd []
550-- []
551--
552-- /Pre-release/
553--
554{-# INLINABLE sliceBeginWith #-}
555sliceBeginWith ::
556 MonadCatch m =>
557 (a -> Bool) -> Fold m a b -> Parser m a b
558sliceBeginWith cond = K.toParserK . D.sliceBeginWith cond
560-- | Like 'sliceSepBy' but the separator elements can be escaped using an
561-- escape char determined by the second predicate.
562--
563-- /Unimplemented/
564{-# INLINABLE escapedSliceSepBy #-}
565escapedSliceSepBy :: -- MonadCatch m =>
566 (a -> Bool) -> (a -> Bool) -> Fold m a b -> Parser m a b
567escapedSliceSepBy _cond _esc = undefined
568 -- K.toParserK . D.escapedSliceSepBy cond esc
570-- | @escapedFrameBy begin end escape@ parses a string framed using @begin@ and
571-- @end@ as the frame begin and end marker elements and @escape@ as an escaping
572-- element to escape the occurrence of the framing elements within the frame.
573-- Nested frames are allowed, but nesting is removed when parsing.
574--
575-- For example,
576--
577-- @
578-- > Stream.parse (Parser.escapedFrameBy (== '{') (== '}') (== '\\') Fold.toList) $ Stream.fromList "{hello}"
579-- "hello"
580--
581-- > Stream.parse (Parser.escapedFrameBy (== '{') (== '}') (== '\\') Fold.toList) $ Stream.fromList "{hello {world}}"
582-- "hello world"
583--
584-- > Stream.parse (Parser.escapedFrameBy (== '{') (== '}') (== '\\') Fold.toList) $ Stream.fromList "{hello \\{world\\}}"
585-- "hello {world}"
586--
587-- > Stream.parse (Parser.escapedFrameBy (== '{') (== '}') (== '\\') Fold.toList) $ Stream.fromList "{hello {world}"
588-- ParseError "Unterminated '{'"
589--
590-- @
591--
592-- /Unimplemented/
593{-# INLINABLE escapedFrameBy #-}
594escapedFrameBy :: -- MonadCatch m =>
595 (a -> Bool) -> (a -> Bool) -> (a -> Bool) -> Fold m a b -> Parser m a b
596escapedFrameBy _begin _end _escape _p = undefined
597 -- K.toParserK . D.frameBy begin end escape p
599-- | Like 'splitOn' but strips leading, trailing, and repeated separators.
600-- Therefore, @".a..b."@ having '.' as the separator would be parsed as
601-- @["a","b"]@. In other words, its like parsing words from whitespace
602-- separated text.
603--
604-- * Stops - when it finds a word separator after a non-word element
605-- * Fails - never.
606--
607-- @
608-- S.wordsBy pred f = S.parseMany (PR.wordBy pred f)
609-- @
610--
611{-# INLINE wordBy #-}
612wordBy :: MonadCatch m => (a -> Bool) -> Fold m a b -> Parser m a b
613wordBy f = K.toParserK . D.wordBy f
615-- | Given an input stream @[a,b,c,...]@ and a comparison function @cmp@, the
616-- parser assigns the element @a@ to the first group, then if @a \`cmp` b@ is
617-- 'True' @b@ is also assigned to the same group. If @a \`cmp` c@ is 'True'
618-- then @c@ is also assigned to the same group and so on. When the comparison
619-- fails the parser is terminated. Each group is folded using the 'Fold' @f@ and
620-- the result of the fold is the result of the parser.
621--
622-- * Stops - when the comparison fails.
623-- * Fails - never.
624--
625-- >>> :{
626-- runGroupsBy eq =
627-- Stream.toList
628-- . Stream.parseMany (Parser.groupBy eq Fold.toList)
629-- . Stream.fromList
630-- :}
631--
632-- >>> runGroupsBy (<) []
633-- []
634--
635-- >>> runGroupsBy (<) [1]
636-- [[1]]
637--
638-- >>> runGroupsBy (<) [3, 5, 4, 1, 2, 0]
639-- [[3,5,4],[1,2],[0]]
640--
641-- /Pre-release/
642--
643{-# INLINABLE groupBy #-}
644groupBy :: MonadCatch m => (a -> a -> Bool) -> Fold m a b -> Parser m a b
645groupBy eq = K.toParserK . D.groupBy eq
647-- | Unlike 'groupBy' this combinator performs a rolling comparison of two
648-- successive elements in the input stream. Assuming the input stream to the
649-- parser is @[a,b,c,...]@ and the comparison function is @cmp@, the parser
650-- first assigns the element @a@ to the first group, then if @a \`cmp` b@ is
651-- 'True' @b@ is also assigned to the same group. If @b \`cmp` c@ is 'True'
652-- then @c@ is also assigned to the same group and so on. When the comparison
653-- fails the parser is terminated. Each group is folded using the 'Fold' @f@ and
654-- the result of the fold is the result of the parser.
655--
656-- * Stops - when the comparison fails.
657-- * Fails - never.
658--
659-- >>> :{
660-- runGroupsByRolling eq =
661-- Stream.toList
662-- . Stream.parseMany (Parser.groupByRolling eq Fold.toList)
663-- . Stream.fromList
664-- :}
665--
666-- >>> runGroupsByRolling (<) []
667-- []
668--
669-- >>> runGroupsByRolling (<) [1]
670-- [[1]]
671--
672-- >>> runGroupsByRolling (<) [3, 5, 4, 1, 2, 0]
673-- [[3,5],[4],[1,2],[0]]
674--
675-- /Pre-release/
676--
677{-# INLINABLE groupByRolling #-}
678groupByRolling :: MonadCatch m => (a -> a -> Bool) -> Fold m a b -> Parser m a b
679groupByRolling eq = K.toParserK . D.groupByRolling eq
681-- | Match the given sequence of elements using the given comparison function.
682--
683-- >>> Stream.parse (Parser.eqBy (==) "string") $ Stream.fromList "string"
684--
685-- >>> Stream.parse (Parser.eqBy (==) "mismatch") $ Stream.fromList "match"
686-- *** Exception: ParseError "eqBy: failed, yet to match 7 elements"
687--
688-- /Pre-release/
689--
690{-# INLINE eqBy #-}
691eqBy :: MonadCatch m => (a -> a -> Bool) -> [a] -> Parser m a ()
692eqBy cmp = K.toParserK . D.eqBy cmp
694-------------------------------------------------------------------------------
695-- nested parsers
696-------------------------------------------------------------------------------
698-- | Sequential parser application. Apply two parsers sequentially to an input
699-- stream. The input is provided to the first parser, when it is done the
700-- remaining input is provided to the second parser. If both the parsers
701-- succeed their outputs are combined using the supplied function. The
702-- operation fails if any of the parsers fail.
703--
704-- Note: This is a parsing dual of appending streams using
705-- 'Streamly.Prelude.serial', it splits the streams using two parsers and zips
706-- the results.
707--
708-- This implementation is strict in the second argument, therefore, the
709-- following will fail:
710--
711-- >>> Stream.parse (Parser.serialWith const (Parser.satisfy (> 0)) undefined) $ Stream.fromList [1]
712-- *** Exception: Prelude.undefined
713-- ...
714--
715-- Compare with 'Applicative' instance method '<*>'. This implementation allows
716-- stream fusion but has quadratic complexity. This can fuse with other
717-- operations and can be faster than 'Applicative' instance for small number
718-- (less than 8) of compositions.
719--
720-- Many combinators can be expressed using @serialWith@ and other parser
721-- primitives. Some common idioms are described below,
722--
723-- @
724-- span :: (a -> Bool) -> Fold m a b -> Fold m a b -> Parser m a b
725-- span pred f1 f2 = serialWith (,) ('takeWhile' pred f1) ('fromFold' f2)
726-- @
727--
728-- @
729-- spanBy :: (a -> a -> Bool) -> Fold m a b -> Fold m a b -> Parser m a b
730-- spanBy eq f1 f2 = serialWith (,) ('groupBy' eq f1) ('fromFold' f2)
731-- @
732--
733-- @
734-- spanByRolling :: (a -> a -> Bool) -> Fold m a b -> Fold m a b -> Parser m a b
735-- spanByRolling eq f1 f2 = serialWith (,) ('groupByRolling' eq f1) ('fromFold' f2)
736-- @
737--
738-- /Pre-release/
739--
740{-# INLINE serialWith #-}
741serialWith :: MonadCatch m
742 => (a -> b -> c) -> Parser m x a -> Parser m x b -> Parser m x c
743serialWith f p1 p2 =
744 K.toParserK $ D.serialWith f (K.fromParserK p1) (K.fromParserK p2)
746-- | Sequential parser application ignoring the output of the first parser.
747-- Apply two parsers sequentially to an input stream. The input is provided to
748-- the first parser, when it is done the remaining input is provided to the
749-- second parser. The output of the parser is the output of the second parser.
750-- The operation fails if any of the parsers fail.
751--
752-- This implementation is strict in the second argument, therefore, the
753-- following will fail:
754--
755-- >>> Stream.parse (Parser.split_ (Parser.satisfy (> 0)) undefined) $ Stream.fromList [1]
756-- *** Exception: Prelude.undefined
757-- ...
758--
759-- Compare with 'Applicative' instance method '*>'. This implementation allows
760-- stream fusion but has quadratic complexity. This can fuse with other
761-- operations, and can be faster than 'Applicative' instance for small
762-- number (less than 8) of compositions.
763--
764-- /Pre-release/
765--
766{-# INLINE split_ #-}
767split_ :: MonadCatch m => Parser m x a -> Parser m x b -> Parser m x b
768split_ p1 p2 = K.toParserK $ D.split_ (K.fromParserK p1) (K.fromParserK p2)
770-- | @teeWith f p1 p2@ distributes its input to both @p1@ and @p2@ until both
771-- of them succeed or anyone of them fails and combines their output using @f@.
772-- The parser succeeds if both the parsers succeed.
773--
774-- /Pre-release/
775--
776{-# INLINE teeWith #-}
777teeWith :: MonadCatch m
778 => (a -> b -> c) -> Parser m x a -> Parser m x b -> Parser m x c
779teeWith f p1 p2 =
780 K.toParserK $ D.teeWith f (K.fromParserK p1) (K.fromParserK p2)
782-- | Like 'teeWith' but ends parsing and zips the results, if available,
783-- whenever the first parser ends.
784--
785-- /Pre-release/
786--
787{-# INLINE teeWithFst #-}
788teeWithFst :: MonadCatch m
789 => (a -> b -> c) -> Parser m x a -> Parser m x b -> Parser m x c
790teeWithFst f p1 p2 =
791 K.toParserK $ D.teeWithFst f (K.fromParserK p1) (K.fromParserK p2)
793-- | Like 'teeWith' but ends parsing and zips the results, if available,
794-- whenever any of the parsers ends or fails.
795--
796-- /Unimplemented/
797--
798{-# INLINE teeWithMin #-}
799teeWithMin :: MonadCatch m
800 => (a -> b -> c) -> Parser m x a -> Parser m x b -> Parser m x c
801teeWithMin f p1 p2 =
802 K.toParserK $ D.teeWithMin f (K.fromParserK p1) (K.fromParserK p2)
804-- | Sequential alternative. Apply the input to the first parser and return the
805-- result if the parser succeeds. If the first parser fails then backtrack and
806-- apply the same input to the second parser and return the result.
807--
808-- Note: This implementation is not lazy in the second argument. The following
809-- will fail:
810--
811-- >>> Stream.parse (Parser.satisfy (> 0) `Parser.alt` undefined) $ Stream.fromList [1..10]
812-- 1
813--
814-- Compare with 'Alternative' instance method '<|>'. This implementation allows
815-- stream fusion but has quadratic complexity. This can fuse with other
816-- operations and can be much faster than 'Alternative' instance for small
817-- number (less than 8) of alternatives.
818--
819-- /Pre-release/
820--
821{-# INLINE alt #-}
822alt :: MonadCatch m => Parser m x a -> Parser m x a -> Parser m x a
823alt p1 p2 = K.toParserK $ D.alt (K.fromParserK p1) (K.fromParserK p2)
825-- | Shortest alternative. Apply both parsers in parallel but choose the result
826-- from the one which consumed least input i.e. take the shortest succeeding
827-- parse.
828--
829-- /Pre-release/
830--
831{-# INLINE shortest #-}
832shortest :: MonadCatch m
833 => Parser m x a -> Parser m x a -> Parser m x a
834shortest p1 p2 = K.toParserK $ D.shortest (K.fromParserK p1) (K.fromParserK p2)
836-- | Longest alternative. Apply both parsers in parallel but choose the result
837-- from the one which consumed more input i.e. take the longest succeeding
838-- parse.
839--
840-- /Pre-release/
841--
842{-# INLINE longest #-}
843longest :: MonadCatch m
844 => Parser m x a -> Parser m x a -> Parser m x a
845longest p1 p2 = K.toParserK $ D.longest (K.fromParserK p1) (K.fromParserK p2)
847-- | Run a parser without consuming the input.
848--
849-- /Pre-release/
850--
851{-# INLINE lookAhead #-}
852lookAhead :: MonadCatch m => Parser m a b -> Parser m a b
853lookAhead p = K.toParserK $ D.lookAhead $ K.fromParserK p
855-------------------------------------------------------------------------------
856-- Interleaving
857-------------------------------------------------------------------------------
858--
859-- To deinterleave we can chain two parsers one behind the other. The input is
860-- given to the first parser and the input definitively rejected by the first
861-- parser is given to the second parser.
862--
863-- We can either have the parsers themselves buffer the input or use the shared
864-- global buffer to hold it until none of the parsers need it. When the first
865-- parser returns Skip (i.e. rewind) we let the second parser consume the
866-- rejected input and when it is done we move the cursor forward to the first
867-- parser again. This will require a "move forward" command as well.
868--
869-- To implement grep we can use three parsers, one to find the pattern, one
870-- to store the context behind the pattern and one to store the context in
871-- front of the pattern. When a match occurs we need to emit the accumulator of
872-- all the three parsers. One parser can count the line numbers to provide the
873-- line number info.
874--
875-- | Apply two parsers alternately to an input stream. The input stream is
876-- considered an interleaving of two patterns. The two parsers represent the
877-- two patterns.
878--
879-- This undoes a "gintercalate" of two streams.
880--
881-- /Unimplemented/
882--
883{-# INLINE deintercalate #-}
884deintercalate ::
885 -- Monad m =>
886 Fold m a y -> Parser m x a
887 -> Fold m b z -> Parser m x b
888 -> Parser m x (y, z)
889deintercalate = undefined
891-------------------------------------------------------------------------------
892-- Sequential Collection
893-------------------------------------------------------------------------------
894--
895-- | @concatSequence f t@ collects sequential parses of parsers in the
896-- container @t@ using the fold @f@. Fails if the input ends or any of the
897-- parsers fail.
898--
899-- This is same as 'Data.Traversable.sequence' but more efficient.
900--
901-- /Unimplemented/
902--
903{-# INLINE concatSequence #-}
904concatSequence ::
905 -- Foldable t =>
906 Fold m b c -> t (Parser m a b) -> Parser m a c
907concatSequence _f _p = undefined
909-- | Map a 'Parser' returning function on the result of a 'Parser'.
910--
911-- Compare with 'Monad' instance method '>>='. This implementation allows
912-- stream fusion but has quadratic complexity. This can fuse with other
913-- operations and can be much faster than 'Monad' instance for small number
914-- (less than 8) of compositions.
915--
916-- /Pre-release/
917--
918{-# INLINE concatMap #-}
919concatMap :: MonadCatch m
920 => (b -> Parser m a c) -> Parser m a b -> Parser m a c
921concatMap f p = K.toParserK $ D.concatMap (K.fromParserK . f) (K.fromParserK p)
923-------------------------------------------------------------------------------
924-- Alternative Collection
925-------------------------------------------------------------------------------
926--
927-- | @choice parsers@ applies the @parsers@ in order and returns the first
928-- successful parse.
929--
930-- This is same as 'asum' but more efficient.
931--
932-- /Unimplemented/
933--
934{-# INLINE choice #-}
935choice ::
936 -- Foldable t =>
937 t (Parser m a b) -> Parser m a b
938choice _ps = undefined
940-------------------------------------------------------------------------------
941-- Sequential Repetition
942-------------------------------------------------------------------------------
943--
944-- $many
945-- TODO "many" is essentially a Fold because it cannot fail. So it can be
946-- downgraded to a Fold. Or we can make the return type a Fold instead and
947-- upgrade that to a parser when needed.
949-- | Like 'many' but uses a 'Parser' instead of a 'Fold' to collect the
950-- results. Parsing stops or fails if the collecting parser stops or fails.
951--
952-- /Unimplemented/
953--
954{-# INLINE manyP #-}
955manyP :: -- MonadCatch m =>
956 Parser m a b -> Parser m b c -> Parser m a c
957manyP _p _f = undefined -- K.toParserK $ D.manyP (K.fromParserK p) f
959-- | Collect zero or more parses. Apply the supplied parser repeatedly on the
960-- input stream and push the parse results to a downstream fold.
961--
962-- Stops: when the downstream fold stops or the parser fails.
963-- Fails: never, produces zero or more results.
964--
965-- Compare with 'Control.Applicative.many'.
966--
967-- /Pre-release/
968--
969{-# INLINE many #-}
970many :: MonadCatch m => Parser m a b -> Fold m b c -> Parser m a c
971many p f = K.toParserK $ D.many (K.fromParserK p) f
972-- many = countBetween 0 maxBound
974-- Note: many1 would perhaps be a better name for this and consistent with
975-- other names like takeWhile1. But we retain the name "some" for
976-- compatibility.
977--
978-- | Collect one or more parses. Apply the supplied parser repeatedly on the
979-- input stream and push the parse results to a downstream fold.
980--
981-- Stops: when the downstream fold stops or the parser fails.
982-- Fails: if it stops without producing a single result.
983--
984-- @some fld parser = manyP (takeGE 1 fld) parser@
985--
986-- Compare with 'Control.Applicative.some'.
987--
988-- /Pre-release/
989--
990{-# INLINE some #-}
991some :: MonadCatch m => Parser m a b -> Fold m b c -> Parser m a c
992some p f = K.toParserK $ D.some (K.fromParserK p) f
993-- some p f = manyP p (takeGE 1 f)
994-- many = countBetween 1 maxBound
996-- | @countBetween m n f p@ collects between @m@ and @n@ sequential parses of
997-- parser @p@ using the fold @f@. Stop after collecting @n@ results. Fails if
998-- the input ends or the parser fails before @m@ results are collected.
999--
1000-- /Unimplemented/
1002{-# INLINE countBetween #-}
1003countBetween ::
1004 -- MonadCatch m =>
1005 Int -> Int -> Parser m a b -> Fold m b c -> Parser m a c
1006countBetween _m _n _p = undefined
1007-- countBetween m n p f = manyP (takeBetween m n f) p
1009-- | @count n f p@ collects exactly @n@ sequential parses of parser @p@ using
1010-- the fold @f@. Fails if the input ends or the parser fails before @n@
1011-- results are collected.
1013-- /Unimplemented/
1015{-# INLINE count #-}
1016count ::
1017 -- MonadCatch m =>
1018 Int -> Parser m a b -> Fold m b c -> Parser m a c
1019count n = countBetween n n
1020-- count n p f = manyP (takeEQ n f) p
1022-- | Like 'manyTill' but uses a 'Parser' to collect the results instead of a
1023-- 'Fold'. Parsing stops or fails if the collecting parser stops or fails.
1025-- We can implemnent parsers like the following using 'manyTillP':
1027-- @
1028-- countBetweenTill m n f p = manyTillP (takeBetween m n f) p
1029-- @
1031-- /Unimplemented/
1033{-# INLINE manyTillP #-}
1034manyTillP :: -- MonadCatch m =>
1035 Parser m a b -> Parser m a x -> Parser m b c -> Parser m a c
1036manyTillP _p1 _p2 _f = undefined
1037 -- K.toParserK $ D.manyTillP (K.fromParserK p1) (K.fromParserK p2) f
1039-- | @manyTill f collect test@ tries the parser @test@ on the input, if @test@
1040-- fails it backtracks and tries @collect@, after @collect@ succeeds @test@ is
1041-- tried again and so on. The parser stops when @test@ succeeds. The output of
1042-- @test@ is discarded and the output of @collect@ is accumulated by the
1043-- supplied fold. The parser fails if @collect@ fails.
1045-- Stops when the fold @f@ stops.
1047-- /Pre-release/
1049{-# INLINE manyTill #-}
1050manyTill :: MonadCatch m
1051 => Parser m a b -> Parser m a x -> Fold m b c -> Parser m a c
1052manyTill p1 p2 f =
1053 K.toParserK $ D.manyTill f (K.fromParserK p1) (K.fromParserK p2)
1055-- | @manyThen f collect recover@ repeats the parser @collect@ on the input and
1056-- collects the output in the supplied fold. If the the parser @collect@ fails,
1057-- parser @recover@ is run until it stops and then we start repeating the
1058-- parser @collect@ again. The parser fails if the recovery parser fails.
1060-- For example, this can be used to find a key frame in a video stream after an
1061-- error.
1063-- /Unimplemented/
1065{-# INLINE manyThen #-}
1066manyThen :: -- (Foldable t, MonadCatch m) =>
1067 Parser m a b -> Parser m a x -> Fold m b c -> Parser m a c
1068manyThen _parser _recover _f = undefined
1070-------------------------------------------------------------------------------
1071-- Interleaving a collection of parsers
1072-------------------------------------------------------------------------------
1074-- | Apply a collection of parsers to an input stream in a round robin fashion.
1075-- Each parser is applied until it stops and then we repeat starting with the
1076-- the first parser again.
1078-- /Unimplemented/
1080{-# INLINE roundRobin #-}
1081roundRobin :: -- (Foldable t, MonadCatch m) =>
1082 t (Parser m a b) -> Fold m b c -> Parser m a c
1083roundRobin _ps _f = undefined
1085-------------------------------------------------------------------------------
1086-- Repeated Alternatives
1087-------------------------------------------------------------------------------
1089-- | Keep trying a parser up to a maximum of @n@ failures. When the parser
1090-- fails the input consumed till now is dropped and the new instance is tried
1091-- on the fresh input.
1093-- /Unimplemented/
1095{-# INLINE retryMaxTotal #-}
1096retryMaxTotal :: -- (MonadCatch m) =>
1097 Int -> Parser m a b -> Fold m b c -> Parser m a c
1098retryMaxTotal _n _p _f = undefined
1100-- | Like 'retryMaxTotal' but aborts after @n@ successive failures.
1102-- /Unimplemented/
1104{-# INLINE retryMaxSuccessive #-}
1105retryMaxSuccessive :: -- (MonadCatch m) =>
1106 Int -> Parser m a b -> Fold m b c -> Parser m a c
1107retryMaxSuccessive _n _p _f = undefined
1109-- | Keep trying a parser until it succeeds. When the parser fails the input
1110-- consumed till now is dropped and the new instance is tried on the fresh
1111-- input.
1113-- /Unimplemented/
1115{-# INLINE retry #-}
1116retry :: -- (MonadCatch m) =>
1117 Parser m a b -> Parser m a b
1118retry _p = undefined