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