46ae1291c7350213cabe4c4330a5a0bed3eaeef3
[ghc-hetmet.git] / compiler / deSugar / DsListComp.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 %
5
6 Desugaring list comprehensions and array comprehensions
7
8 \begin{code}
9 {-# OPTIONS -fno-warn-incomplete-patterns #-}
10 -- The above warning supression flag is a temporary kludge.
11 -- While working on this module you are encouraged to remove it and fix
12 -- any warnings in the module. See
13 --     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
14 -- for details
15
16 module DsListComp ( dsListComp, dsPArrComp ) where
17
18 #include "HsVersions.h"
19
20 import {-# SOURCE #-} DsExpr ( dsLExpr, dsLocalBinds )
21
22 import HsSyn
23 import TcHsSyn
24 import CoreSyn
25 import MkCore
26
27 import DsMonad          -- the monadery used in the desugarer
28 import DsUtils
29
30 import DynFlags
31 import CoreUtils
32 import Id
33 import Type
34 import TysWiredIn
35 import Match
36 import PrelNames
37 import PrelInfo
38 import SrcLoc
39 import Outputable
40 import FastString
41 \end{code}
42
43 List comprehensions may be desugared in one of two ways: ``ordinary''
44 (as you would expect if you read SLPJ's book) and ``with foldr/build
45 turned on'' (if you read Gill {\em et al.}'s paper on the subject).
46
47 There will be at least one ``qualifier'' in the input.
48
49 \begin{code}
50 dsListComp :: [LStmt Id] 
51            -> LHsExpr Id
52            -> Type              -- Type of list elements
53            -> DsM CoreExpr
54 dsListComp lquals body elt_ty = do 
55     dflags <- getDOptsDs
56     let quals = map unLoc lquals
57     
58     if not (dopt Opt_EnableRewriteRules dflags) || dopt Opt_IgnoreInterfacePragmas dflags
59        -- Either rules are switched off, or we are ignoring what there are;
60        -- Either way foldr/build won't happen, so use the more efficient
61        -- Wadler-style desugaring
62        || isParallelComp quals
63        -- Foldr-style desugaring can't handle parallel list comprehensions
64         then deListComp quals body (mkNilExpr elt_ty)
65         else mkBuildExpr elt_ty (\(c, _) (n, _) -> dfListComp c n quals body) 
66              -- Foldr/build should be enabled, so desugar 
67              -- into foldrs and builds
68
69   where 
70     -- We must test for ParStmt anywhere, not just at the head, because an extension
71     -- to list comprehensions would be to add brackets to specify the associativity
72     -- of qualifier lists. This is really easy to do by adding extra ParStmts into the
73     -- mix of possibly a single element in length, so we do this to leave the possibility open
74     isParallelComp = any isParallelStmt
75   
76     isParallelStmt (ParStmt _) = True
77     isParallelStmt _           = False
78     
79     
80 -- This function lets you desugar a inner list comprehension and a list of the binders
81 -- of that comprehension that we need in the outer comprehension into such an expression
82 -- and the type of the elements that it outputs (tuples of binders)
83 dsInnerListComp :: ([LStmt Id], [Id]) -> DsM (CoreExpr, Type)
84 dsInnerListComp (stmts, bndrs) = do
85         expr <- dsListComp stmts (mkBigLHsVarTup bndrs) bndrs_tuple_type
86         return (expr, bndrs_tuple_type)
87     where
88         bndrs_types = map idType bndrs
89         bndrs_tuple_type = mkBigCoreTupTy bndrs_types
90         
91         
92 -- This function factors out commonality between the desugaring strategies for TransformStmt.
93 -- Given such a statement it gives you back an expression representing how to compute the transformed
94 -- list and the tuple that you need to bind from that list in order to proceed with your desugaring
95 dsTransformStmt :: Stmt Id -> DsM (CoreExpr, LPat Id)
96 dsTransformStmt (TransformStmt stmts binders usingExpr maybeByExpr) = do
97     (expr, binders_tuple_type) <- dsInnerListComp (stmts, binders)
98     usingExpr' <- dsLExpr usingExpr
99     
100     using_args <- 
101         case maybeByExpr of
102             Nothing -> return [expr]
103             Just byExpr -> do
104                 byExpr' <- dsLExpr byExpr
105                 
106                 us <- newUniqueSupply
107                 [tuple_binder] <- newSysLocalsDs [binders_tuple_type]
108                 let byExprWrapper = mkTupleCase us binders byExpr' tuple_binder (Var tuple_binder)
109                 
110                 return [Lam tuple_binder byExprWrapper, expr]
111
112     let inner_list_expr = mkApps usingExpr' ((Type binders_tuple_type) : using_args)
113     
114     let pat = mkBigLHsVarPatTup binders
115     return (inner_list_expr, pat)
116     
117 -- This function factors out commonality between the desugaring strategies for GroupStmt.
118 -- Given such a statement it gives you back an expression representing how to compute the transformed
119 -- list and the tuple that you need to bind from that list in order to proceed with your desugaring
120 dsGroupStmt :: Stmt Id -> DsM (CoreExpr, LPat Id)
121 dsGroupStmt (GroupStmt stmts binderMap by using) = do
122     let (fromBinders, toBinders) = unzip binderMap
123         
124         fromBindersTypes = map idType fromBinders
125         toBindersTypes = map idType toBinders
126         
127         toBindersTupleType = mkBigCoreTupTy toBindersTypes
128     
129     -- Desugar an inner comprehension which outputs a list of tuples of the "from" binders
130     (expr, from_tup_ty) <- dsInnerListComp (stmts, fromBinders)
131     
132     -- Work out what arguments should be supplied to that expression: i.e. is an extraction
133     -- function required? If so, create that desugared function and add to arguments
134     usingExpr' <- dsLExpr (either id noLoc using)
135     usingArgs <- case by of
136                    Nothing   -> return [expr]
137                    Just by_e -> do { by_e' <- dsLExpr by_e
138                                    ; us <- newUniqueSupply
139                                    ; [from_tup_id] <- newSysLocalsDs [from_tup_ty]
140                                    ; let by_wrap = mkTupleCase us fromBinders by_e' 
141                                                    from_tup_id (Var from_tup_id)
142                                    ; return [Lam from_tup_id by_wrap, expr] }
143     
144     -- Create an unzip function for the appropriate arity and element types and find "map"
145     (unzip_fn, unzip_rhs) <- mkUnzipBind fromBindersTypes
146     map_id <- dsLookupGlobalId mapName
147
148     -- Generate the expressions to build the grouped list
149     let -- First we apply the grouping function to the inner list
150         inner_list_expr = mkApps usingExpr' ((Type from_tup_ty) : usingArgs)
151         -- Then we map our "unzip" across it to turn the lists of tuples into tuples of lists
152         -- We make sure we instantiate the type variable "a" to be a list of "from" tuples and
153         -- the "b" to be a tuple of "to" lists!
154         unzipped_inner_list_expr = mkApps (Var map_id) 
155             [Type (mkListTy from_tup_ty), Type toBindersTupleType, Var unzip_fn, inner_list_expr]
156         -- Then finally we bind the unzip function around that expression
157         bound_unzipped_inner_list_expr = Let (Rec [(unzip_fn, unzip_rhs)]) unzipped_inner_list_expr
158     
159     -- Build a pattern that ensures the consumer binds into the NEW binders, which hold lists rather than single values
160     let pat = mkBigLHsVarPatTup toBinders
161     return (bound_unzipped_inner_list_expr, pat)
162     
163 \end{code}
164
165 %************************************************************************
166 %*                                                                      *
167 \subsection[DsListComp-ordinary]{Ordinary desugaring of list comprehensions}
168 %*                                                                      *
169 %************************************************************************
170
171 Just as in Phil's chapter~7 in SLPJ, using the rules for
172 optimally-compiled list comprehensions.  This is what Kevin followed
173 as well, and I quite happily do the same.  The TQ translation scheme
174 transforms a list of qualifiers (either boolean expressions or
175 generators) into a single expression which implements the list
176 comprehension.  Because we are generating 2nd-order polymorphic
177 lambda-calculus, calls to NIL and CONS must be applied to a type
178 argument, as well as their usual value arguments.
179 \begin{verbatim}
180 TE << [ e | qs ] >>  =  TQ << [ e | qs ] ++ Nil (typeOf e) >>
181
182 (Rule C)
183 TQ << [ e | ] ++ L >> = Cons (typeOf e) TE <<e>> TE <<L>>
184
185 (Rule B)
186 TQ << [ e | b , qs ] ++ L >> =
187     if TE << b >> then TQ << [ e | qs ] ++ L >> else TE << L >>
188
189 (Rule A')
190 TQ << [ e | p <- L1, qs ]  ++  L2 >> =
191   letrec
192     h = \ u1 ->
193           case u1 of
194             []        ->  TE << L2 >>
195             (u2 : u3) ->
196                   (( \ TE << p >> -> ( TQ << [e | qs]  ++  (h u3) >> )) u2)
197                     [] (h u3)
198   in
199     h ( TE << L1 >> )
200
201 "h", "u1", "u2", and "u3" are new variables.
202 \end{verbatim}
203
204 @deListComp@ is the TQ translation scheme.  Roughly speaking, @dsExpr@
205 is the TE translation scheme.  Note that we carry around the @L@ list
206 already desugared.  @dsListComp@ does the top TE rule mentioned above.
207
208 To the above, we add an additional rule to deal with parallel list
209 comprehensions.  The translation goes roughly as follows:
210      [ e | p1 <- e11, let v1 = e12, p2 <- e13
211          | q1 <- e21, let v2 = e22, q2 <- e23]
212      =>
213      [ e | ((x1, .., xn), (y1, ..., ym)) <-
214                zip [(x1,..,xn) | p1 <- e11, let v1 = e12, p2 <- e13]
215                    [(y1,..,ym) | q1 <- e21, let v2 = e22, q2 <- e23]]
216 where (x1, .., xn) are the variables bound in p1, v1, p2
217       (y1, .., ym) are the variables bound in q1, v2, q2
218
219 In the translation below, the ParStmt branch translates each parallel branch
220 into a sub-comprehension, and desugars each independently.  The resulting lists
221 are fed to a zip function, we create a binding for all the variables bound in all
222 the comprehensions, and then we hand things off the the desugarer for bindings.
223 The zip function is generated here a) because it's small, and b) because then we
224 don't have to deal with arbitrary limits on the number of zip functions in the
225 prelude, nor which library the zip function came from.
226 The introduced tuples are Boxed, but only because I couldn't get it to work
227 with the Unboxed variety.
228
229 \begin{code}
230
231 deListComp :: [Stmt Id] -> LHsExpr Id -> CoreExpr -> DsM CoreExpr
232
233 deListComp (ParStmt stmtss_w_bndrs : quals) body list
234   = do
235     exps_and_qual_tys <- mapM dsInnerListComp stmtss_w_bndrs
236     let (exps, qual_tys) = unzip exps_and_qual_tys
237     
238     (zip_fn, zip_rhs) <- mkZipBind qual_tys
239
240         -- Deal with [e | pat <- zip l1 .. ln] in example above
241     deBindComp pat (Let (Rec [(zip_fn, zip_rhs)]) (mkApps (Var zip_fn) exps)) 
242                    quals body list
243
244   where 
245         bndrs_s = map snd stmtss_w_bndrs
246
247         -- pat is the pattern ((x1,..,xn), (y1,..,ym)) in the example above
248         pat  = mkBigLHsPatTup pats
249         pats = map mkBigLHsVarPatTup bndrs_s
250
251         -- Last: the one to return
252 deListComp [] body list = do    -- Figure 7.4, SLPJ, p 135, rule C above
253     core_body <- dsLExpr body
254     return (mkConsExpr (exprType core_body) core_body list)
255
256         -- Non-last: must be a guard
257 deListComp (ExprStmt guard _ _ : quals) body list = do  -- rule B above
258     core_guard <- dsLExpr guard
259     core_rest <- deListComp quals body list
260     return (mkIfThenElse core_guard core_rest list)
261
262 -- [e | let B, qs] = let B in [e | qs]
263 deListComp (LetStmt binds : quals) body list = do
264     core_rest <- deListComp quals body list
265     dsLocalBinds binds core_rest
266
267 deListComp (stmt@(TransformStmt {}) : quals) body list = do
268     (inner_list_expr, pat) <- dsTransformStmt stmt
269     deBindComp pat inner_list_expr quals body list
270
271 deListComp (stmt@(GroupStmt {}) : quals) body list = do
272     (inner_list_expr, pat) <- dsGroupStmt stmt
273     deBindComp pat inner_list_expr quals body list
274
275 deListComp (BindStmt pat list1 _ _ : quals) body core_list2 = do -- rule A' above
276     core_list1 <- dsLExpr list1
277     deBindComp pat core_list1 quals body core_list2
278 \end{code}
279
280
281 \begin{code}
282 deBindComp :: OutPat Id
283            -> CoreExpr
284            -> [Stmt Id]
285            -> LHsExpr Id
286            -> CoreExpr
287            -> DsM (Expr Id)
288 deBindComp pat core_list1 quals body core_list2 = do
289     let
290         u3_ty@u1_ty = exprType core_list1       -- two names, same thing
291
292         -- u1_ty is a [alpha] type, and u2_ty = alpha
293         u2_ty = hsLPatType pat
294
295         res_ty = exprType core_list2
296         h_ty   = u1_ty `mkFunTy` res_ty
297         
298     [h, u1, u2, u3] <- newSysLocalsDs [h_ty, u1_ty, u2_ty, u3_ty]
299
300     -- the "fail" value ...
301     let
302         core_fail   = App (Var h) (Var u3)
303         letrec_body = App (Var h) core_list1
304         
305     rest_expr <- deListComp quals body core_fail
306     core_match <- matchSimply (Var u2) (StmtCtxt ListComp) pat rest_expr core_fail      
307     
308     let
309         rhs = Lam u1 $
310               Case (Var u1) u1 res_ty
311                    [(DataAlt nilDataCon,  [],       core_list2),
312                     (DataAlt consDataCon, [u2, u3], core_match)]
313                         -- Increasing order of tag
314             
315     return (Let (Rec [(h, rhs)]) letrec_body)
316 \end{code}
317
318 %************************************************************************
319 %*                                                                      *
320 \subsection[DsListComp-foldr-build]{Foldr/Build desugaring of list comprehensions}
321 %*                                                                      *
322 %************************************************************************
323
324 @dfListComp@ are the rules used with foldr/build turned on:
325
326 \begin{verbatim}
327 TE[ e | ]            c n = c e n
328 TE[ e | b , q ]      c n = if b then TE[ e | q ] c n else n
329 TE[ e | p <- l , q ] c n = let 
330                                 f = \ x b -> case x of
331                                                   p -> TE[ e | q ] c b
332                                                   _ -> b
333                            in
334                            foldr f n l
335 \end{verbatim}
336
337 \begin{code}
338 dfListComp :: Id -> Id -- 'c' and 'n'
339         -> [Stmt Id]   -- the rest of the qual's
340         -> LHsExpr Id
341         -> DsM CoreExpr
342
343         -- Last: the one to return
344 dfListComp c_id n_id [] body = do
345     core_body <- dsLExpr body
346     return (mkApps (Var c_id) [core_body, Var n_id])
347
348         -- Non-last: must be a guard
349 dfListComp c_id n_id (ExprStmt guard _ _  : quals) body = do
350     core_guard <- dsLExpr guard
351     core_rest <- dfListComp c_id n_id quals body
352     return (mkIfThenElse core_guard core_rest (Var n_id))
353
354 dfListComp c_id n_id (LetStmt binds : quals) body = do
355     -- new in 1.3, local bindings
356     core_rest <- dfListComp c_id n_id quals body
357     dsLocalBinds binds core_rest
358
359 dfListComp c_id n_id (stmt@(TransformStmt {}) : quals) body = do
360     (inner_list_expr, pat) <- dsTransformStmt stmt
361     -- Anyway, we bind the newly transformed list via the generic binding function
362     dfBindComp c_id n_id (pat, inner_list_expr) quals body
363
364 dfListComp c_id n_id (stmt@(GroupStmt {}) : quals) body = do
365     (inner_list_expr, pat) <- dsGroupStmt stmt
366     -- Anyway, we bind the newly grouped list via the generic binding function
367     dfBindComp c_id n_id (pat, inner_list_expr) quals body
368     
369 dfListComp c_id n_id (BindStmt pat list1 _ _ : quals) body = do
370     -- evaluate the two lists
371     core_list1 <- dsLExpr list1
372     
373     -- Do the rest of the work in the generic binding builder
374     dfBindComp c_id n_id (pat, core_list1) quals body
375                
376 dfBindComp :: Id -> Id          -- 'c' and 'n'
377        -> (LPat Id, CoreExpr)
378            -> [Stmt Id]                 -- the rest of the qual's
379            -> LHsExpr Id
380            -> DsM CoreExpr
381 dfBindComp c_id n_id (pat, core_list1) quals body = do
382     -- find the required type
383     let x_ty   = hsLPatType pat
384         b_ty   = idType n_id
385
386     -- create some new local id's
387     [b, x] <- newSysLocalsDs [b_ty, x_ty]
388
389     -- build rest of the comprehesion
390     core_rest <- dfListComp c_id b quals body
391
392     -- build the pattern match
393     core_expr <- matchSimply (Var x) (StmtCtxt ListComp)
394                 pat core_rest (Var b)
395
396     -- now build the outermost foldr, and return
397     mkFoldrExpr x_ty b_ty (mkLams [x, b] core_expr) (Var n_id) core_list1
398 \end{code}
399
400 %************************************************************************
401 %*                                                                      *
402 \subsection[DsFunGeneration]{Generation of zip/unzip functions for use in desugaring}
403 %*                                                                      *
404 %************************************************************************
405
406 \begin{code}
407
408 mkZipBind :: [Type] -> DsM (Id, CoreExpr)
409 -- mkZipBind [t1, t2] 
410 -- = (zip, \as1:[t1] as2:[t2] 
411 --         -> case as1 of 
412 --              [] -> []
413 --              (a1:as'1) -> case as2 of
414 --                              [] -> []
415 --                              (a2:as'2) -> (a1, a2) : zip as'1 as'2)]
416
417 mkZipBind elt_tys = do
418     ass  <- mapM newSysLocalDs  elt_list_tys
419     as'  <- mapM newSysLocalDs  elt_tys
420     as's <- mapM newSysLocalDs  elt_list_tys
421     
422     zip_fn <- newSysLocalDs zip_fn_ty
423     
424     let inner_rhs = mkConsExpr elt_tuple_ty 
425                         (mkBigCoreVarTup as')
426                         (mkVarApps (Var zip_fn) as's)
427         zip_body  = foldr mk_case inner_rhs (zip3 ass as' as's)
428     
429     return (zip_fn, mkLams ass zip_body)
430   where
431     elt_list_tys      = map mkListTy elt_tys
432     elt_tuple_ty      = mkBigCoreTupTy elt_tys
433     elt_tuple_list_ty = mkListTy elt_tuple_ty
434     
435     zip_fn_ty         = mkFunTys elt_list_tys elt_tuple_list_ty
436
437     mk_case (as, a', as') rest
438           = Case (Var as) as elt_tuple_list_ty
439                   [(DataAlt nilDataCon,  [],        mkNilExpr elt_tuple_ty),
440                    (DataAlt consDataCon, [a', as'], rest)]
441                         -- Increasing order of tag
442             
443             
444 mkUnzipBind :: [Type] -> DsM (Id, CoreExpr)
445 -- mkUnzipBind [t1, t2] 
446 -- = (unzip, \ys :: [(t1, t2)] -> foldr (\ax :: (t1, t2) axs :: ([t1], [t2])
447 --     -> case ax of
448 --      (x1, x2) -> case axs of
449 --                (xs1, xs2) -> (x1 : xs1, x2 : xs2))
450 --      ([], [])
451 --      ys)
452 -- 
453 -- We use foldr here in all cases, even if rules are turned off, because we may as well!
454 mkUnzipBind elt_tys = do
455     ax  <- newSysLocalDs elt_tuple_ty
456     axs <- newSysLocalDs elt_list_tuple_ty
457     ys  <- newSysLocalDs elt_tuple_list_ty
458     xs  <- mapM newSysLocalDs elt_tys
459     xss <- mapM newSysLocalDs elt_list_tys
460     
461     unzip_fn <- newSysLocalDs unzip_fn_ty
462
463     [us1, us2] <- sequence [newUniqueSupply, newUniqueSupply]
464
465     let nil_tuple = mkBigCoreTup (map mkNilExpr elt_tys)
466         
467         concat_expressions = map mkConcatExpression (zip3 elt_tys (map Var xs) (map Var xss))
468         tupled_concat_expression = mkBigCoreTup concat_expressions
469         
470         folder_body_inner_case = mkTupleCase us1 xss tupled_concat_expression axs (Var axs)
471         folder_body_outer_case = mkTupleCase us2 xs folder_body_inner_case ax (Var ax)
472         folder_body = mkLams [ax, axs] folder_body_outer_case
473         
474     unzip_body <- mkFoldrExpr elt_tuple_ty elt_list_tuple_ty folder_body nil_tuple (Var ys)
475     return (unzip_fn, mkLams [ys] unzip_body)
476   where
477     elt_tuple_ty       = mkBigCoreTupTy elt_tys
478     elt_tuple_list_ty  = mkListTy elt_tuple_ty
479     elt_list_tys       = map mkListTy elt_tys
480     elt_list_tuple_ty  = mkBigCoreTupTy elt_list_tys
481     
482     unzip_fn_ty        = elt_tuple_list_ty `mkFunTy` elt_list_tuple_ty
483             
484     mkConcatExpression (list_element_ty, head, tail) = mkConsExpr list_element_ty head tail
485             
486             
487
488 \end{code}
489
490 %************************************************************************
491 %*                                                                      *
492 \subsection[DsPArrComp]{Desugaring of array comprehensions}
493 %*                                                                      *
494 %************************************************************************
495
496 \begin{code}
497
498 -- entry point for desugaring a parallel array comprehension
499 --
500 --   [:e | qss:] = <<[:e | qss:]>> () [:():]
501 --
502 dsPArrComp :: [Stmt Id] 
503             -> LHsExpr Id
504             -> Type                 -- Don't use; called with `undefined' below
505             -> DsM CoreExpr
506 dsPArrComp [ParStmt qss] body _  =  -- parallel comprehension
507   dePArrParComp qss body
508
509 -- Special case for simple generators:
510 --
511 --  <<[:e' | p <- e, qs:]>> = <<[: e' | qs :]>> p e
512 --
513 -- if matching again p cannot fail, or else
514 --
515 --  <<[:e' | p <- e, qs:]>> = 
516 --    <<[:e' | qs:]>> p (filterP (\x -> case x of {p -> True; _ -> False}) e)
517 --
518 dsPArrComp (BindStmt p e _ _ : qs) body _ = do
519     filterP <- dsLookupGlobalId filterPName
520     ce <- dsLExpr e
521     let ety'ce  = parrElemType ce
522         false   = Var falseDataConId
523         true    = Var trueDataConId
524     v <- newSysLocalDs ety'ce
525     pred <- matchSimply (Var v) (StmtCtxt PArrComp) p true false
526     let gen | isIrrefutableHsPat p = ce
527             | otherwise            = mkApps (Var filterP) [Type ety'ce, mkLams [v] pred, ce]
528     dePArrComp qs body p gen
529
530 dsPArrComp qs            body _  = do -- no ParStmt in `qs'
531     sglP <- dsLookupGlobalId singletonPName
532     let unitArray = mkApps (Var sglP) [Type unitTy, mkCoreTup []]
533     dePArrComp qs body (noLoc $ WildPat unitTy) unitArray
534
535
536
537 -- the work horse
538 --
539 dePArrComp :: [Stmt Id] 
540            -> LHsExpr Id
541            -> LPat Id           -- the current generator pattern
542            -> CoreExpr          -- the current generator expression
543            -> DsM CoreExpr
544 --
545 --  <<[:e' | :]>> pa ea = mapP (\pa -> e') ea
546 --
547 dePArrComp [] e' pa cea = do
548     mapP <- dsLookupGlobalId mapPName
549     let ty = parrElemType cea
550     (clam, ty'e') <- deLambda ty pa e'
551     return $ mkApps (Var mapP) [Type ty, Type ty'e', clam, cea]
552 --
553 --  <<[:e' | b, qs:]>> pa ea = <<[:e' | qs:]>> pa (filterP (\pa -> b) ea)
554 --
555 dePArrComp (ExprStmt b _ _ : qs) body pa cea = do
556     filterP <- dsLookupGlobalId filterPName
557     let ty = parrElemType cea
558     (clam,_) <- deLambda ty pa b
559     dePArrComp qs body pa (mkApps (Var filterP) [Type ty, clam, cea])
560
561 --
562 --  <<[:e' | p <- e, qs:]>> pa ea =
563 --    let ef = \pa -> e
564 --    in
565 --    <<[:e' | qs:]>> (pa, p) (crossMap ea ef)
566 --
567 -- if matching again p cannot fail, or else
568 --
569 --  <<[:e' | p <- e, qs:]>> pa ea = 
570 --    let ef = \pa -> filterP (\x -> case x of {p -> True; _ -> False}) e
571 --    in
572 --    <<[:e' | qs:]>> (pa, p) (crossMapP ea ef)
573 --
574 dePArrComp (BindStmt p e _ _ : qs) body pa cea = do
575     filterP <- dsLookupGlobalId filterPName
576     crossMapP <- dsLookupGlobalId crossMapPName
577     ce <- dsLExpr e
578     let ety'cea = parrElemType cea
579         ety'ce  = parrElemType ce
580         false   = Var falseDataConId
581         true    = Var trueDataConId
582     v <- newSysLocalDs ety'ce
583     pred <- matchSimply (Var v) (StmtCtxt PArrComp) p true false
584     let cef | isIrrefutableHsPat p = ce
585             | otherwise            = mkApps (Var filterP) [Type ety'ce, mkLams [v] pred, ce]
586     (clam, _) <- mkLambda ety'cea pa cef
587     let ety'cef = ety'ce                    -- filter doesn't change the element type
588         pa'     = mkLHsPatTup [pa, p]
589
590     dePArrComp qs body pa' (mkApps (Var crossMapP) 
591                                  [Type ety'cea, Type ety'cef, cea, clam])
592 --
593 --  <<[:e' | let ds, qs:]>> pa ea = 
594 --    <<[:e' | qs:]>> (pa, (x_1, ..., x_n)) 
595 --                    (mapP (\v@pa -> let ds in (v, (x_1, ..., x_n))) ea)
596 --  where
597 --    {x_1, ..., x_n} = DV (ds)         -- Defined Variables
598 --
599 dePArrComp (LetStmt ds : qs) body pa cea = do
600     mapP <- dsLookupGlobalId mapPName
601     let xs     = collectLocalBinders ds
602         ty'cea = parrElemType cea
603     v <- newSysLocalDs ty'cea
604     clet <- dsLocalBinds ds (mkCoreTup (map Var xs))
605     let'v <- newSysLocalDs (exprType clet)
606     let projBody = mkCoreLet (NonRec let'v clet) $ 
607                    mkCoreTup [Var v, Var let'v]
608         errTy    = exprType projBody
609         errMsg   = ptext (sLit "DsListComp.dePArrComp: internal error!")
610     cerr <- mkErrorAppDs pAT_ERROR_ID errTy errMsg
611     ccase <- matchSimply (Var v) (StmtCtxt PArrComp) pa projBody cerr
612     let pa'    = mkLHsPatTup [pa, mkLHsPatTup (map nlVarPat xs)]
613         proj   = mkLams [v] ccase
614     dePArrComp qs body pa' (mkApps (Var mapP) 
615                                    [Type ty'cea, Type errTy, proj, cea])
616 --
617 -- The parser guarantees that parallel comprehensions can only appear as
618 -- singeltons qualifier lists, which we already special case in the caller.
619 -- So, encountering one here is a bug.
620 --
621 dePArrComp (ParStmt _ : _) _ _ _ = 
622   panic "DsListComp.dePArrComp: malformed comprehension AST"
623
624 --  <<[:e' | qs | qss:]>> pa ea = 
625 --    <<[:e' | qss:]>> (pa, (x_1, ..., x_n)) 
626 --                     (zipP ea <<[:(x_1, ..., x_n) | qs:]>>)
627 --    where
628 --      {x_1, ..., x_n} = DV (qs)
629 --
630 dePArrParComp :: [([LStmt Id], [Id])] -> LHsExpr Id -> DsM CoreExpr
631 dePArrParComp qss body = do
632     (pQss, ceQss) <- deParStmt qss
633     dePArrComp [] body pQss ceQss
634   where
635     deParStmt []             =
636       -- empty parallel statement lists have no source representation
637       panic "DsListComp.dePArrComp: Empty parallel list comprehension"
638     deParStmt ((qs, xs):qss) = do        -- first statement
639       let res_expr = mkLHsVarTuple xs
640       cqs <- dsPArrComp (map unLoc qs) res_expr undefined
641       parStmts qss (mkLHsVarPatTup xs) cqs
642     ---
643     parStmts []             pa cea = return (pa, cea)
644     parStmts ((qs, xs):qss) pa cea = do  -- subsequent statements (zip'ed)
645       zipP <- dsLookupGlobalId zipPName
646       let pa'      = mkLHsPatTup [pa, mkLHsVarPatTup xs]
647           ty'cea   = parrElemType cea
648           res_expr = mkLHsVarTuple xs
649       cqs <- dsPArrComp (map unLoc qs) res_expr undefined
650       let ty'cqs = parrElemType cqs
651           cea'   = mkApps (Var zipP) [Type ty'cea, Type ty'cqs, cea, cqs]
652       parStmts qss pa' cea'
653
654 -- generate Core corresponding to `\p -> e'
655 --
656 deLambda :: Type                        -- type of the argument
657           -> LPat Id                    -- argument pattern
658           -> LHsExpr Id                 -- body
659           -> DsM (CoreExpr, Type)
660 deLambda ty p e =
661     mkLambda ty p =<< dsLExpr e
662
663 -- generate Core for a lambda pattern match, where the body is already in Core
664 --
665 mkLambda :: Type                        -- type of the argument
666          -> LPat Id                     -- argument pattern
667          -> CoreExpr                    -- desugared body
668          -> DsM (CoreExpr, Type)
669 mkLambda ty p ce = do
670     v <- newSysLocalDs ty
671     let errMsg = ptext (sLit "DsListComp.deLambda: internal error!")
672         ce'ty  = exprType ce
673     cerr <- mkErrorAppDs pAT_ERROR_ID ce'ty errMsg
674     res <- matchSimply (Var v) (StmtCtxt PArrComp) p ce cerr
675     return (mkLams [v] res, ce'ty)
676
677 -- obtain the element type of the parallel array produced by the given Core
678 -- expression
679 --
680 parrElemType   :: CoreExpr -> Type
681 parrElemType e  = 
682   case splitTyConApp_maybe (exprType e) of
683     Just (tycon, [ty]) | tycon == parrTyCon -> ty
684     _                                                     -> panic
685       "DsListComp.parrElemType: not a parallel array type"
686 \end{code}