1{-# OPTIONS_GHC -Wno-incomplete-uni-patterns #-}
6-- Module : Streamly.Internal.Data.Parser.ParserD.Tee
7-- Copyright : (c) 2020 Composewell Technologies
8-- License : BSD-3-Clause
9-- Maintainer : streamly@composewell.com
10-- Stability : experimental
13-- Parallel parsers. Distributing the input to multiple parsers at the same
16-- For simplicity, we are using code where a particular state is unreachable
17-- but it is not prevented by types. Somehow uni-pattern match using "let"
18-- produces better optimized code compared to using @case@ match and using
19-- explicit error messages in unreachable cases.
21-- There seem to be no way to silence individual warnings so we use a global
22-- incomplete uni-pattern match warning suppression option for the file.
23-- Disabling the warning for other code as well has the potential to mask off
24-- some legit warnings, therefore, we have segregated only the code that uses
25-- uni-pattern matches in this module.
27module Streamly.Internal.Data.Parser.ParserD.Tee
34 -- Parallel alternatives
40import Control.Exception (assert)
41import Control.Monad.Catch (MonadCatch, try)
43 hiding (any, all, takeWhile)
45import Fusion.Plugin.Types (Fuse(..))
46import Streamly.Internal.Data.Parser.ParserD.Type
47 (Initial(..), Parser(..), Step(..), ParseError)
49-------------------------------------------------------------------------------
50-- Distribute input to two parsers and collect both results
51-------------------------------------------------------------------------------
53-- When the input stream is distributed to two parsers, both the parsers can
54-- backtrack independently. Therefore, we need separate buffer state for each
59-- We can keep the state of each parser in the zipper and pass around that
60-- zipper to the parsers. Each parser can consume from the zipper and then pass
61-- around the zipper to the other parser.
65-- In the approach we have taken here, the driver pushes one element at a time
66-- to the tee and each of the parsers in the tee may buffer it independently
67-- for backtracking. So they do not need to depend on the original stream
68-- source for individual parser backtracking. Problem arises when both the
69-- parsers backtrack and they do not need any input from the driver rather they
70-- must consume from their buffers. For such situation we may need a
71-- "Continue" style driver command from the tee so that the driver runs
72-- the tee without providing it any input. Or we may need a local driver loop
73-- until new input is to be demanded from the input stream.
75-- When the tee errors out or stops, the tee driver may have to backtrack by
76-- the specified amount (or the tee must return the leftover input). Therefore,
77-- the tee driver also has to buffer, this leads to triple buffering.
79-- When the tee stops we need to determine the backtracking amount from the
80-- leftover of both the parsers. Since both the parsers may have consumed
81-- different lengths of the stream we consider the maximum of the two as
84 -- XXX We can use Initial instead of StepState
85{-# ANN type StepState Fuse #-}
86data StepState s a = StepState s | StepResult a
88-- | State of the pair of parsers in a tee composition
89-- Note: strictness annotation is important for fusing the constructors
90{-# ANN type TeeState Fuse #-}
91data TeeState sL sR x a b =
92-- @TeePair (past buffer, parser state, future-buffer1, future-buffer2) ...@
93 TeePair !([x], StepState sL a, [x], [x]) !([x], StepState sR b, [x], [x])
95{-# ANN type Res Fuse #-}
96data Res = Yld Int | Stp Int | Skp | Err String
98-- | See 'Streamly.Internal.Data.Parser.teeWith'.
102{-# INLINE teeWith #-}
104 => (a -> b -> c) -> Parser m x a -> Parser m x b -> Parser m x c
105teeWith zf (Parser stepL initialL extractL) (Parser stepR initialR extractR) =
106 Parser step initial extract
110 {-# INLINE_LATE initial #-}
114 return $ case resL of
117 IPartial sr -> IPartial $ TeePair ([], StepState sl, [], [])
118 ([], StepState sr, [], [])
119 IDone br -> IPartial $ TeePair ([], StepState sl, [], [])
120 ([], StepResult br, [], [])
121 IError err -> IError err
125 IPartial $ TeePair ([], StepResult bl, [], [])
126 ([], StepState sr, [], [])
127 IDone br -> IDone $ zf bl br
128 IError err -> IError err
129 IError err -> IError err
131 {-# INLINE consume #-}
132 consume buf inp1 inp2 stp st y = do
133 let (x, inp11, inp21) =
136 z : [] -> (z, reverse (x:inp2), [])
137 z : zs -> (z, zs, x:inp2)
140 return (buf1, r, inp11, inp21)
142 -- XXX This is currently broken, even though both the parsers need to
143 -- consume from their buffers after backtracking the driver would still be
144 -- pushing more input to the buffers.
146 -- consume one input item and return the next state of the fold
147 {-# INLINE useStream #-}
148 useStream buf inp1 inp2 stp st y = do
149 (buf1, r, inp11, inp21) <- consume buf inp1 inp2 stp st y
152 let state = ([], StepState s, inp11, inp21)
153 in return (state, Yld 0)
155 let src0 = Prelude.take n buf1
156 src = Prelude.reverse src0
157 state = ([], StepState s, src ++ inp11, inp21)
158 in assert (n <= length buf1) (return (state, Yld n))
160 let state = (Prelude.take n buf1, StepResult b, inp11, inp21)
161 in assert (n <= length buf1) (return (state, Stp n))
162 -- Continue 0 s -> (buf1, Right s, inp11, inp21)
164 let (src0, buf2) = splitAt n buf1
165 src = Prelude.reverse src0
166 state = (buf2, StepState s, src ++ inp11, inp21)
167 in assert (n <= length buf1) (return (state, Skp))
168 Error err -> return (undefined, Err err)
170 {-# INLINE_LATE step #-}
171 step (TeePair (bufL, StepState sL, inpL1, inpL2)
172 (bufR, StepState sR, inpR1, inpR2)) x = do
173 (l,stL) <- useStream bufL inpL1 inpL2 stepL sL x
174 (r,stR) <- useStream bufR inpR1 inpR2 stepR sR x
175 let next = TeePair l r
176 return $ case (stL,stR) of
177 (Yld n1, Yld n2) -> Partial (min n1 n2) next
178 (Yld n1, Stp n2) -> Partial (min n1 n2) next
179 (Stp n1, Yld n2) -> Partial (min n1 n2) next
181 -- Uni-pattern match results in better optimized code compared
183 let (_, StepResult rL, _, _) = l
184 (_, StepResult rR, _, _) = r
185 in Done (min n1 n2) (zf rL rR)
186 (Err err, _) -> Error err
187 (_, Err err) -> Error err
190 step (TeePair (bufL, StepState sL, inpL1, inpL2)
191 r@(_, StepResult rR, _, _)) x = do
192 (l,stL) <- useStream bufL inpL1 inpL2 stepL sL x
193 let next = TeePair l r
194 -- XXX If the unused count of this stream is lower than the unused
195 -- count of the stopped stream, only then this will be correct. We need
196 -- to fix the other case. We need to keep incrementing the unused count
197 -- of the stopped stream and take the min of the two.
199 Yld n -> Partial n next
201 let (_, StepResult rL, _, _) = l
203 Skp -> Continue 0 next
206 step (TeePair l@(_, StepResult rL, _, _)
207 (bufR, StepState sR, inpR1, inpR2)) x = do
208 (r, stR) <- useStream bufR inpR1 inpR2 stepR sR x
209 let next = TeePair l r
210 -- XXX If the unused count of this stream is lower than the unused
211 -- count of the stopped stream, only then this will be correct. We need
212 -- to fix the other case. We need to keep incrementing the unused count
213 -- of the stopped stream and take the min of the two.
215 Yld n -> Partial n next
217 let (_, StepResult rR, _, _) = r
219 Skp -> Continue 0 next
224 {-# INLINE_LATE extract #-}
227 TeePair (_, StepState sL, _, _) (_, StepState sR, _, _) -> do
231 TeePair (_, StepState sL, _, _) (_, StepResult rR, _, _) -> do
234 TeePair (_, StepResult rL, _, _) (_, StepState sR, _, _) -> do
237 TeePair (_, StepResult rL, _, _) (_, StepResult rR, _, _) ->
240-- | See 'Streamly.Internal.Data.Parser.teeWithFst'.
244{-# INLINE teeWithFst #-}
246 => (a -> b -> c) -> Parser m x a -> Parser m x b -> Parser m x c
247teeWithFst zf (Parser stepL initialL extractL)
248 (Parser stepR initialR extractR) =
249 Parser step initial extract
253 {-# INLINE_LATE initial #-}
259 return $ case resR of
260 IPartial sr -> IPartial $ TeePair ([], StepState sl, [], [])
261 ([], StepState sr, [], [])
262 IDone br -> IPartial $ TeePair ([], StepState sl, [], [])
263 ([], StepResult br, [], [])
264 IError err -> IError err
267 IPartial sr -> IDone . zf bl <$> extractR sr
268 IDone br -> return $ IDone $ zf bl br
269 IError err -> return $ IError err
270 IError err -> return $ IError err
272 {-# INLINE consume #-}
273 consume buf inp1 inp2 stp st y = do
274 let (x, inp11, inp21) =
277 z : [] -> (z, reverse (x:inp2), [])
278 z : zs -> (z, zs, x:inp2)
281 return (buf1, r, inp11, inp21)
283 -- consume one input item and return the next state of the fold
284 {-# INLINE useStream #-}
285 useStream buf inp1 inp2 stp st y = do
286 (buf1, r, inp11, inp21) <- consume buf inp1 inp2 stp st y
289 let state = ([], StepState s, inp11, inp21)
290 in return (state, Yld 0)
291 Partial n _ -> return (undefined, Yld n) -- Not implemented
293 let state = (Prelude.take n buf1, StepResult b, inp11, inp21)
294 in assert (n <= length buf1) (return (state, Stp n))
295 -- Continue 0 s -> (buf1, Right s, inp11, inp21)
297 let (src0, buf2) = splitAt n buf1
298 src = Prelude.reverse src0
299 state = (buf2, StepState s, src ++ inp11, inp21)
300 in assert (n <= length buf1) (return (state, Skp))
301 Error err -> return (undefined, Err err)
303 {-# INLINE_LATE step #-}
304 step (TeePair (bufL, StepState sL, inpL1, inpL2)
305 (bufR, StepState sR, inpR1, inpR2)) x = do
306 (l,stL) <- useStream bufL inpL1 inpL2 stepL sL x
307 (r,stR) <- useStream bufR inpR1 inpR2 stepR sR x
308 let next = TeePair l r
310 -- XXX what if the first parser returns an unused count which is
311 -- more than the second parser's unused count? It does not make
312 -- sense for the second parser to consume more than the first
313 -- parser. We reset the input cursor based on the first parser.
314 -- Error out if the second one has consumed more then the first?
316 -- Uni-pattern match results in better optimized code compared
318 let (_, StepResult rL, _, _) = l
319 (_, StepResult rR, _, _) = r
320 in return $ Done n1 (zf rL rR)
322 let (_, StepResult rL, _, _) = l
323 (_, StepState ssR, _, _) = r
326 return $ Done n1 (zf rL rR)
327 (Yld n1, Yld n2) -> return $ Partial (min n1 n2) next
328 (Yld n1, Stp n2) -> return $ Partial (min n1 n2) next
329 (Err err, _) -> return $ Error err
330 (_, Err err) -> return $ Error err
331 _ -> return $ Continue 0 next
333 step (TeePair (bufL, StepState sL, inpL1, inpL2)
334 r@(_, StepResult rR, _, _)) x = do
335 (l,stL) <- useStream bufL inpL1 inpL2 stepL sL x
336 let next = TeePair l r
337 -- XXX If the unused count of this stream is lower than the unused
338 -- count of the stopped stream, only then this will be correct. We need
339 -- to fix the other case. We need to keep incrementing the unused count
340 -- of the stopped stream and take the min of the two.
342 Yld n -> Partial n next
344 let (_, StepResult rL, _, _) = l
346 Skp -> Continue 0 next
351 {-# INLINE_LATE extract #-}
354 TeePair (_, StepState sL, _, _) (_, StepState sR, _, _) -> do
358 TeePair (_, StepState sL, _, _) (_, StepResult rR, _, _) -> do
361 _ -> error "unreachable"
363-- | See 'Streamly.Internal.Data.Parser.teeWithMin'.
367{-# INLINE teeWithMin #-}
370 (a -> b -> c) -> Parser m x a -> Parser m x b -> Parser m x c
371teeWithMin = undefined
373-------------------------------------------------------------------------------
374-- Distribute input to two parsers and choose one result
375-------------------------------------------------------------------------------
377-- | See 'Streamly.Internal.Data.Parser.shortest'.
381{-# INLINE shortest #-}
382shortest :: Monad m => Parser m x a -> Parser m x a -> Parser m x a
383shortest (Parser stepL initialL extractL) (Parser stepR initialR _) =
384 Parser step initial extract
388 {-# INLINE_LATE initial #-}
392 return $ case resL of
395 IPartial sr -> IPartial $ TeePair ([], StepState sl, [], [])
396 ([], StepState sr, [], [])
398 IError err -> IError err
402 IPartial _ -> IError errL
404 IError errR -> IError errR
406 {-# INLINE consume #-}
407 consume buf inp1 inp2 stp st y = do
408 let (x, inp11, inp21) =
411 z : [] -> (z, reverse (x:inp2), [])
412 z : zs -> (z, zs, x:inp2)
415 return (buf1, r, inp11, inp21)
417 -- consume one input item and return the next state of the fold
418 {-# INLINE useStream #-}
419 useStream buf inp1 inp2 stp st y = do
420 (buf1, r, inp11, inp21) <- consume buf inp1 inp2 stp st y
423 let state = ([], StepState s, inp11, inp21)
424 in return (state, Yld 0)
425 Partial n _ -> return (undefined, Yld n) -- Not implemented
427 let state = (Prelude.take n buf1, StepResult b, inp11, inp21)
428 in assert (n <= length buf1) (return (state, Stp n))
429 -- Continue 0 s -> (buf1, Right s, inp11, inp21)
431 let (src0, buf2) = splitAt n buf1
432 src = Prelude.reverse src0
433 state = (buf2, StepState s, src ++ inp11, inp21)
434 in assert (n <= length buf1) (return (state, Skp))
435 Error err -> return (undefined, Err err)
437 -- XXX Even if a parse finished earlier it may not be shortest if the other
438 -- parser finishes later but returns a lot of unconsumed input. Our current
439 -- criterion of shortest is whichever parse decided to stop earlier.
440 {-# INLINE_LATE step #-}
441 step (TeePair (bufL, StepState sL, inpL1, inpL2)
442 (bufR, StepState sR, inpR1, inpR2)) x = do
443 (l,stL) <- useStream bufL inpL1 inpL2 stepL sL x
444 (r,stR) <- useStream bufR inpR1 inpR2 stepR sR x
445 let next = TeePair l r
446 return $ case (stL,stR) of
448 let (_, StepResult rL, _, _) = l
451 let (_, StepResult rR, _, _) = r
453 (Yld n1, Yld n2) -> Partial (min n1 n2) next
454 (Err err, _) -> Error err
455 (_, Err err) -> Error err
460 {-# INLINE_LATE extract #-}
463 TeePair (_, StepState sL, _, _) _ -> extractL sL
464 _ -> error "unreachable"
466-- | See 'Streamly.Internal.Data.Parser.longest'.
470{-# INLINE longest #-}
471longest :: MonadCatch m => Parser m x a -> Parser m x a -> Parser m x a
472longest (Parser stepL initialL extractL) (Parser stepR initialR extractR) =
473 Parser step initial extract
478 {-# INLINE_LATE initial #-}
482 return $ case resL of
485 IPartial sr -> IPartial $ TeePair ([], StepState sl, [], [])
486 ([], StepState sr, [], [])
487 IDone br -> IPartial $ TeePair ([], StepState sl, [], [])
488 ([], StepResult br, [], [])
490 IPartial $ TeePair ([], StepState sl, [], [])
491 ([], StepResult undefined, [], [])
495 IPartial $ TeePair ([], StepResult bl, [], [])
496 ([], StepState sr, [], [])
502 IPartial $ TeePair ([], StepResult undefined, [], [])
503 ([], StepState sr, [], [])
505 IError err -> IError err
507 {-# INLINE consume #-}
508 consume buf inp1 inp2 stp st y = do
509 let (x, inp11, inp21) =
512 z : [] -> (z, reverse (x:inp2), [])
513 z : zs -> (z, zs, x:inp2)
516 return (buf1, r, inp11, inp21)
518 -- consume one input item and return the next state of the fold
519 {-# INLINE useStream #-}
520 useStream buf inp1 inp2 stp st y = do
521 (buf1, r, inp11, inp21) <- consume buf inp1 inp2 stp st y
524 let state = ([], StepState s, inp11, inp21)
525 in return (state, Yld 0)
526 Partial n _ -> return (undefined, Yld n) -- Not implemented
528 let state = (Prelude.take n buf1, StepResult b, inp11, inp21)
529 in assert (n <= length buf1) (return (state, Stp n))
530 -- Continue 0 s -> (buf1, Right s, inp11, inp21)
532 let (src0, buf2) = splitAt n buf1
533 src = Prelude.reverse src0
534 state = (buf2, StepState s, src ++ inp11, inp21)
535 in assert (n <= length buf1) (return (state, Skp))
536 Error err -> return (undefined, Err err)
538 {-# INLINE_LATE step #-}
539 step (TeePair (bufL, StepState sL, inpL1, inpL2)
540 (bufR, StepState sR, inpR1, inpR2)) x = do
541 (l,stL) <- useStream bufL inpL1 inpL2 stepL sL x
542 (r,stR) <- useStream bufR inpR1 inpR2 stepR sR x
543 let next = TeePair l r
544 return $ case (stL,stR) of
545 (Yld n1, Yld n2) -> Partial (min n1 n2) next
546 (Yld n1, Stp n2) -> Partial (min n1 n2) next
547 (Stp n1, Yld n2) -> Partial (min n1 n2) next
549 let (_, StepResult rL, _, _) = l
550 (_, StepResult rR, _, _) = r
551 in Done (max n1 n2) (if n1 >= n2 then rL else rR)
552 (Err err, _) -> Error err
553 (_, Err err) -> Error err
556 -- XXX the parser that finishes last may not be the longest because it may
557 -- return a lot of unused input which makes it shorter. Our current
558 -- criterion of deciding longest is based on whoever decides to finish
559 -- last and not whoever consumed more input.
561 -- To actually know who made more progress we need to keep an account of
562 -- how many items are unconsumed since the last yield.
564 step (TeePair (bufL, StepState sL, inpL1, inpL2)
565 r@(_, StepResult _, _, _)) x = do
566 (l,stL) <- useStream bufL inpL1 inpL2 stepL sL x
567 let next = TeePair l r
569 Yld n -> Partial n next
571 let (_, StepResult rL, _, _) = l
573 Skp -> Continue 0 next
576 step (TeePair l@(_, StepResult _, _, _)
577 (bufR, StepState sR, inpR1, inpR2)) x = do
578 (r, stR) <- useStream bufR inpR1 inpR2 stepR sR x
579 let next = TeePair l r
581 Yld n -> Partial n next
583 let (_, StepResult rR, _, _) = r
585 Skp -> Continue 0 next
590 {-# INLINE_LATE extract #-}
592 -- XXX When results are partial we may not be able to precisely compare
593 -- which parser has made more progress till now. One way to do that is
594 -- to figure out the actually consumed input up to the last yield.
597 TeePair (_, StepState sL, _, _) (_, StepState sR, _, _) -> do
598 r <- try $ extractL sL
600 Left (_ :: ParseError) -> extractR sR
602 TeePair (_, StepState sL, _, _) (_, StepResult rR, _, _) -> do
603 r <- try $ extractL sL
605 Left (_ :: ParseError) -> return rR
607 TeePair (_, StepResult rL, _, _) (_, StepState sR, _, _) -> do
608 r <- try $ extractR sR
610 Left (_ :: ParseError) -> return rL
612 TeePair (_, StepResult _, _, _) (_, StepResult _, _, _) ->
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