White space only
[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,
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 import MkId             ( seqId )
52
53 import Type
54 import TypeRep
55 import TysPrim          ( alphaTyVar )
56 import DataCon          ( DataCon, dataConWorkId )
57
58 import FastString
59 import UniqSupply
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 == seqId                -- 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                    _                     -> mkWildId 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 (mkWildId arg_ty) res_ty [(DEFAULT,[],App fun (Var arg_id))]
137   where
138     arg_id = mkWildId arg_ty    -- Lots of shadowing, but it doesn't matter,
139                                 -- because 'fun ' should not have a free wild-id
140 \end{code}
141
142 Note [Desugaring seq (1)]  cf Trac #1031
143 ~~~~~~~~~~~~~~~~~~~~~~~~~
144    f x y = x `seq` (y `seq` (# x,y #))
145
146 The [CoreSyn let/app invariant] means that, other things being equal, because 
147 the argument to the outer 'seq' has an unlifted type, we'll use call-by-value thus:
148
149    f x y = case (y `seq` (# x,y #)) of v -> x `seq` v
150
151 But that is bad for two reasons: 
152   (a) we now evaluate y before x, and 
153   (b) we can't bind v to an unboxed pair
154
155 Seq is very, very special!  So we recognise it right here, and desugar to
156         case x of _ -> case y of _ -> (# x,y #)
157
158 Note [Desugaring seq (2)]  cf Trac #2231
159 ~~~~~~~~~~~~~~~~~~~~~~~~~
160 Consider
161    let chp = case b of { True -> fst x; False -> 0 }
162    in chp `seq` ...chp...
163 Here the seq is designed to plug the space leak of retaining (snd x)
164 for too long.
165
166 If we rely on the ordinary inlining of seq, we'll get
167    let chp = case b of { True -> fst x; False -> 0 }
168    case chp of _ { I# -> ...chp... }
169
170 But since chp is cheap, and the case is an alluring contet, we'll
171 inline chp into the case scrutinee.  Now there is only one use of chp,
172 so we'll inline a second copy.  Alas, we've now ruined the purpose of
173 the seq, by re-introducing the space leak:
174     case (case b of {True -> fst x; False -> 0}) of
175       I# _ -> ...case b of {True -> fst x; False -> 0}...
176
177 We can try to avoid doing this by ensuring that the binder-swap in the
178 case happens, so we get his at an early stage:
179    case chp of chp2 { I# -> ...chp2... }
180 But this is fragile.  The real culprit is the source program.  Perhaps we
181 should have said explicitly
182    let !chp2 = chp in ...chp2...
183
184 But that's painful.  So the code here does a little hack to make seq
185 more robust: a saturated application of 'seq' is turned *directly* into
186 the case expression. So we desugar to:
187    let chp = case b of { True -> fst x; False -> 0 }
188    case chp of chp { I# -> ...chp... }
189 Notice the shadowing of the case binder! And now all is well.
190
191 The reason it's a hack is because if you define mySeq=seq, the hack
192 won't work on mySeq.  
193
194 Note [Desugaring seq (3)] cf Trac #2409
195 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
196 The isLocalId ensures that we don't turn 
197         True `seq` e
198 into
199         case True of True { ... }
200 which stupidly tries to bind the datacon 'True'. 
201 \begin{code}
202 -- The functions from this point don't really do anything cleverer than
203 -- their counterparts in CoreSyn, but they are here for consistency
204
205 -- | Create a lambda where the given expression has a number of variables
206 -- bound over it. The leftmost binder is that bound by the outermost
207 -- lambda in the result
208 mkCoreLams :: [CoreBndr] -> CoreExpr -> CoreExpr
209 mkCoreLams = mkLams
210 \end{code}
211
212 %************************************************************************
213 %*                                                                      *
214 \subsection{Making literals}
215 %*                                                                      *
216 %************************************************************************
217
218 \begin{code}
219 -- | Create a 'CoreExpr' which will evaluate to the given @Int@
220 mkIntExpr      :: Integer    -> CoreExpr            -- Result = I# i :: Int
221 mkIntExpr  i = mkConApp intDataCon  [mkIntLit i]
222
223 -- | Create a 'CoreExpr' which will evaluate to the given @Int@
224 mkIntExprInt   :: Int        -> CoreExpr            -- Result = I# i :: Int
225 mkIntExprInt  i = mkConApp intDataCon  [mkIntLitInt i]
226
227 -- | Create a 'CoreExpr' which will evaluate to the a @Word@ with the given value
228 mkWordExpr     :: Integer    -> CoreExpr
229 mkWordExpr w = mkConApp wordDataCon [mkWordLit w]
230
231 -- | Create a 'CoreExpr' which will evaluate to the given @Word@
232 mkWordExprWord :: Word       -> CoreExpr
233 mkWordExprWord w = mkConApp wordDataCon [mkWordLitWord w]
234
235 -- | Create a 'CoreExpr' which will evaluate to the given @Integer@
236 mkIntegerExpr  :: MonadThings m => Integer    -> m CoreExpr  -- Result :: Integer
237 mkIntegerExpr i
238   | inIntRange i        -- Small enough, so start from an Int
239     = do integer_id <- lookupId smallIntegerName
240          return (mkSmallIntegerLit integer_id i)
241
242 -- Special case for integral literals with a large magnitude:
243 -- They are transformed into an expression involving only smaller
244 -- integral literals. This improves constant folding.
245
246   | otherwise = do       -- Big, so start from a string
247       plus_id <- lookupId plusIntegerName
248       times_id <- lookupId timesIntegerName
249       integer_id <- lookupId smallIntegerName
250       let
251            lit i = mkSmallIntegerLit integer_id i
252            plus a b  = Var plus_id  `App` a `App` b
253            times a b = Var times_id `App` a `App` b
254
255            -- Transform i into (x1 + (x2 + (x3 + (...) * b) * b) * b) with abs xi <= b
256            horner :: Integer -> Integer -> CoreExpr
257            horner b i | abs q <= 1 = if r == 0 || r == i 
258                                      then lit i 
259                                      else lit r `plus` lit (i-r)
260                       | r == 0     =               horner b q `times` lit b
261                       | otherwise  = lit r `plus` (horner b q `times` lit b)
262                       where
263                         (q,r) = i `quotRem` b
264
265       return (horner tARGET_MAX_INT i)
266   where
267     mkSmallIntegerLit :: Id -> Integer -> CoreExpr
268     mkSmallIntegerLit small_integer i = mkApps (Var small_integer) [mkIntLit i]
269
270
271 -- | Create a 'CoreExpr' which will evaluate to the given @Float@
272 mkFloatExpr :: Float -> CoreExpr
273 mkFloatExpr f = mkConApp floatDataCon [mkFloatLitFloat f]
274
275 -- | Create a 'CoreExpr' which will evaluate to the given @Double@
276 mkDoubleExpr :: Double -> CoreExpr
277 mkDoubleExpr d = mkConApp doubleDataCon [mkDoubleLitDouble d]
278
279
280 -- | Create a 'CoreExpr' which will evaluate to the given @Char@
281 mkCharExpr     :: Char             -> CoreExpr      -- Result = C# c :: Int
282 mkCharExpr c = mkConApp charDataCon [mkCharLit c]
283
284 -- | Create a 'CoreExpr' which will evaluate to the given @String@
285 mkStringExpr   :: MonadThings m => String     -> m CoreExpr  -- Result :: String
286 -- | Create a 'CoreExpr' which will evaluate to a string morally equivalent to the given @FastString@
287 mkStringExprFS :: MonadThings m => FastString -> m CoreExpr  -- Result :: String
288
289 mkStringExpr str = mkStringExprFS (mkFastString str)
290
291 mkStringExprFS str
292   | nullFS str
293   = return (mkNilExpr charTy)
294
295   | lengthFS str == 1
296   = do let the_char = mkCharExpr (headFS str)
297        return (mkConsExpr charTy the_char (mkNilExpr charTy))
298
299   | all safeChar chars
300   = do unpack_id <- lookupId unpackCStringName
301        return (App (Var unpack_id) (Lit (MachStr str)))
302
303   | otherwise
304   = do unpack_id <- lookupId unpackCStringUtf8Name
305        return (App (Var unpack_id) (Lit (MachStr str)))
306
307   where
308     chars = unpackFS str
309     safeChar c = ord c >= 1 && ord c <= 0x7F
310 \end{code}
311
312 %************************************************************************
313 %*                                                                      *
314 \subsection{Tuple constructors}
315 %*                                                                      *
316 %************************************************************************
317
318 \begin{code}
319
320 -- $big_tuples
321 -- #big_tuples#
322 --
323 -- GHCs built in tuples can only go up to 'mAX_TUPLE_SIZE' in arity, but
324 -- we might concievably want to build such a massive tuple as part of the
325 -- output of a desugaring stage (notably that for list comprehensions).
326 --
327 -- We call tuples above this size \"big tuples\", and emulate them by
328 -- creating and pattern matching on >nested< tuples that are expressible
329 -- by GHC.
330 --
331 -- Nesting policy: it's better to have a 2-tuple of 10-tuples (3 objects)
332 -- than a 10-tuple of 2-tuples (11 objects), so we want the leaves of any
333 -- construction to be big.
334 --
335 -- If you just use the 'mkBigCoreTup', 'mkBigCoreVarTupTy', 'mkTupleSelector'
336 -- and 'mkTupleCase' functions to do all your work with tuples you should be
337 -- fine, and not have to worry about the arity limitation at all.
338
339 -- | Lifts a \"small\" constructor into a \"big\" constructor by recursive decompositon
340 mkChunkified :: ([a] -> a)      -- ^ \"Small\" constructor function, of maximum input arity 'mAX_TUPLE_SIZE'
341              -> [a]             -- ^ Possible \"big\" list of things to construct from
342              -> a               -- ^ Constructed thing made possible by recursive decomposition
343 mkChunkified small_tuple as = mk_big_tuple (chunkify as)
344   where
345         -- Each sub-list is short enough to fit in a tuple
346     mk_big_tuple [as] = small_tuple as
347     mk_big_tuple as_s = mk_big_tuple (chunkify (map small_tuple as_s))
348
349 chunkify :: [a] -> [[a]]
350 -- ^ Split a list into lists that are small enough to have a corresponding
351 -- tuple arity. The sub-lists of the result all have length <= 'mAX_TUPLE_SIZE'
352 -- But there may be more than 'mAX_TUPLE_SIZE' sub-lists
353 chunkify xs
354   | n_xs <= mAX_TUPLE_SIZE = [xs] 
355   | otherwise              = split xs
356   where
357     n_xs     = length xs
358     split [] = []
359     split xs = take mAX_TUPLE_SIZE xs : split (drop mAX_TUPLE_SIZE xs)
360     
361 \end{code}
362
363 Creating tuples and their types for Core expressions 
364
365 @mkBigCoreVarTup@ builds a tuple; the inverse to @mkTupleSelector@.  
366
367 * If it has only one element, it is the identity function.
368
369 * If there are more elements than a big tuple can have, it nests 
370   the tuples.  
371
372 \begin{code}
373
374 -- | Build a small tuple holding the specified variables
375 mkCoreVarTup :: [Id] -> CoreExpr
376 mkCoreVarTup ids = mkCoreTup (map Var ids)
377
378 -- | Bulid the type of a small tuple that holds the specified variables
379 mkCoreVarTupTy :: [Id] -> Type
380 mkCoreVarTupTy ids = mkCoreTupTy (map idType ids)
381
382 -- | Build a small tuple holding the specified expressions
383 mkCoreTup :: [CoreExpr] -> CoreExpr
384 mkCoreTup []  = Var unitDataConId
385 mkCoreTup [c] = c
386 mkCoreTup cs  = mkConApp (tupleCon Boxed (length cs))
387                          (map (Type . exprType) cs ++ cs)
388
389 -- | Build the type of a small tuple that holds the specified type of thing
390 mkCoreTupTy :: [Type] -> Type
391 mkCoreTupTy [ty] = ty
392 mkCoreTupTy tys  = mkTupleTy Boxed (length tys) tys
393
394
395 -- | Build a big tuple holding the specified variables
396 mkBigCoreVarTup :: [Id] -> CoreExpr
397 mkBigCoreVarTup ids = mkBigCoreTup (map Var ids)
398
399 -- | Build the type of a big tuple that holds the specified variables
400 mkBigCoreVarTupTy :: [Id] -> Type
401 mkBigCoreVarTupTy ids = mkBigCoreTupTy (map idType ids)
402
403 -- | Build a big tuple holding the specified expressions
404 mkBigCoreTup :: [CoreExpr] -> CoreExpr
405 mkBigCoreTup = mkChunkified mkCoreTup
406
407 -- | Build the type of a big tuple that holds the specified type of thing
408 mkBigCoreTupTy :: [Type] -> Type
409 mkBigCoreTupTy = mkChunkified mkCoreTupTy
410 \end{code}
411
412 %************************************************************************
413 %*                                                                      *
414 \subsection{Tuple destructors}
415 %*                                                                      *
416 %************************************************************************
417
418 \begin{code}
419 -- | Builds a selector which scrutises the given
420 -- expression and extracts the one name from the list given.
421 -- If you want the no-shadowing rule to apply, the caller
422 -- is responsible for making sure that none of these names
423 -- are in scope.
424 --
425 -- If there is just one 'Id' in the tuple, then the selector is
426 -- just the identity.
427 --
428 -- If necessary, we pattern match on a \"big\" tuple.
429 mkTupleSelector :: [Id]         -- ^ The 'Id's to pattern match the tuple against
430                 -> Id           -- ^ The 'Id' to select
431                 -> Id           -- ^ A variable of the same type as the scrutinee
432                 -> CoreExpr     -- ^ Scrutinee
433                 -> CoreExpr     -- ^ Selector expression
434
435 -- mkTupleSelector [a,b,c,d] b v e
436 --          = case e of v { 
437 --                (p,q) -> case p of p {
438 --                           (a,b) -> b }}
439 -- We use 'tpl' vars for the p,q, since shadowing does not matter.
440 --
441 -- In fact, it's more convenient to generate it innermost first, getting
442 --
443 --        case (case e of v 
444 --                (p,q) -> p) of p
445 --          (a,b) -> b
446 mkTupleSelector vars the_var scrut_var scrut
447   = mk_tup_sel (chunkify vars) the_var
448   where
449     mk_tup_sel [vars] the_var = mkSmallTupleSelector vars the_var scrut_var scrut
450     mk_tup_sel vars_s the_var = mkSmallTupleSelector group the_var tpl_v $
451                                 mk_tup_sel (chunkify tpl_vs) tpl_v
452         where
453           tpl_tys = [mkCoreTupTy (map idType gp) | gp <- vars_s]
454           tpl_vs  = mkTemplateLocals tpl_tys
455           [(tpl_v, group)] = [(tpl,gp) | (tpl,gp) <- zipEqual "mkTupleSelector" tpl_vs vars_s,
456                                          the_var `elem` gp ]
457 \end{code}
458
459 \begin{code}
460 -- | Like 'mkTupleSelector' but for tuples that are guaranteed
461 -- never to be \"big\".
462 --
463 -- > mkSmallTupleSelector [x] x v e = [| e |]
464 -- > mkSmallTupleSelector [x,y,z] x v e = [| case e of v { (x,y,z) -> x } |]
465 mkSmallTupleSelector :: [Id]        -- The tuple args
466           -> Id         -- The selected one
467           -> Id         -- A variable of the same type as the scrutinee
468           -> CoreExpr        -- Scrutinee
469           -> CoreExpr
470 mkSmallTupleSelector [var] should_be_the_same_var _ scrut
471   = ASSERT(var == should_be_the_same_var)
472     scrut
473 mkSmallTupleSelector vars the_var scrut_var scrut
474   = ASSERT( notNull vars )
475     Case scrut scrut_var (idType the_var)
476          [(DataAlt (tupleCon Boxed (length vars)), vars, Var the_var)]
477 \end{code}
478
479 \begin{code}
480 -- | A generalization of 'mkTupleSelector', allowing the body
481 -- of the case to be an arbitrary expression.
482 --
483 -- To avoid shadowing, we use uniques to invent new variables.
484 --
485 -- If necessary we pattern match on a \"big\" tuple.
486 mkTupleCase :: UniqSupply       -- ^ For inventing names of intermediate variables
487             -> [Id]             -- ^ The tuple identifiers to pattern match on
488             -> CoreExpr         -- ^ Body of the case
489             -> Id               -- ^ A variable of the same type as the scrutinee
490             -> CoreExpr         -- ^ Scrutinee
491             -> CoreExpr
492 -- ToDo: eliminate cases where none of the variables are needed.
493 --
494 --         mkTupleCase uniqs [a,b,c,d] body v e
495 --           = case e of v { (p,q) ->
496 --             case p of p { (a,b) ->
497 --             case q of q { (c,d) ->
498 --             body }}}
499 mkTupleCase uniqs vars body scrut_var scrut
500   = mk_tuple_case uniqs (chunkify vars) body
501   where
502     -- This is the case where don't need any nesting
503     mk_tuple_case _ [vars] body
504       = mkSmallTupleCase vars body scrut_var scrut
505       
506     -- This is the case where we must make nest tuples at least once
507     mk_tuple_case us vars_s body
508       = let (us', vars', body') = foldr one_tuple_case (us, [], body) vars_s
509             in mk_tuple_case us' (chunkify vars') body'
510     
511     one_tuple_case chunk_vars (us, vs, body)
512       = let (us1, us2) = splitUniqSupply us
513             scrut_var = mkSysLocal (fsLit "ds") (uniqFromSupply us1)
514               (mkCoreTupTy (map idType chunk_vars))
515             body' = mkSmallTupleCase chunk_vars body scrut_var (Var scrut_var)
516         in (us2, scrut_var:vs, body')
517 \end{code}
518
519 \begin{code}
520 -- | As 'mkTupleCase', but for a tuple that is small enough to be guaranteed
521 -- not to need nesting.
522 mkSmallTupleCase
523         :: [Id]         -- ^ The tuple args
524         -> CoreExpr     -- ^ Body of the case
525         -> Id           -- ^ A variable of the same type as the scrutinee
526         -> CoreExpr     -- ^ Scrutinee
527         -> CoreExpr
528
529 mkSmallTupleCase [var] body _scrut_var scrut
530   = bindNonRec var scrut body
531 mkSmallTupleCase vars body scrut_var scrut
532 -- One branch no refinement?
533   = Case scrut scrut_var (exprType body) [(DataAlt (tupleCon Boxed (length vars)), vars, body)]
534 \end{code}
535
536 %************************************************************************
537 %*                                                                      *
538 \subsection{Common list manipulation expressions}
539 %*                                                                      *
540 %************************************************************************
541
542 Call the constructor Ids when building explicit lists, so that they
543 interact well with rules.
544
545 \begin{code}
546 -- | Makes a list @[]@ for lists of the specified type
547 mkNilExpr :: Type -> CoreExpr
548 mkNilExpr ty = mkConApp nilDataCon [Type ty]
549
550 -- | Makes a list @(:)@ for lists of the specified type
551 mkConsExpr :: Type -> CoreExpr -> CoreExpr -> CoreExpr
552 mkConsExpr ty hd tl = mkConApp consDataCon [Type ty, hd, tl]
553
554 -- | Make a list containing the given expressions, where the list has the given type
555 mkListExpr :: Type -> [CoreExpr] -> CoreExpr
556 mkListExpr ty xs = foldr (mkConsExpr ty) (mkNilExpr ty) xs
557
558 -- | Make a fully applied 'foldr' expression
559 mkFoldrExpr :: MonadThings m
560             => Type             -- ^ Element type of the list
561             -> Type             -- ^ Fold result type
562             -> CoreExpr         -- ^ "Cons" function expression for the fold
563             -> CoreExpr         -- ^ "Nil" expression for the fold
564             -> CoreExpr         -- ^ List expression being folded acress
565             -> m CoreExpr
566 mkFoldrExpr elt_ty result_ty c n list = do
567     foldr_id <- lookupId foldrName
568     return (Var foldr_id `App` Type elt_ty 
569            `App` Type result_ty
570            `App` c
571            `App` n
572            `App` list)
573
574 -- | Make a 'build' expression applied to a locally-bound worker function
575 mkBuildExpr :: (MonadThings m, MonadUnique m)
576             => Type                                     -- ^ Type of list elements to be built
577             -> ((Id, Type) -> (Id, Type) -> m CoreExpr) -- ^ Function that, given information about the 'Id's
578                                                         -- of the binders for the build worker function, returns
579                                                         -- the body of that worker
580             -> m CoreExpr
581 mkBuildExpr elt_ty mk_build_inside = do
582     [n_tyvar] <- newTyVars [alphaTyVar]
583     let n_ty = mkTyVarTy n_tyvar
584         c_ty = mkFunTys [elt_ty, n_ty] n_ty
585     [c, n] <- sequence [mkSysLocalM (fsLit "c") c_ty, mkSysLocalM (fsLit "n") n_ty]
586     
587     build_inside <- mk_build_inside (c, c_ty) (n, n_ty)
588     
589     build_id <- lookupId buildName
590     return $ Var build_id `App` Type elt_ty `App` mkLams [n_tyvar, c, n] build_inside
591   where
592     newTyVars tyvar_tmpls = do
593       uniqs <- getUniquesM
594       return (zipWith setTyVarUnique tyvar_tmpls uniqs)
595 \end{code}