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.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
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-------------------------------------------------------------------------------
222-- | Make a 'Parser' from a 'Fold'.
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-------------------------------------------------------------------------------
234-- This is the dual of stream "fromPure".
236-- | A parser that always yields a pure value without consuming any input.
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".
248-- | A parser that always yields the result of an effectful action without
249-- consuming any input.
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".
259-- | A parser that always fails with an error message without consuming
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".
272-- | A parser that always fails with an effectful error message and without
273-- consuming any input.
278dieM :: MonadCatch m => m String -> Parser m a b
279dieM = K.toParserK . D.dieM
281-------------------------------------------------------------------------------
283-------------------------------------------------------------------------------
285-- | Peek the head element of a stream, without consuming it. Fails if it
286-- encounters end of input.
288-- >>> Stream.parse ((,) <$> Parser.peek <*> Parser.satisfy (> 0)) $ Stream.fromList [1]
292-- peek = lookAhead (satisfy True)
298peek :: MonadCatch m => Parser m a a
299peek = K.toParserK D.peek
301-- | Succeeds if we are at the end of input, fails otherwise.
303-- >>> Stream.parse ((,) <$> Parser.satisfy (> 0) <*> Parser.eof) $ Stream.fromList [1]
309eof :: MonadCatch m => Parser m a ()
310eof = K.toParserK D.eof
312-- | Returns the next element if it passes the predicate, fails otherwise.
314-- >>> Stream.parse (Parser.satisfy (== 1)) $ Stream.fromList [1,0,1]
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'
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.
340either :: MonadCatch m => (a -> Either String b) -> Parser m a b
341either = K.toParserK . D.either
343-------------------------------------------------------------------------------
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.
350-- Stops after @n@ elements.
351-- Fails if the stream ends before @m@ elements could be taken.
357-- takeBetween' low high ls = Stream.parse prsr (Stream.fromList ls)
358-- where prsr = Parser.takeBetween low high Fold.toList
363-- >>> takeBetween' 2 4 [1, 2, 3, 4, 5]
366-- >>> takeBetween' 2 4 [1, 2]
369-- >>> takeBetween' 2 4 [1]
370-- *** Exception: ParseError "takeBetween: Expecting alteast 2 elements, got 1"
372-- >>> takeBetween' 0 0 [1, 2]
375-- >>> takeBetween' 0 1 []
378-- @takeBetween@ is the most general take operation, other take operations can
379-- be defined in terms of takeBetween. For example:
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
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.
397-- * Stops - after consuming @n@ elements.
398-- * Fails - if the stream or the collecting fold ends before it can collect
399-- exactly @n@ elements.
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"
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.
412-- * Stops - when the collecting fold stops.
413-- * Fails - if the stream or the collecting fold ends before producing @n@
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"
419-- >>> Stream.parse (Parser.takeGE 4 Fold.toList) $ Stream.fromList [1,0,1,0,1]
425takeGE :: MonadCatch m => Int -> Fold m a b -> Parser m a b
426takeGE n = K.toParserK . D.takeGE n
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
435-- This is a generalized version of takeWhile, for example 'takeWhile1' can be
436-- implemented in terms of this:
439-- takeWhile1 cond p = takeWhile cond (takeBetween 1 maxBound p)
442-- Stops: when the condition fails or the collecting parser stops.
443-- Fails: when the collecting parser fails.
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.
455-- * Stops - when the predicate fails or the collecting fold stops.
458-- >>> Stream.parse (Parser.takeWhile (== 0) Fold.toList) $ Stream.fromList [0,0,1,0,1]
461-- We can implement a @breakOn@ using 'takeWhile':
464-- breakOn p = takeWhile (not p)
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.
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.
484-- This is also called @skipWhile@ in some parsing libraries.
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.
495-- This is a generalized slicing parser which can be used to implement other
499-- sliceSepByMax cond n p = sliceSepByP cond (take n p)
500-- sliceSepByBetween cond m n p = sliceSepByP cond (takeBetween m n p)
505{-# INLINABLE sliceSepByP #-}
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.
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.
526-- * Stops - when the predicate succeeds in non-leading position.
529-- S.splitWithPrefix pred f = S.parseMany (PR.sliceBeginWith pred f)
534-- sliceBeginWithOdd ls = Stream.parse prsr (Stream.fromList ls)
535-- where prsr = Parser.sliceBeginWith odd Fold.toList
539-- >>> sliceBeginWithOdd [2, 4, 6, 3]
540-- *** Exception: sliceBeginWith : slice begins with an element which fails the predicate
543-- >>> sliceBeginWithOdd [3, 5, 7, 4]
546-- >>> sliceBeginWithOdd [3, 4, 6, 8, 5]
549-- >>> sliceBeginWithOdd []
554{-# INLINABLE sliceBeginWith #-}
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.
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.
578-- > Stream.parse (Parser.escapedFrameBy (== '{') (== '}') (== '\\') Fold.toList) $ Stream.fromList "{hello}"
581-- > Stream.parse (Parser.escapedFrameBy (== '{') (== '}') (== '\\') Fold.toList) $ Stream.fromList "{hello {world}}"
584-- > Stream.parse (Parser.escapedFrameBy (== '{') (== '}') (== '\\') Fold.toList) $ Stream.fromList "{hello \\{world\\}}"
587-- > Stream.parse (Parser.escapedFrameBy (== '{') (== '}') (== '\\') Fold.toList) $ Stream.fromList "{hello {world}"
588-- ParseError "Unterminated '{'"
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
604-- * Stops - when it finds a word separator after a non-word element
608-- S.wordsBy pred f = S.parseMany (PR.wordBy pred f)
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.
622-- * Stops - when the comparison fails.
628-- . Stream.parseMany (Parser.groupBy eq Fold.toList)
632-- >>> runGroupsBy (<) []
635-- >>> runGroupsBy (<) [1]
638-- >>> runGroupsBy (<) [3, 5, 4, 1, 2, 0]
639-- [[3,5,4],[1,2],[0]]
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.
656-- * Stops - when the comparison fails.
660-- runGroupsByRolling eq =
662-- . Stream.parseMany (Parser.groupByRolling eq Fold.toList)
666-- >>> runGroupsByRolling (<) []
669-- >>> runGroupsByRolling (<) [1]
672-- >>> runGroupsByRolling (<) [3, 5, 4, 1, 2, 0]
673-- [[3,5],[4],[1,2],[0]]
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.
683-- >>> Stream.parse (Parser.eqBy (==) "string") $ Stream.fromList "string"
685-- >>> Stream.parse (Parser.eqBy (==) "mismatch") $ Stream.fromList "match"
686-- *** Exception: ParseError "eqBy: failed, yet to match 7 elements"
691eqBy :: MonadCatch m => (a -> a -> Bool) -> [a] -> Parser m a ()
692eqBy cmp = K.toParserK . D.eqBy cmp
694-------------------------------------------------------------------------------
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.
704-- Note: This is a parsing dual of appending streams using
705-- 'Streamly.Prelude.serial', it splits the streams using two parsers and zips
708-- This implementation is strict in the second argument, therefore, the
709-- following will fail:
711-- >>> Stream.parse (Parser.serialWith const (Parser.satisfy (> 0)) undefined) $ Stream.fromList [1]
712-- *** Exception: Prelude.undefined
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.
720-- Many combinators can be expressed using @serialWith@ and other parser
721-- primitives. Some common idioms are described below,
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)
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)
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)
740{-# INLINE serialWith #-}
741serialWith :: MonadCatch m
742 => (a -> b -> c) -> Parser m x a -> Parser m x b -> Parser m x c
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.
752-- This implementation is strict in the second argument, therefore, the
753-- following will fail:
755-- >>> Stream.parse (Parser.split_ (Parser.satisfy (> 0)) undefined) $ Stream.fromList [1]
756-- *** Exception: Prelude.undefined
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.
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.
776{-# INLINE teeWith #-}
777teeWith :: MonadCatch m
778 => (a -> b -> c) -> Parser m x a -> Parser m x b -> Parser m x c
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.
787{-# INLINE teeWithFst #-}
788teeWithFst :: MonadCatch m
789 => (a -> b -> c) -> Parser m x a -> Parser m x b -> Parser m x c
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.
798{-# INLINE teeWithMin #-}
799teeWithMin :: MonadCatch m
800 => (a -> b -> c) -> Parser m x a -> Parser m x b -> Parser m x c
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.
808-- Note: This implementation is not lazy in the second argument. The following
811-- >>> Stream.parse (Parser.satisfy (> 0) `Parser.alt` undefined) $ Stream.fromList [1..10]
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.
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
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
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.
851{-# INLINE lookAhead #-}
852lookAhead :: MonadCatch m => Parser m a b -> Parser m a b
853lookAhead p = K.toParserK $ D.lookAhead $ K.fromParserK p
855-------------------------------------------------------------------------------
857-------------------------------------------------------------------------------
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.
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.
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
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
879-- This undoes a "gintercalate" of two streams.
883{-# INLINE deintercalate #-}
886 Fold m a y -> Parser m x a
887 -> Fold m b z -> Parser m x b
889deintercalate = undefined
891-------------------------------------------------------------------------------
892-- Sequential Collection
893-------------------------------------------------------------------------------
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
899-- This is same as 'Data.Traversable.sequence' but more efficient.
903{-# INLINE concatSequence #-}
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'.
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.
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-------------------------------------------------------------------------------
927-- | @choice parsers@ applies the @parsers@ in order and returns the first
930-- This is same as 'asum' but more efficient.
937 t (Parser m a b) -> Parser m a b
938choice _ps = undefined
940-------------------------------------------------------------------------------
941-- Sequential Repetition
942-------------------------------------------------------------------------------
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.
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.
962-- Stops: when the downstream fold stops or the parser fails.
963-- Fails: never, produces zero or more results.
965-- Compare with 'Control.Applicative.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
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.
981-- Stops: when the downstream fold stops or the parser fails.
982-- Fails: if it stops without producing a single result.
984-- @some fld parser = manyP (takeGE 1 fld) parser@
986-- Compare with 'Control.Applicative.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.
1002{-# INLINE countBetween #-}
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.
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':
1028-- countBetweenTill m n f p = manyTillP (takeBetween m n f) p
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.
1049{-# INLINE manyTill #-}
1050manyTill :: MonadCatch m
1051 => Parser m a b -> Parser m a x -> Fold m b c -> Parser m a c
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
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.
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.
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.
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
1116retry :: -- (MonadCatch m) =>
1117 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