2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
4 \section[Id]{@Ids@: Value and constructor identifiers}
7 #include "HsVersions.h"
11 GenId(..), -- *naughtily* used in some places (e.g., TcHsSyn)
12 SYN_IE(Id), IdDetails,
14 SYN_IE(ConTag), fIRST_TAG,
15 SYN_IE(DataCon), SYN_IE(DictFun), SYN_IE(DictVar),
38 -- DESTRUCTION (excluding pragmatic info)
53 recordSelectorFieldLabel,
58 cmpId_withSpecDataCon,
64 isConstMethodId_maybe,
67 isDefaultMethodId_maybe,
73 isSuperDictSelId_maybe,
80 unfoldingUnfriendlyId,
86 -- PRINTING and RENUMBERING
97 -- UNFOLDING, ARITY, UPDATE, AND STRICTNESS STUFF (etc)
112 SYN_IE(IdEnv), SYN_IE(GenIdSet), SYN_IE(IdSet),
133 modifyIdEnv_Directly,
143 IMPORT_DELOOPER(IdLoop) -- for paranoia checking
144 IMPORT_DELOOPER(TyLoop) -- for paranoia checking
147 import Class ( classOpString, SYN_IE(Class), GenClass, SYN_IE(ClassOp), GenClassOp )
149 import Maybes ( maybeToBool )
150 import Name ( appendRdr, nameUnique, mkLocalName, isLocalName,
151 isLocallyDefinedName,
152 mkTupleDataConName, mkCompoundName, mkCompoundName2,
153 isLexSym, isLexSpecialSym,
154 isLocallyDefined, changeUnique,
155 getOccName, origName, moduleOf,
156 isExported, ExportFlag(..),
159 import FieldLabel ( fieldLabelName, FieldLabel(..){-instances-} )
160 import PragmaInfo ( PragmaInfo(..) )
161 import PprEnv -- ( SYN_IE(NmbrM), NmbrEnv(..) )
162 import PprType ( getTypeString, typeMaybeString, specMaybeTysSuffix,
168 import SpecEnv ( SpecEnv(..) )
169 import MatchEnv ( MatchEnv )
170 import SrcLoc ( mkBuiltinSrcLoc )
171 import TyCon ( TyCon, mkTupleTyCon, tyConDataCons )
172 import Type ( mkSigmaTy, mkTyVarTys, mkFunTys, mkDictTy,
173 applyTyCon, instantiateTy,
174 tyVarsOfType, applyTypeEnvToTy, typePrimRep,
175 GenType, SYN_IE(ThetaType), SYN_IE(TauType), SYN_IE(Type)
177 import TyVar ( alphaTyVars, isEmptyTyVarSet, SYN_IE(TyVarEnv) )
179 import UniqSet -- practically all of it
180 import Unique ( getBuiltinUniques, pprUnique, showUnique,
182 Unique{-instance Ord3-}
184 import Util ( mapAccumL, nOfThem, zipEqual,
185 panic, panic#, pprPanic, assertPanic
189 Here are the @Id@ and @IdDetails@ datatypes; also see the notes that
192 Every @Id@ has a @Unique@, to uniquify it and for fast comparison, a
193 @Type@, and an @IdInfo@ (non-essential info about it, e.g.,
194 strictness). The essential info about different kinds of @Ids@ is
197 ToDo: possibly cache other stuff in the single-constructor @Id@ type.
201 Unique -- Key for fast comparison
203 ty -- Id's type; used all the time;
204 IdDetails -- Stuff about individual kinds of Ids.
205 PragmaInfo -- Properties of this Id requested by programmer
206 -- eg specialise-me, inline-me
207 IdInfo -- Properties of this Id deduced by compiler
211 data StrictnessMark = MarkedStrict | NotMarkedStrict
215 ---------------- Local values
217 = LocalId Bool -- Local name; mentioned by the user
218 -- True <=> no free type vars
220 | SysLocalId Bool -- Local name; made up by the compiler
223 | SpecPragmaId -- Local name; introduced by the compiler
224 (Maybe Id) -- for explicit specid in pragma
225 Bool -- as for LocalId
227 ---------------- Global values
229 | ImportedId -- Global name (Imported or Implicit); Id imported from an interface
231 | TopLevId -- Global name (LocalDef); Top-level in the orig source pgm
232 -- (not moved there by transformations).
234 -- a TopLevId's type may contain free type variables, if
235 -- the monomorphism restriction applies.
237 ---------------- Data constructors
240 [StrictnessMark] -- Strict args; length = arity
241 [FieldLabel] -- Field labels for this constructor
243 [TyVar] [(Class,Type)] [Type] TyCon
245 -- forall tyvars . theta_ty =>
246 -- unitype_1 -> ... -> unitype_n -> tycon tyvars
248 | TupleConId Int -- Its arity
250 | RecordSelId FieldLabel
252 ---------------- Things to do with overloading
254 | SuperDictSelId -- Selector for superclass dictionary
255 Class -- The class (input dict)
256 Class -- The superclass (result dict)
258 | MethodSelId Class -- An overloaded class operation, with
259 -- a fully polymorphic type. Its code
260 -- just selects a method from the
261 -- dictionary. The class.
262 ClassOp -- The operation
264 -- NB: The IdInfo for a MethodSelId has all the info about its
265 -- related "constant method Ids", which are just
266 -- specialisations of this general one.
268 | DefaultMethodId -- Default method for a particular class op
269 Class -- same class, <blah-blah> info as MethodSelId
270 ClassOp -- (surprise, surprise)
271 Bool -- True <=> I *know* this default method Id
272 -- is a generated one that just says
273 -- `error "No default method for <op>"'.
276 | DictFunId Class -- A DictFun is uniquely identified
277 Type -- by its class and type; this type has free type vars,
278 -- whose identity is irrelevant. Eg Class = Eq
280 -- The "a" is irrelevant. As it is too painful to
281 -- actually do comparisons that way, we kindly supply
282 -- a Unique for that purpose.
283 Module -- module where instance came from
286 | ConstMethodId -- A method which depends only on the type of the
287 -- instance, and not on any further dictionaries etc.
288 Class -- Uniquely identified by:
289 Type -- (class, type, classop) triple
291 Module -- module where instance came from
293 | InstId -- An instance of a dictionary, class operation,
294 -- or overloaded value (Local name)
295 Bool -- as for LocalId
297 | SpecId -- A specialisation of another Id
298 Id -- Id of which this is a specialisation
299 [Maybe Type] -- Types at which it is specialised;
300 -- A "Nothing" says this type ain't relevant.
301 Bool -- True <=> no free type vars; it's not enough
302 -- to know about the unspec version, because
303 -- we may specialise to a type w/ free tyvars
304 -- (i.e., in one of the "Maybe Type" dudes).
306 | WorkerId -- A "worker" for some other Id
307 Id -- Id for which this is a worker
315 DictFunIds are generated from instance decls.
320 instance Foo a => Foo [a] where
323 generates the dict fun id decl
325 dfun.Foo.[*] = \d -> ...
327 The dfun id is uniquely named by the (class, type) pair. Notice, it
328 isn't a (class,tycon) pair any more, because we may get manually or
329 automatically generated specialisations of the instance decl:
331 instance Foo [Int] where
338 The type variables in the name are irrelevant; we print them as stars.
341 Constant method ids are generated from instance decls where
342 there is no context; that is, no dictionaries are needed to
343 construct the method. Example
345 instance Foo Int where
348 Then we get a constant method
353 It is possible, albeit unusual, to have a constant method
354 for an instance decl which has type vars:
356 instance Foo [a] where
360 We get the constant method
364 So a constant method is identified by a class/op/type triple.
365 The type variables in the type are irrelevant.
368 For Ids whose names must be known/deducible in other modules, we have
369 to conjure up their worker's names (and their worker's worker's
370 names... etc) in a known systematic way.
373 %************************************************************************
375 \subsection[Id-documentation]{Documentation}
377 %************************************************************************
381 The @Id@ datatype describes {\em values}. The basic things we want to
382 know: (1)~a value's {\em type} (@idType@ is a very common
383 operation in the compiler); and (2)~what ``flavour'' of value it might
384 be---for example, it can be terribly useful to know that a value is a
388 %----------------------------------------------------------------------
389 \item[@DataConId@:] For the data constructors declared by a @data@
390 declaration. Their type is kept in {\em two} forms---as a regular
391 @Type@ (in the usual place), and also in its constituent pieces (in
392 the ``details''). We are frequently interested in those pieces.
394 %----------------------------------------------------------------------
395 \item[@TupleConId@:] This is just a special shorthand for @DataCons@ for
396 the infinite family of tuples.
398 %----------------------------------------------------------------------
399 \item[@ImportedId@:] These are values defined outside this module.
400 {\em Everything} we want to know about them must be stored here (or in
403 %----------------------------------------------------------------------
404 \item[@TopLevId@:] These are values defined at the top-level in this
405 module; i.e., those which {\em might} be exported (hence, a
406 @Name@). It does {\em not} include those which are moved to the
407 top-level through program transformations.
409 We also guarantee that @TopLevIds@ will {\em stay} at top-level.
410 Theoretically, they could be floated inwards, but there's no known
411 advantage in doing so. This way, we can keep them with the same
412 @Unique@ throughout (no cloning), and, in general, we don't have to be
413 so paranoid about them.
415 In particular, we had the following problem generating an interface:
416 We have to ``stitch together'' info (1)~from the typechecker-produced
417 global-values list (GVE) and (2)~from the STG code [which @Ids@ have
418 what arities]. If the @Uniques@ on the @TopLevIds@ can {\em change}
419 between (1) and (2), you're sunk!
421 %----------------------------------------------------------------------
422 \item[@MethodSelId@:] A selector from a dictionary; it may select either
423 a method or a dictionary for one of the class's superclasses.
425 %----------------------------------------------------------------------
428 @mkDictFunId [a,b..] theta C T@ is the function derived from the
431 instance theta => C (T a b ..) where
434 It builds function @Id@ which maps dictionaries for theta,
435 to a dictionary for C (T a b ..).
437 *Note* that with the ``Mark Jones optimisation'', the theta may
438 include dictionaries for the immediate superclasses of C at the type
441 %----------------------------------------------------------------------
444 %----------------------------------------------------------------------
447 %----------------------------------------------------------------------
450 %----------------------------------------------------------------------
451 \item[@LocalId@:] A purely-local value, e.g., a function argument,
452 something defined in a @where@ clauses, ... --- but which appears in
453 the original program text.
455 %----------------------------------------------------------------------
456 \item[@SysLocalId@:] Same as a @LocalId@, except does {\em not} appear in
457 the original program text; these are introduced by the compiler in
460 %----------------------------------------------------------------------
461 \item[@SpecPragmaId@:] Introduced by the compiler to record
462 Specialisation pragmas. It is dead code which MUST NOT be removed
463 before specialisation.
468 %----------------------------------------------------------------------
471 @DataCons@ @TupleCons@, @Importeds@, @TopLevIds@, @SuperDictSelIds@,
472 @MethodSelIds@, @DictFunIds@, and @DefaultMethodIds@ have the following
476 They have no free type variables, so if you are making a
477 type-variable substitution you don't need to look inside them.
479 They are constants, so they are not free variables. (When the STG
480 machine makes a closure, it puts all the free variables in the
481 closure; the above are not required.)
483 Note that @InstIds@, @Locals@ and @SysLocals@ {\em may} have the above
484 properties, but they may not.
487 %************************************************************************
489 \subsection[Id-general-funs]{General @Id@-related functions}
491 %************************************************************************
494 unsafeGenId2Id :: GenId ty -> Id
495 unsafeGenId2Id (Id u n ty d p i) = Id u n (panic "unsafeGenId2Id:ty") d p i
497 isDataCon id = is_data (unsafeGenId2Id id)
499 is_data (Id _ _ _ (DataConId _ _ _ _ _ _ _) _ _) = True
500 is_data (Id _ _ _ (TupleConId _) _ _) = True
501 is_data (Id _ _ _ (SpecId unspec _ _) _ _) = is_data unspec
502 is_data other = False
505 isTupleCon id = is_tuple (unsafeGenId2Id id)
507 is_tuple (Id _ _ _ (TupleConId _) _ _) = True
508 is_tuple (Id _ _ _ (SpecId unspec _ _) _ _) = is_tuple unspec
509 is_tuple other = False
512 isSpecId_maybe (Id _ _ _ (SpecId unspec ty_maybes _) _ _)
513 = ASSERT(not (maybeToBool (isSpecId_maybe unspec)))
514 Just (unspec, ty_maybes)
515 isSpecId_maybe other_id
518 isSpecPragmaId_maybe (Id _ _ _ (SpecPragmaId specid _) _ _)
520 isSpecPragmaId_maybe other_id
525 @toplevelishId@ tells whether an @Id@ {\em may} be defined in a nested
526 @let(rec)@ (returns @False@), or whether it is {\em sure} to be
527 defined at top level (returns @True@). This is used to decide whether
528 the @Id@ is a candidate free variable. NB: you are only {\em sure}
529 about something if it returns @True@!
532 toplevelishId :: Id -> Bool
533 idHasNoFreeTyVars :: Id -> Bool
535 toplevelishId (Id _ _ _ details _ _)
538 chk (DataConId _ _ _ _ _ _ _) = True
539 chk (TupleConId _) = True
540 chk (RecordSelId _) = True
541 chk ImportedId = True
542 chk TopLevId = True -- NB: see notes
543 chk (SuperDictSelId _ _) = True
544 chk (MethodSelId _ _) = True
545 chk (DefaultMethodId _ _ _) = True
546 chk (DictFunId _ _ _) = True
547 chk (ConstMethodId _ _ _ _) = True
548 chk (SpecId unspec _ _) = toplevelishId unspec
549 -- depends what the unspecialised thing is
550 chk (WorkerId unwrkr) = toplevelishId unwrkr
551 chk (InstId _) = False -- these are local
552 chk (LocalId _) = False
553 chk (SysLocalId _) = False
554 chk (SpecPragmaId _ _) = False
556 idHasNoFreeTyVars (Id _ _ _ details _ info)
559 chk (DataConId _ _ _ _ _ _ _) = True
560 chk (TupleConId _) = True
561 chk (RecordSelId _) = True
562 chk ImportedId = True
564 chk (SuperDictSelId _ _) = True
565 chk (MethodSelId _ _) = True
566 chk (DefaultMethodId _ _ _) = True
567 chk (DictFunId _ _ _) = True
568 chk (ConstMethodId _ _ _ _) = True
569 chk (WorkerId unwrkr) = idHasNoFreeTyVars unwrkr
570 chk (SpecId _ _ no_free_tvs) = no_free_tvs
571 chk (InstId no_free_tvs) = no_free_tvs
572 chk (LocalId no_free_tvs) = no_free_tvs
573 chk (SysLocalId no_free_tvs) = no_free_tvs
574 chk (SpecPragmaId _ no_free_tvs) = no_free_tvs
578 isTopLevId (Id _ _ _ TopLevId _ _) = True
579 isTopLevId other = False
581 isImportedId (Id _ _ _ ImportedId _ _) = True
582 isImportedId other = False
584 isBottomingId (Id _ _ _ _ _ info) = bottomIsGuaranteed (getInfo info)
586 isSysLocalId (Id _ _ _ (SysLocalId _) _ _) = True
587 isSysLocalId other = False
589 isSpecPragmaId (Id _ _ _ (SpecPragmaId _ _) _ _) = True
590 isSpecPragmaId other = False
592 isMethodSelId (Id _ _ _ (MethodSelId _ _) _ _) = True
593 isMethodSelId _ = False
595 isDefaultMethodId (Id _ _ _ (DefaultMethodId _ _ _) _ _) = True
596 isDefaultMethodId other = False
598 isDefaultMethodId_maybe (Id _ _ _ (DefaultMethodId cls clsop err) _ _)
599 = Just (cls, clsop, err)
600 isDefaultMethodId_maybe other = Nothing
602 isDictFunId (Id _ _ _ (DictFunId _ _ _) _ _) = True
603 isDictFunId other = False
605 isConstMethodId (Id _ _ _ (ConstMethodId _ _ _ _) _ _) = True
606 isConstMethodId other = False
608 isConstMethodId_maybe (Id _ _ _ (ConstMethodId cls ty clsop _) _ _)
609 = Just (cls, ty, clsop)
610 isConstMethodId_maybe other = Nothing
612 isSuperDictSelId_maybe (Id _ _ _ (SuperDictSelId c sc) _ _) = Just (c, sc)
613 isSuperDictSelId_maybe other_id = Nothing
615 isWorkerId (Id _ _ _ (WorkerId _) _ _) = True
616 isWorkerId other = False
618 isWrapperId id = workerExists (getIdStrictness id)
623 pprIdInUnfolding :: IdSet -> Id -> Pretty
625 pprIdInUnfolding in_scopes v
630 if v `elementOfUniqSet` in_scopes then
631 pprUnique (idUnique v)
633 -- ubiquitous Ids with special syntax:
634 else if v == nilDataCon then
636 else if isTupleCon v then
637 ppBeside (ppPStr SLIT("_TUP_")) (ppInt (dataConArity v))
639 -- ones to think about:
642 (Id _ _ _ v_details _ _) = v
645 -- these ones must have been exported by their original module
646 ImportedId -> pp_full_name
648 -- these ones' exportedness checked later...
649 TopLevId -> pp_full_name
650 DataConId _ _ _ _ _ _ _ -> pp_full_name
652 RecordSelId lbl -> ppr sty lbl
654 -- class-ish things: class already recorded as "mentioned"
656 -> ppCat [ppPStr SLIT("_SDSEL_"), pp_class c, pp_class sc]
658 -> ppCat [ppPStr SLIT("_METH_"), pp_class c, pp_class_op o]
659 DefaultMethodId c o _
660 -> ppCat [ppPStr SLIT("_DEFM_"), pp_class c, pp_class_op o]
662 -- instance-ish things: should we try to figure out
663 -- *exactly* which extra instances have to be exported? (ToDo)
665 -> ppCat [ppPStr SLIT("_DFUN_"), pp_class c, pp_type t]
666 ConstMethodId c t o _
667 -> ppCat [ppPStr SLIT("_CONSTM_"), pp_class c, pp_class_op o, pp_type t]
669 -- specialisations and workers
670 SpecId unspec ty_maybes _
672 pp = pprIdInUnfolding in_scopes unspec
674 ppCat [ppPStr SLIT("_SPEC_"), pp, ppLbrack,
675 ppIntersperse pp'SP{-'-} (map pp_ty_maybe ty_maybes),
680 pp = pprIdInUnfolding in_scopes unwrkr
682 ppBeside (ppPStr SLIT("_WRKR_ ")) pp
684 -- anything else? we're nae interested
685 other_id -> panic "pprIdInUnfolding:mystery Id"
687 ppr_Unfolding = PprUnfolding (panic "Id:ppr_Unfolding")
691 (OrigName m_str n_str) = origName "Id:ppr_Unfolding" v
694 if isLexSym n_str && not (isLexSpecialSym n_str) then
695 ppBesides [ppLparen, ppPStr n_str, ppRparen]
699 if isPreludeDefined v then
702 ppCat [ppPStr SLIT("_ORIG_"), ppPStr m_str, pp_n]
704 pp_class :: Class -> Pretty
705 pp_class_op :: ClassOp -> Pretty
706 pp_type :: Type -> Pretty
707 pp_ty_maybe :: Maybe Type -> Pretty
709 pp_class clas = ppr ppr_Unfolding clas
710 pp_class_op op = ppr ppr_Unfolding op
712 pp_type t = ppBesides [ppLparen, ppr ppr_Unfolding t, ppRparen]
714 pp_ty_maybe Nothing = ppPStr SLIT("_N_")
715 pp_ty_maybe (Just t) = pp_type t
719 @whatsMentionedInId@ ferrets out the types/classes/instances on which
720 this @Id@ depends. If this Id is to appear in an interface, then
721 those entities had Jolly Well be in scope. Someone else up the
722 call-tree decides that.
727 :: IdSet -- Ids known to be in scope
728 -> Id -- Id being processed
729 -> (Bag Id, Bag TyCon, Bag Class) -- mentioned Ids/TyCons/etc.
731 whatsMentionedInId in_scopes v
736 = getMentionedTyConsAndClassesFromType v_ty
738 result0 id_bag = (id_bag, tycons, clss)
741 = (ids `unionBags` unitBag v, -- we add v to "mentioned"...
742 tcs `unionBags` tycons,
746 if v `elementOfUniqSet` in_scopes then
747 result0 emptyBag -- v not added to "mentioned"
749 -- ones to think about:
752 (Id _ _ _ v_details _ _) = v
755 -- specialisations and workers
756 SpecId unspec ty_maybes _
758 (ids2, tcs2, cs2) = whatsMentionedInId in_scopes unspec
760 result1 ids2 tcs2 cs2
764 (ids2, tcs2, cs2) = whatsMentionedInId in_scopes unwrkr
766 result1 ids2 tcs2 cs2
768 anything_else -> result0 (unitBag v) -- v is added to "mentioned"
772 Tell them who my wrapper function is.
775 myWrapperMaybe :: Id -> Maybe Id
777 myWrapperMaybe (Id _ _ _ (WorkerId my_wrapper) _ _) = Just my_wrapper
778 myWrapperMaybe other_id = Nothing
783 unfoldingUnfriendlyId -- return True iff it is definitely a bad
784 :: Id -- idea to export an unfolding that
785 -> Bool -- mentions this Id. Reason: it cannot
786 -- possibly be seen in another module.
788 unfoldingUnfriendlyId id = not (externallyVisibleId id)
791 @externallyVisibleId@: is it true that another module might be
792 able to ``see'' this Id?
794 We need the @toplevelishId@ check as well as @isExported@ for when we
795 compile instance declarations in the prelude. @DictFunIds@ are
796 ``exported'' if either their class or tycon is exported, but, in
797 compiling the prelude, the compiler may not recognise that as true.
800 externallyVisibleId :: Id -> Bool
802 externallyVisibleId id@(Id _ _ _ details _ _)
803 = if isLocallyDefined id then
804 toplevelishId id && (isExported id || isDataCon id)
805 -- NB: the use of "isExported" is most dodgy;
806 -- We may eventually move to a situation where
807 -- every Id is "externallyVisible", even if the
808 -- module system's namespace control renders it
812 -- if visible here, it must be visible elsewhere, too.
816 idWantsToBeINLINEd :: Id -> Bool
818 idWantsToBeINLINEd (Id _ _ _ _ IWantToBeINLINEd _) = True
819 idWantsToBeINLINEd _ = False
822 For @unlocaliseId@: See the brief commentary in
823 \tr{simplStg/SimplStg.lhs}.
827 unlocaliseId :: FAST_STRING{-modulename-} -> Id -> Maybe Id
829 unlocaliseId mod (Id u fn ty info TopLevId)
830 = Just (Id u (unlocaliseFullName fn) ty info TopLevId)
832 unlocaliseId mod (Id u sn ty info (LocalId no_ftvs))
833 = --false?: ASSERT(no_ftvs)
835 full_name = unlocaliseShortName mod u sn
837 Just (Id u full_name ty info TopLevId)
839 unlocaliseId mod (Id u sn ty info (SysLocalId no_ftvs))
840 = --false?: on PreludeGlaST: ASSERT(no_ftvs)
842 full_name = unlocaliseShortName mod u sn
844 Just (Id u full_name ty info TopLevId)
846 unlocaliseId mod (Id u n ty info (SpecId unspec ty_maybes no_ftvs))
847 = case unlocalise_parent mod u unspec of
849 Just xx -> Just (Id u n ty info (SpecId xx ty_maybes no_ftvs))
851 unlocaliseId mod (Id u n ty info (WorkerId unwrkr))
852 = case unlocalise_parent mod u unwrkr of
854 Just xx -> Just (Id u n ty info (WorkerId xx))
856 unlocaliseId mod (Id u name ty info (InstId no_ftvs))
857 = Just (Id u full_name ty info TopLevId)
858 -- type might be wrong, but it hardly matters
859 -- at this stage (just before printing C) ToDo
861 name = nameOf (origName "Id.unlocaliseId" name)
862 full_name = mkFullName mod name InventedInThisModule ExportAll mkGeneratedSrcLoc
864 unlocaliseId mod other_id = Nothing
867 -- we have to be Very Careful for workers/specs of
870 unlocalise_parent mod uniq (Id _ sn ty info (LocalId no_ftvs))
871 = --false?: ASSERT(no_ftvs)
873 full_name = unlocaliseShortName mod uniq sn
875 Just (Id uniq full_name ty info TopLevId)
877 unlocalise_parent mod uniq (Id _ sn ty info (SysLocalId no_ftvs))
878 = --false?: ASSERT(no_ftvs)
880 full_name = unlocaliseShortName mod uniq sn
882 Just (Id uniq full_name ty info TopLevId)
884 unlocalise_parent mod uniq other_id = unlocaliseId mod other_id
885 -- we're OK otherwise
889 CLAIM (not ASSERTed) for @applyTypeEnvToId@ and @applySubstToId@:
890 `Top-levelish Ids'' cannot have any free type variables, so applying
891 the type-env cannot have any effect. (NB: checked in CoreLint?)
893 The special casing is in @applyTypeEnvToId@, not @apply_to_Id@, as the
894 former ``should be'' the usual crunch point.
897 type TypeEnv = TyVarEnv Type
899 applyTypeEnvToId :: TypeEnv -> Id -> Id
901 applyTypeEnvToId type_env id@(Id _ _ ty _ _ _)
902 | idHasNoFreeTyVars id
905 = apply_to_Id ( \ ty ->
906 applyTypeEnvToTy type_env ty
911 apply_to_Id :: (Type -> Type) -> Id -> Id
913 apply_to_Id ty_fn (Id u n ty details prag info)
917 Id u n new_ty (apply_to_details details) prag (apply_to_IdInfo ty_fn info)
919 apply_to_details (SpecId unspec ty_maybes no_ftvs)
921 new_unspec = apply_to_Id ty_fn unspec
922 new_maybes = map apply_to_maybe ty_maybes
924 SpecId new_unspec new_maybes (no_free_tvs ty)
925 -- ToDo: gratuitous recalc no_ftvs???? (also InstId)
927 apply_to_maybe Nothing = Nothing
928 apply_to_maybe (Just ty) = Just (ty_fn ty)
930 apply_to_details (WorkerId unwrkr)
932 new_unwrkr = apply_to_Id ty_fn unwrkr
936 apply_to_details other = other
939 Sadly, I don't think the one using the magic typechecker substitution
940 can be done with @apply_to_Id@. Here we go....
942 Strictness is very important here. We can't leave behind thunks
943 with pointers to the substitution: it {\em must} be single-threaded.
947 applySubstToId :: Subst -> Id -> (Subst, Id)
949 applySubstToId subst id@(Id u n ty info details)
950 -- *cannot* have a "idHasNoFreeTyVars" get-out clause
951 -- because, in the typechecker, we are still
952 -- *concocting* the types.
953 = case (applySubstToTy subst ty) of { (s2, new_ty) ->
954 case (applySubstToIdInfo s2 info) of { (s3, new_info) ->
955 case (apply_to_details s3 new_ty details) of { (s4, new_details) ->
956 (s4, Id u n new_ty new_info new_details) }}}
958 apply_to_details subst _ (InstId inst no_ftvs)
959 = case (applySubstToInst subst inst) of { (s2, new_inst) ->
960 (s2, InstId new_inst no_ftvs{-ToDo:right???-}) }
962 apply_to_details subst new_ty (SpecId unspec ty_maybes _)
963 = case (applySubstToId subst unspec) of { (s2, new_unspec) ->
964 case (mapAccumL apply_to_maybe s2 ty_maybes) of { (s3, new_maybes) ->
965 (s3, SpecId new_unspec new_maybes (no_free_tvs new_ty)) }}
966 -- NB: recalc no_ftvs (I think it's necessary (?) WDP 95/04)
968 apply_to_maybe subst Nothing = (subst, Nothing)
969 apply_to_maybe subst (Just ty)
970 = case (applySubstToTy subst ty) of { (s2, new_ty) ->
973 apply_to_details subst _ (WorkerId unwrkr)
974 = case (applySubstToId subst unwrkr) of { (s2, new_unwrkr) ->
975 (s2, WorkerId new_unwrkr) }
977 apply_to_details subst _ other = (subst, other)
981 %************************************************************************
983 \subsection[Id-type-funs]{Type-related @Id@ functions}
985 %************************************************************************
988 idType :: GenId ty -> ty
990 idType (Id _ _ ty _ _ _) = ty
995 getMentionedTyConsAndClassesFromId :: Id -> (Bag TyCon, Bag Class)
997 getMentionedTyConsAndClassesFromId id
998 = getMentionedTyConsAndClassesFromType (idType id)
1003 idPrimRep i = typePrimRep (idType i)
1008 getInstIdModule (Id _ _ _ (DictFunId _ _ mod)) = mod
1009 getInstIdModule (Id _ _ _ (ConstMethodId _ _ _ mod)) = mod
1010 getInstIdModule other = panic "Id:getInstIdModule"
1014 %************************************************************************
1016 \subsection[Id-overloading]{Functions related to overloading}
1018 %************************************************************************
1021 mkSuperDictSelId u c sc ty info
1022 = mk_classy_id (SuperDictSelId c sc) SLIT("sdsel") (Left (origName "mkSuperDictSelId" sc)) u c ty info
1024 mkMethodSelId u rec_c op ty info
1025 = mk_classy_id (MethodSelId rec_c op) SLIT("meth") (Right (classOpString op)) u rec_c ty info
1027 mkDefaultMethodId u rec_c op gen ty info
1028 = mk_classy_id (DefaultMethodId rec_c op gen) SLIT("defm") (Right (classOpString op)) u rec_c ty info
1030 mk_classy_id details str op_str u rec_c ty info
1031 = Id u n ty details NoPragmaInfo info
1033 cname = getName rec_c -- we get other info out of here
1034 cname_orig = origName "mk_classy_id" cname
1035 cmod = moduleOf cname_orig
1037 n = mkCompoundName u cmod str [Left cname_orig, op_str] cname
1039 mkDictFunId u c ity full_ty from_here locn mod info
1040 = Id u n full_ty (DictFunId c ity mod) NoPragmaInfo info
1042 n = mkCompoundName2 u mod SLIT("dfun") (Left (origName "mkDictFunId" c) : renum_type_string full_ty ity) from_here locn
1044 mkConstMethodId u c op ity full_ty from_here locn mod info
1045 = Id u n full_ty (ConstMethodId c ity op mod) NoPragmaInfo info
1047 n = mkCompoundName2 u mod SLIT("const") (Left (origName "mkConstMethodId" c) : Right (classOpString op) : renum_type_string full_ty ity) from_here locn
1049 renum_type_string full_ty ity
1051 nmbrType full_ty `thenNmbr` \ _ -> -- so all the tyvars get added to renumbering...
1052 nmbrType ity `thenNmbr` \ rn_ity ->
1053 returnNmbr (getTypeString rn_ity)
1056 mkWorkerId u unwrkr ty info
1057 = Id u n ty (WorkerId unwrkr) NoPragmaInfo info
1059 unwrkr_name = getName unwrkr
1060 unwrkr_orig = trace "mkWorkerId:origName:" $ origName "mkWorkerId" unwrkr_name
1061 umod = moduleOf unwrkr_orig
1063 n = mkCompoundName u umod SLIT("wrk") [Left unwrkr_orig] unwrkr_name
1065 mkInstId u ty name = Id u (changeUnique name u) ty (InstId (no_free_tvs ty)) NoPragmaInfo noIdInfo
1068 getConstMethodId clas op ty
1069 = -- constant-method info is hidden in the IdInfo of
1070 -- the class-op id (as mentioned up above).
1072 sel_id = getMethodSelId clas op
1074 case (lookupConstMethodId (getIdSpecialisation sel_id) ty) of
1076 Nothing -> pprError "ERROR: getConstMethodId:" (ppAboves [
1077 ppCat [ppr PprDebug ty, ppr PprDebug ops, ppr PprDebug op_ids,
1078 ppr PprDebug sel_id],
1079 ppStr "(This can arise if an interface pragma refers to an instance",
1080 ppStr "but there is no imported interface which *defines* that instance.",
1081 ppStr "The info above, however ugly, should indicate what else you need to import."
1086 %************************************************************************
1088 \subsection[local-funs]{@LocalId@-related functions}
1090 %************************************************************************
1093 mkImported n ty info = Id (nameUnique n) n ty ImportedId NoPragmaInfo info
1096 updateIdType :: Id -> Type -> Id
1097 updateIdType (Id u n _ info details) ty = Id u n ty info details
1102 type MyTy a b = GenType (GenTyVar a) b
1103 type MyId a b = GenId (MyTy a b)
1105 no_free_tvs ty = isEmptyTyVarSet (tyVarsOfType ty)
1107 -- SysLocal: for an Id being created by the compiler out of thin air...
1108 -- UserLocal: an Id with a name the user might recognize...
1109 mkSysLocal, mkUserLocal :: FAST_STRING -> Unique -> MyTy a b -> SrcLoc -> MyId a b
1111 mkSysLocal str uniq ty loc
1112 = Id uniq (mkLocalName uniq str True{-emph uniq-} loc) ty (SysLocalId (no_free_tvs ty)) NoPragmaInfo noIdInfo
1114 mkUserLocal str uniq ty loc
1115 = Id uniq (mkLocalName uniq str False{-emph name-} loc) ty (LocalId (no_free_tvs ty)) NoPragmaInfo noIdInfo
1117 -- mkUserId builds a local or top-level Id, depending on the name given
1118 mkUserId :: Name -> MyTy a b -> PragmaInfo -> MyId a b
1119 mkUserId name ty pragma_info
1121 = Id (nameUnique name) name ty (LocalId (no_free_tvs ty)) pragma_info noIdInfo
1123 = Id (nameUnique name) name ty
1124 (if isLocallyDefinedName name then TopLevId else ImportedId)
1125 pragma_info noIdInfo
1132 -- for a SpecPragmaId being created by the compiler out of thin air...
1133 mkSpecPragmaId :: FAST_STRING -> Unique -> Type -> Maybe Id -> SrcLoc -> Id
1134 mkSpecPragmaId str uniq ty specid loc
1135 = Id uniq (mkShortName str loc) ty noIdInfo (SpecPragmaId specid (no_free_tvs ty))
1138 mkSpecId u unspec ty_maybes ty info
1139 = ASSERT(not (maybeToBool (isSpecId_maybe unspec)))
1140 Id u n ty info (SpecId unspec ty_maybes (no_free_tvs ty))
1142 -- Specialised version of constructor: only used in STG and code generation
1143 -- Note: The specialsied Id has the same unique as the unspeced Id
1145 mkSameSpecCon ty_maybes unspec@(Id u n ty info details)
1146 = ASSERT(isDataCon unspec)
1147 ASSERT(not (maybeToBool (isSpecId_maybe unspec)))
1148 Id u n new_ty info (SpecId unspec ty_maybes (no_free_tvs new_ty))
1150 new_ty = specialiseTy ty ty_maybes 0
1152 localiseId :: Id -> Id
1153 localiseId id@(Id u n ty info details)
1154 = Id u (mkShortName name loc) ty info (LocalId (no_free_tvs ty))
1156 name = getOccName id
1160 mkIdWithNewUniq :: Id -> Unique -> Id
1162 mkIdWithNewUniq (Id _ n ty details prag info) u
1163 = Id u (changeUnique n u) ty details prag info
1166 Make some local @Ids@ for a template @CoreExpr@. These have bogus
1167 @Uniques@, but that's OK because the templates are supposed to be
1168 instantiated before use.
1170 mkTemplateLocals :: [Type] -> [Id]
1171 mkTemplateLocals tys
1172 = zipWith (\ u -> \ ty -> mkSysLocal SLIT("tpl") u ty mkBuiltinSrcLoc)
1173 (getBuiltinUniques (length tys))
1178 getIdInfo :: GenId ty -> IdInfo
1179 getPragmaInfo :: GenId ty -> PragmaInfo
1181 getIdInfo (Id _ _ _ _ _ info) = info
1182 getPragmaInfo (Id _ _ _ _ info _) = info
1184 replaceIdInfo :: Id -> IdInfo -> Id
1186 replaceIdInfo (Id u n ty details pinfo _) info = Id u n ty details pinfo info
1189 selectIdInfoForSpecId :: Id -> IdInfo
1190 selectIdInfoForSpecId unspec
1191 = ASSERT(not (maybeToBool (isSpecId_maybe unspec)))
1192 noIdInfo `addInfo_UF` getIdUnfolding unspec
1196 %************************************************************************
1198 \subsection[Id-arities]{Arity-related functions}
1200 %************************************************************************
1202 For locally-defined Ids, the code generator maintains its own notion
1203 of their arities; so it should not be asking... (but other things
1204 besides the code-generator need arity info!)
1207 getIdArity :: Id -> ArityInfo
1208 getIdArity id@(Id _ _ _ _ _ id_info)
1209 = --ASSERT( not (isDataCon id))
1212 dataConArity, dataConNumFields :: DataCon -> Int
1214 dataConArity id@(Id _ _ _ _ _ id_info)
1215 = ASSERT(isDataCon id)
1216 case (arityMaybe (getInfo id_info)) of
1218 Nothing -> pprPanic "dataConArity:Nothing:" (pprId PprDebug id)
1221 = ASSERT(isDataCon id)
1222 case (dataConSig id) of { (_, _, arg_tys, _) ->
1225 isNullaryDataCon con = dataConNumFields con == 0 -- function of convenience
1227 addIdArity :: Id -> Int -> Id
1228 addIdArity (Id u n ty details pinfo info) arity
1229 = Id u n ty details pinfo (info `addInfo` (mkArityInfo arity))
1232 %************************************************************************
1234 \subsection[constructor-funs]{@DataCon@-related functions (incl.~tuples)}
1236 %************************************************************************
1240 -> [StrictnessMark] -> [FieldLabel]
1241 -> [TyVar] -> ThetaType -> [TauType] -> TyCon
1244 -- can get the tag and all the pieces of the type from the Type
1246 mkDataCon n stricts fields tvs ctxt args_tys tycon
1247 = ASSERT(length stricts == length args_tys)
1250 -- NB: data_con self-recursion; should be OK as tags are not
1251 -- looked at until late in the game.
1256 (DataConId data_con_tag stricts fields tvs ctxt args_tys tycon)
1257 IWantToBeINLINEd -- Always inline constructors if possible
1260 data_con_tag = position_within fIRST_TAG data_con_family
1262 data_con_family = tyConDataCons tycon
1264 position_within :: Int -> [Id] -> Int
1266 position_within acc (c:cs)
1267 = if c == data_con then acc else position_within (acc+1) cs
1269 position_within acc []
1270 = panic "mkDataCon: con not found in family"
1274 = mkSigmaTy tvs ctxt
1275 (mkFunTys args_tys (applyTyCon tycon (mkTyVarTys tvs)))
1277 datacon_info = noIdInfo `addInfo_UF` unfolding
1278 `addInfo` mkArityInfo arity
1279 --ToDo: `addInfo` specenv
1281 arity = length ctxt + length args_tys
1288 -- else -- do some business...
1290 (tyvars, dict_vars, vars) = mk_uf_bits tvs ctxt args_tys tycon
1291 tyvar_tys = mkTyVarTys tyvars
1293 case (Con data_con tyvar_tys [VarArg v | v <- vars]) of { plain_Con ->
1295 mkUnfolding EssentialUnfolding -- for data constructors
1296 (mkLam tyvars (dict_vars ++ vars) plain_Con)
1299 mk_uf_bits tvs ctxt arg_tys tycon
1301 (inst_env, tyvars, tyvar_tys)
1302 = instantiateTyVarTemplates tvs
1305 -- the "context" and "arg_tys" have TyVarTemplates in them, so
1306 -- we instantiate those types to have the right TyVars in them
1308 case (map (instantiateTauTy inst_env) (map ctxt_ty ctxt))
1309 of { inst_dict_tys ->
1310 case (map (instantiateTauTy inst_env) arg_tys) of { inst_arg_tys ->
1312 -- We can only have **ONE** call to mkTemplateLocals here;
1313 -- otherwise, we get two blobs of locals w/ mixed-up Uniques
1314 -- (Mega-Sigh) [ToDo]
1315 case (mkTemplateLocals (inst_dict_tys ++ inst_arg_tys)) of { all_vars ->
1317 case (splitAt (length ctxt) all_vars) of { (dict_vars, vars) ->
1319 (tyvars, dict_vars, vars)
1322 -- these are really dubious Types, but they are only to make the
1323 -- binders for the lambdas for tossed-away dicts.
1324 ctxt_ty (clas, ty) = mkDictTy clas ty
1329 mkTupleCon :: Arity -> Id
1332 = Id unique n ty (TupleConId arity) NoPragmaInfo tuplecon_info
1334 n = mkTupleDataConName arity
1336 ty = mkSigmaTy tyvars []
1337 (mkFunTys tyvar_tys (applyTyCon tycon tyvar_tys))
1338 tycon = mkTupleTyCon arity
1339 tyvars = take arity alphaTyVars
1340 tyvar_tys = mkTyVarTys tyvars
1343 = noIdInfo `addInfo_UF` unfolding
1344 `addInfo` mkArityInfo arity
1345 --LATER:? `addInfo` panic "Id:mkTupleCon:pcGenerateTupleSpecs arity ty"
1352 -- else -- do some business...
1354 (tyvars, dict_vars, vars) = mk_uf_bits arity
1355 tyvar_tys = mkTyVarTys tyvars
1357 case (Con data_con tyvar_tys [VarArg v | v <- vars]) of { plain_Con ->
1359 EssentialUnfolding -- data constructors
1360 (mkLam tyvars (dict_vars ++ vars) plain_Con) }
1363 = case (mkTemplateLocals tyvar_tys) of { vars ->
1364 (tyvars, [], vars) }
1366 tyvar_tmpls = take arity alphaTyVars
1367 (_, tyvars, tyvar_tys) = instantiateTyVarTemplates tyvar_tmpls (map uniqueOf tyvar_tmpls)
1371 fIRST_TAG = 1 -- Tags allocated from here for real constructors
1375 dataConTag :: DataCon -> ConTag -- will panic if not a DataCon
1376 dataConTag (Id _ _ _ (DataConId tag _ _ _ _ _ _) _ _) = tag
1377 dataConTag (Id _ _ _ (TupleConId _) _ _) = fIRST_TAG
1378 dataConTag (Id _ _ _ (SpecId unspec _ _) _ _) = dataConTag unspec
1380 dataConTyCon :: DataCon -> TyCon -- will panic if not a DataCon
1381 dataConTyCon (Id _ _ _ (DataConId _ _ _ _ _ _ tycon) _ _) = tycon
1382 dataConTyCon (Id _ _ _ (TupleConId a) _ _) = mkTupleTyCon a
1384 dataConSig :: DataCon -> ([TyVar], ThetaType, [TauType], TyCon)
1385 -- will panic if not a DataCon
1387 dataConSig (Id _ _ _ (DataConId _ _ _ tyvars theta_ty arg_tys tycon) _ _)
1388 = (tyvars, theta_ty, arg_tys, tycon)
1390 dataConSig (Id _ _ _ (TupleConId arity) _ _)
1391 = (tyvars, [], tyvar_tys, mkTupleTyCon arity)
1393 tyvars = take arity alphaTyVars
1394 tyvar_tys = mkTyVarTys tyvars
1396 dataConFieldLabels :: DataCon -> [FieldLabel]
1397 dataConFieldLabels (Id _ _ _ (DataConId _ _ fields _ _ _ _) _ _) = fields
1398 dataConFieldLabels (Id _ _ _ (TupleConId _) _ _) = []
1400 dataConStrictMarks :: DataCon -> [StrictnessMark]
1401 dataConStrictMarks (Id _ _ _ (DataConId _ stricts _ _ _ _ _) _ _) = stricts
1402 dataConStrictMarks (Id _ _ _ (TupleConId arity) _ _)
1403 = nOfThem arity NotMarkedStrict
1405 dataConRawArgTys :: DataCon -> [TauType] -- a function of convenience
1406 dataConRawArgTys con = case (dataConSig con) of { (_,_, arg_tys,_) -> arg_tys }
1408 dataConArgTys :: DataCon
1409 -> [Type] -- Instantiated at these types
1410 -> [Type] -- Needs arguments of these types
1411 dataConArgTys con_id inst_tys
1412 = map (instantiateTy tenv) arg_tys
1414 (tyvars, _, arg_tys, _) = dataConSig con_id
1415 tenv = zipEqual "dataConArgTys" tyvars inst_tys
1419 mkRecordSelId field_label selector_ty
1420 = Id (nameUnique name)
1423 (RecordSelId field_label)
1427 name = fieldLabelName field_label
1429 recordSelectorFieldLabel :: Id -> FieldLabel
1430 recordSelectorFieldLabel (Id _ _ _ (RecordSelId lbl) _ _) = lbl
1434 Data type declarations are of the form:
1436 data Foo a b = C1 ... | C2 ... | ... | Cn ...
1438 For each constructor @Ci@, we want to generate a curried function; so, e.g., for
1439 @C1 x y z@, we want a function binding:
1441 fun_C1 = /\ a -> /\ b -> \ [x, y, z] -> Con C1 [a, b] [x, y, z]
1443 Notice the ``big lambdas'' and type arguments to @Con@---we are producing
1444 2nd-order polymorphic lambda calculus with explicit types.
1446 %************************************************************************
1448 \subsection[unfolding-Ids]{Functions related to @Ids@' unfoldings}
1450 %************************************************************************
1452 @getIdUnfolding@ takes a @Id@ (we are discussing the @DataCon@ case)
1453 and generates an @Unfolding@. The @Ids@ and @TyVars@ don't really
1454 have to be new, because we are only producing a template.
1456 ToDo: what if @DataConId@'s type has a context (haven't thought about it
1459 Note: @getDataConUnfolding@ is a ``poor man's'' version---it is NOT
1460 EXPORTED. It just returns the binders (@TyVars@ and @Ids@) [in the
1461 example above: a, b, and x, y, z], which is enough (in the important
1462 \tr{DsExpr} case). (The middle set of @Ids@ is binders for any
1463 dictionaries, in the even of an overloaded data-constructor---none at
1467 getIdUnfolding :: Id -> Unfolding
1469 getIdUnfolding (Id _ _ _ _ _ info) = getInfo_UF info
1472 addIdUnfolding :: Id -> Unfolding -> Id
1473 addIdUnfolding id@(Id u n ty info details) unfold_details
1475 case (isLocallyDefined id, unfold_details) of
1476 (_, NoUnfolding) -> True
1477 (True, IWantToBeINLINEd _) -> True
1478 (False, IWantToBeINLINEd _) -> False -- v bad
1482 Id u n ty (info `addInfo_UF` unfold_details) details
1486 In generating selector functions (take a dictionary, give back one
1487 component...), we need to what out for the nothing-to-select cases (in
1488 which case the ``selector'' is just an identity function):
1490 class Eq a => Foo a { } # the superdict selector for "Eq"
1492 class Foo a { op :: Complex b => c -> b -> a }
1493 # the method selector for "op";
1494 # note local polymorphism...
1497 %************************************************************************
1499 \subsection[IdInfo-funs]{Functions related to @Ids@' @IdInfos@}
1501 %************************************************************************
1504 getIdDemandInfo :: Id -> DemandInfo
1505 getIdDemandInfo (Id _ _ _ _ _ info) = getInfo info
1507 addIdDemandInfo :: Id -> DemandInfo -> Id
1508 addIdDemandInfo (Id u n ty details prags info) demand_info
1509 = Id u n ty details prags (info `addInfo` demand_info)
1513 getIdUpdateInfo :: Id -> UpdateInfo
1514 getIdUpdateInfo (Id _ _ _ _ _ info) = getInfo info
1516 addIdUpdateInfo :: Id -> UpdateInfo -> Id
1517 addIdUpdateInfo (Id u n ty details prags info) upd_info
1518 = Id u n ty details prags (info `addInfo` upd_info)
1523 getIdArgUsageInfo :: Id -> ArgUsageInfo
1524 getIdArgUsageInfo (Id u n ty info details) = getInfo info
1526 addIdArgUsageInfo :: Id -> ArgUsageInfo -> Id
1527 addIdArgUsageInfo (Id u n ty info details) au_info
1528 = Id u n ty (info `addInfo` au_info) details
1534 getIdFBTypeInfo :: Id -> FBTypeInfo
1535 getIdFBTypeInfo (Id u n ty info details) = getInfo info
1537 addIdFBTypeInfo :: Id -> FBTypeInfo -> Id
1538 addIdFBTypeInfo (Id u n ty info details) upd_info
1539 = Id u n ty (info `addInfo` upd_info) details
1544 getIdSpecialisation :: Id -> SpecEnv
1545 getIdSpecialisation (Id _ _ _ _ _ info) = getInfo info
1547 addIdSpecialisation :: Id -> SpecEnv -> Id
1548 addIdSpecialisation (Id u n ty details prags info) spec_info
1549 = Id u n ty details prags (info `addInfo` spec_info)
1552 Strictness: we snaffle the info out of the IdInfo.
1555 getIdStrictness :: Id -> StrictnessInfo
1557 getIdStrictness (Id _ _ _ _ _ info) = getInfo info
1559 addIdStrictness :: Id -> StrictnessInfo -> Id
1561 addIdStrictness (Id u n ty details prags info) strict_info
1562 = Id u n ty details prags (info `addInfo` strict_info)
1565 %************************************************************************
1567 \subsection[Id-comparison]{Comparison functions for @Id@s}
1569 %************************************************************************
1571 Comparison: equality and ordering---this stuff gets {\em hammered}.
1574 cmpId (Id u1 _ _ _ _ _) (Id u2 _ _ _ _ _) = cmp u1 u2
1575 -- short and very sweet
1579 instance Ord3 (GenId ty) where
1582 instance Eq (GenId ty) where
1583 a == b = case (a `cmp` b) of { EQ_ -> True; _ -> False }
1584 a /= b = case (a `cmp` b) of { EQ_ -> False; _ -> True }
1586 instance Ord (GenId ty) where
1587 a <= b = case (a `cmp` b) of { LT_ -> True; EQ_ -> True; GT__ -> False }
1588 a < b = case (a `cmp` b) of { LT_ -> True; EQ_ -> False; GT__ -> False }
1589 a >= b = case (a `cmp` b) of { LT_ -> False; EQ_ -> True; GT__ -> True }
1590 a > b = case (a `cmp` b) of { LT_ -> False; EQ_ -> False; GT__ -> True }
1591 _tagCmp a b = case (a `cmp` b) of { LT_ -> _LT; EQ_ -> _EQ; GT__ -> _GT }
1594 @cmpId_withSpecDataCon@ ensures that any spectys are taken into
1595 account when comparing two data constructors. We need to do this
1596 because a specialised data constructor has the same Unique as its
1597 unspecialised counterpart.
1600 cmpId_withSpecDataCon :: Id -> Id -> TAG_
1602 cmpId_withSpecDataCon id1 id2
1603 | eq_ids && isDataCon id1 && isDataCon id2
1604 = cmpEqDataCon id1 id2
1609 cmp_ids = cmpId id1 id2
1610 eq_ids = case cmp_ids of { EQ_ -> True; other -> False }
1612 cmpEqDataCon (Id _ _ _ (SpecId _ mtys1 _) _ _) (Id _ _ _ (SpecId _ mtys2 _) _ _)
1613 = panic# "Id.cmpEqDataCon:cmpUniTypeMaybeList mtys1 mtys2"
1615 cmpEqDataCon _ (Id _ _ _ (SpecId _ _ _) _ _) = LT_
1616 cmpEqDataCon (Id _ _ _ (SpecId _ _ _) _ _) _ = GT_
1617 cmpEqDataCon _ _ = EQ_
1620 %************************************************************************
1622 \subsection[Id-other-instances]{Other instance declarations for @Id@s}
1624 %************************************************************************
1627 instance Outputable ty => Outputable (GenId ty) where
1628 ppr sty id = pprId sty id
1630 -- and a SPECIALIZEd one:
1631 instance Outputable {-Id, i.e.:-}(GenId Type) where
1632 ppr sty id = pprId sty id
1634 showId :: PprStyle -> Id -> String
1635 showId sty id = ppShow 80 (pprId sty id)
1638 Default printing code (not used for interfaces):
1640 pprId :: Outputable ty => PprStyle -> GenId ty -> Pretty
1642 pprId sty (Id u n _ _ _ _) = ppr sty n
1643 -- WDP 96/05/06: We can re-elaborate this as we go along...
1647 idUnique (Id u _ _ _ _ _) = u
1649 instance Uniquable (GenId ty) where
1652 instance NamedThing (GenId ty) where
1653 getName this_id@(Id u n _ details _ _) = n
1656 Note: The code generator doesn't carry a @UniqueSupply@, so it uses
1657 the @Uniques@ out of local @Ids@ given to it.
1659 %************************************************************************
1661 \subsection{@IdEnv@s and @IdSet@s}
1663 %************************************************************************
1666 type IdEnv elt = UniqFM elt
1668 nullIdEnv :: IdEnv a
1670 mkIdEnv :: [(GenId ty, a)] -> IdEnv a
1671 unitIdEnv :: GenId ty -> a -> IdEnv a
1672 addOneToIdEnv :: IdEnv a -> GenId ty -> a -> IdEnv a
1673 growIdEnv :: IdEnv a -> IdEnv a -> IdEnv a
1674 growIdEnvList :: IdEnv a -> [(GenId ty, a)] -> IdEnv a
1676 delManyFromIdEnv :: IdEnv a -> [GenId ty] -> IdEnv a
1677 delOneFromIdEnv :: IdEnv a -> GenId ty -> IdEnv a
1678 combineIdEnvs :: (a -> a -> a) -> IdEnv a -> IdEnv a -> IdEnv a
1679 mapIdEnv :: (a -> b) -> IdEnv a -> IdEnv b
1680 modifyIdEnv :: (a -> a) -> IdEnv a -> GenId ty -> IdEnv a
1681 rngIdEnv :: IdEnv a -> [a]
1683 isNullIdEnv :: IdEnv a -> Bool
1684 lookupIdEnv :: IdEnv a -> GenId ty -> Maybe a
1685 lookupNoFailIdEnv :: IdEnv a -> GenId ty -> a
1689 addOneToIdEnv = addToUFM
1690 combineIdEnvs = plusUFM_C
1691 delManyFromIdEnv = delListFromUFM
1692 delOneFromIdEnv = delFromUFM
1694 lookupIdEnv = lookupUFM
1697 nullIdEnv = emptyUFM
1701 growIdEnvList env pairs = plusUFM env (listToUFM pairs)
1702 isNullIdEnv env = sizeUFM env == 0
1703 lookupNoFailIdEnv env id = case (lookupIdEnv env id) of { Just xx -> xx }
1705 -- modifyIdEnv: Look up a thing in the IdEnv, then mash it with the
1706 -- modify function, and put it back.
1708 modifyIdEnv mangle_fn env key
1709 = case (lookupIdEnv env key) of
1711 Just xx -> addOneToIdEnv env key (mangle_fn xx)
1713 modifyIdEnv_Directly mangle_fn env key
1714 = case (lookupUFM_Directly env key) of
1716 Just xx -> addToUFM_Directly env key (mangle_fn xx)
1720 type GenIdSet ty = UniqSet (GenId ty)
1721 type IdSet = UniqSet (GenId Type)
1723 emptyIdSet :: GenIdSet ty
1724 intersectIdSets :: GenIdSet ty -> GenIdSet ty -> GenIdSet ty
1725 unionIdSets :: GenIdSet ty -> GenIdSet ty -> GenIdSet ty
1726 unionManyIdSets :: [GenIdSet ty] -> GenIdSet ty
1727 idSetToList :: GenIdSet ty -> [GenId ty]
1728 unitIdSet :: GenId ty -> GenIdSet ty
1729 addOneToIdSet :: GenIdSet ty -> GenId ty -> GenIdSet ty
1730 elementOfIdSet :: GenId ty -> GenIdSet ty -> Bool
1731 minusIdSet :: GenIdSet ty -> GenIdSet ty -> GenIdSet ty
1732 isEmptyIdSet :: GenIdSet ty -> Bool
1733 mkIdSet :: [GenId ty] -> GenIdSet ty
1735 emptyIdSet = emptyUniqSet
1736 unitIdSet = unitUniqSet
1737 addOneToIdSet = addOneToUniqSet
1738 intersectIdSets = intersectUniqSets
1739 unionIdSets = unionUniqSets
1740 unionManyIdSets = unionManyUniqSets
1741 idSetToList = uniqSetToList
1742 elementOfIdSet = elementOfUniqSet
1743 minusIdSet = minusUniqSet
1744 isEmptyIdSet = isEmptyUniqSet
1749 addId, nmbrId, nmbrDataCon :: Id -> NmbrM Id
1751 addId id@(Id u n ty det prag info) nenv@(NmbrEnv ui ut uu idenv tvenv uvenv)
1752 = case (lookupUFM_Directly idenv u) of
1753 Just xx -> trace "addId: already in map!" $
1756 if toplevelishId id then
1757 trace "addId: can't add toplevelish!" $
1759 else -- alloc a new unique for this guy
1760 -- and add an entry in the idenv
1761 -- NB: *** KNOT-TYING ***
1763 nenv_plus_id = NmbrEnv (incrUnique ui) ut uu
1764 (addToUFM_Directly idenv u new_id)
1767 (nenv2, new_ty) = nmbrType ty nenv_plus_id
1768 (nenv3, new_det) = nmbr_details det nenv2
1770 new_id = Id ui n new_ty new_det prag info
1774 nmbrId id@(Id u n ty det prag info) nenv@(NmbrEnv ui ut uu idenv tvenv uvenv)
1775 = case (lookupUFM_Directly idenv u) of
1776 Just xx -> (nenv, xx)
1778 if not (toplevelishId id) then
1779 trace "nmbrId: lookup failed" $
1783 (nenv2, new_ty) = nmbrType ty nenv
1784 (nenv3, new_det) = nmbr_details det nenv2
1786 new_id = Id u n new_ty new_det prag info
1790 -- used when renumbering TyCons to produce data decls...
1791 nmbrDataCon id@(Id _ _ _ (TupleConId _) _ _) nenv
1792 = (nenv, id) -- nothing to do for tuples
1794 nmbrDataCon id@(Id u n ty (DataConId tag marks fields tvs theta arg_tys tc) prag info) nenv@(NmbrEnv ui ut uu idenv tvenv uvenv)
1795 = case (lookupUFM_Directly idenv u) of
1796 Just xx -> trace "nmbrDataCon: in env???\n" (nenv, xx)
1799 (nenv2, new_fields) = (mapNmbr nmbrField fields) nenv
1800 (nenv3, new_arg_tys) = (mapNmbr nmbrType arg_tys) nenv2
1802 new_det = DataConId tag marks new_fields (bottom "tvs") (bottom "theta") new_arg_tys tc
1803 new_id = Id u n (bottom "ty") new_det prag info
1807 bottom msg = panic ("nmbrDataCon"++msg)
1810 nmbr_details :: IdDetails -> NmbrM IdDetails
1812 nmbr_details (DataConId tag marks fields tvs theta arg_tys tc)
1813 = mapNmbr nmbrTyVar tvs `thenNmbr` \ new_tvs ->
1814 mapNmbr nmbrField fields `thenNmbr` \ new_fields ->
1815 mapNmbr nmbr_theta theta `thenNmbr` \ new_theta ->
1816 mapNmbr nmbrType arg_tys `thenNmbr` \ new_arg_tys ->
1817 returnNmbr (DataConId tag marks new_fields new_tvs new_theta new_arg_tys tc)
1820 = --nmbrClass c `thenNmbr` \ new_c ->
1821 nmbrType t `thenNmbr` \ new_t ->
1822 returnNmbr (c, new_t)
1824 -- ToDo:add more cases as needed
1825 nmbr_details other_details = returnNmbr other_details
1828 nmbrField (FieldLabel n ty tag)
1829 = nmbrType ty `thenNmbr` \ new_ty ->
1830 returnNmbr (FieldLabel n new_ty tag)