DsListComp.lhs 24.8 KB
Newer Older
1
%
Simon Marlow's avatar
Simon Marlow committed
2
% (c) The University of Glasgow 2006
3
% (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4
%
Simon Marlow's avatar
Simon Marlow committed
5 6

Desugaring list comprehensions and array comprehensions
7 8

\begin{code}
9
{-# OPTIONS -fno-warn-incomplete-patterns #-}
10 11 12
-- The above warning supression flag is a temporary kludge.
-- While working on this module you are encouraged to remove it and fix
-- any warnings in the module. See
Ian Lynagh's avatar
Ian Lynagh committed
13
--     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
14 15
-- for details

chak's avatar
chak committed
16
module DsListComp ( dsListComp, dsPArrComp ) where
17

18 19
#include "HsVersions.h"

20
import {-# SOURCE #-} DsExpr ( dsLExpr, dsLocalBinds )
21

22
import HsSyn
Simon Marlow's avatar
Simon Marlow committed
23
import TcHsSyn
24
import CoreSyn
25
import MkCore
26

27
import DsMonad		-- the monadery used in the desugarer
28
import DsUtils
29

Simon Marlow's avatar
Simon Marlow committed
30 31
import DynFlags
import CoreUtils
32
import Id
Simon Marlow's avatar
Simon Marlow committed
33 34 35 36 37
import Type
import TysWiredIn
import Match
import PrelNames
import SrcLoc
38
import Outputable
39
import FastString
40 41 42 43 44 45 46 47 48
\end{code}

List comprehensions may be desugared in one of two ways: ``ordinary''
(as you would expect if you read SLPJ's book) and ``with foldr/build
turned on'' (if you read Gill {\em et al.}'s paper on the subject).

There will be at least one ``qualifier'' in the input.

\begin{code}
49
dsListComp :: [LStmt Id] 
50
	   -> LHsExpr Id
51 52
	   -> Type		-- Type of list elements
	   -> DsM CoreExpr
53 54 55 56
dsListComp lquals body elt_ty = do 
    dflags <- getDOptsDs
    let quals = map unLoc lquals
    
57
    if not (dopt Opt_EnableRewriteRules dflags) || dopt Opt_IgnoreInterfacePragmas dflags
58 59 60 61 62 63
       -- Either rules are switched off, or we are ignoring what there are;
       -- Either way foldr/build won't happen, so use the more efficient
       -- Wadler-style desugaring
       || isParallelComp quals
       -- Foldr-style desugaring can't handle parallel list comprehensions
        then deListComp quals body (mkNilExpr elt_ty)
64 65 66
        else mkBuildExpr elt_ty (\(c, _) (n, _) -> dfListComp c n quals body) 
             -- Foldr/build should be enabled, so desugar 
             -- into foldrs and builds
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94

  where 
    -- We must test for ParStmt anywhere, not just at the head, because an extension
    -- to list comprehensions would be to add brackets to specify the associativity
    -- of qualifier lists. This is really easy to do by adding extra ParStmts into the
    -- mix of possibly a single element in length, so we do this to leave the possibility open
    isParallelComp = any isParallelStmt
  
    isParallelStmt (ParStmt _) = True
    isParallelStmt _           = False
    
    
-- This function lets you desugar a inner list comprehension and a list of the binders
-- of that comprehension that we need in the outer comprehension into such an expression
-- and the type of the elements that it outputs (tuples of binders)
dsInnerListComp :: ([LStmt Id], [Id]) -> DsM (CoreExpr, Type)
dsInnerListComp (stmts, bndrs) = do
        expr <- dsListComp stmts (mkBigLHsVarTup bndrs) bndrs_tuple_type
        return (expr, bndrs_tuple_type)
    where
        bndrs_types = map idType bndrs
        bndrs_tuple_type = mkBigCoreTupTy bndrs_types
        
        
-- This function factors out commonality between the desugaring strategies for TransformStmt.
-- Given such a statement it gives you back an expression representing how to compute the transformed
-- list and the tuple that you need to bind from that list in order to proceed with your desugaring
dsTransformStmt :: Stmt Id -> DsM (CoreExpr, LPat Id)
95 96 97
dsTransformStmt (TransformStmt stmts binders usingExpr maybeByExpr)
 = do { (expr, binders_tuple_type) <- dsInnerListComp (stmts, binders)
      ; usingExpr' <- dsLExpr usingExpr
98
    
99 100
      ; using_args <-
          case maybeByExpr of
101 102 103 104 105 106 107 108 109 110
            Nothing -> return [expr]
            Just byExpr -> do
                byExpr' <- dsLExpr byExpr
                
                us <- newUniqueSupply
                [tuple_binder] <- newSysLocalsDs [binders_tuple_type]
                let byExprWrapper = mkTupleCase us binders byExpr' tuple_binder (Var tuple_binder)
                
                return [Lam tuple_binder byExprWrapper, expr]

111 112 113
      ; let inner_list_expr = mkApps usingExpr' ((Type binders_tuple_type) : using_args)
            pat = mkBigLHsVarPatTup binders
      ; return (inner_list_expr, pat) }
114 115 116 117 118
    
-- This function factors out commonality between the desugaring strategies for GroupStmt.
-- Given such a statement it gives you back an expression representing how to compute the transformed
-- list and the tuple that you need to bind from that list in order to proceed with your desugaring
dsGroupStmt :: Stmt Id -> DsM (CoreExpr, LPat Id)
119
dsGroupStmt (GroupStmt stmts binderMap by using) = do
120 121 122 123 124 125 126 127
    let (fromBinders, toBinders) = unzip binderMap
        
        fromBindersTypes = map idType fromBinders
        toBindersTypes = map idType toBinders
        
        toBindersTupleType = mkBigCoreTupTy toBindersTypes
    
    -- Desugar an inner comprehension which outputs a list of tuples of the "from" binders
128
    (expr, from_tup_ty) <- dsInnerListComp (stmts, fromBinders)
129 130 131
    
    -- Work out what arguments should be supplied to that expression: i.e. is an extraction
    -- function required? If so, create that desugared function and add to arguments
132 133 134 135 136 137 138 139 140
    usingExpr' <- dsLExpr (either id noLoc using)
    usingArgs <- case by of
                   Nothing   -> return [expr]
 		   Just by_e -> do { by_e' <- dsLExpr by_e
                                   ; us <- newUniqueSupply
                                   ; [from_tup_id] <- newSysLocalsDs [from_tup_ty]
                                   ; let by_wrap = mkTupleCase us fromBinders by_e' 
                                                   from_tup_id (Var from_tup_id)
                                   ; return [Lam from_tup_id by_wrap, expr] }
141 142 143 144 145 146 147
    
    -- Create an unzip function for the appropriate arity and element types and find "map"
    (unzip_fn, unzip_rhs) <- mkUnzipBind fromBindersTypes
    map_id <- dsLookupGlobalId mapName

    -- Generate the expressions to build the grouped list
    let -- First we apply the grouping function to the inner list
148
        inner_list_expr = mkApps usingExpr' ((Type from_tup_ty) : usingArgs)
149 150 151 152
        -- Then we map our "unzip" across it to turn the lists of tuples into tuples of lists
        -- We make sure we instantiate the type variable "a" to be a list of "from" tuples and
        -- the "b" to be a tuple of "to" lists!
        unzipped_inner_list_expr = mkApps (Var map_id) 
153
            [Type (mkListTy from_tup_ty), Type toBindersTupleType, Var unzip_fn, inner_list_expr]
154 155 156 157 158 159 160
        -- Then finally we bind the unzip function around that expression
        bound_unzipped_inner_list_expr = Let (Rec [(unzip_fn, unzip_rhs)]) unzipped_inner_list_expr
    
    -- Build a pattern that ensures the consumer binds into the NEW binders, which hold lists rather than single values
    let pat = mkBigLHsVarPatTup toBinders
    return (bound_unzipped_inner_list_expr, pat)
    
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
\end{code}

%************************************************************************
%*									*
\subsection[DsListComp-ordinary]{Ordinary desugaring of list comprehensions}
%*									*
%************************************************************************

Just as in Phil's chapter~7 in SLPJ, using the rules for
optimally-compiled list comprehensions.  This is what Kevin followed
as well, and I quite happily do the same.  The TQ translation scheme
transforms a list of qualifiers (either boolean expressions or
generators) into a single expression which implements the list
comprehension.  Because we are generating 2nd-order polymorphic
lambda-calculus, calls to NIL and CONS must be applied to a type
argument, as well as their usual value arguments.
\begin{verbatim}
TE << [ e | qs ] >>  =  TQ << [ e | qs ] ++ Nil (typeOf e) >>

(Rule C)
TQ << [ e | ] ++ L >> = Cons (typeOf e) TE <<e>> TE <<L>>

(Rule B)
TQ << [ e | b , qs ] ++ L >> =
    if TE << b >> then TQ << [ e | qs ] ++ L >> else TE << L >>

(Rule A')
TQ << [ e | p <- L1, qs ]  ++  L2 >> =
  letrec
    h = \ u1 ->
    	  case u1 of
	    []        ->  TE << L2 >>
	    (u2 : u3) ->
		  (( \ TE << p >> -> ( TQ << [e | qs]  ++  (h u3) >> )) u2)
		    [] (h u3)
  in
    h ( TE << L1 >> )

"h", "u1", "u2", and "u3" are new variables.
\end{verbatim}

@deListComp@ is the TQ translation scheme.  Roughly speaking, @dsExpr@
is the TE translation scheme.  Note that we carry around the @L@ list
already desugared.  @dsListComp@ does the top TE rule mentioned above.

206 207 208 209 210
To the above, we add an additional rule to deal with parallel list
comprehensions.  The translation goes roughly as follows:
     [ e | p1 <- e11, let v1 = e12, p2 <- e13
         | q1 <- e21, let v2 = e22, q2 <- e23]
     =>
211 212 213 214 215 216
     [ e | ((x1, .., xn), (y1, ..., ym)) <-
               zip [(x1,..,xn) | p1 <- e11, let v1 = e12, p2 <- e13]
                   [(y1,..,ym) | q1 <- e21, let v2 = e22, q2 <- e23]]
where (x1, .., xn) are the variables bound in p1, v1, p2
      (y1, .., ym) are the variables bound in q1, v2, q2

217
In the translation below, the ParStmt branch translates each parallel branch
218 219 220 221 222 223 224 225
into a sub-comprehension, and desugars each independently.  The resulting lists
are fed to a zip function, we create a binding for all the variables bound in all
the comprehensions, and then we hand things off the the desugarer for bindings.
The zip function is generated here a) because it's small, and b) because then we
don't have to deal with arbitrary limits on the number of zip functions in the
prelude, nor which library the zip function came from.
The introduced tuples are Boxed, but only because I couldn't get it to work
with the Unboxed variety.
226

227
\begin{code}
228

229
deListComp :: [Stmt Id] -> LHsExpr Id -> CoreExpr -> DsM CoreExpr
230

231
deListComp (ParStmt stmtss_w_bndrs : quals) body list
232
  = do
233
    exps_and_qual_tys <- mapM dsInnerListComp stmtss_w_bndrs
234 235 236
    let (exps, qual_tys) = unzip exps_and_qual_tys
    
    (zip_fn, zip_rhs) <- mkZipBind qual_tys
237 238 239

	-- Deal with [e | pat <- zip l1 .. ln] in example above
    deBindComp pat (Let (Rec [(zip_fn, zip_rhs)]) (mkApps (Var zip_fn) exps)) 
240
		   quals body list
241

242 243 244 245
  where 
	bndrs_s = map snd stmtss_w_bndrs

	-- pat is the pattern ((x1,..,xn), (y1,..,ym)) in the example above
246
	pat  = mkBigLHsPatTup pats
247
	pats = map mkBigLHsVarPatTup bndrs_s
248

249
	-- Last: the one to return
250 251 252
deListComp [] body list = do    -- Figure 7.4, SLPJ, p 135, rule C above
    core_body <- dsLExpr body
    return (mkConsExpr (exprType core_body) core_body list)
253

254
	-- Non-last: must be a guard
255 256 257 258
deListComp (ExprStmt guard _ _ : quals) body list = do  -- rule B above
    core_guard <- dsLExpr guard
    core_rest <- deListComp quals body list
    return (mkIfThenElse core_guard core_rest list)
259

260
-- [e | let B, qs] = let B in [e | qs]
261 262
deListComp (LetStmt binds : quals) body list = do
    core_rest <- deListComp quals body list
263
    dsLocalBinds binds core_rest
264

265
deListComp (stmt@(TransformStmt {}) : quals) body list = do
266 267 268
    (inner_list_expr, pat) <- dsTransformStmt stmt
    deBindComp pat inner_list_expr quals body list

269
deListComp (stmt@(GroupStmt {}) : quals) body list = do
270 271 272
    (inner_list_expr, pat) <- dsGroupStmt stmt
    deBindComp pat inner_list_expr quals body list

273 274
deListComp (BindStmt pat list1 _ _ : quals) body core_list2 = do -- rule A' above
    core_list1 <- dsLExpr list1
275
    deBindComp pat core_list1 quals body core_list2
276 277
\end{code}

278

279
\begin{code}
280 281 282 283 284 285
deBindComp :: OutPat Id
           -> CoreExpr
           -> [Stmt Id]
           -> LHsExpr Id
           -> CoreExpr
           -> DsM (Expr Id)
286 287 288
deBindComp pat core_list1 quals body core_list2 = do
    let
        u3_ty@u1_ty = exprType core_list1	-- two names, same thing
289

290 291
        -- u1_ty is a [alpha] type, and u2_ty = alpha
        u2_ty = hsLPatType pat
292

293 294 295 296
        res_ty = exprType core_list2
        h_ty   = u1_ty `mkFunTy` res_ty
        
    [h, u1, u2, u3] <- newSysLocalsDs [h_ty, u1_ty, u2_ty, u3_ty]
297

298
    -- the "fail" value ...
299
    let
300 301 302 303 304 305
        core_fail   = App (Var h) (Var u3)
        letrec_body = App (Var h) core_list1
        
    rest_expr <- deListComp quals body core_fail
    core_match <- matchSimply (Var u2) (StmtCtxt ListComp) pat rest_expr core_fail	
    
306
    let
307
        rhs = Lam u1 $
308 309 310
	      Case (Var u1) u1 res_ty
		   [(DataAlt nilDataCon,  [], 	    core_list2),
		    (DataAlt consDataCon, [u2, u3], core_match)]
311
			-- Increasing order of tag
312 313
            
    return (Let (Rec [(h, rhs)]) letrec_body)
314 315
\end{code}

316 317 318 319 320 321 322
%************************************************************************
%*									*
\subsection[DsListComp-foldr-build]{Foldr/Build desugaring of list comprehensions}
%*									*
%************************************************************************

@dfListComp@ are the rules used with foldr/build turned on:
323

324
\begin{verbatim}
325 326 327 328 329 330 331 332
TE[ e | ]            c n = c e n
TE[ e | b , q ]      c n = if b then TE[ e | q ] c n else n
TE[ e | p <- l , q ] c n = let 
				f = \ x b -> case x of
						  p -> TE[ e | q ] c b
						  _ -> b
			   in
			   foldr f n l
333
\end{verbatim}
334

335
\begin{code}
336 337 338 339
dfListComp :: Id -> Id -- 'c' and 'n'
        -> [Stmt Id]   -- the rest of the qual's
        -> LHsExpr Id
        -> DsM CoreExpr
340

341
	-- Last: the one to return
342 343 344
dfListComp c_id n_id [] body = do
    core_body <- dsLExpr body
    return (mkApps (Var c_id) [core_body, Var n_id])
345

346
	-- Non-last: must be a guard
347 348 349 350 351 352 353 354
dfListComp c_id n_id (ExprStmt guard _ _  : quals) body = do
    core_guard <- dsLExpr guard
    core_rest <- dfListComp c_id n_id quals body
    return (mkIfThenElse core_guard core_rest (Var n_id))

dfListComp c_id n_id (LetStmt binds : quals) body = do
    -- new in 1.3, local bindings
    core_rest <- dfListComp c_id n_id quals body
355
    dsLocalBinds binds core_rest
356

357
dfListComp c_id n_id (stmt@(TransformStmt {}) : quals) body = do
358 359 360 361
    (inner_list_expr, pat) <- dsTransformStmt stmt
    -- Anyway, we bind the newly transformed list via the generic binding function
    dfBindComp c_id n_id (pat, inner_list_expr) quals body

362
dfListComp c_id n_id (stmt@(GroupStmt {}) : quals) body = do
363 364 365 366 367
    (inner_list_expr, pat) <- dsGroupStmt stmt
    -- Anyway, we bind the newly grouped list via the generic binding function
    dfBindComp c_id n_id (pat, inner_list_expr) quals body
    
dfListComp c_id n_id (BindStmt pat list1 _ _ : quals) body = do
368
    -- evaluate the two lists
369 370 371 372 373 374 375 376 377 378 379
    core_list1 <- dsLExpr list1
    
    -- Do the rest of the work in the generic binding builder
    dfBindComp c_id n_id (pat, core_list1) quals body
               
dfBindComp :: Id -> Id	        -- 'c' and 'n'
       -> (LPat Id, CoreExpr)
	   -> [Stmt Id] 	        -- the rest of the qual's
	   -> LHsExpr Id
	   -> DsM CoreExpr
dfBindComp c_id n_id (pat, core_list1) quals body = do
380
    -- find the required type
381
    let x_ty   = hsLPatType pat
382
        b_ty   = idType n_id
383 384

    -- create some new local id's
385
    [b, x] <- newSysLocalsDs [b_ty, x_ty]
386 387

    -- build rest of the comprehesion
388
    core_rest <- dfListComp c_id b quals body
389 390

    -- build the pattern match
391 392
    core_expr <- matchSimply (Var x) (StmtCtxt ListComp)
		pat core_rest (Var b)
393 394

    -- now build the outermost foldr, and return
395
    mkFoldrExpr x_ty b_ty (mkLams [x, b] core_expr) (Var n_id) core_list1
396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
\end{code}

%************************************************************************
%*									*
\subsection[DsFunGeneration]{Generation of zip/unzip functions for use in desugaring}
%*									*
%************************************************************************

\begin{code}

mkZipBind :: [Type] -> DsM (Id, CoreExpr)
-- mkZipBind [t1, t2] 
-- = (zip, \as1:[t1] as2:[t2] 
--	   -> case as1 of 
--		[] -> []
--		(a1:as'1) -> case as2 of
--				[] -> []
--				(a2:as'2) -> (a1, a2) : zip as'1 as'2)]

mkZipBind elt_tys = do
416 417 418
    ass  <- mapM newSysLocalDs  elt_list_tys
    as'  <- mapM newSysLocalDs  elt_tys
    as's <- mapM newSysLocalDs  elt_list_tys
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
    
    zip_fn <- newSysLocalDs zip_fn_ty
    
    let inner_rhs = mkConsExpr elt_tuple_ty 
			(mkBigCoreVarTup as')
			(mkVarApps (Var zip_fn) as's)
        zip_body  = foldr mk_case inner_rhs (zip3 ass as' as's)
    
    return (zip_fn, mkLams ass zip_body)
  where
    elt_list_tys      = map mkListTy elt_tys
    elt_tuple_ty      = mkBigCoreTupTy elt_tys
    elt_tuple_list_ty = mkListTy elt_tuple_ty
    
    zip_fn_ty         = mkFunTys elt_list_tys elt_tuple_list_ty

    mk_case (as, a', as') rest
	  = Case (Var as) as elt_tuple_list_ty
		  [(DataAlt nilDataCon,  [],        mkNilExpr elt_tuple_ty),
		   (DataAlt consDataCon, [a', as'], rest)]
			-- Increasing order of tag
            
            
mkUnzipBind :: [Type] -> DsM (Id, CoreExpr)
-- mkUnzipBind [t1, t2] 
-- = (unzip, \ys :: [(t1, t2)] -> foldr (\ax :: (t1, t2) axs :: ([t1], [t2])
--     -> case ax of
--      (x1, x2) -> case axs of
--                (xs1, xs2) -> (x1 : xs1, x2 : xs2))
--      ([], [])
--      ys)
-- 
-- We use foldr here in all cases, even if rules are turned off, because we may as well!
mkUnzipBind elt_tys = do
    ax  <- newSysLocalDs elt_tuple_ty
    axs <- newSysLocalDs elt_list_tuple_ty
    ys  <- newSysLocalDs elt_tuple_list_ty
456 457
    xs  <- mapM newSysLocalDs elt_tys
    xss <- mapM newSysLocalDs elt_list_tys
458 459 460 461 462 463 464 465 466 467 468 469 470 471
    
    unzip_fn <- newSysLocalDs unzip_fn_ty

    [us1, us2] <- sequence [newUniqueSupply, newUniqueSupply]

    let nil_tuple = mkBigCoreTup (map mkNilExpr elt_tys)
        
        concat_expressions = map mkConcatExpression (zip3 elt_tys (map Var xs) (map Var xss))
        tupled_concat_expression = mkBigCoreTup concat_expressions
        
        folder_body_inner_case = mkTupleCase us1 xss tupled_concat_expression axs (Var axs)
        folder_body_outer_case = mkTupleCase us2 xs folder_body_inner_case ax (Var ax)
        folder_body = mkLams [ax, axs] folder_body_outer_case
        
472 473
    unzip_body <- mkFoldrExpr elt_tuple_ty elt_list_tuple_ty folder_body nil_tuple (Var ys)
    return (unzip_fn, mkLams [ys] unzip_body)
474 475 476 477 478 479 480 481 482 483 484 485
  where
    elt_tuple_ty       = mkBigCoreTupTy elt_tys
    elt_tuple_list_ty  = mkListTy elt_tuple_ty
    elt_list_tys       = map mkListTy elt_tys
    elt_list_tuple_ty  = mkBigCoreTupTy elt_list_tys
    
    unzip_fn_ty        = elt_tuple_list_ty `mkFunTy` elt_list_tuple_ty
            
    mkConcatExpression (list_element_ty, head, tail) = mkConsExpr list_element_ty head tail
            
            

486 487
\end{code}

chak's avatar
chak committed
488 489 490 491 492 493 494 495 496 497 498 499
%************************************************************************
%*									*
\subsection[DsPArrComp]{Desugaring of array comprehensions}
%*									*
%************************************************************************

\begin{code}

-- entry point for desugaring a parallel array comprehension
--
--   [:e | qss:] = <<[:e | qss:]>> () [:():]
--
500 501 502 503
dsPArrComp :: [Stmt Id] 
            -> LHsExpr Id
            -> Type		    -- Don't use; called with `undefined' below
            -> DsM CoreExpr
504 505
dsPArrComp [ParStmt qss] body _  =  -- parallel comprehension
  dePArrParComp qss body
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527

-- Special case for simple generators:
--
--  <<[:e' | p <- e, qs:]>> = <<[: e' | qs :]>> p e
--
-- if matching again p cannot fail, or else
--
--  <<[:e' | p <- e, qs:]>> = 
--    <<[:e' | qs:]>> p (filterP (\x -> case x of {p -> True; _ -> False}) e)
--
dsPArrComp (BindStmt p e _ _ : qs) body _ = do
    filterP <- dsLookupGlobalId filterPName
    ce <- dsLExpr e
    let ety'ce  = parrElemType ce
        false   = Var falseDataConId
        true    = Var trueDataConId
    v <- newSysLocalDs ety'ce
    pred <- matchSimply (Var v) (StmtCtxt PArrComp) p true false
    let gen | isIrrefutableHsPat p = ce
            | otherwise            = mkApps (Var filterP) [Type ety'ce, mkLams [v] pred, ce]
    dePArrComp qs body p gen

528 529 530
dsPArrComp qs            body _  = do -- no ParStmt in `qs'
    sglP <- dsLookupGlobalId singletonPName
    let unitArray = mkApps (Var sglP) [Type unitTy, mkCoreTup []]
531
    dePArrComp qs body (noLoc $ WildPat unitTy) unitArray
532

533 534


chak's avatar
chak committed
535 536
-- the work horse
--
537
dePArrComp :: [Stmt Id] 
538
	   -> LHsExpr Id
539 540
	   -> LPat Id		-- the current generator pattern
	   -> CoreExpr		-- the current generator expression
chak's avatar
chak committed
541 542 543 544
	   -> DsM CoreExpr
--
--  <<[:e' | :]>> pa ea = mapP (\pa -> e') ea
--
545 546 547 548 549
dePArrComp [] e' pa cea = do
    mapP <- dsLookupGlobalId mapPName
    let ty = parrElemType cea
    (clam, ty'e') <- deLambda ty pa e'
    return $ mkApps (Var mapP) [Type ty, Type ty'e', clam, cea]
chak's avatar
chak committed
550 551 552
--
--  <<[:e' | b, qs:]>> pa ea = <<[:e' | qs:]>> pa (filterP (\pa -> b) ea)
--
553 554 555 556 557
dePArrComp (ExprStmt b _ _ : qs) body pa cea = do
    filterP <- dsLookupGlobalId filterPName
    let ty = parrElemType cea
    (clam,_) <- deLambda ty pa b
    dePArrComp qs body pa (mkApps (Var filterP) [Type ty, clam, cea])
558 559 560 561 562 563 564 565

--
--  <<[:e' | p <- e, qs:]>> pa ea =
--    let ef = \pa -> e
--    in
--    <<[:e' | qs:]>> (pa, p) (crossMap ea ef)
--
-- if matching again p cannot fail, or else
chak's avatar
chak committed
566 567
--
--  <<[:e' | p <- e, qs:]>> pa ea = 
568
--    let ef = \pa -> filterP (\x -> case x of {p -> True; _ -> False}) e
chak's avatar
chak committed
569
--    in
570
--    <<[:e' | qs:]>> (pa, p) (crossMapP ea ef)
chak's avatar
chak committed
571
--
572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
dePArrComp (BindStmt p e _ _ : qs) body pa cea = do
    filterP <- dsLookupGlobalId filterPName
    crossMapP <- dsLookupGlobalId crossMapPName
    ce <- dsLExpr e
    let ety'cea = parrElemType cea
        ety'ce  = parrElemType ce
        false   = Var falseDataConId
        true    = Var trueDataConId
    v <- newSysLocalDs ety'ce
    pred <- matchSimply (Var v) (StmtCtxt PArrComp) p true false
    let cef | isIrrefutableHsPat p = ce
            | otherwise            = mkApps (Var filterP) [Type ety'ce, mkLams [v] pred, ce]
    (clam, _) <- mkLambda ety'cea pa cef
    let ety'cef = ety'ce		    -- filter doesn't change the element type
        pa'     = mkLHsPatTup [pa, p]

    dePArrComp qs body pa' (mkApps (Var crossMapP) 
                                 [Type ety'cea, Type ety'cef, cea, clam])
chak's avatar
chak committed
590 591 592
--
--  <<[:e' | let ds, qs:]>> pa ea = 
--    <<[:e' | qs:]>> (pa, (x_1, ..., x_n)) 
593
--		      (mapP (\v@pa -> let ds in (v, (x_1, ..., x_n))) ea)
chak's avatar
chak committed
594 595 596
--  where
--    {x_1, ..., x_n} = DV (ds)		-- Defined Variables
--
597 598
dePArrComp (LetStmt ds : qs) body pa cea = do
    mapP <- dsLookupGlobalId mapPName
599
    let xs     = collectLocalBinders ds
600 601 602 603
        ty'cea = parrElemType cea
    v <- newSysLocalDs ty'cea
    clet <- dsLocalBinds ds (mkCoreTup (map Var xs))
    let'v <- newSysLocalDs (exprType clet)
604
    let projBody = mkCoreLet (NonRec let'v clet) $ 
605 606
                   mkCoreTup [Var v, Var let'v]
        errTy    = exprType projBody
607
        errMsg   = ptext (sLit "DsListComp.dePArrComp: internal error!")
608 609 610 611 612 613
    cerr <- mkErrorAppDs pAT_ERROR_ID errTy errMsg
    ccase <- matchSimply (Var v) (StmtCtxt PArrComp) pa projBody cerr
    let pa'    = mkLHsPatTup [pa, mkLHsPatTup (map nlVarPat xs)]
        proj   = mkLams [v] ccase
    dePArrComp qs body pa' (mkApps (Var mapP) 
                                   [Type ty'cea, Type errTy, proj, cea])
chak's avatar
chak committed
614
--
615 616 617 618 619 620 621
-- The parser guarantees that parallel comprehensions can only appear as
-- singeltons qualifier lists, which we already special case in the caller.
-- So, encountering one here is a bug.
--
dePArrComp (ParStmt _ : _) _ _ _ = 
  panic "DsListComp.dePArrComp: malformed comprehension AST"

chak's avatar
chak committed
622 623 624 625 626 627
--  <<[:e' | qs | qss:]>> pa ea = 
--    <<[:e' | qss:]>> (pa, (x_1, ..., x_n)) 
--		       (zipP ea <<[:(x_1, ..., x_n) | qs:]>>)
--    where
--      {x_1, ..., x_n} = DV (qs)
--
628
dePArrParComp :: [([LStmt Id], [Id])] -> LHsExpr Id -> DsM CoreExpr
629 630 631
dePArrParComp qss body = do
    (pQss, ceQss) <- deParStmt qss
    dePArrComp [] body pQss ceQss
chak's avatar
chak committed
632 633
  where
    deParStmt []             =
634
      -- empty parallel statement lists have no source representation
chak's avatar
chak committed
635
      panic "DsListComp.dePArrComp: Empty parallel list comprehension"
636
    deParStmt ((qs, xs):qss) = do        -- first statement
637
      let res_expr = mkLHsVarTuple xs
638
      cqs <- dsPArrComp (map unLoc qs) res_expr undefined
639
      parStmts qss (mkLHsVarPatTup xs) cqs
chak's avatar
chak committed
640 641
    ---
    parStmts []             pa cea = return (pa, cea)
642 643
    parStmts ((qs, xs):qss) pa cea = do  -- subsequent statements (zip'ed)
      zipP <- dsLookupGlobalId zipPName
644
      let pa'      = mkLHsPatTup [pa, mkLHsVarPatTup xs]
645
          ty'cea   = parrElemType cea
646
          res_expr = mkLHsVarTuple xs
647
      cqs <- dsPArrComp (map unLoc qs) res_expr undefined
chak's avatar
chak committed
648
      let ty'cqs = parrElemType cqs
649
          cea'   = mkApps (Var zipP) [Type ty'cea, Type ty'cqs, cea, cqs]
chak's avatar
chak committed
650
      parStmts qss pa' cea'
chak's avatar
chak committed
651 652 653

-- generate Core corresponding to `\p -> e'
--
654 655 656 657 658
deLambda :: Type			-- type of the argument
	  -> LPat Id			-- argument pattern
	  -> LHsExpr Id			-- body
	  -> DsM (CoreExpr, Type)
deLambda ty p e =
659
    mkLambda ty p =<< dsLExpr e
660 661 662 663 664 665 666

-- generate Core for a lambda pattern match, where the body is already in Core
--
mkLambda :: Type			-- type of the argument
	 -> LPat Id			-- argument pattern
	 -> CoreExpr			-- desugared body
	 -> DsM (CoreExpr, Type)
667 668
mkLambda ty p ce = do
    v <- newSysLocalDs ty
669
    let errMsg = ptext (sLit "DsListComp.deLambda: internal error!")
670 671 672 673
        ce'ty  = exprType ce
    cerr <- mkErrorAppDs pAT_ERROR_ID ce'ty errMsg
    res <- matchSimply (Var v) (StmtCtxt PArrComp) p ce cerr
    return (mkLams [v] res, ce'ty)
chak's avatar
chak committed
674 675 676 677 678 679 680

-- obtain the element type of the parallel array produced by the given Core
-- expression
--
parrElemType   :: CoreExpr -> Type
parrElemType e  = 
  case splitTyConApp_maybe (exprType e) of
681
    Just (tycon, [ty]) | tycon == parrTyCon -> ty
chak's avatar
chak committed
682 683 684
    _							  -> panic
      "DsListComp.parrElemType: not a parallel array type"
\end{code}