fea637fafe434cb0330a49baead603e5de74df80
[ghc.git] / compiler / deSugar / DsListComp.hs
1 {-
2 (c) The University of Glasgow 2006
3 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4
5
6 Desugaring list comprehensions, monad comprehensions and array comprehensions
7 -}
8
9 {-# LANGUAGE CPP, NamedFieldPuns #-}
10 {-# LANGUAGE TypeFamilies #-}
11
12 module DsListComp ( dsListComp, dsPArrComp, dsMonadComp ) where
13
14 #include "HsVersions.h"
15
16 import GhcPrelude
17
18 import {-# SOURCE #-} DsExpr ( dsExpr, dsLExpr, dsLExprNoLP, dsLocalBinds, dsSyntaxExpr )
19
20 import HsSyn
21 import TcHsSyn
22 import CoreSyn
23 import MkCore
24
25 import DsMonad -- the monadery used in the desugarer
26 import DsUtils
27
28 import DynFlags
29 import CoreUtils
30 import Id
31 import Type
32 import TysWiredIn
33 import Match
34 import PrelNames
35 import SrcLoc
36 import Outputable
37 import TcType
38 import ListSetOps( getNth )
39 import Util
40
41 {-
42 List comprehensions may be desugared in one of two ways: ``ordinary''
43 (as you would expect if you read SLPJ's book) and ``with foldr/build
44 turned on'' (if you read Gill {\em et al.}'s paper on the subject).
45
46 There will be at least one ``qualifier'' in the input.
47 -}
48
49 dsListComp :: [ExprLStmt GhcTc]
50 -> Type -- Type of entire list
51 -> DsM CoreExpr
52 dsListComp lquals res_ty = do
53 dflags <- getDynFlags
54 let quals = map unLoc lquals
55 elt_ty = case tcTyConAppArgs res_ty of
56 [elt_ty] -> elt_ty
57 _ -> pprPanic "dsListComp" (ppr res_ty $$ ppr lquals)
58
59 if not (gopt Opt_EnableRewriteRules dflags) || gopt Opt_IgnoreInterfacePragmas dflags
60 -- Either rules are switched off, or we are ignoring what there are;
61 -- Either way foldr/build won't happen, so use the more efficient
62 -- Wadler-style desugaring
63 || isParallelComp quals
64 -- Foldr-style desugaring can't handle parallel list comprehensions
65 then deListComp quals (mkNilExpr elt_ty)
66 else mkBuildExpr elt_ty (\(c, _) (n, _) -> dfListComp c n quals)
67 -- Foldr/build should be enabled, so desugar
68 -- into foldrs and builds
69
70 where
71 -- We must test for ParStmt anywhere, not just at the head, because an extension
72 -- to list comprehensions would be to add brackets to specify the associativity
73 -- of qualifier lists. This is really easy to do by adding extra ParStmts into the
74 -- mix of possibly a single element in length, so we do this to leave the possibility open
75 isParallelComp = any isParallelStmt
76
77 isParallelStmt (ParStmt {}) = True
78 isParallelStmt _ = False
79
80
81 -- This function lets you desugar a inner list comprehension and a list of the binders
82 -- of that comprehension that we need in the outer comprehension into such an expression
83 -- and the type of the elements that it outputs (tuples of binders)
84 dsInnerListComp :: (ParStmtBlock GhcTc GhcTc) -> DsM (CoreExpr, Type)
85 dsInnerListComp (ParStmtBlock stmts bndrs _)
86 = do { let bndrs_tuple_type = mkBigCoreVarTupTy bndrs
87 list_ty = mkListTy bndrs_tuple_type
88
89 -- really use original bndrs below!
90 ; expr <- dsListComp (stmts ++ [noLoc $ mkLastStmt (mkBigLHsVarTupId bndrs)]) list_ty
91
92 ; return (expr, bndrs_tuple_type) }
93
94 -- This function factors out commonality between the desugaring strategies for GroupStmt.
95 -- Given such a statement it gives you back an expression representing how to compute the transformed
96 -- list and the tuple that you need to bind from that list in order to proceed with your desugaring
97 dsTransStmt :: ExprStmt GhcTc -> DsM (CoreExpr, LPat GhcTc)
98 dsTransStmt (TransStmt { trS_form = form, trS_stmts = stmts, trS_bndrs = binderMap
99 , trS_by = by, trS_using = using }) = do
100 let (from_bndrs, to_bndrs) = unzip binderMap
101
102 let from_bndrs_tys = map idType from_bndrs
103 to_bndrs_tys = map idType to_bndrs
104
105 to_bndrs_tup_ty = mkBigCoreTupTy to_bndrs_tys
106
107 -- Desugar an inner comprehension which outputs a list of tuples of the "from" binders
108 (expr', from_tup_ty) <- dsInnerListComp (ParStmtBlock stmts from_bndrs noSyntaxExpr)
109
110 -- Work out what arguments should be supplied to that expression: i.e. is an extraction
111 -- function required? If so, create that desugared function and add to arguments
112 usingExpr' <- dsLExpr using
113 usingArgs' <- case by of
114 Nothing -> return [expr']
115 Just by_e -> do { by_e' <- dsLExpr by_e
116 ; lam' <- matchTuple from_bndrs by_e'
117 ; return [lam', expr'] }
118
119 -- Create an unzip function for the appropriate arity and element types and find "map"
120 unzip_stuff' <- mkUnzipBind form from_bndrs_tys
121 map_id <- dsLookupGlobalId mapName
122
123 -- Generate the expressions to build the grouped list
124 let -- First we apply the grouping function to the inner list
125 inner_list_expr' = mkApps usingExpr' usingArgs'
126 -- Then we map our "unzip" across it to turn the lists of tuples into tuples of lists
127 -- We make sure we instantiate the type variable "a" to be a list of "from" tuples and
128 -- the "b" to be a tuple of "to" lists!
129 -- Then finally we bind the unzip function around that expression
130 bound_unzipped_inner_list_expr'
131 = case unzip_stuff' of
132 Nothing -> inner_list_expr'
133 Just (unzip_fn', unzip_rhs') ->
134 Let (Rec [(unzip_fn', unzip_rhs')]) $
135 mkApps (Var map_id) $
136 [ Type (mkListTy from_tup_ty)
137 , Type to_bndrs_tup_ty
138 , Var unzip_fn'
139 , inner_list_expr' ]
140
141 dsNoLevPoly (tcFunResultTyN (length usingArgs') (exprType usingExpr'))
142 (text "In the result of a" <+> quotes (text "using") <+> text "function:" <+> ppr using)
143
144 -- Build a pattern that ensures the consumer binds into the NEW binders,
145 -- which hold lists rather than single values
146 let pat = mkBigLHsVarPatTupId to_bndrs -- NB: no '!
147 return (bound_unzipped_inner_list_expr', pat)
148
149 dsTransStmt _ = panic "dsTransStmt: Not given a TransStmt"
150
151 {-
152 ************************************************************************
153 * *
154 \subsection[DsListComp-ordinary]{Ordinary desugaring of list comprehensions}
155 * *
156 ************************************************************************
157
158 Just as in Phil's chapter~7 in SLPJ, using the rules for
159 optimally-compiled list comprehensions. This is what Kevin followed
160 as well, and I quite happily do the same. The TQ translation scheme
161 transforms a list of qualifiers (either boolean expressions or
162 generators) into a single expression which implements the list
163 comprehension. Because we are generating 2nd-order polymorphic
164 lambda-calculus, calls to NIL and CONS must be applied to a type
165 argument, as well as their usual value arguments.
166 \begin{verbatim}
167 TE << [ e | qs ] >> = TQ << [ e | qs ] ++ Nil (typeOf e) >>
168
169 (Rule C)
170 TQ << [ e | ] ++ L >> = Cons (typeOf e) TE <<e>> TE <<L>>
171
172 (Rule B)
173 TQ << [ e | b , qs ] ++ L >> =
174 if TE << b >> then TQ << [ e | qs ] ++ L >> else TE << L >>
175
176 (Rule A')
177 TQ << [ e | p <- L1, qs ] ++ L2 >> =
178 letrec
179 h = \ u1 ->
180 case u1 of
181 [] -> TE << L2 >>
182 (u2 : u3) ->
183 (( \ TE << p >> -> ( TQ << [e | qs] ++ (h u3) >> )) u2)
184 [] (h u3)
185 in
186 h ( TE << L1 >> )
187
188 "h", "u1", "u2", and "u3" are new variables.
189 \end{verbatim}
190
191 @deListComp@ is the TQ translation scheme. Roughly speaking, @dsExpr@
192 is the TE translation scheme. Note that we carry around the @L@ list
193 already desugared. @dsListComp@ does the top TE rule mentioned above.
194
195 To the above, we add an additional rule to deal with parallel list
196 comprehensions. The translation goes roughly as follows:
197 [ e | p1 <- e11, let v1 = e12, p2 <- e13
198 | q1 <- e21, let v2 = e22, q2 <- e23]
199 =>
200 [ e | ((x1, .., xn), (y1, ..., ym)) <-
201 zip [(x1,..,xn) | p1 <- e11, let v1 = e12, p2 <- e13]
202 [(y1,..,ym) | q1 <- e21, let v2 = e22, q2 <- e23]]
203 where (x1, .., xn) are the variables bound in p1, v1, p2
204 (y1, .., ym) are the variables bound in q1, v2, q2
205
206 In the translation below, the ParStmt branch translates each parallel branch
207 into a sub-comprehension, and desugars each independently. The resulting lists
208 are fed to a zip function, we create a binding for all the variables bound in all
209 the comprehensions, and then we hand things off the the desugarer for bindings.
210 The zip function is generated here a) because it's small, and b) because then we
211 don't have to deal with arbitrary limits on the number of zip functions in the
212 prelude, nor which library the zip function came from.
213 The introduced tuples are Boxed, but only because I couldn't get it to work
214 with the Unboxed variety.
215 -}
216
217 deListComp :: [ExprStmt GhcTc] -> CoreExpr -> DsM CoreExpr
218
219 deListComp [] _ = panic "deListComp"
220
221 deListComp (LastStmt body _ _ : quals) list
222 = -- Figure 7.4, SLPJ, p 135, rule C above
223 ASSERT( null quals )
224 do { core_body <- dsLExpr body
225 ; return (mkConsExpr (exprType core_body) core_body list) }
226
227 -- Non-last: must be a guard
228 deListComp (BodyStmt guard _ _ _ : quals) list = do -- rule B above
229 core_guard <- dsLExpr guard
230 core_rest <- deListComp quals list
231 return (mkIfThenElse core_guard core_rest list)
232
233 -- [e | let B, qs] = let B in [e | qs]
234 deListComp (LetStmt binds : quals) list = do
235 core_rest <- deListComp quals list
236 dsLocalBinds binds core_rest
237
238 deListComp (stmt@(TransStmt {}) : quals) list = do
239 (inner_list_expr, pat) <- dsTransStmt stmt
240 deBindComp pat inner_list_expr quals list
241
242 deListComp (BindStmt pat list1 _ _ _ : quals) core_list2 = do -- rule A' above
243 core_list1 <- dsLExprNoLP list1
244 deBindComp pat core_list1 quals core_list2
245
246 deListComp (ParStmt stmtss_w_bndrs _ _ _ : quals) list
247 = do { exps_and_qual_tys <- mapM dsInnerListComp stmtss_w_bndrs
248 ; let (exps, qual_tys) = unzip exps_and_qual_tys
249
250 ; (zip_fn, zip_rhs) <- mkZipBind qual_tys
251
252 -- Deal with [e | pat <- zip l1 .. ln] in example above
253 ; deBindComp pat (Let (Rec [(zip_fn, zip_rhs)]) (mkApps (Var zip_fn) exps))
254 quals list }
255 where
256 bndrs_s = [bs | ParStmtBlock _ bs _ <- stmtss_w_bndrs]
257
258 -- pat is the pattern ((x1,..,xn), (y1,..,ym)) in the example above
259 pat = mkBigLHsPatTupId pats
260 pats = map mkBigLHsVarPatTupId bndrs_s
261
262 deListComp (RecStmt {} : _) _ = panic "deListComp RecStmt"
263
264 deListComp (ApplicativeStmt {} : _) _ =
265 panic "deListComp ApplicativeStmt"
266
267 deBindComp :: OutPat GhcTc
268 -> CoreExpr
269 -> [ExprStmt GhcTc]
270 -> CoreExpr
271 -> DsM (Expr Id)
272 deBindComp pat core_list1 quals core_list2 = do
273 let u3_ty@u1_ty = exprType core_list1 -- two names, same thing
274
275 -- u1_ty is a [alpha] type, and u2_ty = alpha
276 let u2_ty = hsLPatType pat
277
278 let res_ty = exprType core_list2
279 h_ty = u1_ty `mkFunTy` res_ty
280
281 -- no levity polymorphism here, as list comprehensions don't work
282 -- with RebindableSyntax. NB: These are *not* monad comps.
283 [h, u1, u2, u3] <- newSysLocalsDs [h_ty, u1_ty, u2_ty, u3_ty]
284
285 -- the "fail" value ...
286 let
287 core_fail = App (Var h) (Var u3)
288 letrec_body = App (Var h) core_list1
289
290 rest_expr <- deListComp quals core_fail
291 core_match <- matchSimply (Var u2) (StmtCtxt ListComp) pat rest_expr core_fail
292
293 let
294 rhs = Lam u1 $
295 Case (Var u1) u1 res_ty
296 [(DataAlt nilDataCon, [], core_list2),
297 (DataAlt consDataCon, [u2, u3], core_match)]
298 -- Increasing order of tag
299
300 return (Let (Rec [(h, rhs)]) letrec_body)
301
302 {-
303 ************************************************************************
304 * *
305 \subsection[DsListComp-foldr-build]{Foldr/Build desugaring of list comprehensions}
306 * *
307 ************************************************************************
308
309 @dfListComp@ are the rules used with foldr/build turned on:
310
311 \begin{verbatim}
312 TE[ e | ] c n = c e n
313 TE[ e | b , q ] c n = if b then TE[ e | q ] c n else n
314 TE[ e | p <- l , q ] c n = let
315 f = \ x b -> case x of
316 p -> TE[ e | q ] c b
317 _ -> b
318 in
319 foldr f n l
320 \end{verbatim}
321 -}
322
323 dfListComp :: Id -> Id -- 'c' and 'n'
324 -> [ExprStmt GhcTc] -- the rest of the qual's
325 -> DsM CoreExpr
326
327 dfListComp _ _ [] = panic "dfListComp"
328
329 dfListComp c_id n_id (LastStmt body _ _ : quals)
330 = ASSERT( null quals )
331 do { core_body <- dsLExprNoLP body
332 ; return (mkApps (Var c_id) [core_body, Var n_id]) }
333
334 -- Non-last: must be a guard
335 dfListComp c_id n_id (BodyStmt guard _ _ _ : quals) = do
336 core_guard <- dsLExpr guard
337 core_rest <- dfListComp c_id n_id quals
338 return (mkIfThenElse core_guard core_rest (Var n_id))
339
340 dfListComp c_id n_id (LetStmt binds : quals) = do
341 -- new in 1.3, local bindings
342 core_rest <- dfListComp c_id n_id quals
343 dsLocalBinds binds core_rest
344
345 dfListComp c_id n_id (stmt@(TransStmt {}) : quals) = do
346 (inner_list_expr, pat) <- dsTransStmt stmt
347 -- Anyway, we bind the newly grouped list via the generic binding function
348 dfBindComp c_id n_id (pat, inner_list_expr) quals
349
350 dfListComp c_id n_id (BindStmt pat list1 _ _ _ : quals) = do
351 -- evaluate the two lists
352 core_list1 <- dsLExpr list1
353
354 -- Do the rest of the work in the generic binding builder
355 dfBindComp c_id n_id (pat, core_list1) quals
356
357 dfListComp _ _ (ParStmt {} : _) = panic "dfListComp ParStmt"
358 dfListComp _ _ (RecStmt {} : _) = panic "dfListComp RecStmt"
359 dfListComp _ _ (ApplicativeStmt {} : _) =
360 panic "dfListComp ApplicativeStmt"
361
362 dfBindComp :: Id -> Id -- 'c' and 'n'
363 -> (LPat GhcTc, CoreExpr)
364 -> [ExprStmt GhcTc] -- the rest of the qual's
365 -> DsM CoreExpr
366 dfBindComp c_id n_id (pat, core_list1) quals = do
367 -- find the required type
368 let x_ty = hsLPatType pat
369 let b_ty = idType n_id
370
371 -- create some new local id's
372 b <- newSysLocalDs b_ty
373 x <- newSysLocalDs x_ty
374
375 -- build rest of the comprehesion
376 core_rest <- dfListComp c_id b quals
377
378 -- build the pattern match
379 core_expr <- matchSimply (Var x) (StmtCtxt ListComp)
380 pat core_rest (Var b)
381
382 -- now build the outermost foldr, and return
383 mkFoldrExpr x_ty b_ty (mkLams [x, b] core_expr) (Var n_id) core_list1
384
385 {-
386 ************************************************************************
387 * *
388 \subsection[DsFunGeneration]{Generation of zip/unzip functions for use in desugaring}
389 * *
390 ************************************************************************
391 -}
392
393 mkZipBind :: [Type] -> DsM (Id, CoreExpr)
394 -- mkZipBind [t1, t2]
395 -- = (zip, \as1:[t1] as2:[t2]
396 -- -> case as1 of
397 -- [] -> []
398 -- (a1:as'1) -> case as2 of
399 -- [] -> []
400 -- (a2:as'2) -> (a1, a2) : zip as'1 as'2)]
401
402 mkZipBind elt_tys = do
403 ass <- mapM newSysLocalDs elt_list_tys
404 as' <- mapM newSysLocalDs elt_tys
405 as's <- mapM newSysLocalDs elt_list_tys
406
407 zip_fn <- newSysLocalDs zip_fn_ty
408
409 let inner_rhs = mkConsExpr elt_tuple_ty
410 (mkBigCoreVarTup as')
411 (mkVarApps (Var zip_fn) as's)
412 zip_body = foldr mk_case inner_rhs (zip3 ass as' as's)
413
414 return (zip_fn, mkLams ass zip_body)
415 where
416 elt_list_tys = map mkListTy elt_tys
417 elt_tuple_ty = mkBigCoreTupTy elt_tys
418 elt_tuple_list_ty = mkListTy elt_tuple_ty
419
420 zip_fn_ty = mkFunTys elt_list_tys elt_tuple_list_ty
421
422 mk_case (as, a', as') rest
423 = Case (Var as) as elt_tuple_list_ty
424 [(DataAlt nilDataCon, [], mkNilExpr elt_tuple_ty),
425 (DataAlt consDataCon, [a', as'], rest)]
426 -- Increasing order of tag
427
428
429 mkUnzipBind :: TransForm -> [Type] -> DsM (Maybe (Id, CoreExpr))
430 -- mkUnzipBind [t1, t2]
431 -- = (unzip, \ys :: [(t1, t2)] -> foldr (\ax :: (t1, t2) axs :: ([t1], [t2])
432 -- -> case ax of
433 -- (x1, x2) -> case axs of
434 -- (xs1, xs2) -> (x1 : xs1, x2 : xs2))
435 -- ([], [])
436 -- ys)
437 --
438 -- We use foldr here in all cases, even if rules are turned off, because we may as well!
439 mkUnzipBind ThenForm _
440 = return Nothing -- No unzipping for ThenForm
441 mkUnzipBind _ elt_tys
442 = do { ax <- newSysLocalDs elt_tuple_ty
443 ; axs <- newSysLocalDs elt_list_tuple_ty
444 ; ys <- newSysLocalDs elt_tuple_list_ty
445 ; xs <- mapM newSysLocalDs elt_tys
446 ; xss <- mapM newSysLocalDs elt_list_tys
447
448 ; unzip_fn <- newSysLocalDs unzip_fn_ty
449
450 ; [us1, us2] <- sequence [newUniqueSupply, newUniqueSupply]
451
452 ; let nil_tuple = mkBigCoreTup (map mkNilExpr elt_tys)
453 concat_expressions = map mkConcatExpression (zip3 elt_tys (map Var xs) (map Var xss))
454 tupled_concat_expression = mkBigCoreTup concat_expressions
455
456 folder_body_inner_case = mkTupleCase us1 xss tupled_concat_expression axs (Var axs)
457 folder_body_outer_case = mkTupleCase us2 xs folder_body_inner_case ax (Var ax)
458 folder_body = mkLams [ax, axs] folder_body_outer_case
459
460 ; unzip_body <- mkFoldrExpr elt_tuple_ty elt_list_tuple_ty folder_body nil_tuple (Var ys)
461 ; return (Just (unzip_fn, mkLams [ys] unzip_body)) }
462 where
463 elt_tuple_ty = mkBigCoreTupTy elt_tys
464 elt_tuple_list_ty = mkListTy elt_tuple_ty
465 elt_list_tys = map mkListTy elt_tys
466 elt_list_tuple_ty = mkBigCoreTupTy elt_list_tys
467
468 unzip_fn_ty = elt_tuple_list_ty `mkFunTy` elt_list_tuple_ty
469
470 mkConcatExpression (list_element_ty, head, tail) = mkConsExpr list_element_ty head tail
471
472 {-
473 ************************************************************************
474 * *
475 \subsection[DsPArrComp]{Desugaring of array comprehensions}
476 * *
477 ************************************************************************
478 -}
479
480 -- entry point for desugaring a parallel array comprehension
481 --
482 -- [:e | qss:] = <<[:e | qss:]>> () [:():]
483 --
484 dsPArrComp :: [ExprStmt GhcTc]
485 -> DsM CoreExpr
486
487 -- Special case for parallel comprehension
488 dsPArrComp (ParStmt qss _ _ _ : quals) = dePArrParComp qss quals
489
490 -- Special case for simple generators:
491 --
492 -- <<[:e' | p <- e, qs:]>> = <<[: e' | qs :]>> p e
493 --
494 -- if matching again p cannot fail, or else
495 --
496 -- <<[:e' | p <- e, qs:]>> =
497 -- <<[:e' | qs:]>> p (filterP (\x -> case x of {p -> True; _ -> False}) e)
498 --
499 dsPArrComp (BindStmt p e _ _ _ : qs) = do
500 filterP <- dsDPHBuiltin filterPVar
501 ce <- dsLExprNoLP e
502 let ety'ce = parrElemType ce
503 false = Var falseDataConId
504 true = Var trueDataConId
505 v <- newSysLocalDs ety'ce
506 pred <- matchSimply (Var v) (StmtCtxt PArrComp) p true false
507 let gen | isIrrefutableHsPat p = ce
508 | otherwise = mkApps (Var filterP) [Type ety'ce, mkLams [v] pred, ce]
509 dePArrComp qs p gen
510
511 dsPArrComp qs = do -- no ParStmt in `qs'
512 sglP <- dsDPHBuiltin singletonPVar
513 let unitArray = mkApps (Var sglP) [Type unitTy, mkCoreTup []]
514 dePArrComp qs (noLoc $ WildPat unitTy) unitArray
515
516
517
518 -- the work horse
519 --
520 dePArrComp :: [ExprStmt GhcTc]
521 -> LPat GhcTc -- the current generator pattern
522 -> CoreExpr -- the current generator expression
523 -> DsM CoreExpr
524
525 dePArrComp [] _ _ = panic "dePArrComp"
526
527 --
528 -- <<[:e' | :]>> pa ea = mapP (\pa -> e') ea
529 --
530 dePArrComp (LastStmt e' _ _ : quals) pa cea
531 = ASSERT( null quals )
532 do { mapP <- dsDPHBuiltin mapPVar
533 ; let ty = parrElemType cea
534 ; (clam, ty'e') <- deLambda ty pa e'
535 ; return $ mkApps (Var mapP) [Type ty, Type ty'e', clam, cea] }
536 --
537 -- <<[:e' | b, qs:]>> pa ea = <<[:e' | qs:]>> pa (filterP (\pa -> b) ea)
538 --
539 dePArrComp (BodyStmt b _ _ _ : qs) pa cea = do
540 filterP <- dsDPHBuiltin filterPVar
541 let ty = parrElemType cea
542 (clam,_) <- deLambda ty pa b
543 dePArrComp qs pa (mkApps (Var filterP) [Type ty, clam, cea])
544
545 --
546 -- <<[:e' | p <- e, qs:]>> pa ea =
547 -- let ef = \pa -> e
548 -- in
549 -- <<[:e' | qs:]>> (pa, p) (crossMap ea ef)
550 --
551 -- if matching again p cannot fail, or else
552 --
553 -- <<[:e' | p <- e, qs:]>> pa ea =
554 -- let ef = \pa -> filterP (\x -> case x of {p -> True; _ -> False}) e
555 -- in
556 -- <<[:e' | qs:]>> (pa, p) (crossMapP ea ef)
557 --
558 dePArrComp (BindStmt p e _ _ _ : qs) pa cea = do
559 filterP <- dsDPHBuiltin filterPVar
560 crossMapP <- dsDPHBuiltin crossMapPVar
561 ce <- dsLExpr e
562 let ety'cea = parrElemType cea
563 ety'ce = parrElemType ce
564 false = Var falseDataConId
565 true = Var trueDataConId
566 v <- newSysLocalDs ety'ce
567 pred <- matchSimply (Var v) (StmtCtxt PArrComp) p true false
568 let cef | isIrrefutableHsPat p = ce
569 | otherwise = mkApps (Var filterP) [Type ety'ce, mkLams [v] pred, ce]
570 (clam, _) <- mkLambda ety'cea pa cef
571 let ety'cef = ety'ce -- filter doesn't change the element type
572 pa' = mkLHsPatTup [pa, p]
573
574 dePArrComp qs pa' (mkApps (Var crossMapP)
575 [Type ety'cea, Type ety'cef, cea, clam])
576 --
577 -- <<[:e' | let ds, qs:]>> pa ea =
578 -- <<[:e' | qs:]>> (pa, (x_1, ..., x_n))
579 -- (mapP (\v@pa -> let ds in (v, (x_1, ..., x_n))) ea)
580 -- where
581 -- {x_1, ..., x_n} = DV (ds) -- Defined Variables
582 --
583 dePArrComp (LetStmt lds@(L _ ds) : qs) pa cea = do
584 mapP <- dsDPHBuiltin mapPVar
585 let xs = collectLocalBinders ds
586 ty'cea = parrElemType cea
587 v <- newSysLocalDs ty'cea
588 clet <- dsLocalBinds lds (mkCoreTup (map Var xs))
589 let'v <- newSysLocalDs (exprType clet)
590 let projBody = mkCoreLet (NonRec let'v clet) $
591 mkCoreTup [Var v, Var let'v]
592 errTy = exprType projBody
593 errMsg = text "DsListComp.dePArrComp: internal error!"
594 cerr <- mkErrorAppDs pAT_ERROR_ID errTy errMsg
595 ccase <- matchSimply (Var v) (StmtCtxt PArrComp) pa projBody cerr
596 let pa' = mkLHsPatTup [pa, mkLHsPatTup (map nlVarPat xs)]
597 proj = mkLams [v] ccase
598 dePArrComp qs pa' (mkApps (Var mapP)
599 [Type ty'cea, Type errTy, proj, cea])
600 --
601 -- The parser guarantees that parallel comprehensions can only appear as
602 -- singleton qualifier lists, which we already special case in the caller.
603 -- So, encountering one here is a bug.
604 --
605 dePArrComp (ParStmt {} : _) _ _ =
606 panic "DsListComp.dePArrComp: malformed comprehension AST: ParStmt"
607 dePArrComp (TransStmt {} : _) _ _ = panic "DsListComp.dePArrComp: TransStmt"
608 dePArrComp (RecStmt {} : _) _ _ = panic "DsListComp.dePArrComp: RecStmt"
609 dePArrComp (ApplicativeStmt {} : _) _ _ =
610 panic "DsListComp.dePArrComp: ApplicativeStmt"
611
612 -- <<[:e' | qs | qss:]>> pa ea =
613 -- <<[:e' | qss:]>> (pa, (x_1, ..., x_n))
614 -- (zipP ea <<[:(x_1, ..., x_n) | qs:]>>)
615 -- where
616 -- {x_1, ..., x_n} = DV (qs)
617 --
618 dePArrParComp :: [ParStmtBlock GhcTc GhcTc] -> [ExprStmt GhcTc] -> DsM CoreExpr
619 dePArrParComp qss quals = do
620 (pQss, ceQss) <- deParStmt qss
621 dePArrComp quals pQss ceQss
622 where
623 deParStmt [] =
624 -- empty parallel statement lists have no source representation
625 panic "DsListComp.dePArrComp: Empty parallel list comprehension"
626 deParStmt (ParStmtBlock qs xs _:qss) = do -- first statement
627 let res_expr = mkLHsVarTuple xs
628 cqs <- dsPArrComp (map unLoc qs ++ [mkLastStmt res_expr])
629 parStmts qss (mkLHsVarPatTup xs) cqs
630 ---
631 parStmts [] pa cea = return (pa, cea)
632 parStmts (ParStmtBlock qs xs _:qss) pa cea = do -- subsequent statements (zip'ed)
633 zipP <- dsDPHBuiltin zipPVar
634 let pa' = mkLHsPatTup [pa, mkLHsVarPatTup xs]
635 ty'cea = parrElemType cea
636 res_expr = mkLHsVarTuple xs
637 cqs <- dsPArrComp (map unLoc qs ++ [mkLastStmt res_expr])
638 let ty'cqs = parrElemType cqs
639 cea' = mkApps (Var zipP) [Type ty'cea, Type ty'cqs, cea, cqs]
640 parStmts qss pa' cea'
641
642 -- generate Core corresponding to `\p -> e'
643 --
644 deLambda :: Type -- type of the argument (not levity-polymorphic)
645 -> LPat GhcTc -- argument pattern
646 -> LHsExpr GhcTc -- body
647 -> DsM (CoreExpr, Type)
648 deLambda ty p e =
649 mkLambda ty p =<< dsLExpr e
650
651 -- generate Core for a lambda pattern match, where the body is already in Core
652 --
653 mkLambda :: Type -- type of the argument (not levity-polymorphic)
654 -> LPat GhcTc -- argument pattern
655 -> CoreExpr -- desugared body
656 -> DsM (CoreExpr, Type)
657 mkLambda ty p ce = do
658 v <- newSysLocalDs ty
659 let errMsg = text "DsListComp.deLambda: internal error!"
660 ce'ty = exprType ce
661 cerr <- mkErrorAppDs pAT_ERROR_ID ce'ty errMsg
662 res <- matchSimply (Var v) (StmtCtxt PArrComp) p ce cerr
663 return (mkLams [v] res, ce'ty)
664
665 -- obtain the element type of the parallel array produced by the given Core
666 -- expression
667 --
668 parrElemType :: CoreExpr -> Type
669 parrElemType e =
670 case splitTyConApp_maybe (exprType e) of
671 Just (tycon, [ty]) | tycon == parrTyCon -> ty
672 _ -> panic
673 "DsListComp.parrElemType: not a parallel array type"
674
675 -- Translation for monad comprehensions
676
677 -- Entry point for monad comprehension desugaring
678 dsMonadComp :: [ExprLStmt GhcTc] -> DsM CoreExpr
679 dsMonadComp stmts = dsMcStmts stmts
680
681 dsMcStmts :: [ExprLStmt GhcTc] -> DsM CoreExpr
682 dsMcStmts [] = panic "dsMcStmts"
683 dsMcStmts (L loc stmt : lstmts) = putSrcSpanDs loc (dsMcStmt stmt lstmts)
684
685 ---------------
686 dsMcStmt :: ExprStmt GhcTc -> [ExprLStmt GhcTc] -> DsM CoreExpr
687
688 dsMcStmt (LastStmt body _ ret_op) stmts
689 = ASSERT( null stmts )
690 do { body' <- dsLExpr body
691 ; dsSyntaxExpr ret_op [body'] }
692
693 -- [ .. | let binds, stmts ]
694 dsMcStmt (LetStmt binds) stmts
695 = do { rest <- dsMcStmts stmts
696 ; dsLocalBinds binds rest }
697
698 -- [ .. | a <- m, stmts ]
699 dsMcStmt (BindStmt pat rhs bind_op fail_op bind_ty) stmts
700 = do { rhs' <- dsLExpr rhs
701 ; dsMcBindStmt pat rhs' bind_op fail_op bind_ty stmts }
702
703 -- Apply `guard` to the `exp` expression
704 --
705 -- [ .. | exp, stmts ]
706 --
707 dsMcStmt (BodyStmt exp then_exp guard_exp _) stmts
708 = do { exp' <- dsLExpr exp
709 ; rest <- dsMcStmts stmts
710 ; guard_exp' <- dsSyntaxExpr guard_exp [exp']
711 ; dsSyntaxExpr then_exp [guard_exp', rest] }
712
713 -- Group statements desugar like this:
714 --
715 -- [| (q, then group by e using f); rest |]
716 -- ---> f {qt} (\qv -> e) [| q; return qv |] >>= \ n_tup ->
717 -- case unzip n_tup of qv' -> [| rest |]
718 --
719 -- where variables (v1:t1, ..., vk:tk) are bound by q
720 -- qv = (v1, ..., vk)
721 -- qt = (t1, ..., tk)
722 -- (>>=) :: m2 a -> (a -> m3 b) -> m3 b
723 -- f :: forall a. (a -> t) -> m1 a -> m2 (n a)
724 -- n_tup :: n qt
725 -- unzip :: n qt -> (n t1, ..., n tk) (needs Functor n)
726
727 dsMcStmt (TransStmt { trS_stmts = stmts, trS_bndrs = bndrs
728 , trS_by = by, trS_using = using
729 , trS_ret = return_op, trS_bind = bind_op
730 , trS_bind_arg_ty = n_tup_ty' -- n (a,b,c)
731 , trS_fmap = fmap_op, trS_form = form }) stmts_rest
732 = do { let (from_bndrs, to_bndrs) = unzip bndrs
733
734 ; let from_bndr_tys = map idType from_bndrs -- Types ty
735
736
737 -- Desugar an inner comprehension which outputs a list of tuples of the "from" binders
738 ; expr' <- dsInnerMonadComp stmts from_bndrs return_op
739
740 -- Work out what arguments should be supplied to that expression: i.e. is an extraction
741 -- function required? If so, create that desugared function and add to arguments
742 ; usingExpr' <- dsLExpr using
743 ; usingArgs' <- case by of
744 Nothing -> return [expr']
745 Just by_e -> do { by_e' <- dsLExpr by_e
746 ; lam' <- matchTuple from_bndrs by_e'
747 ; return [lam', expr'] }
748
749 -- Generate the expressions to build the grouped list
750 -- Build a pattern that ensures the consumer binds into the NEW binders,
751 -- which hold monads rather than single values
752 ; let tup_n_ty' = mkBigCoreVarTupTy to_bndrs
753
754 ; body <- dsMcStmts stmts_rest
755 ; n_tup_var' <- newSysLocalDsNoLP n_tup_ty'
756 ; tup_n_var' <- newSysLocalDs tup_n_ty'
757 ; tup_n_expr' <- mkMcUnzipM form fmap_op n_tup_var' from_bndr_tys
758 ; us <- newUniqueSupply
759 ; let rhs' = mkApps usingExpr' usingArgs'
760 body' = mkTupleCase us to_bndrs body tup_n_var' tup_n_expr'
761
762 ; dsSyntaxExpr bind_op [rhs', Lam n_tup_var' body'] }
763
764 -- Parallel statements. Use `Control.Monad.Zip.mzip` to zip parallel
765 -- statements, for example:
766 --
767 -- [ body | qs1 | qs2 | qs3 ]
768 -- -> [ body | (bndrs1, (bndrs2, bndrs3))
769 -- <- [bndrs1 | qs1] `mzip` ([bndrs2 | qs2] `mzip` [bndrs3 | qs3]) ]
770 --
771 -- where `mzip` has type
772 -- mzip :: forall a b. m a -> m b -> m (a,b)
773 -- NB: we need a polymorphic mzip because we call it several times
774
775 dsMcStmt (ParStmt blocks mzip_op bind_op bind_ty) stmts_rest
776 = do { exps_w_tys <- mapM ds_inner blocks -- Pairs (exp :: m ty, ty)
777 ; mzip_op' <- dsExpr mzip_op
778
779 ; let -- The pattern variables
780 pats = [ mkBigLHsVarPatTupId bs | ParStmtBlock _ bs _ <- blocks]
781 -- Pattern with tuples of variables
782 -- [v1,v2,v3] => (v1, (v2, v3))
783 pat = foldr1 (\p1 p2 -> mkLHsPatTup [p1, p2]) pats
784 (rhs, _) = foldr1 (\(e1,t1) (e2,t2) ->
785 (mkApps mzip_op' [Type t1, Type t2, e1, e2],
786 mkBoxedTupleTy [t1,t2]))
787 exps_w_tys
788
789 ; dsMcBindStmt pat rhs bind_op noSyntaxExpr bind_ty stmts_rest }
790 where
791 ds_inner (ParStmtBlock stmts bndrs return_op)
792 = do { exp <- dsInnerMonadComp stmts bndrs return_op
793 ; return (exp, mkBigCoreVarTupTy bndrs) }
794
795 dsMcStmt stmt _ = pprPanic "dsMcStmt: unexpected stmt" (ppr stmt)
796
797
798 matchTuple :: [Id] -> CoreExpr -> DsM CoreExpr
799 -- (matchTuple [a,b,c] body)
800 -- returns the Core term
801 -- \x. case x of (a,b,c) -> body
802 matchTuple ids body
803 = do { us <- newUniqueSupply
804 ; tup_id <- newSysLocalDs (mkBigCoreVarTupTy ids)
805 ; return (Lam tup_id $ mkTupleCase us ids body tup_id (Var tup_id)) }
806
807 -- general `rhs' >>= \pat -> stmts` desugaring where `rhs'` is already a
808 -- desugared `CoreExpr`
809 dsMcBindStmt :: LPat GhcTc
810 -> CoreExpr -- ^ the desugared rhs of the bind statement
811 -> SyntaxExpr GhcTc
812 -> SyntaxExpr GhcTc
813 -> Type -- ^ S in (>>=) :: Q -> (R -> S) -> T
814 -> [ExprLStmt GhcTc]
815 -> DsM CoreExpr
816 dsMcBindStmt pat rhs' bind_op fail_op res1_ty stmts
817 = do { body <- dsMcStmts stmts
818 ; var <- selectSimpleMatchVarL pat
819 ; match <- matchSinglePat (Var var) (StmtCtxt DoExpr) pat
820 res1_ty (cantFailMatchResult body)
821 ; match_code <- handle_failure pat match fail_op
822 ; dsSyntaxExpr bind_op [rhs', Lam var match_code] }
823
824 where
825 -- In a monad comprehension expression, pattern-match failure just calls
826 -- the monadic `fail` rather than throwing an exception
827 handle_failure pat match fail_op
828 | matchCanFail match
829 = do { dflags <- getDynFlags
830 ; fail_msg <- mkStringExpr (mk_fail_msg dflags pat)
831 ; fail_expr <- dsSyntaxExpr fail_op [fail_msg]
832 ; extractMatchResult match fail_expr }
833 | otherwise
834 = extractMatchResult match (error "It can't fail")
835
836 mk_fail_msg :: DynFlags -> Located e -> String
837 mk_fail_msg dflags pat
838 = "Pattern match failure in monad comprehension at " ++
839 showPpr dflags (getLoc pat)
840
841 -- Desugar nested monad comprehensions, for example in `then..` constructs
842 -- dsInnerMonadComp quals [a,b,c] ret_op
843 -- returns the desugaring of
844 -- [ (a,b,c) | quals ]
845
846 dsInnerMonadComp :: [ExprLStmt GhcTc]
847 -> [Id] -- Return a tuple of these variables
848 -> SyntaxExpr GhcTc -- The monomorphic "return" operator
849 -> DsM CoreExpr
850 dsInnerMonadComp stmts bndrs ret_op
851 = dsMcStmts (stmts ++ [noLoc (LastStmt (mkBigLHsVarTupId bndrs) False ret_op)])
852
853
854 -- The `unzip` function for `GroupStmt` in a monad comprehensions
855 --
856 -- unzip :: m (a,b,..) -> (m a,m b,..)
857 -- unzip m_tuple = ( liftM selN1 m_tuple
858 -- , liftM selN2 m_tuple
859 -- , .. )
860 --
861 -- mkMcUnzipM fmap ys [t1, t2]
862 -- = ( fmap (selN1 :: (t1, t2) -> t1) ys
863 -- , fmap (selN2 :: (t1, t2) -> t2) ys )
864
865 mkMcUnzipM :: TransForm
866 -> HsExpr GhcTcId -- fmap
867 -> Id -- Of type n (a,b,c)
868 -> [Type] -- [a,b,c] (not levity-polymorphic)
869 -> DsM CoreExpr -- Of type (n a, n b, n c)
870 mkMcUnzipM ThenForm _ ys _
871 = return (Var ys) -- No unzipping to do
872
873 mkMcUnzipM _ fmap_op ys elt_tys
874 = do { fmap_op' <- dsExpr fmap_op
875 ; xs <- mapM newSysLocalDs elt_tys
876 ; let tup_ty = mkBigCoreTupTy elt_tys
877 ; tup_xs <- newSysLocalDs tup_ty
878
879 ; let mk_elt i = mkApps fmap_op' -- fmap :: forall a b. (a -> b) -> n a -> n b
880 [ Type tup_ty, Type (getNth elt_tys i)
881 , mk_sel i, Var ys]
882
883 mk_sel n = Lam tup_xs $
884 mkTupleSelector xs (getNth xs n) tup_xs (Var tup_xs)
885
886 ; return (mkBigCoreTup (map mk_elt [0..length elt_tys - 1])) }