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