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