Module header tidyup, phase 1
[ghc-hetmet.git] / compiler / basicTypes / MkId.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The AQUA Project, Glasgow University, 1998
4 %
5
6 This module contains definitions for the IdInfo for things that
7 have a standard form, namely:
8
9         * data constructors
10         * record selectors
11         * method and superclass selectors
12         * primitive operations
13
14 \begin{code}
15 module MkId (
16         mkDictFunId, mkDefaultMethodId,
17         mkDictSelId, 
18
19         mkDataConIds,
20         mkRecordSelId, 
21         mkPrimOpId, mkFCallId,
22
23         mkReboxingAlt, wrapNewTypeBody, unwrapNewTypeBody,
24         mkUnpackCase, mkProductBox,
25
26         -- And some particular Ids; see below for why they are wired in
27         wiredInIds, ghcPrimIds,
28         unsafeCoerceId, realWorldPrimId, voidArgId, nullAddrId, seqId,
29         lazyId, lazyIdUnfolding, lazyIdKey, 
30
31         mkRuntimeErrorApp,
32         rEC_CON_ERROR_ID, iRREFUT_PAT_ERROR_ID, rUNTIME_ERROR_ID,
33         nON_EXHAUSTIVE_GUARDS_ERROR_ID, nO_METHOD_BINDING_ERROR_ID,
34         pAT_ERROR_ID, eRROR_ID,
35
36         unsafeCoerceName
37     ) where
38
39 #include "HsVersions.h"
40
41 import Rules
42 import TysPrim
43 import TysWiredIn
44 import PrelRules
45 import Type
46 import TcGadt
47 import HsBinds
48 import Coercion
49 import TcType
50 import CoreUtils
51 import CoreUnfold
52 import Literal
53 import TyCon
54 import Class
55 import VarSet
56 import Name
57 import OccName
58 import PrimOp
59 import ForeignCall
60 import DataCon
61 import Id
62 import Var              ( Var, TyVar)
63 import IdInfo
64 import NewDemand
65 import DmdAnal
66 import CoreSyn
67 import Unique
68 import Maybes
69 import PrelNames
70 import BasicTypes       hiding ( SuccessFlag(..) )
71 import Util
72 import Outputable
73 import FastString
74 import ListSetOps
75 \end{code}              
76
77 %************************************************************************
78 %*                                                                      *
79 \subsection{Wired in Ids}
80 %*                                                                      *
81 %************************************************************************
82
83 \begin{code}
84 wiredInIds
85   = [   -- These error-y things are wired in because we don't yet have
86         -- a way to express in an interface file that the result type variable
87         -- is 'open'; that is can be unified with an unboxed type
88         -- 
89         -- [The interface file format now carry such information, but there's
90         -- no way yet of expressing at the definition site for these 
91         -- error-reporting functions that they have an 'open' 
92         -- result type. -- sof 1/99]
93
94     eRROR_ID,   -- This one isn't used anywhere else in the compiler
95                 -- But we still need it in wiredInIds so that when GHC
96                 -- compiles a program that mentions 'error' we don't
97                 -- import its type from the interface file; we just get
98                 -- the Id defined here.  Which has an 'open-tyvar' type.
99
100     rUNTIME_ERROR_ID,
101     iRREFUT_PAT_ERROR_ID,
102     nON_EXHAUSTIVE_GUARDS_ERROR_ID,
103     nO_METHOD_BINDING_ERROR_ID,
104     pAT_ERROR_ID,
105     rEC_CON_ERROR_ID,
106
107     lazyId
108     ] ++ ghcPrimIds
109
110 -- These Ids are exported from GHC.Prim
111 ghcPrimIds
112   = [   -- These can't be defined in Haskell, but they have
113         -- perfectly reasonable unfoldings in Core
114     realWorldPrimId,
115     unsafeCoerceId,
116     nullAddrId,
117     seqId
118     ]
119 \end{code}
120
121 %************************************************************************
122 %*                                                                      *
123 \subsection{Data constructors}
124 %*                                                                      *
125 %************************************************************************
126
127 The wrapper for a constructor is an ordinary top-level binding that evaluates
128 any strict args, unboxes any args that are going to be flattened, and calls
129 the worker.
130
131 We're going to build a constructor that looks like:
132
133         data (Data a, C b) =>  T a b = T1 !a !Int b
134
135         T1 = /\ a b -> 
136              \d1::Data a, d2::C b ->
137              \p q r -> case p of { p ->
138                        case q of { q ->
139                        Con T1 [a,b] [p,q,r]}}
140
141 Notice that
142
143 * d2 is thrown away --- a context in a data decl is used to make sure
144   one *could* construct dictionaries at the site the constructor
145   is used, but the dictionary isn't actually used.
146
147 * We have to check that we can construct Data dictionaries for
148   the types a and Int.  Once we've done that we can throw d1 away too.
149
150 * We use (case p of q -> ...) to evaluate p, rather than "seq" because
151   all that matters is that the arguments are evaluated.  "seq" is 
152   very careful to preserve evaluation order, which we don't need
153   to be here.
154
155   You might think that we could simply give constructors some strictness
156   info, like PrimOps, and let CoreToStg do the let-to-case transformation.
157   But we don't do that because in the case of primops and functions strictness
158   is a *property* not a *requirement*.  In the case of constructors we need to
159   do something active to evaluate the argument.
160
161   Making an explicit case expression allows the simplifier to eliminate
162   it in the (common) case where the constructor arg is already evaluated.
163
164 [Wrappers for data instance tycons]
165 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
166 In the case of data instances, the wrapper also applies the coercion turning
167 the representation type into the family instance type to cast the result of
168 the wrapper.  For example, consider the declarations
169
170   data family Map k :: * -> *
171   data instance Map (a, b) v = MapPair (Map a (Pair b v))
172
173 The tycon to which the datacon MapPair belongs gets a unique internal name of
174 the form :R123Map, and we call it the representation tycon.  In contrast, Map
175 is the family tycon (accessible via tyConFamInst_maybe).  The wrapper and work
176 of MapPair get the types
177
178   $WMapPair :: forall a b v. Map a (Map a b v) -> Map (a, b) v
179   $wMapPair :: forall a b v. Map a (Map a b v) -> :R123Map a b v
180
181 which implies that the wrapper code will have to apply the coercion moving
182 between representation and family type.  It is accessible via
183 tyConFamilyCoercion_maybe and has kind
184
185   Co123Map a b v :: {Map (a, b) v :=: :R123Map a b v}
186
187 This coercion is conditionally applied by wrapFamInstBody.
188
189 \begin{code}
190 mkDataConIds :: Name -> Name -> DataCon -> DataConIds
191 mkDataConIds wrap_name wkr_name data_con
192   | isNewTyCon tycon
193   = DCIds Nothing nt_work_id                 -- Newtype, only has a worker
194
195   | any isMarkedStrict all_strict_marks      -- Algebraic, needs wrapper
196     || not (null eq_spec)                    -- NB: LoadIface.ifaceDeclSubBndrs
197     || isFamInstTyCon tycon                  --     depends on this test
198   = DCIds (Just alg_wrap_id) wrk_id
199
200   | otherwise                                -- Algebraic, no wrapper
201   = DCIds Nothing wrk_id
202   where
203     (univ_tvs, ex_tvs, eq_spec, 
204      theta, orig_arg_tys)          = dataConFullSig data_con
205     tycon                          = dataConTyCon data_con
206
207         ----------- Wrapper --------------
208         -- We used to include the stupid theta in the wrapper's args
209         -- but now we don't.  Instead the type checker just injects these
210         -- extra constraints where necessary.
211     wrap_tvs = (univ_tvs `minusList` map fst eq_spec) ++ ex_tvs
212     subst          = mkTopTvSubst eq_spec
213     famSubst       = ASSERT( length (tyConTyVars tycon  ) ==  
214                              length (mkTyVarTys univ_tvs)   )
215                      zipTopTvSubst (tyConTyVars tycon) (mkTyVarTys univ_tvs)
216                      -- substitution mapping the type constructor's type
217                      -- arguments to the universals of the data constructor
218                      -- (crucial when type checking interfaces)
219     dict_tys       = mkPredTys theta
220     result_ty_args = map (substTyVar subst) univ_tvs
221     result_ty      = case tyConFamInst_maybe tycon of
222                          -- ordinary constructor
223                        Nothing            -> mkTyConApp tycon result_ty_args
224                          -- family instance constructor
225                        Just (familyTyCon, 
226                              instTys)     -> 
227                          mkTyConApp familyTyCon ( substTys subst 
228                                                 . substTys famSubst 
229                                                 $ instTys)
230     wrap_ty        = mkForAllTys wrap_tvs $ mkFunTys dict_tys $
231                      mkFunTys orig_arg_tys $ result_ty
232         -- NB: watch out here if you allow user-written equality 
233         --     constraints in data constructor signatures
234
235         ----------- Worker (algebraic data types only) --------------
236         -- The *worker* for the data constructor is the function that
237         -- takes the representation arguments and builds the constructor.
238     wrk_id = mkGlobalId (DataConWorkId data_con) wkr_name
239                         (dataConRepType data_con) wkr_info
240
241     wkr_arity = dataConRepArity data_con
242     wkr_info  = noCafIdInfo
243                 `setArityInfo`          wkr_arity
244                 `setAllStrictnessInfo`  Just wkr_sig
245                 `setUnfoldingInfo`      evaldUnfolding  -- Record that it's evaluated,
246                                                         -- even if arity = 0
247
248     wkr_sig = mkStrictSig (mkTopDmdType (replicate wkr_arity topDmd) cpr_info)
249         -- Notice that we do *not* say the worker is strict
250         -- even if the data constructor is declared strict
251         --      e.g.    data T = MkT !(Int,Int)
252         -- Why?  Because the *wrapper* is strict (and its unfolding has case
253         -- expresssions that do the evals) but the *worker* itself is not.
254         -- If we pretend it is strict then when we see
255         --      case x of y -> $wMkT y
256         -- the simplifier thinks that y is "sure to be evaluated" (because
257         --  $wMkT is strict) and drops the case.  No, $wMkT is not strict.
258         --
259         -- When the simplifer sees a pattern 
260         --      case e of MkT x -> ...
261         -- it uses the dataConRepStrictness of MkT to mark x as evaluated;
262         -- but that's fine... dataConRepStrictness comes from the data con
263         -- not from the worker Id.
264
265     cpr_info | isProductTyCon tycon && 
266                isDataTyCon tycon    &&
267                wkr_arity > 0        &&
268                wkr_arity <= mAX_CPR_SIZE        = retCPR
269              | otherwise                        = TopRes
270         -- RetCPR is only true for products that are real data types;
271         -- that is, not unboxed tuples or [non-recursive] newtypes
272
273         ----------- Workers for newtypes --------------
274     nt_work_id   = mkGlobalId (DataConWrapId data_con) wkr_name wrap_ty nt_work_info
275     nt_work_info = noCafIdInfo          -- The NoCaf-ness is set by noCafIdInfo
276                   `setArityInfo` 1      -- Arity 1
277                   `setUnfoldingInfo`     newtype_unf
278     newtype_unf  = ASSERT( isVanillaDataCon data_con &&
279                            isSingleton orig_arg_tys )
280                    -- No existentials on a newtype, but it can have a context
281                    -- e.g.      newtype Eq a => T a = MkT (...)
282                    mkCompulsoryUnfolding $ 
283                    mkLams wrap_tvs $ Lam id_arg1 $ 
284                    wrapNewTypeBody tycon result_ty_args
285                        (Var id_arg1)
286
287     id_arg1 = mkTemplateLocal 1 (head orig_arg_tys)
288
289         ----------- Wrappers for algebraic data types -------------- 
290     alg_wrap_id = mkGlobalId (DataConWrapId data_con) wrap_name wrap_ty alg_wrap_info
291     alg_wrap_info = noCafIdInfo         -- The NoCaf-ness is set by noCafIdInfo
292                     `setArityInfo`         alg_arity
293                         -- It's important to specify the arity, so that partial
294                         -- applications are treated as values
295                     `setUnfoldingInfo`     alg_unf
296                     `setAllStrictnessInfo` Just wrap_sig
297
298     all_strict_marks = dataConExStricts data_con ++ dataConStrictMarks data_con
299     wrap_sig = mkStrictSig (mkTopDmdType arg_dmds cpr_info)
300     arg_dmds = map mk_dmd all_strict_marks
301     mk_dmd str | isMarkedStrict str = evalDmd
302                | otherwise          = lazyDmd
303         -- The Cpr info can be important inside INLINE rhss, where the
304         -- wrapper constructor isn't inlined.
305         -- And the argument strictness can be important too; we
306         -- may not inline a contructor when it is partially applied.
307         -- For example:
308         --      data W = C !Int !Int !Int
309         --      ...(let w = C x in ...(w p q)...)...
310         -- we want to see that w is strict in its two arguments
311
312     alg_unf = mkTopUnfolding $ Note InlineMe $
313               mkLams wrap_tvs $ 
314               mkLams dict_args $ mkLams id_args $
315               foldr mk_case con_app 
316                     (zip (dict_args ++ id_args) all_strict_marks)
317                     i3 []
318
319     con_app _ rep_ids = wrapFamInstBody tycon result_ty_args $
320                           Var wrk_id `mkTyApps`  result_ty_args
321                                      `mkVarApps` ex_tvs
322                                      `mkTyApps`  map snd eq_spec
323                                      `mkVarApps` reverse rep_ids
324
325     (dict_args,i2) = mkLocals 1  dict_tys
326     (id_args,i3)   = mkLocals i2 orig_arg_tys
327     alg_arity      = i3-1
328
329     mk_case 
330            :: (Id, StrictnessMark)      -- Arg, strictness
331            -> (Int -> [Id] -> CoreExpr) -- Body
332            -> Int                       -- Next rep arg id
333            -> [Id]                      -- Rep args so far, reversed
334            -> CoreExpr
335     mk_case (arg,strict) body i rep_args
336           = case strict of
337                 NotMarkedStrict -> body i (arg:rep_args)
338                 MarkedStrict 
339                    | isUnLiftedType (idType arg) -> body i (arg:rep_args)
340                    | otherwise ->
341                         Case (Var arg) arg result_ty [(DEFAULT,[], body i (arg:rep_args))]
342
343                 MarkedUnboxed
344                    -> unboxProduct i (Var arg) (idType arg) the_body 
345                       where
346                         the_body i con_args = body i (reverse con_args ++ rep_args)
347
348 mAX_CPR_SIZE :: Arity
349 mAX_CPR_SIZE = 10
350 -- We do not treat very big tuples as CPR-ish:
351 --      a) for a start we get into trouble because there aren't 
352 --         "enough" unboxed tuple types (a tiresome restriction, 
353 --         but hard to fix), 
354 --      b) more importantly, big unboxed tuples get returned mainly
355 --         on the stack, and are often then allocated in the heap
356 --         by the caller.  So doing CPR for them may in fact make
357 --         things worse.
358
359 mkLocals i tys = (zipWith mkTemplateLocal [i..i+n-1] tys, i+n)
360                where
361                  n = length tys
362
363 -- If the type constructor is a representation type of a data instance, wrap
364 -- the expression into a cast adjusting the expression type, which is an
365 -- instance of the representation type, to the corresponding instance of the
366 -- family instance type.
367 --
368 wrapFamInstBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
369 wrapFamInstBody tycon args result_expr
370   | Just co_con <- tyConFamilyCoercion_maybe tycon
371   = mkCoerce (mkSymCoercion (mkTyConApp co_con args)) result_expr
372   | otherwise
373   = result_expr
374 \end{code}
375
376
377 %************************************************************************
378 %*                                                                      *
379 \subsection{Record selectors}
380 %*                                                                      *
381 %************************************************************************
382
383 We're going to build a record selector unfolding that looks like this:
384
385         data T a b c = T1 { ..., op :: a, ...}
386                      | T2 { ..., op :: a, ...}
387                      | T3
388
389         sel = /\ a b c -> \ d -> case d of
390                                     T1 ... x ... -> x
391                                     T2 ... x ... -> x
392                                     other        -> error "..."
393
394 Similarly for newtypes
395
396         newtype N a = MkN { unN :: a->a }
397
398         unN :: N a -> a -> a
399         unN n = coerce (a->a) n
400         
401 We need to take a little care if the field has a polymorphic type:
402
403         data R = R { f :: forall a. a->a }
404
405 Then we want
406
407         f :: forall a. R -> a -> a
408         f = /\ a \ r = case r of
409                           R f -> f a
410
411 (not f :: R -> forall a. a->a, which gives the type inference mechanism 
412 problems at call sites)
413
414 Similarly for (recursive) newtypes
415
416         newtype N = MkN { unN :: forall a. a->a }
417
418         unN :: forall b. N -> b -> b
419         unN = /\b -> \n:N -> (coerce (forall a. a->a) n)
420
421
422 Note [Naughty record selectors]
423 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
424 A "naughty" field is one for which we can't define a record 
425 selector, because an existential type variable would escape.  For example:
426         data T = forall a. MkT { x,y::a }
427 We obviously can't define       
428         x (MkT v _) = v
429 Nevertheless we *do* put a RecordSelId into the type environment
430 so that if the user tries to use 'x' as a selector we can bleat
431 helpfully, rather than saying unhelpfully that 'x' is not in scope.
432 Hence the sel_naughty flag, to identify record selectors that don't really exist.
433
434 In general, a field is naughty if its type mentions a type variable that
435 isn't in the result type of the constructor.
436
437 Note [GADT record selectors]
438 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
439 For GADTs, we require that all constructors with a common field 'f' have the same
440 result type (modulo alpha conversion).  [Checked in TcTyClsDecls.checkValidTyCon]
441 E.g. 
442         data T where
443           T1 { f :: a } :: T [a]
444           T2 { f :: a, y :: b  } :: T [a]
445 and now the selector takes that type as its argument:
446         f :: forall a. T [a] -> a
447         f t = case t of
448                 T1 { f = v } -> v
449                 T2 { f = v } -> v
450 Note the forall'd tyvars of the selector are just the free tyvars
451 of the result type; there may be other tyvars in the constructor's
452 type (e.g. 'b' in T2).
453
454 \begin{code}
455
456 -- Steps for handling "naughty" vs "non-naughty" selectors:
457 --  1. Determine naughtiness by comparing field type vs result type
458 --  2. Install naughty ones with selector_ty of type _|_ and fill in mzero for info
459 --  3. If it's not naughty, do the normal plan.
460
461 mkRecordSelId :: TyCon -> FieldLabel -> Id
462 mkRecordSelId tycon field_label
463         -- Assumes that all fields with the same field label have the same type
464   | is_naughty = naughty_id
465   | otherwise  = sel_id
466   where
467     is_naughty = not (tyVarsOfType field_ty `subVarSet` res_tv_set)
468     sel_id_details = RecordSelId tycon field_label is_naughty
469
470     -- Escapist case here for naughty construcotrs
471     -- We give it no IdInfo, and a type of forall a.a (never looked at)
472     naughty_id = mkGlobalId sel_id_details field_label forall_a_a noCafIdInfo
473     forall_a_a = mkForAllTy alphaTyVar (mkTyVarTy alphaTyVar)
474
475     -- Normal case starts here
476     sel_id = mkGlobalId sel_id_details field_label selector_ty info
477     data_cons         = tyConDataCons tycon     
478     data_cons_w_field = filter has_field data_cons      -- Can't be empty!
479     has_field con     = field_label `elem` dataConFieldLabels con
480
481     con1        = head data_cons_w_field
482     res_tys     = dataConResTys con1
483     res_tv_set  = tyVarsOfTypes res_tys
484     res_tvs     = varSetElems res_tv_set
485     data_ty     = mkTyConApp tycon res_tys
486     field_ty    = dataConFieldType con1 field_label
487     
488         -- *Very* tiresomely, the selectors are (unnecessarily!) overloaded over
489         -- just the dictionaries in the types of the constructors that contain
490         -- the relevant field.  [The Report says that pattern matching on a
491         -- constructor gives the same constraints as applying it.]  Urgh.  
492         --
493         -- However, not all data cons have all constraints (because of
494         -- BuildTyCl.mkDataConStupidTheta).  So we need to find all the data cons 
495         -- involved in the pattern match and take the union of their constraints.
496     stupid_dict_tys = mkPredTys (dataConsStupidTheta data_cons_w_field)
497     n_stupid_dicts  = length stupid_dict_tys
498
499     (field_tyvars,pre_field_theta,field_tau) = tcSplitSigmaTy field_ty
500   
501     field_theta  = filter (not . isEqPred) pre_field_theta
502     field_dict_tys                       = mkPredTys field_theta
503     n_field_dict_tys                     = length field_dict_tys
504         -- If the field has a universally quantified type we have to 
505         -- be a bit careful.  Suppose we have
506         --      data R = R { op :: forall a. Foo a => a -> a }
507         -- Then we can't give op the type
508         --      op :: R -> forall a. Foo a => a -> a
509         -- because the typechecker doesn't understand foralls to the
510         -- right of an arrow.  The "right" type to give it is
511         --      op :: forall a. Foo a => R -> a -> a
512         -- But then we must generate the right unfolding too:
513         --      op = /\a -> \dfoo -> \ r ->
514         --           case r of
515         --              R op -> op a dfoo
516         -- Note that this is exactly the type we'd infer from a user defn
517         --      op (R op) = op
518
519     selector_ty :: Type
520     selector_ty  = mkForAllTys res_tvs $ mkForAllTys field_tyvars $
521                    mkFunTys stupid_dict_tys  $  mkFunTys field_dict_tys $
522                    mkFunTy data_ty field_tau
523       
524     arity = 1 + n_stupid_dicts + n_field_dict_tys
525
526     (strict_sig, rhs_w_str) = dmdAnalTopRhs sel_rhs
527         -- Use the demand analyser to work out strictness.
528         -- With all this unpackery it's not easy!
529
530     info = noCafIdInfo
531            `setCafInfo`           caf_info
532            `setArityInfo`         arity
533            `setUnfoldingInfo`     mkTopUnfolding rhs_w_str
534            `setAllStrictnessInfo` Just strict_sig
535
536         -- Allocate Ids.  We do it a funny way round because field_dict_tys is
537         -- almost always empty.  Also note that we use max_dict_tys
538         -- rather than n_dict_tys, because the latter gives an infinite loop:
539         -- n_dict tys depends on the_alts, which depens on arg_ids, which depends
540         -- on arity, which depends on n_dict tys.  Sigh!  Mega sigh!
541     stupid_dict_ids  = mkTemplateLocalsNum 1 stupid_dict_tys
542     max_stupid_dicts = length (tyConStupidTheta tycon)
543     field_dict_base  = max_stupid_dicts + 1
544     field_dict_ids   = mkTemplateLocalsNum field_dict_base field_dict_tys
545     dict_id_base     = field_dict_base + n_field_dict_tys
546     data_id          = mkTemplateLocal dict_id_base data_ty
547     arg_base         = dict_id_base + 1
548
549     the_alts :: [CoreAlt]
550     the_alts   = map mk_alt data_cons_w_field   -- Already sorted by data-con
551     no_default = length data_cons == length data_cons_w_field   -- No default needed
552
553     default_alt | no_default = []
554                 | otherwise  = [(DEFAULT, [], error_expr)]
555
556         -- The default branch may have CAF refs, because it calls recSelError etc.
557     caf_info    | no_default = NoCafRefs
558                 | otherwise  = MayHaveCafRefs
559
560     sel_rhs = mkLams res_tvs $ mkLams field_tyvars $ 
561               mkLams stupid_dict_ids $ mkLams field_dict_ids $
562               Lam data_id     $ mk_result sel_body
563
564         -- NB: A newtype always has a vanilla DataCon; no existentials etc
565         --     res_tys will simply be the dataConUnivTyVars
566     sel_body | isNewTyCon tycon = unwrapNewTypeBody tycon res_tys (Var data_id)
567              | otherwise        = Case (Var data_id) data_id field_ty (default_alt ++ the_alts)
568
569     mk_result poly_result = mkVarApps (mkVarApps poly_result field_tyvars) field_dict_ids
570         -- We pull the field lambdas to the top, so we need to 
571         -- apply them in the body.  For example:
572         --      data T = MkT { foo :: forall a. a->a }
573         --
574         --      foo :: forall a. T -> a -> a
575         --      foo = /\a. \t:T. case t of { MkT f -> f a }
576
577     mk_alt data_con 
578       =   ASSERT2( res_ty `tcEqType` field_ty, ppr data_con $$ ppr res_ty $$ ppr field_ty )
579           mkReboxingAlt rebox_uniqs data_con (ex_tvs ++ co_tvs ++ arg_vs) rhs
580       where
581            -- get pattern binders with types appropriately instantiated
582         arg_uniqs = map mkBuiltinUnique [arg_base..]
583         (ex_tvs, co_tvs, arg_vs) = dataConOrigInstPat arg_uniqs data_con res_tys
584
585         rebox_base  = arg_base + length ex_tvs + length co_tvs + length arg_vs
586         rebox_uniqs = map mkBuiltinUnique [rebox_base..]
587
588         -- data T :: *->* where T1 { fld :: Maybe b } -> T [b]
589         --      Hence T1 :: forall a b. (a=[b]) => b -> T a
590         -- fld :: forall b. T [b] -> Maybe b
591         -- fld = /\b.\(t:T[b]). case t of 
592         --              T1 b' (c : [b]=[b']) (x:Maybe b') 
593         --                      -> x `cast` Maybe (sym (right c))
594
595         Succeeded refinement = gadtRefine emptyRefinement ex_tvs co_tvs
596         (co_fn, res_ty) = refineType refinement (idType the_arg_id)
597                 -- Generate the refinement for b'=b, 
598                 -- and apply to (Maybe b'), to get (Maybe b)
599
600         rhs = case co_fn of
601                 WpCo co -> Cast (Var the_arg_id) co
602                 id_co       -> ASSERT(isIdHsWrapper id_co) Var the_arg_id
603
604         field_vs    = filter (not . isPredTy . idType) arg_vs 
605         the_arg_id  = assoc "mkRecordSelId:mk_alt" (field_lbls `zip` field_vs) field_label
606         field_lbls  = dataConFieldLabels data_con
607
608     error_expr = mkRuntimeErrorApp rEC_SEL_ERROR_ID field_ty full_msg
609     full_msg   = showSDoc (sep [text "No match in record selector", ppr sel_id])
610
611 -- unbox a product type...
612 -- we will recurse into newtypes, casting along the way, and unbox at the
613 -- first product data constructor we find. e.g.
614 --  
615 --   data PairInt = PairInt Int Int
616 --   newtype S = MkS PairInt
617 --   newtype T = MkT S
618 --
619 -- If we have e = MkT (MkS (PairInt 0 1)) and some body expecting a list of
620 -- ids, we get (modulo int passing)
621 --
622 --   case (e `cast` CoT) `cast` CoS of
623 --     PairInt a b -> body [a,b]
624 --
625 -- The Ints passed around are just for creating fresh locals
626 unboxProduct :: Int -> CoreExpr -> Type -> (Int -> [Id] -> CoreExpr) -> CoreExpr
627 unboxProduct i arg arg_ty body
628   = result
629   where 
630     result = mkUnpackCase the_id arg con_args boxing_con rhs
631     (_tycon, _tycon_args, boxing_con, tys) = deepSplitProductType "unboxProduct" arg_ty
632     ([the_id], i') = mkLocals i [arg_ty]
633     (con_args, i'') = mkLocals i' tys
634     rhs = body i'' con_args
635
636 mkUnpackCase ::  Id -> CoreExpr -> [Id] -> DataCon -> CoreExpr -> CoreExpr
637 -- (mkUnpackCase x e args Con body)
638 --      returns
639 -- case (e `cast` ...) of bndr { Con args -> body }
640 -- 
641 -- the type of the bndr passed in is irrelevent
642 mkUnpackCase bndr arg unpk_args boxing_con body
643   = Case cast_arg (setIdType bndr bndr_ty) (exprType body) [(DataAlt boxing_con, unpk_args, body)]
644   where
645   (cast_arg, bndr_ty) = go (idType bndr) arg
646   go ty arg 
647     | (tycon, tycon_args, _, _)  <- splitProductType "mkUnpackCase" ty
648     , isNewTyCon tycon && not (isRecursiveTyCon tycon)
649     = go (newTyConInstRhs tycon tycon_args) 
650          (unwrapNewTypeBody tycon tycon_args arg)
651     | otherwise = (arg, ty)
652
653 -- ...and the dual
654 reboxProduct :: [Unique]     -- uniques to create new local binders
655              -> Type         -- type of product to box
656              -> ([Unique],   -- remaining uniques
657                  CoreExpr,   -- boxed product
658                  [Id])       -- Ids being boxed into product
659 reboxProduct us ty
660   = let 
661         (_tycon, _tycon_args, _pack_con, con_arg_tys) = deepSplitProductType "reboxProduct" ty
662  
663         us' = dropList con_arg_tys us
664
665         arg_ids  = zipWith (mkSysLocal FSLIT("rb")) us con_arg_tys
666
667         bind_rhs = mkProductBox arg_ids ty
668
669     in
670       (us', bind_rhs, arg_ids)
671
672 mkProductBox :: [Id] -> Type -> CoreExpr
673 mkProductBox arg_ids ty 
674   = result_expr
675   where 
676     (tycon, tycon_args, pack_con, _con_arg_tys) = splitProductType "mkProductBox" ty
677
678     result_expr
679       | isNewTyCon tycon && not (isRecursiveTyCon tycon) 
680       = wrap (mkProductBox arg_ids (newTyConInstRhs tycon tycon_args))
681       | otherwise = mkConApp pack_con (map Type tycon_args ++ map Var arg_ids)
682
683     wrap expr = wrapNewTypeBody tycon tycon_args expr
684
685
686 -- (mkReboxingAlt us con xs rhs) basically constructs the case
687 -- alternative  (con, xs, rhs)
688 -- but it does the reboxing necessary to construct the *source* 
689 -- arguments, xs, from the representation arguments ys.
690 -- For example:
691 --      data T = MkT !(Int,Int) Bool
692 --
693 -- mkReboxingAlt MkT [x,b] r 
694 --      = (DataAlt MkT, [y::Int,z::Int,b], let x = (y,z) in r)
695 --
696 -- mkDataAlt should really be in DataCon, but it can't because
697 -- it manipulates CoreSyn.
698
699 mkReboxingAlt
700   :: [Unique]           -- Uniques for the new Ids
701   -> DataCon
702   -> [Var]              -- Source-level args, including existential dicts
703   -> CoreExpr           -- RHS
704   -> CoreAlt
705
706 mkReboxingAlt us con args rhs
707   | not (any isMarkedUnboxed stricts)
708   = (DataAlt con, args, rhs)
709
710   | otherwise
711   = let
712         (binds, args') = go args stricts us
713     in
714     (DataAlt con, args', mkLets binds rhs)
715
716   where
717     stricts = dataConExStricts con ++ dataConStrictMarks con
718
719     go [] _stricts _us = ([], [])
720
721         -- Type variable case
722     go (arg:args) stricts us 
723       | isTyVar arg
724       = let (binds, args') = go args stricts us
725         in  (binds, arg:args')
726
727         -- Term variable case
728     go (arg:args) (str:stricts) us
729       | isMarkedUnboxed str
730       = 
731         let (binds, unpacked_args')        = go args stricts us'
732             (us', bind_rhs, unpacked_args) = reboxProduct us (idType arg)
733         in
734             (NonRec arg bind_rhs : binds, unpacked_args ++ unpacked_args')
735       | otherwise
736       = let (binds, args') = go args stricts us
737         in  (binds, arg:args')
738 \end{code}
739
740
741 %************************************************************************
742 %*                                                                      *
743 \subsection{Dictionary selectors}
744 %*                                                                      *
745 %************************************************************************
746
747 Selecting a field for a dictionary.  If there is just one field, then
748 there's nothing to do.  
749
750 Dictionary selectors may get nested forall-types.  Thus:
751
752         class Foo a where
753           op :: forall b. Ord b => a -> b -> b
754
755 Then the top-level type for op is
756
757         op :: forall a. Foo a => 
758               forall b. Ord b => 
759               a -> b -> b
760
761 This is unlike ordinary record selectors, which have all the for-alls
762 at the outside.  When dealing with classes it's very convenient to
763 recover the original type signature from the class op selector.
764
765 \begin{code}
766 mkDictSelId :: Name -> Class -> Id
767 mkDictSelId name clas
768   = mkGlobalId (ClassOpId clas) name sel_ty info
769   where
770     sel_ty = mkForAllTys tyvars (mkFunTy (idType dict_id) (idType the_arg_id))
771         -- We can't just say (exprType rhs), because that would give a type
772         --      C a -> C a
773         -- for a single-op class (after all, the selector is the identity)
774         -- But it's type must expose the representation of the dictionary
775         -- to gat (say)         C a -> (a -> a)
776
777     info = noCafIdInfo
778                 `setArityInfo`          1
779                 `setUnfoldingInfo`      mkTopUnfolding rhs
780                 `setAllStrictnessInfo`  Just strict_sig
781
782         -- We no longer use 'must-inline' on record selectors.  They'll
783         -- inline like crazy if they scrutinise a constructor
784
785         -- The strictness signature is of the form U(AAAVAAAA) -> T
786         -- where the V depends on which item we are selecting
787         -- It's worth giving one, so that absence info etc is generated
788         -- even if the selector isn't inlined
789     strict_sig = mkStrictSig (mkTopDmdType [arg_dmd] TopRes)
790     arg_dmd | isNewTyCon tycon = evalDmd
791             | otherwise        = Eval (Prod [ if the_arg_id == id then evalDmd else Abs
792                                             | id <- arg_ids ])
793
794     tycon      = classTyCon clas
795     [data_con] = tyConDataCons tycon
796     tyvars     = dataConUnivTyVars data_con
797     arg_tys    = ASSERT( isVanillaDataCon data_con ) dataConRepArgTys data_con
798     the_arg_id = assoc "MkId.mkDictSelId" (map idName (classSelIds clas) `zip` arg_ids) name
799
800     pred              = mkClassPred clas (mkTyVarTys tyvars)
801     (dict_id:arg_ids) = mkTemplateLocals (mkPredTy pred : arg_tys)
802
803     rhs = mkLams tyvars (Lam dict_id rhs_body)
804     rhs_body | isNewTyCon tycon = unwrapNewTypeBody tycon (map mkTyVarTy tyvars) (Var dict_id)
805              | otherwise        = Case (Var dict_id) dict_id (idType the_arg_id)
806                                        [(DataAlt data_con, arg_ids, Var the_arg_id)]
807
808 wrapNewTypeBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
809 -- The wrapper for the data constructor for a newtype looks like this:
810 --      newtype T a = MkT (a,Int)
811 --      MkT :: forall a. (a,Int) -> T a
812 --      MkT = /\a. \(x:(a,Int)). x `cast` sym (CoT a)
813 -- where CoT is the coercion TyCon assoicated with the newtype
814 --
815 -- The call (wrapNewTypeBody T [a] e) returns the
816 -- body of the wrapper, namely
817 --      e `cast` (CoT [a])
818 --
819 -- If a coercion constructor is prodivided in the newtype, then we use
820 -- it, otherwise the wrap/unwrap are both no-ops 
821 --
822 -- If the we are dealing with a newtype instance, we have a second coercion
823 -- identifying the family instance with the constructor of the newtype
824 -- instance.  This coercion is applied in any case (ie, composed with the
825 -- coercion constructor of the newtype or applied by itself).
826 --
827 wrapNewTypeBody tycon args result_expr
828   = wrapFamInstBody tycon args inner
829   where
830     inner
831       | Just co_con <- newTyConCo_maybe tycon
832       = mkCoerce (mkSymCoercion (mkTyConApp co_con args)) result_expr
833       | otherwise
834       = result_expr
835
836 -- When unwrapping, we do *not* apply any family coercion, because this will
837 -- be done via a CoPat by the type checker.  We have to do it this way as
838 -- computing the right type arguments for the coercion requires more than just
839 -- a spliting operation (cf, TcPat.tcConPat).
840 --
841 unwrapNewTypeBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
842 unwrapNewTypeBody tycon args result_expr
843   | Just co_con <- newTyConCo_maybe tycon
844   = mkCoerce (mkTyConApp co_con args) result_expr
845   | otherwise
846   = result_expr
847
848
849 \end{code}
850
851
852 %************************************************************************
853 %*                                                                      *
854 \subsection{Primitive operations
855 %*                                                                      *
856 %************************************************************************
857
858 \begin{code}
859 mkPrimOpId :: PrimOp -> Id
860 mkPrimOpId prim_op 
861   = id
862   where
863     (tyvars,arg_tys,res_ty, arity, strict_sig) = primOpSig prim_op
864     ty   = mkForAllTys tyvars (mkFunTys arg_tys res_ty)
865     name = mkWiredInName gHC_PRIM (primOpOcc prim_op) 
866                          (mkPrimOpIdUnique (primOpTag prim_op))
867                          (AnId id) UserSyntax
868     id   = mkGlobalId (PrimOpId prim_op) name ty info
869                 
870     info = noCafIdInfo
871            `setSpecInfo`          mkSpecInfo (primOpRules prim_op name)
872            `setArityInfo`         arity
873            `setAllStrictnessInfo` Just strict_sig
874
875 -- For each ccall we manufacture a separate CCallOpId, giving it
876 -- a fresh unique, a type that is correct for this particular ccall,
877 -- and a CCall structure that gives the correct details about calling
878 -- convention etc.  
879 --
880 -- The *name* of this Id is a local name whose OccName gives the full
881 -- details of the ccall, type and all.  This means that the interface 
882 -- file reader can reconstruct a suitable Id
883
884 mkFCallId :: Unique -> ForeignCall -> Type -> Id
885 mkFCallId uniq fcall ty
886   = ASSERT( isEmptyVarSet (tyVarsOfType ty) )
887         -- A CCallOpId should have no free type variables; 
888         -- when doing substitutions won't substitute over it
889     mkGlobalId (FCallId fcall) name ty info
890   where
891     occ_str = showSDoc (braces (ppr fcall <+> ppr ty))
892         -- The "occurrence name" of a ccall is the full info about the
893         -- ccall; it is encoded, but may have embedded spaces etc!
894
895     name = mkFCallName uniq occ_str
896
897     info = noCafIdInfo
898            `setArityInfo`               arity
899            `setAllStrictnessInfo`       Just strict_sig
900
901     (_, tau)     = tcSplitForAllTys ty
902     (arg_tys, _) = tcSplitFunTys tau
903     arity        = length arg_tys
904     strict_sig   = mkStrictSig (mkTopDmdType (replicate arity evalDmd) TopRes)
905 \end{code}
906
907
908 %************************************************************************
909 %*                                                                      *
910 \subsection{DictFuns and default methods}
911 %*                                                                      *
912 %************************************************************************
913
914 Important notes about dict funs and default methods
915 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
916 Dict funs and default methods are *not* ImplicitIds.  Their definition
917 involves user-written code, so we can't figure out their strictness etc
918 based on fixed info, as we can for constructors and record selectors (say).
919
920 We build them as LocalIds, but with External Names.  This ensures that
921 they are taken to account by free-variable finding and dependency
922 analysis (e.g. CoreFVs.exprFreeVars).
923
924 Why shouldn't they be bound as GlobalIds?  Because, in particular, if
925 they are globals, the specialiser floats dict uses above their defns,
926 which prevents good simplifications happening.  Also the strictness
927 analyser treats a occurrence of a GlobalId as imported and assumes it
928 contains strictness in its IdInfo, which isn't true if the thing is
929 bound in the same module as the occurrence.
930
931 It's OK for dfuns to be LocalIds, because we form the instance-env to
932 pass on to the next module (md_insts) in CoreTidy, afer tidying
933 and globalising the top-level Ids.
934
935 BUT make sure they are *exported* LocalIds (mkExportedLocalId) so 
936 that they aren't discarded by the occurrence analyser.
937
938 \begin{code}
939 mkDefaultMethodId dm_name ty = mkExportedLocalId dm_name ty
940
941 mkDictFunId :: Name             -- Name to use for the dict fun;
942             -> [TyVar]
943             -> ThetaType
944             -> Class 
945             -> [Type]
946             -> Id
947
948 mkDictFunId dfun_name inst_tyvars dfun_theta clas inst_tys
949   = mkExportedLocalId dfun_name dfun_ty
950   where
951     dfun_ty = mkSigmaTy inst_tyvars dfun_theta (mkDictTy clas inst_tys)
952
953 {-  1 dec 99: disable the Mark Jones optimisation for the sake
954     of compatibility with Hugs.
955     See `types/InstEnv' for a discussion related to this.
956
957     (class_tyvars, sc_theta, _, _) = classBigSig clas
958     not_const (clas, tys) = not (isEmptyVarSet (tyVarsOfTypes tys))
959     sc_theta' = substClasses (zipTopTvSubst class_tyvars inst_tys) sc_theta
960     dfun_theta = case inst_decl_theta of
961                    []    -> []  -- If inst_decl_theta is empty, then we don't
962                                 -- want to have any dict arguments, so that we can
963                                 -- expose the constant methods.
964
965                    other -> nub (inst_decl_theta ++ filter not_const sc_theta')
966                                 -- Otherwise we pass the superclass dictionaries to
967                                 -- the dictionary function; the Mark Jones optimisation.
968                                 --
969                                 -- NOTE the "nub".  I got caught by this one:
970                                 --   class Monad m => MonadT t m where ...
971                                 --   instance Monad m => MonadT (EnvT env) m where ...
972                                 -- Here, the inst_decl_theta has (Monad m); but so
973                                 -- does the sc_theta'!
974                                 --
975                                 -- NOTE the "not_const".  I got caught by this one too:
976                                 --   class Foo a => Baz a b where ...
977                                 --   instance Wob b => Baz T b where..
978                                 -- Now sc_theta' has Foo T
979 -}
980 \end{code}
981
982
983 %************************************************************************
984 %*                                                                      *
985 \subsection{Un-definable}
986 %*                                                                      *
987 %************************************************************************
988
989 These Ids can't be defined in Haskell.  They could be defined in
990 unfoldings in the wired-in GHC.Prim interface file, but we'd have to
991 ensure that they were definitely, definitely inlined, because there is
992 no curried identifier for them.  That's what mkCompulsoryUnfolding
993 does.  If we had a way to get a compulsory unfolding from an interface
994 file, we could do that, but we don't right now.
995
996 unsafeCoerce# isn't so much a PrimOp as a phantom identifier, that
997 just gets expanded into a type coercion wherever it occurs.  Hence we
998 add it as a built-in Id with an unfolding here.
999
1000 The type variables we use here are "open" type variables: this means
1001 they can unify with both unlifted and lifted types.  Hence we provide
1002 another gun with which to shoot yourself in the foot.
1003
1004 \begin{code}
1005 mkWiredInIdName mod fs uniq id
1006  = mkWiredInName mod (mkOccNameFS varName fs) uniq (AnId id) UserSyntax
1007
1008 unsafeCoerceName = mkWiredInIdName gHC_PRIM FSLIT("unsafeCoerce#") unsafeCoerceIdKey  unsafeCoerceId
1009 nullAddrName     = mkWiredInIdName gHC_PRIM FSLIT("nullAddr#")     nullAddrIdKey      nullAddrId
1010 seqName          = mkWiredInIdName gHC_PRIM FSLIT("seq")           seqIdKey           seqId
1011 realWorldName    = mkWiredInIdName gHC_PRIM FSLIT("realWorld#")    realWorldPrimIdKey realWorldPrimId
1012 lazyIdName       = mkWiredInIdName gHC_BASE FSLIT("lazy")         lazyIdKey           lazyId
1013
1014 errorName                = mkWiredInIdName gHC_ERR FSLIT("error")            errorIdKey eRROR_ID
1015 recSelErrorName          = mkWiredInIdName gHC_ERR FSLIT("recSelError")     recSelErrorIdKey rEC_SEL_ERROR_ID
1016 runtimeErrorName         = mkWiredInIdName gHC_ERR FSLIT("runtimeError")    runtimeErrorIdKey rUNTIME_ERROR_ID
1017 irrefutPatErrorName      = mkWiredInIdName gHC_ERR FSLIT("irrefutPatError") irrefutPatErrorIdKey iRREFUT_PAT_ERROR_ID
1018 recConErrorName          = mkWiredInIdName gHC_ERR FSLIT("recConError")     recConErrorIdKey rEC_CON_ERROR_ID
1019 patErrorName             = mkWiredInIdName gHC_ERR FSLIT("patError")         patErrorIdKey pAT_ERROR_ID
1020 noMethodBindingErrorName = mkWiredInIdName gHC_ERR FSLIT("noMethodBindingError")
1021                                            noMethodBindingErrorIdKey nO_METHOD_BINDING_ERROR_ID
1022 nonExhaustiveGuardsErrorName 
1023   = mkWiredInIdName gHC_ERR FSLIT("nonExhaustiveGuardsError") 
1024                     nonExhaustiveGuardsErrorIdKey nON_EXHAUSTIVE_GUARDS_ERROR_ID
1025 \end{code}
1026
1027 \begin{code}
1028 -- unsafeCoerce# :: forall a b. a -> b
1029 unsafeCoerceId
1030   = pcMiscPrelId unsafeCoerceName ty info
1031   where
1032     info = noCafIdInfo `setUnfoldingInfo` mkCompulsoryUnfolding rhs
1033            
1034
1035     ty  = mkForAllTys [openAlphaTyVar,openBetaTyVar]
1036                       (mkFunTy openAlphaTy openBetaTy)
1037     [x] = mkTemplateLocals [openAlphaTy]
1038     rhs = mkLams [openAlphaTyVar,openBetaTyVar,x] $
1039 --       Note (Coerce openBetaTy openAlphaTy) (Var x)
1040          Cast (Var x) (mkUnsafeCoercion openAlphaTy openBetaTy)
1041
1042 -- nullAddr# :: Addr#
1043 -- The reason is is here is because we don't provide 
1044 -- a way to write this literal in Haskell.
1045 nullAddrId 
1046   = pcMiscPrelId nullAddrName addrPrimTy info
1047   where
1048     info = noCafIdInfo `setUnfoldingInfo` 
1049            mkCompulsoryUnfolding (Lit nullAddrLit)
1050
1051 seqId
1052   = pcMiscPrelId seqName ty info
1053   where
1054     info = noCafIdInfo `setUnfoldingInfo` mkCompulsoryUnfolding rhs
1055            
1056
1057     ty  = mkForAllTys [alphaTyVar,openBetaTyVar]
1058                       (mkFunTy alphaTy (mkFunTy openBetaTy openBetaTy))
1059     [x,y] = mkTemplateLocals [alphaTy, openBetaTy]
1060     rhs = mkLams [alphaTyVar,openBetaTyVar,x,y] (Case (Var x) x openBetaTy [(DEFAULT, [], Var y)])
1061
1062 -- lazy :: forall a?. a? -> a?   (i.e. works for unboxed types too)
1063 -- Used to lazify pseq:         pseq a b = a `seq` lazy b
1064 -- 
1065 -- Also, no strictness: by being a built-in Id, all the info about lazyId comes from here,
1066 -- not from GHC.Base.hi.   This is important, because the strictness
1067 -- analyser will spot it as strict!
1068 --
1069 -- Also no unfolding in lazyId: it gets "inlined" by a HACK in the worker/wrapper pass
1070 --      (see WorkWrap.wwExpr)   
1071 -- We could use inline phases to do this, but that would be vulnerable to changes in 
1072 -- phase numbering....we must inline precisely after strictness analysis.
1073 lazyId
1074   = pcMiscPrelId lazyIdName ty info
1075   where
1076     info = noCafIdInfo
1077     ty  = mkForAllTys [alphaTyVar] (mkFunTy alphaTy alphaTy)
1078
1079 lazyIdUnfolding :: CoreExpr     -- Used to expand 'lazyId' after strictness anal
1080 lazyIdUnfolding = mkLams [openAlphaTyVar,x] (Var x)
1081                 where
1082                   [x] = mkTemplateLocals [openAlphaTy]
1083 \end{code}
1084
1085 @realWorld#@ used to be a magic literal, \tr{void#}.  If things get
1086 nasty as-is, change it back to a literal (@Literal@).
1087
1088 voidArgId is a Local Id used simply as an argument in functions
1089 where we just want an arg to avoid having a thunk of unlifted type.
1090 E.g.
1091         x = \ void :: State# RealWorld -> (# p, q #)
1092
1093 This comes up in strictness analysis
1094
1095 \begin{code}
1096 realWorldPrimId -- :: State# RealWorld
1097   = pcMiscPrelId realWorldName realWorldStatePrimTy
1098                  (noCafIdInfo `setUnfoldingInfo` evaldUnfolding)
1099         -- The evaldUnfolding makes it look that realWorld# is evaluated
1100         -- which in turn makes Simplify.interestingArg return True,
1101         -- which in turn makes INLINE things applied to realWorld# likely
1102         -- to be inlined
1103
1104 voidArgId       -- :: State# RealWorld
1105   = mkSysLocal FSLIT("void") voidArgIdKey realWorldStatePrimTy
1106 \end{code}
1107
1108
1109 %************************************************************************
1110 %*                                                                      *
1111 \subsection[PrelVals-error-related]{@error@ and friends; @trace@}
1112 %*                                                                      *
1113 %************************************************************************
1114
1115 GHC randomly injects these into the code.
1116
1117 @patError@ is just a version of @error@ for pattern-matching
1118 failures.  It knows various ``codes'' which expand to longer
1119 strings---this saves space!
1120
1121 @absentErr@ is a thing we put in for ``absent'' arguments.  They jolly
1122 well shouldn't be yanked on, but if one is, then you will get a
1123 friendly message from @absentErr@ (rather than a totally random
1124 crash).
1125
1126 @parError@ is a special version of @error@ which the compiler does
1127 not know to be a bottoming Id.  It is used in the @_par_@ and @_seq_@
1128 templates, but we don't ever expect to generate code for it.
1129
1130 \begin{code}
1131 mkRuntimeErrorApp 
1132         :: Id           -- Should be of type (forall a. Addr# -> a)
1133                         --      where Addr# points to a UTF8 encoded string
1134         -> Type         -- The type to instantiate 'a'
1135         -> String       -- The string to print
1136         -> CoreExpr
1137
1138 mkRuntimeErrorApp err_id res_ty err_msg 
1139   = mkApps (Var err_id) [Type res_ty, err_string]
1140   where
1141     err_string = Lit (mkStringLit err_msg)
1142
1143 rEC_SEL_ERROR_ID                = mkRuntimeErrorId recSelErrorName
1144 rUNTIME_ERROR_ID                = mkRuntimeErrorId runtimeErrorName
1145 iRREFUT_PAT_ERROR_ID            = mkRuntimeErrorId irrefutPatErrorName
1146 rEC_CON_ERROR_ID                = mkRuntimeErrorId recConErrorName
1147 pAT_ERROR_ID                    = mkRuntimeErrorId patErrorName
1148 nO_METHOD_BINDING_ERROR_ID      = mkRuntimeErrorId noMethodBindingErrorName
1149 nON_EXHAUSTIVE_GUARDS_ERROR_ID  = mkRuntimeErrorId nonExhaustiveGuardsErrorName
1150
1151 -- The runtime error Ids take a UTF8-encoded string as argument
1152 mkRuntimeErrorId name = pc_bottoming_Id name runtimeErrorTy
1153 runtimeErrorTy        = mkSigmaTy [openAlphaTyVar] [] (mkFunTy addrPrimTy openAlphaTy)
1154 \end{code}
1155
1156 \begin{code}
1157 eRROR_ID = pc_bottoming_Id errorName errorTy
1158
1159 errorTy  :: Type
1160 errorTy  = mkSigmaTy [openAlphaTyVar] [] (mkFunTys [mkListTy charTy] openAlphaTy)
1161     -- Notice the openAlphaTyVar.  It says that "error" can be applied
1162     -- to unboxed as well as boxed types.  This is OK because it never
1163     -- returns, so the return type is irrelevant.
1164 \end{code}
1165
1166
1167 %************************************************************************
1168 %*                                                                      *
1169 \subsection{Utilities}
1170 %*                                                                      *
1171 %************************************************************************
1172
1173 \begin{code}
1174 pcMiscPrelId :: Name -> Type -> IdInfo -> Id
1175 pcMiscPrelId name ty info
1176   = mkVanillaGlobal name ty info
1177     -- We lie and say the thing is imported; otherwise, we get into
1178     -- a mess with dependency analysis; e.g., core2stg may heave in
1179     -- random calls to GHCbase.unpackPS__.  If GHCbase is the module
1180     -- being compiled, then it's just a matter of luck if the definition
1181     -- will be in "the right place" to be in scope.
1182
1183 pc_bottoming_Id name ty
1184  = pcMiscPrelId name ty bottoming_info
1185  where
1186     bottoming_info = vanillaIdInfo `setAllStrictnessInfo` Just strict_sig
1187         -- Do *not* mark them as NoCafRefs, because they can indeed have
1188         -- CAF refs.  For example, pAT_ERROR_ID calls GHC.Err.untangle,
1189         -- which has some CAFs
1190         -- In due course we may arrange that these error-y things are
1191         -- regarded by the GC as permanently live, in which case we
1192         -- can give them NoCaf info.  As it is, any function that calls
1193         -- any pc_bottoming_Id will itself have CafRefs, which bloats
1194         -- SRTs.
1195
1196     strict_sig     = mkStrictSig (mkTopDmdType [evalDmd] BotRes)
1197         -- These "bottom" out, no matter what their arguments
1198 \end{code}
1199