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