2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
4 \section[Id]{@Ids@: Value and constructor identifiers}
7 #include "HsVersions.h"
10 GenId, Id(..), -- Abstract
11 StrictnessMark(..), -- An enumaration
12 ConTag(..), DictVar(..), DictFun(..), DataCon(..),
15 mkSysLocal, mkUserLocal,
17 mkSpecId, mkSameSpecCon,
18 selectIdInfoForSpecId,
21 mkDataCon, mkTupleCon,
23 mkMethodSelId, mkSuperDictSelId, mkDefaultMethodId,
24 mkConstMethodId, getConstMethodId,
27 mkId, mkDictFunId, mkInstId,
33 getIdInfo, replaceIdInfo,
35 idPrimRep, getInstIdModule,
36 getMentionedTyConsAndClassesFromId,
38 dataConTag, dataConStrictMarks,
39 dataConSig, dataConRawArgTys, dataConArgTys,
40 dataConTyCon, dataConArity,
43 recordSelectorFieldLabel,
46 isDataCon, isTupleCon,
48 isSpecId_maybe, isSpecPragmaId_maybe,
49 toplevelishId, externallyVisibleId,
50 isTopLevId, isWorkerId, isWrapperId,
51 isImportedId, isSysLocalId,
53 isMethodSelId, isDefaultMethodId_maybe, isSuperDictSelId_maybe,
56 isConstMethodId_maybe,
57 cmpId_withSpecDataCon,
60 unfoldingUnfriendlyId, -- ToDo: rm, eventually
62 -- dataConMentionsNonPreludeTyCon,
65 applySubstToId, applyTypeEnvToId,
66 -- not exported: apply_to_Id, -- please don't use this, generally
68 -- UNFOLDING, ARITY, UPDATE, AND STRICTNESS STUFF (etc)
69 getIdArity, addIdArity,
70 getIdDemandInfo, addIdDemandInfo,
71 getIdSpecialisation, addIdSpecialisation,
72 getIdStrictness, addIdStrictness,
73 getIdUnfolding, addIdUnfolding,
74 getIdUpdateInfo, addIdUpdateInfo,
75 getIdArgUsageInfo, addIdArgUsageInfo,
76 getIdFBTypeInfo, addIdFBTypeInfo,
77 -- don't export the types, lest OptIdInfo be dragged in!
87 -- "Environments" keyed off of Ids, and sets of Ids
89 lookupIdEnv, lookupNoFailIdEnv, nullIdEnv, unitIdEnv, mkIdEnv,
90 growIdEnv, growIdEnvList, isNullIdEnv, addOneToIdEnv,
91 delOneFromIdEnv, delManyFromIdEnv, modifyIdEnv, combineIdEnvs,
94 -- and to make the interface self-sufficient...
95 GenIdSet(..), IdSet(..)
99 IMPORT_DELOOPER(IdLoop) -- for paranoia checking
100 IMPORT_DELOOPER(TyLoop) -- for paranoia checking
103 import Class ( classOpString, Class(..), GenClass, ClassOp(..), GenClassOp )
104 import CStrings ( identToC, cSEP )
106 import Maybes ( maybeToBool )
107 import Name ( appendRdr, nameUnique, mkLocalName, isLocalName,
108 isLocallyDefinedName,
109 mkTupleDataConName, mkCompoundName, mkCompoundName2,
110 isLexSym, isLexSpecialSym,
111 isLocallyDefined, changeUnique,
112 getOccName, origName, moduleOf,
113 isExported, ExportFlag(..),
116 import FieldLabel ( fieldLabelName, FieldLabel(..){-instances-} )
117 import PragmaInfo ( PragmaInfo(..) )
118 import PprEnv -- ( NmbrM(..), NmbrEnv(..) )
119 import PprType ( getTypeString, typeMaybeString, specMaybeTysSuffix,
125 import SrcLoc ( mkBuiltinSrcLoc )
126 import TyCon ( TyCon, mkTupleTyCon, tyConDataCons )
127 import Type ( mkSigmaTy, mkTyVarTys, mkFunTys, mkDictTy,
128 applyTyCon, isPrimType, instantiateTy,
129 tyVarsOfType, applyTypeEnvToTy, typePrimRep,
130 GenType, ThetaType(..), TauType(..), Type(..)
132 import TyVar ( alphaTyVars, isEmptyTyVarSet, TyVarEnv(..) )
134 import UniqSet -- practically all of it
135 import Unique ( getBuiltinUniques, pprUnique, showUnique,
137 Unique{-instance Ord3-}
139 import Util ( mapAccumL, nOfThem, zipEqual,
140 panic, panic#, pprPanic, assertPanic
144 Here are the @Id@ and @IdDetails@ datatypes; also see the notes that
147 Every @Id@ has a @Unique@, to uniquify it and for fast comparison, a
148 @Type@, and an @IdInfo@ (non-essential info about it, e.g.,
149 strictness). The essential info about different kinds of @Ids@ is
152 ToDo: possibly cache other stuff in the single-constructor @Id@ type.
156 Unique -- Key for fast comparison
158 ty -- Id's type; used all the time;
159 IdDetails -- Stuff about individual kinds of Ids.
160 PragmaInfo -- Properties of this Id requested by programmer
161 -- eg specialise-me, inline-me
162 IdInfo -- Properties of this Id deduced by compiler
166 data StrictnessMark = MarkedStrict | NotMarkedStrict
170 ---------------- Local values
172 = LocalId Bool -- Local name; mentioned by the user
173 -- True <=> no free type vars
175 | SysLocalId Bool -- Local name; made up by the compiler
178 | SpecPragmaId -- Local name; introduced by the compiler
179 (Maybe Id) -- for explicit specid in pragma
180 Bool -- as for LocalId
182 ---------------- Global values
184 | ImportedId -- Global name (Imported or Implicit); Id imported from an interface
186 | TopLevId -- Global name (LocalDef); Top-level in the orig source pgm
187 -- (not moved there by transformations).
189 -- a TopLevId's type may contain free type variables, if
190 -- the monomorphism restriction applies.
192 ---------------- Data constructors
195 [StrictnessMark] -- Strict args; length = arity
196 [FieldLabel] -- Field labels for this constructor
198 [TyVar] [(Class,Type)] [Type] TyCon
200 -- forall tyvars . theta_ty =>
201 -- unitype_1 -> ... -> unitype_n -> tycon tyvars
203 | TupleConId Int -- Its arity
205 | RecordSelId FieldLabel
207 ---------------- Things to do with overloading
209 | SuperDictSelId -- Selector for superclass dictionary
210 Class -- The class (input dict)
211 Class -- The superclass (result dict)
213 | MethodSelId Class -- An overloaded class operation, with
214 -- a fully polymorphic type. Its code
215 -- just selects a method from the
216 -- dictionary. The class.
217 ClassOp -- The operation
219 -- NB: The IdInfo for a MethodSelId has all the info about its
220 -- related "constant method Ids", which are just
221 -- specialisations of this general one.
223 | DefaultMethodId -- Default method for a particular class op
224 Class -- same class, <blah-blah> info as MethodSelId
225 ClassOp -- (surprise, surprise)
226 Bool -- True <=> I *know* this default method Id
227 -- is a generated one that just says
228 -- `error "No default method for <op>"'.
231 | DictFunId Class -- A DictFun is uniquely identified
232 Type -- by its class and type; this type has free type vars,
233 -- whose identity is irrelevant. Eg Class = Eq
235 -- The "a" is irrelevant. As it is too painful to
236 -- actually do comparisons that way, we kindly supply
237 -- a Unique for that purpose.
238 Module -- module where instance came from
241 | ConstMethodId -- A method which depends only on the type of the
242 -- instance, and not on any further dictionaries etc.
243 Class -- Uniquely identified by:
244 Type -- (class, type, classop) triple
246 Module -- module where instance came from
248 | InstId -- An instance of a dictionary, class operation,
249 -- or overloaded value (Local name)
250 Bool -- as for LocalId
252 | SpecId -- A specialisation of another Id
253 Id -- Id of which this is a specialisation
254 [Maybe Type] -- Types at which it is specialised;
255 -- A "Nothing" says this type ain't relevant.
256 Bool -- True <=> no free type vars; it's not enough
257 -- to know about the unspec version, because
258 -- we may specialise to a type w/ free tyvars
259 -- (i.e., in one of the "Maybe Type" dudes).
261 | WorkerId -- A "worker" for some other Id
262 Id -- Id for which this is a worker
270 DictFunIds are generated from instance decls.
275 instance Foo a => Foo [a] where
278 generates the dict fun id decl
280 dfun.Foo.[*] = \d -> ...
282 The dfun id is uniquely named by the (class, type) pair. Notice, it
283 isn't a (class,tycon) pair any more, because we may get manually or
284 automatically generated specialisations of the instance decl:
286 instance Foo [Int] where
293 The type variables in the name are irrelevant; we print them as stars.
296 Constant method ids are generated from instance decls where
297 there is no context; that is, no dictionaries are needed to
298 construct the method. Example
300 instance Foo Int where
303 Then we get a constant method
308 It is possible, albeit unusual, to have a constant method
309 for an instance decl which has type vars:
311 instance Foo [a] where
315 We get the constant method
319 So a constant method is identified by a class/op/type triple.
320 The type variables in the type are irrelevant.
323 For Ids whose names must be known/deducible in other modules, we have
324 to conjure up their worker's names (and their worker's worker's
325 names... etc) in a known systematic way.
328 %************************************************************************
330 \subsection[Id-documentation]{Documentation}
332 %************************************************************************
336 The @Id@ datatype describes {\em values}. The basic things we want to
337 know: (1)~a value's {\em type} (@idType@ is a very common
338 operation in the compiler); and (2)~what ``flavour'' of value it might
339 be---for example, it can be terribly useful to know that a value is a
343 %----------------------------------------------------------------------
344 \item[@DataConId@:] For the data constructors declared by a @data@
345 declaration. Their type is kept in {\em two} forms---as a regular
346 @Type@ (in the usual place), and also in its constituent pieces (in
347 the ``details''). We are frequently interested in those pieces.
349 %----------------------------------------------------------------------
350 \item[@TupleConId@:] This is just a special shorthand for @DataCons@ for
351 the infinite family of tuples.
353 %----------------------------------------------------------------------
354 \item[@ImportedId@:] These are values defined outside this module.
355 {\em Everything} we want to know about them must be stored here (or in
358 %----------------------------------------------------------------------
359 \item[@TopLevId@:] These are values defined at the top-level in this
360 module; i.e., those which {\em might} be exported (hence, a
361 @Name@). It does {\em not} include those which are moved to the
362 top-level through program transformations.
364 We also guarantee that @TopLevIds@ will {\em stay} at top-level.
365 Theoretically, they could be floated inwards, but there's no known
366 advantage in doing so. This way, we can keep them with the same
367 @Unique@ throughout (no cloning), and, in general, we don't have to be
368 so paranoid about them.
370 In particular, we had the following problem generating an interface:
371 We have to ``stitch together'' info (1)~from the typechecker-produced
372 global-values list (GVE) and (2)~from the STG code [which @Ids@ have
373 what arities]. If the @Uniques@ on the @TopLevIds@ can {\em change}
374 between (1) and (2), you're sunk!
376 %----------------------------------------------------------------------
377 \item[@MethodSelId@:] A selector from a dictionary; it may select either
378 a method or a dictionary for one of the class's superclasses.
380 %----------------------------------------------------------------------
383 @mkDictFunId [a,b..] theta C T@ is the function derived from the
386 instance theta => C (T a b ..) where
389 It builds function @Id@ which maps dictionaries for theta,
390 to a dictionary for C (T a b ..).
392 *Note* that with the ``Mark Jones optimisation'', the theta may
393 include dictionaries for the immediate superclasses of C at the type
396 %----------------------------------------------------------------------
399 %----------------------------------------------------------------------
402 %----------------------------------------------------------------------
405 %----------------------------------------------------------------------
406 \item[@LocalId@:] A purely-local value, e.g., a function argument,
407 something defined in a @where@ clauses, ... --- but which appears in
408 the original program text.
410 %----------------------------------------------------------------------
411 \item[@SysLocalId@:] Same as a @LocalId@, except does {\em not} appear in
412 the original program text; these are introduced by the compiler in
415 %----------------------------------------------------------------------
416 \item[@SpecPragmaId@:] Introduced by the compiler to record
417 Specialisation pragmas. It is dead code which MUST NOT be removed
418 before specialisation.
423 %----------------------------------------------------------------------
426 @DataCons@ @TupleCons@, @Importeds@, @TopLevIds@, @SuperDictSelIds@,
427 @MethodSelIds@, @DictFunIds@, and @DefaultMethodIds@ have the following
431 They have no free type variables, so if you are making a
432 type-variable substitution you don't need to look inside them.
434 They are constants, so they are not free variables. (When the STG
435 machine makes a closure, it puts all the free variables in the
436 closure; the above are not required.)
438 Note that @InstIds@, @Locals@ and @SysLocals@ {\em may} have the above
439 properties, but they may not.
442 %************************************************************************
444 \subsection[Id-general-funs]{General @Id@-related functions}
446 %************************************************************************
449 unsafeGenId2Id :: GenId ty -> Id
450 unsafeGenId2Id (Id u n ty d p i) = Id u n (panic "unsafeGenId2Id:ty") d p i
452 isDataCon id = is_data (unsafeGenId2Id id)
454 is_data (Id _ _ _ (DataConId _ _ _ _ _ _ _) _ _) = True
455 is_data (Id _ _ _ (TupleConId _) _ _) = True
456 is_data (Id _ _ _ (SpecId unspec _ _) _ _) = is_data unspec
457 is_data other = False
460 isTupleCon id = is_tuple (unsafeGenId2Id id)
462 is_tuple (Id _ _ _ (TupleConId _) _ _) = True
463 is_tuple (Id _ _ _ (SpecId unspec _ _) _ _) = is_tuple unspec
464 is_tuple other = False
467 isSpecId_maybe (Id _ _ _ (SpecId unspec ty_maybes _) _ _)
468 = ASSERT(not (maybeToBool (isSpecId_maybe unspec)))
469 Just (unspec, ty_maybes)
470 isSpecId_maybe other_id
473 isSpecPragmaId_maybe (Id _ _ _ (SpecPragmaId specid _) _ _)
475 isSpecPragmaId_maybe other_id
480 @toplevelishId@ tells whether an @Id@ {\em may} be defined in a nested
481 @let(rec)@ (returns @False@), or whether it is {\em sure} to be
482 defined at top level (returns @True@). This is used to decide whether
483 the @Id@ is a candidate free variable. NB: you are only {\em sure}
484 about something if it returns @True@!
487 toplevelishId :: Id -> Bool
488 idHasNoFreeTyVars :: Id -> Bool
490 toplevelishId (Id _ _ _ details _ _)
493 chk (DataConId _ _ _ _ _ _ _) = True
494 chk (TupleConId _) = True
495 chk (RecordSelId _) = True
496 chk ImportedId = True
497 chk TopLevId = True -- NB: see notes
498 chk (SuperDictSelId _ _) = True
499 chk (MethodSelId _ _) = True
500 chk (DefaultMethodId _ _ _) = True
501 chk (DictFunId _ _ _) = True
502 chk (ConstMethodId _ _ _ _) = True
503 chk (SpecId unspec _ _) = toplevelishId unspec
504 -- depends what the unspecialised thing is
505 chk (WorkerId unwrkr) = toplevelishId unwrkr
506 chk (InstId _) = False -- these are local
507 chk (LocalId _) = False
508 chk (SysLocalId _) = False
509 chk (SpecPragmaId _ _) = False
511 idHasNoFreeTyVars (Id _ _ _ details _ info)
514 chk (DataConId _ _ _ _ _ _ _) = True
515 chk (TupleConId _) = True
516 chk (RecordSelId _) = True
517 chk ImportedId = True
519 chk (SuperDictSelId _ _) = True
520 chk (MethodSelId _ _) = True
521 chk (DefaultMethodId _ _ _) = True
522 chk (DictFunId _ _ _) = True
523 chk (ConstMethodId _ _ _ _) = True
524 chk (WorkerId unwrkr) = idHasNoFreeTyVars unwrkr
525 chk (SpecId _ _ no_free_tvs) = no_free_tvs
526 chk (InstId no_free_tvs) = no_free_tvs
527 chk (LocalId no_free_tvs) = no_free_tvs
528 chk (SysLocalId no_free_tvs) = no_free_tvs
529 chk (SpecPragmaId _ no_free_tvs) = no_free_tvs
533 isTopLevId (Id _ _ _ TopLevId _ _) = True
534 isTopLevId other = False
536 isImportedId (Id _ _ _ ImportedId _ _) = True
537 isImportedId other = False
539 isBottomingId (Id _ _ _ _ _ info) = bottomIsGuaranteed (getInfo info)
541 isSysLocalId (Id _ _ _ (SysLocalId _) _ _) = True
542 isSysLocalId other = False
544 isSpecPragmaId (Id _ _ _ (SpecPragmaId _ _) _ _) = True
545 isSpecPragmaId other = False
547 isMethodSelId (Id _ _ _ (MethodSelId _ _) _ _) = True
548 isMethodSelId _ = False
550 isDefaultMethodId (Id _ _ _ (DefaultMethodId _ _ _) _ _) = True
551 isDefaultMethodId other = False
553 isDefaultMethodId_maybe (Id _ _ _ (DefaultMethodId cls clsop err) _ _)
554 = Just (cls, clsop, err)
555 isDefaultMethodId_maybe other = Nothing
557 isDictFunId (Id _ _ _ (DictFunId _ _ _) _ _) = True
558 isDictFunId other = False
560 isConstMethodId (Id _ _ _ (ConstMethodId _ _ _ _) _ _) = True
561 isConstMethodId other = False
563 isConstMethodId_maybe (Id _ _ _ (ConstMethodId cls ty clsop _) _ _)
564 = Just (cls, ty, clsop)
565 isConstMethodId_maybe other = Nothing
567 isSuperDictSelId_maybe (Id _ _ _ (SuperDictSelId c sc) _ _) = Just (c, sc)
568 isSuperDictSelId_maybe other_id = Nothing
570 isWorkerId (Id _ _ _ (WorkerId _) _ _) = True
571 isWorkerId other = False
574 isWrapperId id = workerExists (getIdStrictness id)
580 pprIdInUnfolding :: IdSet -> Id -> Pretty
582 pprIdInUnfolding in_scopes v
587 if v `elementOfUniqSet` in_scopes then
588 pprUnique (idUnique v)
590 -- ubiquitous Ids with special syntax:
591 else if v == nilDataCon then
593 else if isTupleCon v then
594 ppBeside (ppPStr SLIT("_TUP_")) (ppInt (dataConArity v))
596 -- ones to think about:
599 (Id _ _ _ v_details _ _) = v
602 -- these ones must have been exported by their original module
603 ImportedId -> pp_full_name
605 -- these ones' exportedness checked later...
606 TopLevId -> pp_full_name
607 DataConId _ _ _ _ _ _ _ -> pp_full_name
609 RecordSelId lbl -> ppr sty lbl
611 -- class-ish things: class already recorded as "mentioned"
613 -> ppCat [ppPStr SLIT("_SDSEL_"), pp_class c, pp_class sc]
615 -> ppCat [ppPStr SLIT("_METH_"), pp_class c, pp_class_op o]
616 DefaultMethodId c o _
617 -> ppCat [ppPStr SLIT("_DEFM_"), pp_class c, pp_class_op o]
619 -- instance-ish things: should we try to figure out
620 -- *exactly* which extra instances have to be exported? (ToDo)
622 -> ppCat [ppPStr SLIT("_DFUN_"), pp_class c, pp_type t]
623 ConstMethodId c t o _
624 -> ppCat [ppPStr SLIT("_CONSTM_"), pp_class c, pp_class_op o, pp_type t]
626 -- specialisations and workers
627 SpecId unspec ty_maybes _
629 pp = pprIdInUnfolding in_scopes unspec
631 ppCat [ppPStr SLIT("_SPEC_"), pp, ppLbrack,
632 ppIntersperse pp'SP{-'-} (map pp_ty_maybe ty_maybes),
637 pp = pprIdInUnfolding in_scopes unwrkr
639 ppBeside (ppPStr SLIT("_WRKR_ ")) pp
641 -- anything else? we're nae interested
642 other_id -> panic "pprIdInUnfolding:mystery Id"
644 ppr_Unfolding = PprUnfolding (panic "Id:ppr_Unfolding")
648 (OrigName m_str n_str) = origName "Id:ppr_Unfolding" v
651 if isLexSym n_str && not (isLexSpecialSym n_str) then
652 ppBesides [ppLparen, ppPStr n_str, ppRparen]
656 if isPreludeDefined v then
659 ppCat [ppPStr SLIT("_ORIG_"), ppPStr m_str, pp_n]
661 pp_class :: Class -> Pretty
662 pp_class_op :: ClassOp -> Pretty
663 pp_type :: Type -> Pretty
664 pp_ty_maybe :: Maybe Type -> Pretty
666 pp_class clas = ppr ppr_Unfolding clas
667 pp_class_op op = ppr ppr_Unfolding op
669 pp_type t = ppBesides [ppLparen, ppr ppr_Unfolding t, ppRparen]
671 pp_ty_maybe Nothing = ppPStr SLIT("_N_")
672 pp_ty_maybe (Just t) = pp_type t
676 @whatsMentionedInId@ ferrets out the types/classes/instances on which
677 this @Id@ depends. If this Id is to appear in an interface, then
678 those entities had Jolly Well be in scope. Someone else up the
679 call-tree decides that.
684 :: IdSet -- Ids known to be in scope
685 -> Id -- Id being processed
686 -> (Bag Id, Bag TyCon, Bag Class) -- mentioned Ids/TyCons/etc.
688 whatsMentionedInId in_scopes v
693 = getMentionedTyConsAndClassesFromType v_ty
695 result0 id_bag = (id_bag, tycons, clss)
698 = (ids `unionBags` unitBag v, -- we add v to "mentioned"...
699 tcs `unionBags` tycons,
703 if v `elementOfUniqSet` in_scopes then
704 result0 emptyBag -- v not added to "mentioned"
706 -- ones to think about:
709 (Id _ _ _ v_details _ _) = v
712 -- specialisations and workers
713 SpecId unspec ty_maybes _
715 (ids2, tcs2, cs2) = whatsMentionedInId in_scopes unspec
717 result1 ids2 tcs2 cs2
721 (ids2, tcs2, cs2) = whatsMentionedInId in_scopes unwrkr
723 result1 ids2 tcs2 cs2
725 anything_else -> result0 (unitBag v) -- v is added to "mentioned"
729 Tell them who my wrapper function is.
732 myWrapperMaybe :: Id -> Maybe Id
734 myWrapperMaybe (Id _ _ _ (WorkerId my_wrapper) _ _) = Just my_wrapper
735 myWrapperMaybe other_id = Nothing
740 unfoldingUnfriendlyId -- return True iff it is definitely a bad
741 :: Id -- idea to export an unfolding that
742 -> Bool -- mentions this Id. Reason: it cannot
743 -- possibly be seen in another module.
745 unfoldingUnfriendlyId id = panic "Id.unfoldingUnfriendlyId"
748 unfoldingUnfriendlyId id
749 | not (externallyVisibleId id) -- that settles that...
752 unfoldingUnfriendlyId (Id _ _ _ (WorkerId wrapper) _ _)
753 = class_thing wrapper
755 -- "class thing": If we're going to use this worker Id in
756 -- an interface, we *have* to be able to untangle the wrapper's
757 -- strictness when reading it back in. At the moment, this
758 -- is not always possible: in precisely those cases where
759 -- we pass tcGenPragmas a "Nothing" for its "ty_maybe".
761 class_thing (Id _ _ _ (SuperDictSelId _ _) _ _) = True
762 class_thing (Id _ _ _ (MethodSelId _ _) _ _) = True
763 class_thing (Id _ _ _ (DefaultMethodId _ _ _) _ _) = True
764 class_thing other = False
766 unfoldingUnfriendlyId (Id _ _ _ (SpecId d@(Id _ _ _ dfun@(DictFunId _ t _)) _ _) _ _)
767 -- a SPEC of a DictFunId can end up w/ gratuitous
768 -- TyVar(Templates) in the i/face; only a problem
769 -- if -fshow-pragma-name-errs; but we can do without the pain.
770 -- A HACK in any case (WDP 94/05/02)
771 = naughty_DictFunId dfun
773 unfoldingUnfriendlyId d@(Id _ _ _ dfun@(DictFunId _ t _) _ _)
774 = naughty_DictFunId dfun -- similar deal...
776 unfoldingUnfriendlyId other_id = False -- is friendly in all other cases
778 naughty_DictFunId :: IdDetails -> Bool
779 -- True <=> has a TyVar(Template) in the "type" part of its "name"
781 naughty_DictFunId (DictFunId _ _ _) = panic "False" -- came from outside; must be OK
782 naughty_DictFunId (DictFunId _ ty _)
783 = not (isGroundTy ty)
787 @externallyVisibleId@: is it true that another module might be
788 able to ``see'' this Id?
790 We need the @toplevelishId@ check as well as @isExported@ for when we
791 compile instance declarations in the prelude. @DictFunIds@ are
792 ``exported'' if either their class or tycon is exported, but, in
793 compiling the prelude, the compiler may not recognise that as true.
796 externallyVisibleId :: Id -> Bool
798 externallyVisibleId id@(Id _ _ _ details _ _)
799 = if isLocallyDefined id then
800 toplevelishId id && isExported id && not (weird_datacon details)
802 not (weird_tuplecon details)
803 -- if visible here, it must be visible elsewhere, too.
805 -- If it's a DataCon, it's not enough to know it (meaning
806 -- its TyCon) is exported; we need to know that it might
807 -- be visible outside. Consider:
809 -- data Foo a = Mumble | BigFoo a WeirdLocalType
811 -- We can't tell the outside world *anything* about Foo, because
812 -- of WeirdLocalType; but we need to know this when asked if
813 -- "Mumble" is externally visible...
816 weird_datacon (DataConId _ _ _ _ _ _ tycon)
817 = maybeToBool (maybePurelyLocalTyCon tycon)
819 weird_datacon not_a_datacon_therefore_not_weird = False
821 weird_tuplecon (TupleConId arity)
822 = arity > 32 -- sigh || isBigTupleTyCon tycon -- generated *purely* for local use
823 weird_tuplecon _ = False
827 idWantsToBeINLINEd :: Id -> Bool
829 idWantsToBeINLINEd (Id _ _ _ _ IWantToBeINLINEd _) = True
830 idWantsToBeINLINEd _ = False
833 For @unlocaliseId@: See the brief commentary in
834 \tr{simplStg/SimplStg.lhs}.
838 unlocaliseId :: FAST_STRING{-modulename-} -> Id -> Maybe Id
840 unlocaliseId mod (Id u fn ty info TopLevId)
841 = Just (Id u (unlocaliseFullName fn) ty info TopLevId)
843 unlocaliseId mod (Id u sn ty info (LocalId no_ftvs))
844 = --false?: ASSERT(no_ftvs)
846 full_name = unlocaliseShortName mod u sn
848 Just (Id u full_name ty info TopLevId)
850 unlocaliseId mod (Id u sn ty info (SysLocalId no_ftvs))
851 = --false?: on PreludeGlaST: ASSERT(no_ftvs)
853 full_name = unlocaliseShortName mod u sn
855 Just (Id u full_name ty info TopLevId)
857 unlocaliseId mod (Id u n ty info (SpecId unspec ty_maybes no_ftvs))
858 = case unlocalise_parent mod u unspec of
860 Just xx -> Just (Id u n ty info (SpecId xx ty_maybes no_ftvs))
862 unlocaliseId mod (Id u n ty info (WorkerId unwrkr))
863 = case unlocalise_parent mod u unwrkr of
865 Just xx -> Just (Id u n ty info (WorkerId xx))
867 unlocaliseId mod (Id u name ty info (InstId no_ftvs))
868 = Just (Id u full_name ty info TopLevId)
869 -- type might be wrong, but it hardly matters
870 -- at this stage (just before printing C) ToDo
872 name = nameOf (origName "Id.unlocaliseId" name)
873 full_name = mkFullName mod name InventedInThisModule ExportAll mkGeneratedSrcLoc
875 unlocaliseId mod other_id = Nothing
878 -- we have to be Very Careful for workers/specs of
881 unlocalise_parent mod uniq (Id _ sn ty info (LocalId no_ftvs))
882 = --false?: ASSERT(no_ftvs)
884 full_name = unlocaliseShortName mod uniq sn
886 Just (Id uniq full_name ty info TopLevId)
888 unlocalise_parent mod uniq (Id _ sn ty info (SysLocalId no_ftvs))
889 = --false?: ASSERT(no_ftvs)
891 full_name = unlocaliseShortName mod uniq sn
893 Just (Id uniq full_name ty info TopLevId)
895 unlocalise_parent mod uniq other_id = unlocaliseId mod other_id
896 -- we're OK otherwise
900 CLAIM (not ASSERTed) for @applyTypeEnvToId@ and @applySubstToId@:
901 `Top-levelish Ids'' cannot have any free type variables, so applying
902 the type-env cannot have any effect. (NB: checked in CoreLint?)
904 The special casing is in @applyTypeEnvToId@, not @apply_to_Id@, as the
905 former ``should be'' the usual crunch point.
908 type TypeEnv = TyVarEnv Type
910 applyTypeEnvToId :: TypeEnv -> Id -> Id
912 applyTypeEnvToId type_env id@(Id _ _ ty _ _ _)
913 | idHasNoFreeTyVars id
916 = apply_to_Id ( \ ty ->
917 applyTypeEnvToTy type_env ty
922 apply_to_Id :: (Type -> Type) -> Id -> Id
924 apply_to_Id ty_fn (Id u n ty details prag info)
928 Id u n new_ty (apply_to_details details) prag (apply_to_IdInfo ty_fn info)
930 apply_to_details (SpecId unspec ty_maybes no_ftvs)
932 new_unspec = apply_to_Id ty_fn unspec
933 new_maybes = map apply_to_maybe ty_maybes
935 SpecId new_unspec new_maybes (no_free_tvs ty)
936 -- ToDo: gratuitous recalc no_ftvs???? (also InstId)
938 apply_to_maybe Nothing = Nothing
939 apply_to_maybe (Just ty) = Just (ty_fn ty)
941 apply_to_details (WorkerId unwrkr)
943 new_unwrkr = apply_to_Id ty_fn unwrkr
947 apply_to_details other = other
950 Sadly, I don't think the one using the magic typechecker substitution
951 can be done with @apply_to_Id@. Here we go....
953 Strictness is very important here. We can't leave behind thunks
954 with pointers to the substitution: it {\em must} be single-threaded.
958 applySubstToId :: Subst -> Id -> (Subst, Id)
960 applySubstToId subst id@(Id u n ty info details)
961 -- *cannot* have a "idHasNoFreeTyVars" get-out clause
962 -- because, in the typechecker, we are still
963 -- *concocting* the types.
964 = case (applySubstToTy subst ty) of { (s2, new_ty) ->
965 case (applySubstToIdInfo s2 info) of { (s3, new_info) ->
966 case (apply_to_details s3 new_ty details) of { (s4, new_details) ->
967 (s4, Id u n new_ty new_info new_details) }}}
969 apply_to_details subst _ (InstId inst no_ftvs)
970 = case (applySubstToInst subst inst) of { (s2, new_inst) ->
971 (s2, InstId new_inst no_ftvs{-ToDo:right???-}) }
973 apply_to_details subst new_ty (SpecId unspec ty_maybes _)
974 = case (applySubstToId subst unspec) of { (s2, new_unspec) ->
975 case (mapAccumL apply_to_maybe s2 ty_maybes) of { (s3, new_maybes) ->
976 (s3, SpecId new_unspec new_maybes (no_free_tvs new_ty)) }}
977 -- NB: recalc no_ftvs (I think it's necessary (?) WDP 95/04)
979 apply_to_maybe subst Nothing = (subst, Nothing)
980 apply_to_maybe subst (Just ty)
981 = case (applySubstToTy subst ty) of { (s2, new_ty) ->
984 apply_to_details subst _ (WorkerId unwrkr)
985 = case (applySubstToId subst unwrkr) of { (s2, new_unwrkr) ->
986 (s2, WorkerId new_unwrkr) }
988 apply_to_details subst _ other = (subst, other)
992 %************************************************************************
994 \subsection[Id-type-funs]{Type-related @Id@ functions}
996 %************************************************************************
999 idType :: GenId ty -> ty
1001 idType (Id _ _ ty _ _ _) = ty
1006 getMentionedTyConsAndClassesFromId :: Id -> (Bag TyCon, Bag Class)
1008 getMentionedTyConsAndClassesFromId id
1009 = getMentionedTyConsAndClassesFromType (idType id)
1014 idPrimRep i = typePrimRep (idType i)
1019 getInstIdModule (Id _ _ _ (DictFunId _ _ mod)) = mod
1020 getInstIdModule (Id _ _ _ (ConstMethodId _ _ _ mod)) = mod
1021 getInstIdModule other = panic "Id:getInstIdModule"
1025 %************************************************************************
1027 \subsection[Id-overloading]{Functions related to overloading}
1029 %************************************************************************
1032 mkSuperDictSelId u c sc ty info
1033 = mk_classy_id (SuperDictSelId c sc) SLIT("sdsel") (Left (origName "mkSuperDictSelId" sc)) u c ty info
1035 mkMethodSelId u rec_c op ty info
1036 = mk_classy_id (MethodSelId rec_c op) SLIT("meth") (Right (classOpString op)) u rec_c ty info
1038 mkDefaultMethodId u rec_c op gen ty info
1039 = mk_classy_id (DefaultMethodId rec_c op gen) SLIT("defm") (Right (classOpString op)) u rec_c ty info
1041 mk_classy_id details str op_str u rec_c ty info
1042 = Id u n ty details NoPragmaInfo info
1044 cname = getName rec_c -- we get other info out of here
1045 cname_orig = origName "mk_classy_id" cname
1046 cmod = moduleOf cname_orig
1048 n = mkCompoundName u cmod str [Left cname_orig, op_str] cname
1050 mkDictFunId u c ity full_ty from_here locn mod info
1051 = Id u n full_ty (DictFunId c ity mod) NoPragmaInfo info
1053 n = mkCompoundName2 u mod SLIT("dfun") (Left (origName "mkDictFunId" c) : map Right (getTypeString ity)) from_here locn
1055 mkConstMethodId u c op ity full_ty from_here locn mod info
1056 = Id u n full_ty (ConstMethodId c ity op mod) NoPragmaInfo info
1058 n = mkCompoundName2 u mod SLIT("const") (Left (origName "mkConstMethodId" c) : Right (classOpString op) : map Right (getTypeString ity)) from_here locn
1060 mkWorkerId u unwrkr ty info
1061 = Id u n ty (WorkerId unwrkr) NoPragmaInfo info
1063 unwrkr_name = getName unwrkr
1064 unwrkr_orig = trace "mkWorkerId:origName:" $ origName "mkWorkerId" unwrkr_name
1065 umod = moduleOf unwrkr_orig
1067 n = mkCompoundName u umod SLIT("wrk") [Left unwrkr_orig] unwrkr_name
1069 mkInstId u ty name = Id u (changeUnique name u) ty (InstId (no_free_tvs ty)) NoPragmaInfo noIdInfo
1072 getConstMethodId clas op ty
1073 = -- constant-method info is hidden in the IdInfo of
1074 -- the class-op id (as mentioned up above).
1076 sel_id = getMethodSelId clas op
1078 case (lookupConstMethodId (getIdSpecialisation sel_id) ty) of
1080 Nothing -> pprError "ERROR: getConstMethodId:" (ppAboves [
1081 ppCat [ppr PprDebug ty, ppr PprDebug ops, ppr PprDebug op_ids,
1082 ppr PprDebug sel_id],
1083 ppStr "(This can arise if an interface pragma refers to an instance",
1084 ppStr "but there is no imported interface which *defines* that instance.",
1085 ppStr "The info above, however ugly, should indicate what else you need to import."
1090 %************************************************************************
1092 \subsection[local-funs]{@LocalId@-related functions}
1094 %************************************************************************
1097 mkImported n ty info = Id (nameUnique n) n ty ImportedId NoPragmaInfo info
1100 updateIdType :: Id -> Type -> Id
1101 updateIdType (Id u n _ info details) ty = Id u n ty info details
1106 type MyTy a b = GenType (GenTyVar a) b
1107 type MyId a b = GenId (MyTy a b)
1109 no_free_tvs ty = isEmptyTyVarSet (tyVarsOfType ty)
1111 -- SysLocal: for an Id being created by the compiler out of thin air...
1112 -- UserLocal: an Id with a name the user might recognize...
1113 mkSysLocal, mkUserLocal :: FAST_STRING -> Unique -> MyTy a b -> SrcLoc -> MyId a b
1115 mkSysLocal str uniq ty loc
1116 = Id uniq (mkLocalName uniq str True{-emph uniq-} loc) ty (SysLocalId (no_free_tvs ty)) NoPragmaInfo noIdInfo
1118 mkUserLocal str uniq ty loc
1119 = Id uniq (mkLocalName uniq str False{-emph name-} loc) ty (LocalId (no_free_tvs ty)) NoPragmaInfo noIdInfo
1121 -- mkUserId builds a local or top-level Id, depending on the name given
1122 mkUserId :: Name -> MyTy a b -> PragmaInfo -> MyId a b
1123 mkUserId name ty pragma_info
1125 = Id (nameUnique name) name ty (LocalId (no_free_tvs ty)) pragma_info noIdInfo
1127 = Id (nameUnique name) name ty
1128 (if isLocallyDefinedName name then TopLevId else ImportedId)
1129 pragma_info noIdInfo
1136 -- for a SpecPragmaId being created by the compiler out of thin air...
1137 mkSpecPragmaId :: FAST_STRING -> Unique -> Type -> Maybe Id -> SrcLoc -> Id
1138 mkSpecPragmaId str uniq ty specid loc
1139 = Id uniq (mkShortName str loc) ty noIdInfo (SpecPragmaId specid (no_free_tvs ty))
1142 mkSpecId u unspec ty_maybes ty info
1143 = ASSERT(not (maybeToBool (isSpecId_maybe unspec)))
1144 Id u n ty info (SpecId unspec ty_maybes (no_free_tvs ty))
1146 -- Specialised version of constructor: only used in STG and code generation
1147 -- Note: The specialsied Id has the same unique as the unspeced Id
1149 mkSameSpecCon ty_maybes unspec@(Id u n ty info details)
1150 = ASSERT(isDataCon unspec)
1151 ASSERT(not (maybeToBool (isSpecId_maybe unspec)))
1152 Id u n new_ty info (SpecId unspec ty_maybes (no_free_tvs new_ty))
1154 new_ty = specialiseTy ty ty_maybes 0
1156 localiseId :: Id -> Id
1157 localiseId id@(Id u n ty info details)
1158 = Id u (mkShortName name loc) ty info (LocalId (no_free_tvs ty))
1160 name = getOccName id
1164 mkIdWithNewUniq :: Id -> Unique -> Id
1166 mkIdWithNewUniq (Id _ n ty details prag info) u
1167 = Id u (changeUnique n u) ty details prag info
1170 Make some local @Ids@ for a template @CoreExpr@. These have bogus
1171 @Uniques@, but that's OK because the templates are supposed to be
1172 instantiated before use.
1174 mkTemplateLocals :: [Type] -> [Id]
1175 mkTemplateLocals tys
1176 = zipWith (\ u -> \ ty -> mkSysLocal SLIT("tpl") u ty mkBuiltinSrcLoc)
1177 (getBuiltinUniques (length tys))
1182 getIdInfo :: GenId ty -> IdInfo
1183 getPragmaInfo :: GenId ty -> PragmaInfo
1185 getIdInfo (Id _ _ _ _ _ info) = info
1186 getPragmaInfo (Id _ _ _ _ info _) = info
1189 replaceIdInfo :: Id -> IdInfo -> Id
1191 replaceIdInfo (Id u n ty _ details) info = Id u n ty info details
1193 selectIdInfoForSpecId :: Id -> IdInfo
1194 selectIdInfoForSpecId unspec
1195 = ASSERT(not (maybeToBool (isSpecId_maybe unspec)))
1196 noIdInfo `addInfo_UF` getIdUnfolding unspec
1200 %************************************************************************
1202 \subsection[Id-arities]{Arity-related functions}
1204 %************************************************************************
1206 For locally-defined Ids, the code generator maintains its own notion
1207 of their arities; so it should not be asking... (but other things
1208 besides the code-generator need arity info!)
1211 getIdArity :: Id -> ArityInfo
1212 getIdArity (Id _ _ _ _ _ id_info) = getInfo id_info
1214 dataConArity :: DataCon -> Int
1215 dataConArity id@(Id _ _ _ _ _ id_info)
1216 = ASSERT(isDataCon id)
1217 case (arityMaybe (getInfo id_info)) of
1218 Nothing -> pprPanic "dataConArity:Nothing:" (pprId PprDebug id)
1221 isNullaryDataCon con = dataConArity con == 0 -- function of convenience
1223 addIdArity :: Id -> Int -> Id
1224 addIdArity (Id u n ty details pinfo info) arity
1225 = Id u n ty details pinfo (info `addInfo` (mkArityInfo arity))
1228 %************************************************************************
1230 \subsection[constructor-funs]{@DataCon@-related functions (incl.~tuples)}
1232 %************************************************************************
1236 -> [StrictnessMark] -> [FieldLabel]
1237 -> [TyVar] -> ThetaType -> [TauType] -> TyCon
1240 -- can get the tag and all the pieces of the type from the Type
1242 mkDataCon n stricts fields tvs ctxt args_tys tycon
1243 = ASSERT(length stricts == length args_tys)
1246 -- NB: data_con self-recursion; should be OK as tags are not
1247 -- looked at until late in the game.
1252 (DataConId data_con_tag stricts fields tvs ctxt args_tys tycon)
1256 data_con_tag = position_within fIRST_TAG data_con_family
1258 data_con_family = tyConDataCons tycon
1260 position_within :: Int -> [Id] -> Int
1262 position_within acc (c:cs)
1263 = if c == data_con then acc else position_within (acc+1) cs
1265 position_within acc []
1266 = panic "mkDataCon: con not found in family"
1270 = mkSigmaTy tvs ctxt
1271 (mkFunTys args_tys (applyTyCon tycon (mkTyVarTys tvs)))
1273 datacon_info = noIdInfo `addInfo_UF` unfolding
1274 `addInfo` mkArityInfo arity
1275 --ToDo: `addInfo` specenv
1277 arity = length args_tys
1284 -- else -- do some business...
1286 (tyvars, dict_vars, vars) = mk_uf_bits tvs ctxt args_tys tycon
1287 tyvar_tys = mkTyVarTys tyvars
1289 case (Con data_con tyvar_tys [VarArg v | v <- vars]) of { plain_Con ->
1291 mkUnfolding EssentialUnfolding -- for data constructors
1292 (mkLam tyvars (dict_vars ++ vars) plain_Con)
1295 mk_uf_bits tvs ctxt arg_tys tycon
1297 (inst_env, tyvars, tyvar_tys)
1298 = instantiateTyVarTemplates tvs
1301 -- the "context" and "arg_tys" have TyVarTemplates in them, so
1302 -- we instantiate those types to have the right TyVars in them
1304 case (map (instantiateTauTy inst_env) (map ctxt_ty ctxt))
1305 of { inst_dict_tys ->
1306 case (map (instantiateTauTy inst_env) arg_tys) of { inst_arg_tys ->
1308 -- We can only have **ONE** call to mkTemplateLocals here;
1309 -- otherwise, we get two blobs of locals w/ mixed-up Uniques
1310 -- (Mega-Sigh) [ToDo]
1311 case (mkTemplateLocals (inst_dict_tys ++ inst_arg_tys)) of { all_vars ->
1313 case (splitAt (length ctxt) all_vars) of { (dict_vars, vars) ->
1315 (tyvars, dict_vars, vars)
1318 -- these are really dubious Types, but they are only to make the
1319 -- binders for the lambdas for tossed-away dicts.
1320 ctxt_ty (clas, ty) = mkDictTy clas ty
1325 mkTupleCon :: Arity -> Id
1328 = Id unique n ty (TupleConId arity) NoPragmaInfo tuplecon_info
1330 n = mkTupleDataConName arity
1332 ty = mkSigmaTy tyvars []
1333 (mkFunTys tyvar_tys (applyTyCon tycon tyvar_tys))
1334 tycon = mkTupleTyCon arity
1335 tyvars = take arity alphaTyVars
1336 tyvar_tys = mkTyVarTys tyvars
1339 = noIdInfo `addInfo_UF` unfolding
1340 `addInfo` mkArityInfo arity
1341 --LATER:? `addInfo` panic "Id:mkTupleCon:pcGenerateTupleSpecs arity ty"
1348 -- else -- do some business...
1350 (tyvars, dict_vars, vars) = mk_uf_bits arity
1351 tyvar_tys = mkTyVarTys tyvars
1353 case (Con data_con tyvar_tys [VarArg v | v <- vars]) of { plain_Con ->
1355 EssentialUnfolding -- data constructors
1356 (mkLam tyvars (dict_vars ++ vars) plain_Con) }
1359 = case (mkTemplateLocals tyvar_tys) of { vars ->
1360 (tyvars, [], vars) }
1362 tyvar_tmpls = take arity alphaTyVars
1363 (_, tyvars, tyvar_tys) = instantiateTyVarTemplates tyvar_tmpls (map uniqueOf tyvar_tmpls)
1367 fIRST_TAG = 1 -- Tags allocated from here for real constructors
1371 dataConTag :: DataCon -> ConTag -- will panic if not a DataCon
1372 dataConTag (Id _ _ _ (DataConId tag _ _ _ _ _ _) _ _) = tag
1373 dataConTag (Id _ _ _ (TupleConId _) _ _) = fIRST_TAG
1374 dataConTag (Id _ _ _ (SpecId unspec _ _) _ _) = dataConTag unspec
1376 dataConTyCon :: DataCon -> TyCon -- will panic if not a DataCon
1377 dataConTyCon (Id _ _ _ (DataConId _ _ _ _ _ _ tycon) _ _) = tycon
1378 dataConTyCon (Id _ _ _ (TupleConId a) _ _) = mkTupleTyCon a
1380 dataConSig :: DataCon -> ([TyVar], ThetaType, [TauType], TyCon)
1381 -- will panic if not a DataCon
1383 dataConSig (Id _ _ _ (DataConId _ _ _ tyvars theta_ty arg_tys tycon) _ _)
1384 = (tyvars, theta_ty, arg_tys, tycon)
1386 dataConSig (Id _ _ _ (TupleConId arity) _ _)
1387 = (tyvars, [], tyvar_tys, mkTupleTyCon arity)
1389 tyvars = take arity alphaTyVars
1390 tyvar_tys = mkTyVarTys tyvars
1392 dataConFieldLabels :: DataCon -> [FieldLabel]
1393 dataConFieldLabels (Id _ _ _ (DataConId _ _ fields _ _ _ _) _ _) = fields
1394 dataConFieldLabels (Id _ _ _ (TupleConId _) _ _) = []
1396 dataConStrictMarks :: DataCon -> [StrictnessMark]
1397 dataConStrictMarks (Id _ _ _ (DataConId _ stricts _ _ _ _ _) _ _) = stricts
1398 dataConStrictMarks (Id _ _ _ (TupleConId arity) _ _)
1399 = nOfThem arity NotMarkedStrict
1401 dataConRawArgTys :: DataCon -> [TauType] -- a function of convenience
1402 dataConRawArgTys con = case (dataConSig con) of { (_,_, arg_tys,_) -> arg_tys }
1404 dataConArgTys :: DataCon
1405 -> [Type] -- Instantiated at these types
1406 -> [Type] -- Needs arguments of these types
1407 dataConArgTys con_id inst_tys
1408 = map (instantiateTy tenv) arg_tys
1410 (tyvars, _, arg_tys, _) = dataConSig con_id
1411 tenv = zipEqual "dataConArgTys" tyvars inst_tys
1415 mkRecordSelId field_label selector_ty
1416 = Id (nameUnique name)
1419 (RecordSelId field_label)
1423 name = fieldLabelName field_label
1425 recordSelectorFieldLabel :: Id -> FieldLabel
1426 recordSelectorFieldLabel (Id _ _ _ (RecordSelId lbl) _ _) = lbl
1430 Data type declarations are of the form:
1432 data Foo a b = C1 ... | C2 ... | ... | Cn ...
1434 For each constructor @Ci@, we want to generate a curried function; so, e.g., for
1435 @C1 x y z@, we want a function binding:
1437 fun_C1 = /\ a -> /\ b -> \ [x, y, z] -> Con C1 [a, b] [x, y, z]
1439 Notice the ``big lambdas'' and type arguments to @Con@---we are producing
1440 2nd-order polymorphic lambda calculus with explicit types.
1442 %************************************************************************
1444 \subsection[unfolding-Ids]{Functions related to @Ids@' unfoldings}
1446 %************************************************************************
1448 @getIdUnfolding@ takes a @Id@ (we are discussing the @DataCon@ case)
1449 and generates an @UnfoldingDetails@ for its unfolding. The @Ids@ and
1450 @TyVars@ don't really have to be new, because we are only producing a
1453 ToDo: what if @DataConId@'s type has a context (haven't thought about it
1456 Note: @getDataConUnfolding@ is a ``poor man's'' version---it is NOT
1457 EXPORTED. It just returns the binders (@TyVars@ and @Ids@) [in the
1458 example above: a, b, and x, y, z], which is enough (in the important
1459 \tr{DsExpr} case). (The middle set of @Ids@ is binders for any
1460 dictionaries, in the even of an overloaded data-constructor---none at
1464 getIdUnfolding :: Id -> UnfoldingDetails
1466 getIdUnfolding (Id _ _ _ _ _ info) = getInfo_UF info
1469 addIdUnfolding :: Id -> UnfoldingDetails -> Id
1470 addIdUnfolding id@(Id u n ty info details) unfold_details
1472 case (isLocallyDefined id, unfold_details) of
1473 (_, NoUnfoldingDetails) -> True
1474 (True, IWantToBeINLINEd _) -> True
1475 (False, IWantToBeINLINEd _) -> False -- v bad
1479 Id u n ty (info `addInfo_UF` unfold_details) details
1483 In generating selector functions (take a dictionary, give back one
1484 component...), we need to what out for the nothing-to-select cases (in
1485 which case the ``selector'' is just an identity function):
1487 class Eq a => Foo a { } # the superdict selector for "Eq"
1489 class Foo a { op :: Complex b => c -> b -> a }
1490 # the method selector for "op";
1491 # note local polymorphism...
1494 %************************************************************************
1496 \subsection[IdInfo-funs]{Functions related to @Ids@' @IdInfos@}
1498 %************************************************************************
1501 getIdDemandInfo :: Id -> DemandInfo
1502 getIdDemandInfo (Id _ _ _ _ _ info) = getInfo info
1504 addIdDemandInfo :: Id -> DemandInfo -> Id
1505 addIdDemandInfo (Id u n ty details prags info) demand_info
1506 = Id u n ty details prags (info `addInfo` demand_info)
1510 getIdUpdateInfo :: Id -> UpdateInfo
1511 getIdUpdateInfo (Id _ _ _ _ _ info) = getInfo info
1513 addIdUpdateInfo :: Id -> UpdateInfo -> Id
1514 addIdUpdateInfo (Id u n ty details prags info) upd_info
1515 = Id u n ty details prags (info `addInfo` upd_info)
1520 getIdArgUsageInfo :: Id -> ArgUsageInfo
1521 getIdArgUsageInfo (Id u n ty info details) = getInfo info
1523 addIdArgUsageInfo :: Id -> ArgUsageInfo -> Id
1524 addIdArgUsageInfo (Id u n ty info details) au_info
1525 = Id u n ty (info `addInfo` au_info) details
1531 getIdFBTypeInfo :: Id -> FBTypeInfo
1532 getIdFBTypeInfo (Id u n ty info details) = getInfo info
1534 addIdFBTypeInfo :: Id -> FBTypeInfo -> Id
1535 addIdFBTypeInfo (Id u n ty info details) upd_info
1536 = Id u n ty (info `addInfo` upd_info) details
1542 getIdSpecialisation :: Id -> SpecEnv
1543 getIdSpecialisation (Id _ _ _ _ _ info) = getInfo info
1545 addIdSpecialisation :: Id -> SpecEnv -> Id
1546 addIdSpecialisation (Id u n ty details prags info) spec_info
1547 = Id u n ty details prags (info `addInfo` spec_info)
1551 Strictness: we snaffle the info out of the IdInfo.
1554 getIdStrictness :: Id -> StrictnessInfo
1556 getIdStrictness (Id _ _ _ _ _ info) = getInfo info
1558 addIdStrictness :: Id -> StrictnessInfo -> Id
1560 addIdStrictness (Id u n ty details prags info) strict_info
1561 = Id u n ty details prags (info `addInfo` strict_info)
1564 %************************************************************************
1566 \subsection[Id-comparison]{Comparison functions for @Id@s}
1568 %************************************************************************
1570 Comparison: equality and ordering---this stuff gets {\em hammered}.
1573 cmpId (Id u1 _ _ _ _ _) (Id u2 _ _ _ _ _) = cmp u1 u2
1574 -- short and very sweet
1578 instance Ord3 (GenId ty) where
1581 instance Eq (GenId ty) where
1582 a == b = case (a `cmp` b) of { EQ_ -> True; _ -> False }
1583 a /= b = case (a `cmp` b) of { EQ_ -> False; _ -> True }
1585 instance Ord (GenId ty) where
1586 a <= b = case (a `cmp` b) of { LT_ -> True; EQ_ -> True; GT__ -> False }
1587 a < b = case (a `cmp` b) of { LT_ -> True; EQ_ -> False; GT__ -> False }
1588 a >= b = case (a `cmp` b) of { LT_ -> False; EQ_ -> True; GT__ -> True }
1589 a > b = case (a `cmp` b) of { LT_ -> False; EQ_ -> False; GT__ -> True }
1590 _tagCmp a b = case (a `cmp` b) of { LT_ -> _LT; EQ_ -> _EQ; GT__ -> _GT }
1593 @cmpId_withSpecDataCon@ ensures that any spectys are taken into
1594 account when comparing two data constructors. We need to do this
1595 because a specialised data constructor has the same Unique as its
1596 unspecialised counterpart.
1599 cmpId_withSpecDataCon :: Id -> Id -> TAG_
1601 cmpId_withSpecDataCon id1 id2
1602 | eq_ids && isDataCon id1 && isDataCon id2
1603 = cmpEqDataCon id1 id2
1608 cmp_ids = cmpId id1 id2
1609 eq_ids = case cmp_ids of { EQ_ -> True; other -> False }
1611 cmpEqDataCon (Id _ _ _ (SpecId _ mtys1 _) _ _) (Id _ _ _ (SpecId _ mtys2 _) _ _)
1612 = panic# "Id.cmpEqDataCon:cmpUniTypeMaybeList mtys1 mtys2"
1614 cmpEqDataCon _ (Id _ _ _ (SpecId _ _ _) _ _) = LT_
1615 cmpEqDataCon (Id _ _ _ (SpecId _ _ _) _ _) _ = GT_
1616 cmpEqDataCon _ _ = EQ_
1619 %************************************************************************
1621 \subsection[Id-other-instances]{Other instance declarations for @Id@s}
1623 %************************************************************************
1626 instance Outputable ty => Outputable (GenId ty) where
1627 ppr sty id = pprId sty id
1629 -- and a SPECIALIZEd one:
1630 instance Outputable {-Id, i.e.:-}(GenId Type) where
1631 ppr sty id = pprId sty id
1633 showId :: PprStyle -> Id -> String
1634 showId sty id = ppShow 80 (pprId sty id)
1637 Default printing code (not used for interfaces):
1639 pprId :: Outputable ty => PprStyle -> GenId ty -> Pretty
1641 pprId sty (Id u n _ _ _ _) = ppr sty n
1642 -- WDP 96/05/06: We can re-elaborate this as we go along...
1646 idUnique (Id u _ _ _ _ _) = u
1648 instance Uniquable (GenId ty) where
1651 instance NamedThing (GenId ty) where
1652 getName this_id@(Id u n _ details _ _) = n
1655 Note: The code generator doesn't carry a @UniqueSupply@, so it uses
1656 the @Uniques@ out of local @Ids@ given to it.
1658 %************************************************************************
1660 \subsection{@IdEnv@s and @IdSet@s}
1662 %************************************************************************
1665 type IdEnv elt = UniqFM elt
1667 nullIdEnv :: IdEnv a
1669 mkIdEnv :: [(GenId ty, a)] -> IdEnv a
1670 unitIdEnv :: GenId ty -> a -> IdEnv a
1671 addOneToIdEnv :: IdEnv a -> GenId ty -> a -> IdEnv a
1672 growIdEnv :: IdEnv a -> IdEnv a -> IdEnv a
1673 growIdEnvList :: IdEnv a -> [(GenId ty, a)] -> IdEnv a
1675 delManyFromIdEnv :: IdEnv a -> [GenId ty] -> IdEnv a
1676 delOneFromIdEnv :: IdEnv a -> GenId ty -> IdEnv a
1677 combineIdEnvs :: (a -> a -> a) -> IdEnv a -> IdEnv a -> IdEnv a
1678 mapIdEnv :: (a -> b) -> IdEnv a -> IdEnv b
1679 modifyIdEnv :: IdEnv a -> (a -> a) -> GenId ty -> IdEnv a
1680 rngIdEnv :: IdEnv a -> [a]
1682 isNullIdEnv :: IdEnv a -> Bool
1683 lookupIdEnv :: IdEnv a -> GenId ty -> Maybe a
1684 lookupNoFailIdEnv :: IdEnv a -> GenId ty -> a
1688 addOneToIdEnv = addToUFM
1689 combineIdEnvs = plusUFM_C
1690 delManyFromIdEnv = delListFromUFM
1691 delOneFromIdEnv = delFromUFM
1693 lookupIdEnv = lookupUFM
1696 nullIdEnv = emptyUFM
1700 growIdEnvList env pairs = plusUFM env (listToUFM pairs)
1701 isNullIdEnv env = sizeUFM env == 0
1702 lookupNoFailIdEnv env id = case (lookupIdEnv env id) of { Just xx -> xx }
1704 -- modifyIdEnv: Look up a thing in the IdEnv, then mash it with the
1705 -- modify function, and put it back.
1707 modifyIdEnv env mangle_fn key
1708 = case (lookupIdEnv env key) of
1710 Just xx -> addOneToIdEnv env key (mangle_fn xx)
1714 type GenIdSet ty = UniqSet (GenId ty)
1715 type IdSet = UniqSet (GenId Type)
1717 emptyIdSet :: GenIdSet ty
1718 intersectIdSets :: GenIdSet ty -> GenIdSet ty -> GenIdSet ty
1719 unionIdSets :: GenIdSet ty -> GenIdSet ty -> GenIdSet ty
1720 unionManyIdSets :: [GenIdSet ty] -> GenIdSet ty
1721 idSetToList :: GenIdSet ty -> [GenId ty]
1722 unitIdSet :: GenId ty -> GenIdSet ty
1723 addOneToIdSet :: GenIdSet ty -> GenId ty -> GenIdSet ty
1724 elementOfIdSet :: GenId ty -> GenIdSet ty -> Bool
1725 minusIdSet :: GenIdSet ty -> GenIdSet ty -> GenIdSet ty
1726 isEmptyIdSet :: GenIdSet ty -> Bool
1727 mkIdSet :: [GenId ty] -> GenIdSet ty
1729 emptyIdSet = emptyUniqSet
1730 unitIdSet = unitUniqSet
1731 addOneToIdSet = addOneToUniqSet
1732 intersectIdSets = intersectUniqSets
1733 unionIdSets = unionUniqSets
1734 unionManyIdSets = unionManyUniqSets
1735 idSetToList = uniqSetToList
1736 elementOfIdSet = elementOfUniqSet
1737 minusIdSet = minusUniqSet
1738 isEmptyIdSet = isEmptyUniqSet
1743 addId, nmbrId :: Id -> NmbrM Id
1745 addId id@(Id u n ty det prag info) nenv@(NmbrEnv ui ut uu idenv tvenv uvenv)
1746 = case (lookupUFM_Directly idenv u) of
1747 Just xx -> _trace "addId: already in map!" $
1750 if toplevelishId id then
1751 _trace "addId: can't add toplevelish!" $
1753 else -- alloc a new unique for this guy
1754 -- and add an entry in the idenv
1755 -- NB: *** KNOT-TYING ***
1757 nenv_plus_id = NmbrEnv (incrUnique ui) ut uu
1758 (addToUFM_Directly idenv u new_id)
1761 (nenv2, new_ty) = nmbrType ty nenv_plus_id
1762 (nenv3, new_det) = nmbr_details det nenv2
1764 new_id = Id ui n new_ty new_det prag info
1768 nmbrId id@(Id u n ty det prag info) nenv@(NmbrEnv ui ut uu idenv tvenv uvenv)
1769 = case (lookupUFM_Directly idenv u) of
1770 Just xx -> (nenv, xx)
1772 if not (toplevelishId id) then
1773 _trace "nmbrId: lookup failed" $
1777 (nenv2, new_ty) = nmbrType ty nenv
1778 (nenv3, new_det) = nmbr_details det nenv2
1780 new_id = Id u n new_ty new_det prag info
1785 nmbr_details :: IdDetails -> NmbrM IdDetails
1787 nmbr_details (DataConId tag marks fields tvs theta arg_tys tc)
1788 = mapNmbr nmbrTyVar tvs `thenNmbr` \ new_tvs ->
1789 mapNmbr nmbrField fields `thenNmbr` \ new_fields ->
1790 mapNmbr nmbr_theta theta `thenNmbr` \ new_theta ->
1791 mapNmbr nmbrType arg_tys `thenNmbr` \ new_arg_tys ->
1792 returnNmbr (DataConId tag marks new_fields new_tvs new_theta new_arg_tys tc)
1795 = --nmbrClass c `thenNmbr` \ new_c ->
1796 nmbrType t `thenNmbr` \ new_t ->
1797 returnNmbr (c, new_t)
1799 -- ToDo:add more cases as needed
1800 nmbr_details other_details = returnNmbr other_details
1803 nmbrField (FieldLabel n ty tag)
1804 = nmbrType ty `thenNmbr` \ new_ty ->
1805 returnNmbr (FieldLabel n new_ty tag)