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