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