a4977474315c2cefad537b4ba62e2d8041cbc7a1
[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         mkWildValBinder, mkWildEvBinder,
9         
10         -- * Constructing boxed literals
11         mkWordExpr, mkWordExprWord,
12         mkIntExpr, mkIntExprInt,
13         mkIntegerExpr,
14         mkFloatExpr, mkDoubleExpr,
15         mkCharExpr, mkStringExpr, mkStringExprFS,
16         
17         -- * Constructing general big tuples
18         -- $big_tuples
19         mkChunkified,
20         
21         -- * Constructing small tuples
22         mkCoreVarTup, mkCoreVarTupTy, mkCoreTup, 
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
38         -- * Error Ids 
39         mkRuntimeErrorApp, mkImpossibleExpr, errorIds,
40         rEC_CON_ERROR_ID, iRREFUT_PAT_ERROR_ID, rUNTIME_ERROR_ID,
41         nON_EXHAUSTIVE_GUARDS_ERROR_ID, nO_METHOD_BINDING_ERROR_ID,
42         pAT_ERROR_ID, eRROR_ID, rEC_SEL_ERROR_ID, aBSENT_ERROR_ID
43     ) where
44
45 #include "HsVersions.h"
46
47 import Id
48 import IdInfo
49 import Var      ( EvVar, mkWildCoVar, setTyVarUnique )
50
51 import CoreSyn
52 import CoreUtils        ( exprType, needsCaseBinding, bindNonRec )
53 import Literal
54 import HscTypes
55
56 import TysWiredIn
57 import PrelNames
58
59 import TcType           ( mkSigmaTy )
60 import Type
61 import TysPrim
62 import DataCon          ( DataCon, dataConWorkId )
63 import Demand
64 import Name
65 import Outputable
66 import FastString
67 import UniqSupply
68 import Unique           ( mkBuiltinUnique )
69 import BasicTypes
70 import Util             ( notNull, zipEqual )
71 import Constants
72
73 import Data.Char        ( ord )
74 import Data.Word
75
76 infixl 4 `mkCoreApp`, `mkCoreApps`
77 \end{code}
78
79 %************************************************************************
80 %*                                                                      *
81 \subsection{Basic CoreSyn construction}
82 %*                                                                      *
83 %************************************************************************
84
85 \begin{code}
86 -- | Bind a binding group over an expression, using a @let@ or @case@ as
87 -- appropriate (see "CoreSyn#let_app_invariant")
88 mkCoreLet :: CoreBind -> CoreExpr -> CoreExpr
89 mkCoreLet (NonRec bndr rhs) body        -- See Note [CoreSyn let/app invariant]
90   | needsCaseBinding (idType bndr) rhs
91   = Case rhs bndr (exprType body) [(DEFAULT,[],body)]
92 mkCoreLet bind body
93   = Let bind body
94
95 -- | Bind a list of binding groups over an expression. The leftmost binding
96 -- group becomes the outermost group in the resulting expression
97 mkCoreLets :: [CoreBind] -> CoreExpr -> CoreExpr
98 mkCoreLets binds body = foldr mkCoreLet body binds
99
100 -- | Construct an expression which represents the application of one expression
101 -- to the other
102 mkCoreApp :: CoreExpr -> CoreExpr -> CoreExpr
103 -- Check the invariant that the arg of an App is ok-for-speculation if unlifted
104 -- See CoreSyn Note [CoreSyn let/app invariant]
105 mkCoreApp fun (Type ty) = App fun (Type ty)
106 mkCoreApp fun arg       = ASSERT2( isFunTy fun_ty, ppr fun $$ ppr arg )
107                           mk_val_app fun arg arg_ty res_ty
108                       where
109                         fun_ty = exprType fun
110                         (arg_ty, res_ty) = splitFunTy fun_ty
111
112 -- | Construct an expression which represents the application of a number of
113 -- expressions to another. The leftmost expression in the list is applied first
114 mkCoreApps :: CoreExpr -> [CoreExpr] -> CoreExpr
115 -- Slightly more efficient version of (foldl mkCoreApp)
116 mkCoreApps orig_fun orig_args
117   = go orig_fun (exprType orig_fun) orig_args
118   where
119     go fun _      []               = fun
120     go fun fun_ty (Type ty : args) = go (App fun (Type ty)) (applyTy fun_ty ty) args
121     go fun fun_ty (arg     : args) = ASSERT2( isFunTy fun_ty, ppr fun_ty $$ ppr orig_fun $$ ppr orig_args )
122                                      go (mk_val_app fun arg arg_ty res_ty) res_ty args
123                                    where
124                                      (arg_ty, res_ty) = splitFunTy fun_ty
125
126 -- | Construct an expression which represents the application of a number of
127 -- expressions to that of a data constructor expression. The leftmost expression
128 -- in the list is applied first
129 mkCoreConApps :: DataCon -> [CoreExpr] -> CoreExpr
130 mkCoreConApps con args = mkCoreApps (Var (dataConWorkId con)) args
131
132 -----------
133 mk_val_app :: CoreExpr -> CoreExpr -> Type -> Type -> CoreExpr
134 mk_val_app fun arg arg_ty _        -- See Note [CoreSyn let/app invariant]
135   | not (needsCaseBinding arg_ty arg)
136   = App fun arg                -- The vastly common case
137
138 mk_val_app fun arg arg_ty res_ty
139   = Case arg arg_id res_ty [(DEFAULT,[],App fun (Var arg_id))]
140   where
141     arg_id = mkWildValBinder arg_ty    
142         -- Lots of shadowing, but it doesn't matter,
143         -- because 'fun ' should not have a free wild-id
144         --
145         -- This is Dangerous.  But this is the only place we play this 
146         -- game, mk_val_app returns an expression that does not have
147         -- have a free wild-id.  So the only thing that can go wrong
148         -- is if you take apart this case expression, and pass a 
149         -- fragmet of it as the fun part of a 'mk_val_app'.
150
151 mkWildEvBinder :: PredType -> EvVar
152 mkWildEvBinder pred@(EqPred {}) = mkWildCoVar     (mkPredTy pred)
153 mkWildEvBinder pred             = mkWildValBinder (mkPredTy pred)
154
155 -- | Make a /wildcard binder/. This is typically used when you need a binder 
156 -- that you expect to use only at a *binding* site.  Do not use it at
157 -- occurrence sites because it has a single, fixed unique, and it's very
158 -- easy to get into difficulties with shadowing.  That's why it is used so little.
159 mkWildValBinder :: Type -> Id
160 mkWildValBinder ty = mkSysLocal (fsLit "wild") (mkBuiltinUnique 1) ty
161
162 mkWildCase :: CoreExpr -> Type -> Type -> [CoreAlt] -> CoreExpr
163 -- Make a case expression whose case binder is unused
164 -- The alts should not have any occurrences of WildId
165 mkWildCase scrut scrut_ty res_ty alts 
166   = Case scrut (mkWildValBinder scrut_ty) res_ty alts
167
168 mkIfThenElse :: CoreExpr -> CoreExpr -> CoreExpr -> CoreExpr
169 mkIfThenElse guard then_expr else_expr
170 -- Not going to be refining, so okay to take the type of the "then" clause
171   = mkWildCase guard boolTy (exprType then_expr) 
172          [ (DataAlt falseDataCon, [], else_expr),       -- Increasing order of tag!
173            (DataAlt trueDataCon,  [], then_expr) ]
174 \end{code}
175
176 The functions from this point don't really do anything cleverer than
177 their counterparts in CoreSyn, but they are here for consistency
178
179 \begin{code}
180 -- | Create a lambda where the given expression has a number of variables
181 -- bound over it. The leftmost binder is that bound by the outermost
182 -- lambda in the result
183 mkCoreLams :: [CoreBndr] -> CoreExpr -> CoreExpr
184 mkCoreLams = mkLams
185 \end{code}
186
187 %************************************************************************
188 %*                                                                      *
189 \subsection{Making literals}
190 %*                                                                      *
191 %************************************************************************
192
193 \begin{code}
194 -- | Create a 'CoreExpr' which will evaluate to the given @Int@
195 mkIntExpr      :: Integer    -> CoreExpr            -- Result = I# i :: Int
196 mkIntExpr  i = mkConApp intDataCon  [mkIntLit i]
197
198 -- | Create a 'CoreExpr' which will evaluate to the given @Int@
199 mkIntExprInt   :: Int        -> CoreExpr            -- Result = I# i :: Int
200 mkIntExprInt  i = mkConApp intDataCon  [mkIntLitInt i]
201
202 -- | Create a 'CoreExpr' which will evaluate to the a @Word@ with the given value
203 mkWordExpr     :: Integer    -> CoreExpr
204 mkWordExpr w = mkConApp wordDataCon [mkWordLit w]
205
206 -- | Create a 'CoreExpr' which will evaluate to the given @Word@
207 mkWordExprWord :: Word       -> CoreExpr
208 mkWordExprWord w = mkConApp wordDataCon [mkWordLitWord w]
209
210 -- | Create a 'CoreExpr' which will evaluate to the given @Integer@
211 mkIntegerExpr  :: MonadThings m => Integer    -> m CoreExpr  -- Result :: Integer
212 mkIntegerExpr i
213   | inIntRange i        -- Small enough, so start from an Int
214     = do integer_id <- lookupId smallIntegerName
215          return (mkSmallIntegerLit integer_id i)
216
217 -- Special case for integral literals with a large magnitude:
218 -- They are transformed into an expression involving only smaller
219 -- integral literals. This improves constant folding.
220
221   | otherwise = do       -- Big, so start from a string
222       plus_id <- lookupId plusIntegerName
223       times_id <- lookupId timesIntegerName
224       integer_id <- lookupId smallIntegerName
225       let
226            lit i = mkSmallIntegerLit integer_id i
227            plus a b  = Var plus_id  `App` a `App` b
228            times a b = Var times_id `App` a `App` b
229
230            -- Transform i into (x1 + (x2 + (x3 + (...) * b) * b) * b) with abs xi <= b
231            horner :: Integer -> Integer -> CoreExpr
232            horner b i | abs q <= 1 = if r == 0 || r == i 
233                                      then lit i 
234                                      else lit r `plus` lit (i-r)
235                       | r == 0     =               horner b q `times` lit b
236                       | otherwise  = lit r `plus` (horner b q `times` lit b)
237                       where
238                         (q,r) = i `quotRem` b
239
240       return (horner tARGET_MAX_INT i)
241   where
242     mkSmallIntegerLit :: Id -> Integer -> CoreExpr
243     mkSmallIntegerLit small_integer i = mkApps (Var small_integer) [mkIntLit i]
244
245
246 -- | Create a 'CoreExpr' which will evaluate to the given @Float@
247 mkFloatExpr :: Float -> CoreExpr
248 mkFloatExpr f = mkConApp floatDataCon [mkFloatLitFloat f]
249
250 -- | Create a 'CoreExpr' which will evaluate to the given @Double@
251 mkDoubleExpr :: Double -> CoreExpr
252 mkDoubleExpr d = mkConApp doubleDataCon [mkDoubleLitDouble d]
253
254
255 -- | Create a 'CoreExpr' which will evaluate to the given @Char@
256 mkCharExpr     :: Char             -> CoreExpr      -- Result = C# c :: Int
257 mkCharExpr c = mkConApp charDataCon [mkCharLit c]
258
259 -- | Create a 'CoreExpr' which will evaluate to the given @String@
260 mkStringExpr   :: MonadThings m => String     -> m CoreExpr  -- Result :: String
261 -- | Create a 'CoreExpr' which will evaluate to a string morally equivalent to the given @FastString@
262 mkStringExprFS :: MonadThings m => FastString -> m CoreExpr  -- Result :: String
263
264 mkStringExpr str = mkStringExprFS (mkFastString str)
265
266 mkStringExprFS str
267   | nullFS str
268   = return (mkNilExpr charTy)
269
270   | lengthFS str == 1
271   = do let the_char = mkCharExpr (headFS str)
272        return (mkConsExpr charTy the_char (mkNilExpr charTy))
273
274   | all safeChar chars
275   = do unpack_id <- lookupId unpackCStringName
276        return (App (Var unpack_id) (Lit (MachStr str)))
277
278   | otherwise
279   = do unpack_id <- lookupId unpackCStringUtf8Name
280        return (App (Var unpack_id) (Lit (MachStr str)))
281
282   where
283     chars = unpackFS str
284     safeChar c = ord c >= 1 && ord c <= 0x7F
285 \end{code}
286
287 %************************************************************************
288 %*                                                                      *
289 \subsection{Tuple constructors}
290 %*                                                                      *
291 %************************************************************************
292
293 \begin{code}
294
295 -- $big_tuples
296 -- #big_tuples#
297 --
298 -- GHCs built in tuples can only go up to 'mAX_TUPLE_SIZE' in arity, but
299 -- we might concievably want to build such a massive tuple as part of the
300 -- output of a desugaring stage (notably that for list comprehensions).
301 --
302 -- We call tuples above this size \"big tuples\", and emulate them by
303 -- creating and pattern matching on >nested< tuples that are expressible
304 -- by GHC.
305 --
306 -- Nesting policy: it's better to have a 2-tuple of 10-tuples (3 objects)
307 -- than a 10-tuple of 2-tuples (11 objects), so we want the leaves of any
308 -- construction to be big.
309 --
310 -- If you just use the 'mkBigCoreTup', 'mkBigCoreVarTupTy', 'mkTupleSelector'
311 -- and 'mkTupleCase' functions to do all your work with tuples you should be
312 -- fine, and not have to worry about the arity limitation at all.
313
314 -- | Lifts a \"small\" constructor into a \"big\" constructor by recursive decompositon
315 mkChunkified :: ([a] -> a)      -- ^ \"Small\" constructor function, of maximum input arity 'mAX_TUPLE_SIZE'
316              -> [a]             -- ^ Possible \"big\" list of things to construct from
317              -> a               -- ^ Constructed thing made possible by recursive decomposition
318 mkChunkified small_tuple as = mk_big_tuple (chunkify as)
319   where
320         -- Each sub-list is short enough to fit in a tuple
321     mk_big_tuple [as] = small_tuple as
322     mk_big_tuple as_s = mk_big_tuple (chunkify (map small_tuple as_s))
323
324 chunkify :: [a] -> [[a]]
325 -- ^ Split a list into lists that are small enough to have a corresponding
326 -- tuple arity. The sub-lists of the result all have length <= 'mAX_TUPLE_SIZE'
327 -- But there may be more than 'mAX_TUPLE_SIZE' sub-lists
328 chunkify xs
329   | n_xs <= mAX_TUPLE_SIZE = [xs] 
330   | otherwise              = split xs
331   where
332     n_xs     = length xs
333     split [] = []
334     split xs = take mAX_TUPLE_SIZE xs : split (drop mAX_TUPLE_SIZE xs)
335     
336 \end{code}
337
338 Creating tuples and their types for Core expressions 
339
340 @mkBigCoreVarTup@ builds a tuple; the inverse to @mkTupleSelector@.  
341
342 * If it has only one element, it is the identity function.
343
344 * If there are more elements than a big tuple can have, it nests 
345   the tuples.  
346
347 \begin{code}
348
349 -- | Build a small tuple holding the specified variables
350 mkCoreVarTup :: [Id] -> CoreExpr
351 mkCoreVarTup ids = mkCoreTup (map Var ids)
352
353 -- | Bulid the type of a small tuple that holds the specified variables
354 mkCoreVarTupTy :: [Id] -> Type
355 mkCoreVarTupTy ids = mkBoxedTupleTy (map idType ids)
356
357 -- | Build a small tuple holding the specified expressions
358 mkCoreTup :: [CoreExpr] -> CoreExpr
359 mkCoreTup []  = Var unitDataConId
360 mkCoreTup [c] = c
361 mkCoreTup cs  = mkConApp (tupleCon Boxed (length cs))
362                          (map (Type . exprType) cs ++ cs)
363
364 -- | Build a big tuple holding the specified variables
365 mkBigCoreVarTup :: [Id] -> CoreExpr
366 mkBigCoreVarTup ids = mkBigCoreTup (map Var ids)
367
368 -- | Build the type of a big tuple that holds the specified variables
369 mkBigCoreVarTupTy :: [Id] -> Type
370 mkBigCoreVarTupTy ids = mkBigCoreTupTy (map idType ids)
371
372 -- | Build a big tuple holding the specified expressions
373 mkBigCoreTup :: [CoreExpr] -> CoreExpr
374 mkBigCoreTup = mkChunkified mkCoreTup
375
376 -- | Build the type of a big tuple that holds the specified type of thing
377 mkBigCoreTupTy :: [Type] -> Type
378 mkBigCoreTupTy = mkChunkified mkBoxedTupleTy
379 \end{code}
380
381 %************************************************************************
382 %*                                                                      *
383 \subsection{Tuple destructors}
384 %*                                                                      *
385 %************************************************************************
386
387 \begin{code}
388 -- | Builds a selector which scrutises the given
389 -- expression and extracts the one name from the list given.
390 -- If you want the no-shadowing rule to apply, the caller
391 -- is responsible for making sure that none of these names
392 -- are in scope.
393 --
394 -- If there is just one 'Id' in the tuple, then the selector is
395 -- just the identity.
396 --
397 -- If necessary, we pattern match on a \"big\" tuple.
398 mkTupleSelector :: [Id]         -- ^ The 'Id's to pattern match the tuple against
399                 -> Id           -- ^ The 'Id' to select
400                 -> Id           -- ^ A variable of the same type as the scrutinee
401                 -> CoreExpr     -- ^ Scrutinee
402                 -> CoreExpr     -- ^ Selector expression
403
404 -- mkTupleSelector [a,b,c,d] b v e
405 --          = case e of v { 
406 --                (p,q) -> case p of p {
407 --                           (a,b) -> b }}
408 -- We use 'tpl' vars for the p,q, since shadowing does not matter.
409 --
410 -- In fact, it's more convenient to generate it innermost first, getting
411 --
412 --        case (case e of v 
413 --                (p,q) -> p) of p
414 --          (a,b) -> b
415 mkTupleSelector vars the_var scrut_var scrut
416   = mk_tup_sel (chunkify vars) the_var
417   where
418     mk_tup_sel [vars] the_var = mkSmallTupleSelector vars the_var scrut_var scrut
419     mk_tup_sel vars_s the_var = mkSmallTupleSelector group the_var tpl_v $
420                                 mk_tup_sel (chunkify tpl_vs) tpl_v
421         where
422           tpl_tys = [mkBoxedTupleTy (map idType gp) | gp <- vars_s]
423           tpl_vs  = mkTemplateLocals tpl_tys
424           [(tpl_v, group)] = [(tpl,gp) | (tpl,gp) <- zipEqual "mkTupleSelector" tpl_vs vars_s,
425                                          the_var `elem` gp ]
426 \end{code}
427
428 \begin{code}
429 -- | Like 'mkTupleSelector' but for tuples that are guaranteed
430 -- never to be \"big\".
431 --
432 -- > mkSmallTupleSelector [x] x v e = [| e |]
433 -- > mkSmallTupleSelector [x,y,z] x v e = [| case e of v { (x,y,z) -> x } |]
434 mkSmallTupleSelector :: [Id]        -- The tuple args
435           -> Id         -- The selected one
436           -> Id         -- A variable of the same type as the scrutinee
437           -> CoreExpr        -- Scrutinee
438           -> CoreExpr
439 mkSmallTupleSelector [var] should_be_the_same_var _ scrut
440   = ASSERT(var == should_be_the_same_var)
441     scrut
442 mkSmallTupleSelector vars the_var scrut_var scrut
443   = ASSERT( notNull vars )
444     Case scrut scrut_var (idType the_var)
445          [(DataAlt (tupleCon Boxed (length vars)), vars, Var the_var)]
446 \end{code}
447
448 \begin{code}
449 -- | A generalization of 'mkTupleSelector', allowing the body
450 -- of the case to be an arbitrary expression.
451 --
452 -- To avoid shadowing, we use uniques to invent new variables.
453 --
454 -- If necessary we pattern match on a \"big\" tuple.
455 mkTupleCase :: UniqSupply       -- ^ For inventing names of intermediate variables
456             -> [Id]             -- ^ The tuple identifiers to pattern match on
457             -> CoreExpr         -- ^ Body of the case
458             -> Id               -- ^ A variable of the same type as the scrutinee
459             -> CoreExpr         -- ^ Scrutinee
460             -> CoreExpr
461 -- ToDo: eliminate cases where none of the variables are needed.
462 --
463 --         mkTupleCase uniqs [a,b,c,d] body v e
464 --           = case e of v { (p,q) ->
465 --             case p of p { (a,b) ->
466 --             case q of q { (c,d) ->
467 --             body }}}
468 mkTupleCase uniqs vars body scrut_var scrut
469   = mk_tuple_case uniqs (chunkify vars) body
470   where
471     -- This is the case where don't need any nesting
472     mk_tuple_case _ [vars] body
473       = mkSmallTupleCase vars body scrut_var scrut
474       
475     -- This is the case where we must make nest tuples at least once
476     mk_tuple_case us vars_s body
477       = let (us', vars', body') = foldr one_tuple_case (us, [], body) vars_s
478             in mk_tuple_case us' (chunkify vars') body'
479     
480     one_tuple_case chunk_vars (us, vs, body)
481       = let (us1, us2) = splitUniqSupply us
482             scrut_var = mkSysLocal (fsLit "ds") (uniqFromSupply us1)
483               (mkBoxedTupleTy (map idType chunk_vars))
484             body' = mkSmallTupleCase chunk_vars body scrut_var (Var scrut_var)
485         in (us2, scrut_var:vs, body')
486 \end{code}
487
488 \begin{code}
489 -- | As 'mkTupleCase', but for a tuple that is small enough to be guaranteed
490 -- not to need nesting.
491 mkSmallTupleCase
492         :: [Id]         -- ^ The tuple args
493         -> CoreExpr     -- ^ Body of the case
494         -> Id           -- ^ A variable of the same type as the scrutinee
495         -> CoreExpr     -- ^ Scrutinee
496         -> CoreExpr
497
498 mkSmallTupleCase [var] body _scrut_var scrut
499   = bindNonRec var scrut body
500 mkSmallTupleCase vars body scrut_var scrut
501 -- One branch no refinement?
502   = Case scrut scrut_var (exprType body) [(DataAlt (tupleCon Boxed (length vars)), vars, body)]
503 \end{code}
504
505 %************************************************************************
506 %*                                                                      *
507 \subsection{Common list manipulation expressions}
508 %*                                                                      *
509 %************************************************************************
510
511 Call the constructor Ids when building explicit lists, so that they
512 interact well with rules.
513
514 \begin{code}
515 -- | Makes a list @[]@ for lists of the specified type
516 mkNilExpr :: Type -> CoreExpr
517 mkNilExpr ty = mkConApp nilDataCon [Type ty]
518
519 -- | Makes a list @(:)@ for lists of the specified type
520 mkConsExpr :: Type -> CoreExpr -> CoreExpr -> CoreExpr
521 mkConsExpr ty hd tl = mkConApp consDataCon [Type ty, hd, tl]
522
523 -- | Make a list containing the given expressions, where the list has the given type
524 mkListExpr :: Type -> [CoreExpr] -> CoreExpr
525 mkListExpr ty xs = foldr (mkConsExpr ty) (mkNilExpr ty) xs
526
527 -- | Make a fully applied 'foldr' expression
528 mkFoldrExpr :: MonadThings m
529             => Type             -- ^ Element type of the list
530             -> Type             -- ^ Fold result type
531             -> CoreExpr         -- ^ "Cons" function expression for the fold
532             -> CoreExpr         -- ^ "Nil" expression for the fold
533             -> CoreExpr         -- ^ List expression being folded acress
534             -> m CoreExpr
535 mkFoldrExpr elt_ty result_ty c n list = do
536     foldr_id <- lookupId foldrName
537     return (Var foldr_id `App` Type elt_ty 
538            `App` Type result_ty
539            `App` c
540            `App` n
541            `App` list)
542
543 -- | Make a 'build' expression applied to a locally-bound worker function
544 mkBuildExpr :: (MonadThings m, MonadUnique m)
545             => Type                                     -- ^ Type of list elements to be built
546             -> ((Id, Type) -> (Id, Type) -> m CoreExpr) -- ^ Function that, given information about the 'Id's
547                                                         -- of the binders for the build worker function, returns
548                                                         -- the body of that worker
549             -> m CoreExpr
550 mkBuildExpr elt_ty mk_build_inside = do
551     [n_tyvar] <- newTyVars [alphaTyVar]
552     let n_ty = mkTyVarTy n_tyvar
553         c_ty = mkFunTys [elt_ty, n_ty] n_ty
554     [c, n] <- sequence [mkSysLocalM (fsLit "c") c_ty, mkSysLocalM (fsLit "n") n_ty]
555     
556     build_inside <- mk_build_inside (c, c_ty) (n, n_ty)
557     
558     build_id <- lookupId buildName
559     return $ Var build_id `App` Type elt_ty `App` mkLams [n_tyvar, c, n] build_inside
560   where
561     newTyVars tyvar_tmpls = do
562       uniqs <- getUniquesM
563       return (zipWith setTyVarUnique tyvar_tmpls uniqs)
564 \end{code}
565
566
567 %************************************************************************
568 %*                                                                      *
569                       Error expressions
570 %*                                                                      *
571 %************************************************************************
572
573 \begin{code}
574 mkRuntimeErrorApp 
575         :: Id           -- Should be of type (forall a. Addr# -> a)
576                         --      where Addr# points to a UTF8 encoded string
577         -> Type         -- The type to instantiate 'a'
578         -> String       -- The string to print
579         -> CoreExpr
580
581 mkRuntimeErrorApp err_id res_ty err_msg 
582   = mkApps (Var err_id) [Type res_ty, err_string]
583   where
584     err_string = Lit (mkMachString err_msg)
585
586 mkImpossibleExpr :: Type -> CoreExpr
587 mkImpossibleExpr res_ty
588   = mkRuntimeErrorApp rUNTIME_ERROR_ID res_ty "Impossible case alternative"
589 \end{code}
590
591 %************************************************************************
592 %*                                                                      *
593                      Error Ids
594 %*                                                                      *
595 %************************************************************************
596
597 GHC randomly injects these into the code.
598
599 @patError@ is just a version of @error@ for pattern-matching
600 failures.  It knows various ``codes'' which expand to longer
601 strings---this saves space!
602
603 @absentErr@ is a thing we put in for ``absent'' arguments.  They jolly
604 well shouldn't be yanked on, but if one is, then you will get a
605 friendly message from @absentErr@ (rather than a totally random
606 crash).
607
608 @parError@ is a special version of @error@ which the compiler does
609 not know to be a bottoming Id.  It is used in the @_par_@ and @_seq_@
610 templates, but we don't ever expect to generate code for it.
611
612 \begin{code}
613 errorIds :: [Id]
614 errorIds 
615   = [ eRROR_ID,   -- This one isn't used anywhere else in the compiler
616                   -- But we still need it in wiredInIds so that when GHC
617                   -- compiles a program that mentions 'error' we don't
618                   -- import its type from the interface file; we just get
619                   -- the Id defined here.  Which has an 'open-tyvar' type.
620
621       rUNTIME_ERROR_ID,
622       iRREFUT_PAT_ERROR_ID,
623       nON_EXHAUSTIVE_GUARDS_ERROR_ID,
624       nO_METHOD_BINDING_ERROR_ID,
625       pAT_ERROR_ID,
626       rEC_CON_ERROR_ID,
627       rEC_SEL_ERROR_ID,
628       aBSENT_ERROR_ID ]
629
630 recSelErrorName, runtimeErrorName, absentErrorName :: Name
631 irrefutPatErrorName, recConErrorName, patErrorName :: Name
632 nonExhaustiveGuardsErrorName, noMethodBindingErrorName :: Name
633
634 recSelErrorName     = err_nm "recSelError"     recSelErrorIdKey     rEC_SEL_ERROR_ID
635 absentErrorName     = err_nm "absentError"     absentErrorIdKey     aBSENT_ERROR_ID
636 runtimeErrorName    = err_nm "runtimeError"    runtimeErrorIdKey    rUNTIME_ERROR_ID
637 irrefutPatErrorName = err_nm "irrefutPatError" irrefutPatErrorIdKey iRREFUT_PAT_ERROR_ID
638 recConErrorName     = err_nm "recConError"     recConErrorIdKey     rEC_CON_ERROR_ID
639 patErrorName        = err_nm "patError"        patErrorIdKey        pAT_ERROR_ID
640
641 noMethodBindingErrorName     = err_nm "noMethodBindingError"
642                                   noMethodBindingErrorIdKey nO_METHOD_BINDING_ERROR_ID
643 nonExhaustiveGuardsErrorName = err_nm "nonExhaustiveGuardsError" 
644                                   nonExhaustiveGuardsErrorIdKey nON_EXHAUSTIVE_GUARDS_ERROR_ID
645
646 err_nm :: String -> Unique -> Id -> Name
647 err_nm str uniq id = mkWiredInIdName cONTROL_EXCEPTION_BASE (fsLit str) uniq id
648
649 rEC_SEL_ERROR_ID, rUNTIME_ERROR_ID, iRREFUT_PAT_ERROR_ID, rEC_CON_ERROR_ID :: Id
650 pAT_ERROR_ID, nO_METHOD_BINDING_ERROR_ID, nON_EXHAUSTIVE_GUARDS_ERROR_ID :: Id
651 rEC_SEL_ERROR_ID                = mkRuntimeErrorId recSelErrorName
652 rUNTIME_ERROR_ID                = mkRuntimeErrorId runtimeErrorName
653 iRREFUT_PAT_ERROR_ID            = mkRuntimeErrorId irrefutPatErrorName
654 rEC_CON_ERROR_ID                = mkRuntimeErrorId recConErrorName
655 pAT_ERROR_ID                    = mkRuntimeErrorId patErrorName
656 nO_METHOD_BINDING_ERROR_ID      = mkRuntimeErrorId noMethodBindingErrorName
657 nON_EXHAUSTIVE_GUARDS_ERROR_ID  = mkRuntimeErrorId nonExhaustiveGuardsErrorName
658
659 aBSENT_ERROR_ID :: Id
660 -- Not bottoming; no unfolding!  See Note [Absent error Id] in WwLib
661 aBSENT_ERROR_ID = mkVanillaGlobal absentErrorName runtimeErrorTy
662
663 mkRuntimeErrorId :: Name -> Id
664 mkRuntimeErrorId name = pc_bottoming_Id name runtimeErrorTy
665
666 runtimeErrorTy :: Type
667 -- The runtime error Ids take a UTF8-encoded string as argument
668 runtimeErrorTy = mkSigmaTy [openAlphaTyVar] [] (mkFunTy addrPrimTy openAlphaTy)
669 \end{code}
670
671 \begin{code}
672 errorName :: Name
673 errorName = mkWiredInIdName gHC_ERR (fsLit "error") errorIdKey eRROR_ID
674
675 eRROR_ID :: Id
676 eRROR_ID = pc_bottoming_Id errorName errorTy
677
678 errorTy  :: Type
679 errorTy  = mkSigmaTy [openAlphaTyVar] [] (mkFunTys [mkListTy charTy] openAlphaTy)
680     -- Notice the openAlphaTyVar.  It says that "error" can be applied
681     -- to unboxed as well as boxed types.  This is OK because it never
682     -- returns, so the return type is irrelevant.
683 \end{code}
684
685
686 %************************************************************************
687 %*                                                                      *
688 \subsection{Utilities}
689 %*                                                                      *
690 %************************************************************************
691
692 \begin{code}
693 pc_bottoming_Id :: Name -> Type -> Id
694 -- Function of arity 1, which diverges after being given one argument
695 pc_bottoming_Id name ty
696  = mkVanillaGlobalWithInfo name ty bottoming_info
697  where
698     bottoming_info = vanillaIdInfo `setStrictnessInfo` Just strict_sig
699                                    `setArityInfo`         1
700                         -- Make arity and strictness agree
701
702         -- Do *not* mark them as NoCafRefs, because they can indeed have
703         -- CAF refs.  For example, pAT_ERROR_ID calls GHC.Err.untangle,
704         -- which has some CAFs
705         -- In due course we may arrange that these error-y things are
706         -- regarded by the GC as permanently live, in which case we
707         -- can give them NoCaf info.  As it is, any function that calls
708         -- any pc_bottoming_Id will itself have CafRefs, which bloats
709         -- SRTs.
710
711     strict_sig = mkStrictSig (mkTopDmdType [evalDmd] BotRes)
712         -- These "bottom" out, no matter what their arguments
713 \end{code}
714