Tidy up the treatment of dead binders
[ghc-hetmet.git] / compiler / coreSyn / MkCore.lhs
1 \begin{code}
2 -- | Handy functions for creating much Core syntax
3 module MkCore (
4         -- * Constructing normal syntax
5         mkCoreLet, mkCoreLets,
6         mkCoreApp, mkCoreApps, mkCoreConApps,
7         mkCoreLams, mkWildCase, mkIfThenElse,
8         
9         -- * Constructing boxed literals
10         mkWordExpr, mkWordExprWord,
11         mkIntExpr, mkIntExprInt,
12         mkIntegerExpr,
13         mkFloatExpr, mkDoubleExpr,
14         mkCharExpr, mkStringExpr, mkStringExprFS,
15         
16         -- * Constructing general big tuples
17         -- $big_tuples
18         mkChunkified,
19         
20         -- * Constructing small tuples
21         mkCoreVarTup, mkCoreVarTupTy,
22         mkCoreTup, mkCoreTupTy,
23         
24         -- * Constructing big tuples
25         mkBigCoreVarTup, mkBigCoreVarTupTy,
26         mkBigCoreTup, mkBigCoreTupTy,
27         
28         -- * Deconstructing small tuples
29         mkSmallTupleSelector, mkSmallTupleCase,
30         
31         -- * Deconstructing big tuples
32         mkTupleSelector, mkTupleCase,
33         
34         -- * Constructing list expressions
35         mkNilExpr, mkConsExpr, mkListExpr, 
36         mkFoldrExpr, mkBuildExpr
37     ) where
38
39 #include "HsVersions.h"
40
41 import Id
42 import Var      ( setTyVarUnique )
43
44 import CoreSyn
45 import CoreUtils        ( exprType, needsCaseBinding, bindNonRec )
46 import Literal
47 import HscTypes
48
49 import TysWiredIn
50 import PrelNames
51
52 import Type
53 import TypeRep
54 import TysPrim          ( alphaTyVar )
55 import DataCon          ( DataCon, dataConWorkId )
56
57 import FastString
58 import UniqSupply
59 import Unique           ( mkBuiltinUnique )
60 import BasicTypes
61 import Util             ( notNull, zipEqual )
62 import Panic
63 import Constants
64
65 import Data.Char        ( ord )
66 import Data.Word
67
68 infixl 4 `mkCoreApp`, `mkCoreApps`
69 \end{code}
70
71 %************************************************************************
72 %*                                                                      *
73 \subsection{Basic CoreSyn construction}
74 %*                                                                      *
75 %************************************************************************
76
77 \begin{code}
78 -- | Bind a binding group over an expression, using a @let@ or @case@ as
79 -- appropriate (see "CoreSyn#let_app_invariant")
80 mkCoreLet :: CoreBind -> CoreExpr -> CoreExpr
81 mkCoreLet (NonRec bndr rhs) body        -- See Note [CoreSyn let/app invariant]
82   | needsCaseBinding (idType bndr) rhs
83   = Case rhs bndr (exprType body) [(DEFAULT,[],body)]
84 mkCoreLet bind body
85   = Let bind body
86
87 -- | Bind a list of binding groups over an expression. The leftmost binding
88 -- group becomes the outermost group in the resulting expression
89 mkCoreLets :: [CoreBind] -> CoreExpr -> CoreExpr
90 mkCoreLets binds body = foldr mkCoreLet body binds
91
92 -- | Construct an expression which represents the application of one expression
93 -- to the other
94 mkCoreApp :: CoreExpr -> CoreExpr -> CoreExpr
95 -- Check the invariant that the arg of an App is ok-for-speculation if unlifted
96 -- See CoreSyn Note [CoreSyn let/app invariant]
97 mkCoreApp fun (Type ty) = App fun (Type ty)
98 mkCoreApp fun arg       = mk_val_app fun arg arg_ty res_ty
99                       where
100                         (arg_ty, res_ty) = splitFunTy (exprType fun)
101
102 -- | Construct an expression which represents the application of a number of
103 -- expressions to another. The leftmost expression in the list is applied first
104 mkCoreApps :: CoreExpr -> [CoreExpr] -> CoreExpr
105 -- Slightly more efficient version of (foldl mkCoreApp)
106 mkCoreApps fun args
107   = go fun (exprType fun) args
108   where
109     go fun _      []               = fun
110     go fun fun_ty (Type ty : args) = go (App fun (Type ty)) (applyTy fun_ty ty) args
111     go fun fun_ty (arg     : args) = go (mk_val_app fun arg arg_ty res_ty) res_ty args
112                                    where
113                                      (arg_ty, res_ty) = splitFunTy fun_ty
114
115 -- | Construct an expression which represents the application of a number of
116 -- expressions to that of a data constructor expression. The leftmost expression
117 -- in the list is applied first
118 mkCoreConApps :: DataCon -> [CoreExpr] -> CoreExpr
119 mkCoreConApps con args = mkCoreApps (Var (dataConWorkId con)) args
120
121 -----------
122 mk_val_app :: CoreExpr -> CoreExpr -> Type -> Type -> CoreExpr
123 mk_val_app (Var f `App` Type ty1 `App` Type _ `App` arg1) arg2 _ res_ty
124   | f `hasKey` seqIdKey            -- Note [Desugaring seq (1), (2)]
125   = Case arg1 case_bndr res_ty [(DEFAULT,[],arg2)]
126   where
127     case_bndr = case arg1 of
128                    Var v1 | isLocalId v1 -> v1        -- Note [Desugaring seq (2) and (3)]
129                    _                     -> mkWildBinder ty1
130
131 mk_val_app fun arg arg_ty _        -- See Note [CoreSyn let/app invariant]
132   | not (needsCaseBinding arg_ty arg)
133   = App fun arg                -- The vastly common case
134
135 mk_val_app fun arg arg_ty res_ty
136   = Case arg arg_id res_ty [(DEFAULT,[],App fun (Var arg_id))]
137   where
138     arg_id = mkWildBinder arg_ty    
139         -- Lots of shadowing, but it doesn't matter,
140         -- because 'fun ' should not have a free wild-id
141         --
142         -- This is Dangerous.  But this is the only place we play this 
143         -- game, mk_val_app returns an expression that does not have
144         -- have a free wild-id.  So the only thing that can go wrong
145         -- is if you take apart this case expression, and pass a 
146         -- fragmet of it as the fun part of a 'mk_val_app'.
147
148
149 -- | Make a /wildcard binder/. This is typically used when you need a binder 
150 -- that you expect to use only at a *binding* site.  Do not use it at
151 -- occurrence sites because it has a single, fixed unique, and it's very
152 -- easy to get into difficulties with shadowing.  That's why it is used so little.
153 mkWildBinder :: Type -> Id
154 mkWildBinder ty = mkSysLocal (fsLit "wild") (mkBuiltinUnique 1) ty
155
156 mkWildCase :: CoreExpr -> Type -> Type -> [CoreAlt] -> CoreExpr
157 -- Make a case expression whose case binder is unused
158 -- The alts should not have any occurrences of WildId
159 mkWildCase scrut scrut_ty res_ty alts 
160   = Case scrut (mkWildBinder scrut_ty) res_ty alts
161
162 mkIfThenElse :: CoreExpr -> CoreExpr -> CoreExpr -> CoreExpr
163 mkIfThenElse guard then_expr else_expr
164 -- Not going to be refining, so okay to take the type of the "then" clause
165   = mkWildCase guard boolTy (exprType then_expr) 
166          [ (DataAlt falseDataCon, [], else_expr),       -- Increasing order of tag!
167            (DataAlt trueDataCon,  [], then_expr) ]
168 \end{code}
169
170 Note [Desugaring seq (1)]  cf Trac #1031
171 ~~~~~~~~~~~~~~~~~~~~~~~~~
172    f x y = x `seq` (y `seq` (# x,y #))
173
174 The [CoreSyn let/app invariant] means that, other things being equal, because 
175 the argument to the outer 'seq' has an unlifted type, we'll use call-by-value thus:
176
177    f x y = case (y `seq` (# x,y #)) of v -> x `seq` v
178
179 But that is bad for two reasons: 
180   (a) we now evaluate y before x, and 
181   (b) we can't bind v to an unboxed pair
182
183 Seq is very, very special!  So we recognise it right here, and desugar to
184         case x of _ -> case y of _ -> (# x,y #)
185
186 Note [Desugaring seq (2)]  cf Trac #2231
187 ~~~~~~~~~~~~~~~~~~~~~~~~~
188 Consider
189    let chp = case b of { True -> fst x; False -> 0 }
190    in chp `seq` ...chp...
191 Here the seq is designed to plug the space leak of retaining (snd x)
192 for too long.
193
194 If we rely on the ordinary inlining of seq, we'll get
195    let chp = case b of { True -> fst x; False -> 0 }
196    case chp of _ { I# -> ...chp... }
197
198 But since chp is cheap, and the case is an alluring contet, we'll
199 inline chp into the case scrutinee.  Now there is only one use of chp,
200 so we'll inline a second copy.  Alas, we've now ruined the purpose of
201 the seq, by re-introducing the space leak:
202     case (case b of {True -> fst x; False -> 0}) of
203       I# _ -> ...case b of {True -> fst x; False -> 0}...
204
205 We can try to avoid doing this by ensuring that the binder-swap in the
206 case happens, so we get his at an early stage:
207    case chp of chp2 { I# -> ...chp2... }
208 But this is fragile.  The real culprit is the source program.  Perhaps we
209 should have said explicitly
210    let !chp2 = chp in ...chp2...
211
212 But that's painful.  So the code here does a little hack to make seq
213 more robust: a saturated application of 'seq' is turned *directly* into
214 the case expression. So we desugar to:
215    let chp = case b of { True -> fst x; False -> 0 }
216    case chp of chp { I# -> ...chp... }
217 Notice the shadowing of the case binder! And now all is well.
218
219 The reason it's a hack is because if you define mySeq=seq, the hack
220 won't work on mySeq.  
221
222 Note [Desugaring seq (3)] cf Trac #2409
223 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
224 The isLocalId ensures that we don't turn 
225         True `seq` e
226 into
227         case True of True { ... }
228 which stupidly tries to bind the datacon 'True'. 
229 \begin{code}
230 -- The functions from this point don't really do anything cleverer than
231 -- their counterparts in CoreSyn, but they are here for consistency
232
233 -- | Create a lambda where the given expression has a number of variables
234 -- bound over it. The leftmost binder is that bound by the outermost
235 -- lambda in the result
236 mkCoreLams :: [CoreBndr] -> CoreExpr -> CoreExpr
237 mkCoreLams = mkLams
238 \end{code}
239
240 %************************************************************************
241 %*                                                                      *
242 \subsection{Making literals}
243 %*                                                                      *
244 %************************************************************************
245
246 \begin{code}
247 -- | Create a 'CoreExpr' which will evaluate to the given @Int@
248 mkIntExpr      :: Integer    -> CoreExpr            -- Result = I# i :: Int
249 mkIntExpr  i = mkConApp intDataCon  [mkIntLit i]
250
251 -- | Create a 'CoreExpr' which will evaluate to the given @Int@
252 mkIntExprInt   :: Int        -> CoreExpr            -- Result = I# i :: Int
253 mkIntExprInt  i = mkConApp intDataCon  [mkIntLitInt i]
254
255 -- | Create a 'CoreExpr' which will evaluate to the a @Word@ with the given value
256 mkWordExpr     :: Integer    -> CoreExpr
257 mkWordExpr w = mkConApp wordDataCon [mkWordLit w]
258
259 -- | Create a 'CoreExpr' which will evaluate to the given @Word@
260 mkWordExprWord :: Word       -> CoreExpr
261 mkWordExprWord w = mkConApp wordDataCon [mkWordLitWord w]
262
263 -- | Create a 'CoreExpr' which will evaluate to the given @Integer@
264 mkIntegerExpr  :: MonadThings m => Integer    -> m CoreExpr  -- Result :: Integer
265 mkIntegerExpr i
266   | inIntRange i        -- Small enough, so start from an Int
267     = do integer_id <- lookupId smallIntegerName
268          return (mkSmallIntegerLit integer_id i)
269
270 -- Special case for integral literals with a large magnitude:
271 -- They are transformed into an expression involving only smaller
272 -- integral literals. This improves constant folding.
273
274   | otherwise = do       -- Big, so start from a string
275       plus_id <- lookupId plusIntegerName
276       times_id <- lookupId timesIntegerName
277       integer_id <- lookupId smallIntegerName
278       let
279            lit i = mkSmallIntegerLit integer_id i
280            plus a b  = Var plus_id  `App` a `App` b
281            times a b = Var times_id `App` a `App` b
282
283            -- Transform i into (x1 + (x2 + (x3 + (...) * b) * b) * b) with abs xi <= b
284            horner :: Integer -> Integer -> CoreExpr
285            horner b i | abs q <= 1 = if r == 0 || r == i 
286                                      then lit i 
287                                      else lit r `plus` lit (i-r)
288                       | r == 0     =               horner b q `times` lit b
289                       | otherwise  = lit r `plus` (horner b q `times` lit b)
290                       where
291                         (q,r) = i `quotRem` b
292
293       return (horner tARGET_MAX_INT i)
294   where
295     mkSmallIntegerLit :: Id -> Integer -> CoreExpr
296     mkSmallIntegerLit small_integer i = mkApps (Var small_integer) [mkIntLit i]
297
298
299 -- | Create a 'CoreExpr' which will evaluate to the given @Float@
300 mkFloatExpr :: Float -> CoreExpr
301 mkFloatExpr f = mkConApp floatDataCon [mkFloatLitFloat f]
302
303 -- | Create a 'CoreExpr' which will evaluate to the given @Double@
304 mkDoubleExpr :: Double -> CoreExpr
305 mkDoubleExpr d = mkConApp doubleDataCon [mkDoubleLitDouble d]
306
307
308 -- | Create a 'CoreExpr' which will evaluate to the given @Char@
309 mkCharExpr     :: Char             -> CoreExpr      -- Result = C# c :: Int
310 mkCharExpr c = mkConApp charDataCon [mkCharLit c]
311
312 -- | Create a 'CoreExpr' which will evaluate to the given @String@
313 mkStringExpr   :: MonadThings m => String     -> m CoreExpr  -- Result :: String
314 -- | Create a 'CoreExpr' which will evaluate to a string morally equivalent to the given @FastString@
315 mkStringExprFS :: MonadThings m => FastString -> m CoreExpr  -- Result :: String
316
317 mkStringExpr str = mkStringExprFS (mkFastString str)
318
319 mkStringExprFS str
320   | nullFS str
321   = return (mkNilExpr charTy)
322
323   | lengthFS str == 1
324   = do let the_char = mkCharExpr (headFS str)
325        return (mkConsExpr charTy the_char (mkNilExpr charTy))
326
327   | all safeChar chars
328   = do unpack_id <- lookupId unpackCStringName
329        return (App (Var unpack_id) (Lit (MachStr str)))
330
331   | otherwise
332   = do unpack_id <- lookupId unpackCStringUtf8Name
333        return (App (Var unpack_id) (Lit (MachStr str)))
334
335   where
336     chars = unpackFS str
337     safeChar c = ord c >= 1 && ord c <= 0x7F
338 \end{code}
339
340 %************************************************************************
341 %*                                                                      *
342 \subsection{Tuple constructors}
343 %*                                                                      *
344 %************************************************************************
345
346 \begin{code}
347
348 -- $big_tuples
349 -- #big_tuples#
350 --
351 -- GHCs built in tuples can only go up to 'mAX_TUPLE_SIZE' in arity, but
352 -- we might concievably want to build such a massive tuple as part of the
353 -- output of a desugaring stage (notably that for list comprehensions).
354 --
355 -- We call tuples above this size \"big tuples\", and emulate them by
356 -- creating and pattern matching on >nested< tuples that are expressible
357 -- by GHC.
358 --
359 -- Nesting policy: it's better to have a 2-tuple of 10-tuples (3 objects)
360 -- than a 10-tuple of 2-tuples (11 objects), so we want the leaves of any
361 -- construction to be big.
362 --
363 -- If you just use the 'mkBigCoreTup', 'mkBigCoreVarTupTy', 'mkTupleSelector'
364 -- and 'mkTupleCase' functions to do all your work with tuples you should be
365 -- fine, and not have to worry about the arity limitation at all.
366
367 -- | Lifts a \"small\" constructor into a \"big\" constructor by recursive decompositon
368 mkChunkified :: ([a] -> a)      -- ^ \"Small\" constructor function, of maximum input arity 'mAX_TUPLE_SIZE'
369              -> [a]             -- ^ Possible \"big\" list of things to construct from
370              -> a               -- ^ Constructed thing made possible by recursive decomposition
371 mkChunkified small_tuple as = mk_big_tuple (chunkify as)
372   where
373         -- Each sub-list is short enough to fit in a tuple
374     mk_big_tuple [as] = small_tuple as
375     mk_big_tuple as_s = mk_big_tuple (chunkify (map small_tuple as_s))
376
377 chunkify :: [a] -> [[a]]
378 -- ^ Split a list into lists that are small enough to have a corresponding
379 -- tuple arity. The sub-lists of the result all have length <= 'mAX_TUPLE_SIZE'
380 -- But there may be more than 'mAX_TUPLE_SIZE' sub-lists
381 chunkify xs
382   | n_xs <= mAX_TUPLE_SIZE = [xs] 
383   | otherwise              = split xs
384   where
385     n_xs     = length xs
386     split [] = []
387     split xs = take mAX_TUPLE_SIZE xs : split (drop mAX_TUPLE_SIZE xs)
388     
389 \end{code}
390
391 Creating tuples and their types for Core expressions 
392
393 @mkBigCoreVarTup@ builds a tuple; the inverse to @mkTupleSelector@.  
394
395 * If it has only one element, it is the identity function.
396
397 * If there are more elements than a big tuple can have, it nests 
398   the tuples.  
399
400 \begin{code}
401
402 -- | Build a small tuple holding the specified variables
403 mkCoreVarTup :: [Id] -> CoreExpr
404 mkCoreVarTup ids = mkCoreTup (map Var ids)
405
406 -- | Bulid the type of a small tuple that holds the specified variables
407 mkCoreVarTupTy :: [Id] -> Type
408 mkCoreVarTupTy ids = mkCoreTupTy (map idType ids)
409
410 -- | Build a small tuple holding the specified expressions
411 mkCoreTup :: [CoreExpr] -> CoreExpr
412 mkCoreTup []  = Var unitDataConId
413 mkCoreTup [c] = c
414 mkCoreTup cs  = mkConApp (tupleCon Boxed (length cs))
415                          (map (Type . exprType) cs ++ cs)
416
417 -- | Build the type of a small tuple that holds the specified type of thing
418 mkCoreTupTy :: [Type] -> Type
419 mkCoreTupTy [ty] = ty
420 mkCoreTupTy tys  = mkTupleTy Boxed (length tys) tys
421
422
423 -- | Build a big tuple holding the specified variables
424 mkBigCoreVarTup :: [Id] -> CoreExpr
425 mkBigCoreVarTup ids = mkBigCoreTup (map Var ids)
426
427 -- | Build the type of a big tuple that holds the specified variables
428 mkBigCoreVarTupTy :: [Id] -> Type
429 mkBigCoreVarTupTy ids = mkBigCoreTupTy (map idType ids)
430
431 -- | Build a big tuple holding the specified expressions
432 mkBigCoreTup :: [CoreExpr] -> CoreExpr
433 mkBigCoreTup = mkChunkified mkCoreTup
434
435 -- | Build the type of a big tuple that holds the specified type of thing
436 mkBigCoreTupTy :: [Type] -> Type
437 mkBigCoreTupTy = mkChunkified mkCoreTupTy
438 \end{code}
439
440 %************************************************************************
441 %*                                                                      *
442 \subsection{Tuple destructors}
443 %*                                                                      *
444 %************************************************************************
445
446 \begin{code}
447 -- | Builds a selector which scrutises the given
448 -- expression and extracts the one name from the list given.
449 -- If you want the no-shadowing rule to apply, the caller
450 -- is responsible for making sure that none of these names
451 -- are in scope.
452 --
453 -- If there is just one 'Id' in the tuple, then the selector is
454 -- just the identity.
455 --
456 -- If necessary, we pattern match on a \"big\" tuple.
457 mkTupleSelector :: [Id]         -- ^ The 'Id's to pattern match the tuple against
458                 -> Id           -- ^ The 'Id' to select
459                 -> Id           -- ^ A variable of the same type as the scrutinee
460                 -> CoreExpr     -- ^ Scrutinee
461                 -> CoreExpr     -- ^ Selector expression
462
463 -- mkTupleSelector [a,b,c,d] b v e
464 --          = case e of v { 
465 --                (p,q) -> case p of p {
466 --                           (a,b) -> b }}
467 -- We use 'tpl' vars for the p,q, since shadowing does not matter.
468 --
469 -- In fact, it's more convenient to generate it innermost first, getting
470 --
471 --        case (case e of v 
472 --                (p,q) -> p) of p
473 --          (a,b) -> b
474 mkTupleSelector vars the_var scrut_var scrut
475   = mk_tup_sel (chunkify vars) the_var
476   where
477     mk_tup_sel [vars] the_var = mkSmallTupleSelector vars the_var scrut_var scrut
478     mk_tup_sel vars_s the_var = mkSmallTupleSelector group the_var tpl_v $
479                                 mk_tup_sel (chunkify tpl_vs) tpl_v
480         where
481           tpl_tys = [mkCoreTupTy (map idType gp) | gp <- vars_s]
482           tpl_vs  = mkTemplateLocals tpl_tys
483           [(tpl_v, group)] = [(tpl,gp) | (tpl,gp) <- zipEqual "mkTupleSelector" tpl_vs vars_s,
484                                          the_var `elem` gp ]
485 \end{code}
486
487 \begin{code}
488 -- | Like 'mkTupleSelector' but for tuples that are guaranteed
489 -- never to be \"big\".
490 --
491 -- > mkSmallTupleSelector [x] x v e = [| e |]
492 -- > mkSmallTupleSelector [x,y,z] x v e = [| case e of v { (x,y,z) -> x } |]
493 mkSmallTupleSelector :: [Id]        -- The tuple args
494           -> Id         -- The selected one
495           -> Id         -- A variable of the same type as the scrutinee
496           -> CoreExpr        -- Scrutinee
497           -> CoreExpr
498 mkSmallTupleSelector [var] should_be_the_same_var _ scrut
499   = ASSERT(var == should_be_the_same_var)
500     scrut
501 mkSmallTupleSelector vars the_var scrut_var scrut
502   = ASSERT( notNull vars )
503     Case scrut scrut_var (idType the_var)
504          [(DataAlt (tupleCon Boxed (length vars)), vars, Var the_var)]
505 \end{code}
506
507 \begin{code}
508 -- | A generalization of 'mkTupleSelector', allowing the body
509 -- of the case to be an arbitrary expression.
510 --
511 -- To avoid shadowing, we use uniques to invent new variables.
512 --
513 -- If necessary we pattern match on a \"big\" tuple.
514 mkTupleCase :: UniqSupply       -- ^ For inventing names of intermediate variables
515             -> [Id]             -- ^ The tuple identifiers to pattern match on
516             -> CoreExpr         -- ^ Body of the case
517             -> Id               -- ^ A variable of the same type as the scrutinee
518             -> CoreExpr         -- ^ Scrutinee
519             -> CoreExpr
520 -- ToDo: eliminate cases where none of the variables are needed.
521 --
522 --         mkTupleCase uniqs [a,b,c,d] body v e
523 --           = case e of v { (p,q) ->
524 --             case p of p { (a,b) ->
525 --             case q of q { (c,d) ->
526 --             body }}}
527 mkTupleCase uniqs vars body scrut_var scrut
528   = mk_tuple_case uniqs (chunkify vars) body
529   where
530     -- This is the case where don't need any nesting
531     mk_tuple_case _ [vars] body
532       = mkSmallTupleCase vars body scrut_var scrut
533       
534     -- This is the case where we must make nest tuples at least once
535     mk_tuple_case us vars_s body
536       = let (us', vars', body') = foldr one_tuple_case (us, [], body) vars_s
537             in mk_tuple_case us' (chunkify vars') body'
538     
539     one_tuple_case chunk_vars (us, vs, body)
540       = let (us1, us2) = splitUniqSupply us
541             scrut_var = mkSysLocal (fsLit "ds") (uniqFromSupply us1)
542               (mkCoreTupTy (map idType chunk_vars))
543             body' = mkSmallTupleCase chunk_vars body scrut_var (Var scrut_var)
544         in (us2, scrut_var:vs, body')
545 \end{code}
546
547 \begin{code}
548 -- | As 'mkTupleCase', but for a tuple that is small enough to be guaranteed
549 -- not to need nesting.
550 mkSmallTupleCase
551         :: [Id]         -- ^ The tuple args
552         -> CoreExpr     -- ^ Body of the case
553         -> Id           -- ^ A variable of the same type as the scrutinee
554         -> CoreExpr     -- ^ Scrutinee
555         -> CoreExpr
556
557 mkSmallTupleCase [var] body _scrut_var scrut
558   = bindNonRec var scrut body
559 mkSmallTupleCase vars body scrut_var scrut
560 -- One branch no refinement?
561   = Case scrut scrut_var (exprType body) [(DataAlt (tupleCon Boxed (length vars)), vars, body)]
562 \end{code}
563
564 %************************************************************************
565 %*                                                                      *
566 \subsection{Common list manipulation expressions}
567 %*                                                                      *
568 %************************************************************************
569
570 Call the constructor Ids when building explicit lists, so that they
571 interact well with rules.
572
573 \begin{code}
574 -- | Makes a list @[]@ for lists of the specified type
575 mkNilExpr :: Type -> CoreExpr
576 mkNilExpr ty = mkConApp nilDataCon [Type ty]
577
578 -- | Makes a list @(:)@ for lists of the specified type
579 mkConsExpr :: Type -> CoreExpr -> CoreExpr -> CoreExpr
580 mkConsExpr ty hd tl = mkConApp consDataCon [Type ty, hd, tl]
581
582 -- | Make a list containing the given expressions, where the list has the given type
583 mkListExpr :: Type -> [CoreExpr] -> CoreExpr
584 mkListExpr ty xs = foldr (mkConsExpr ty) (mkNilExpr ty) xs
585
586 -- | Make a fully applied 'foldr' expression
587 mkFoldrExpr :: MonadThings m
588             => Type             -- ^ Element type of the list
589             -> Type             -- ^ Fold result type
590             -> CoreExpr         -- ^ "Cons" function expression for the fold
591             -> CoreExpr         -- ^ "Nil" expression for the fold
592             -> CoreExpr         -- ^ List expression being folded acress
593             -> m CoreExpr
594 mkFoldrExpr elt_ty result_ty c n list = do
595     foldr_id <- lookupId foldrName
596     return (Var foldr_id `App` Type elt_ty 
597            `App` Type result_ty
598            `App` c
599            `App` n
600            `App` list)
601
602 -- | Make a 'build' expression applied to a locally-bound worker function
603 mkBuildExpr :: (MonadThings m, MonadUnique m)
604             => Type                                     -- ^ Type of list elements to be built
605             -> ((Id, Type) -> (Id, Type) -> m CoreExpr) -- ^ Function that, given information about the 'Id's
606                                                         -- of the binders for the build worker function, returns
607                                                         -- the body of that worker
608             -> m CoreExpr
609 mkBuildExpr elt_ty mk_build_inside = do
610     [n_tyvar] <- newTyVars [alphaTyVar]
611     let n_ty = mkTyVarTy n_tyvar
612         c_ty = mkFunTys [elt_ty, n_ty] n_ty
613     [c, n] <- sequence [mkSysLocalM (fsLit "c") c_ty, mkSysLocalM (fsLit "n") n_ty]
614     
615     build_inside <- mk_build_inside (c, c_ty) (n, n_ty)
616     
617     build_id <- lookupId buildName
618     return $ Var build_id `App` Type elt_ty `App` mkLams [n_tyvar, c, n] build_inside
619   where
620     newTyVars tyvar_tmpls = do
621       uniqs <- getUniquesM
622       return (zipWith setTyVarUnique tyvar_tmpls uniqs)
623 \end{code}