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 MatchEnv ( MatchEnv )
169 import SrcLoc ( mkBuiltinSrcLoc )
170 import TyCon ( TyCon, mkTupleTyCon, tyConDataCons )
171 import Type ( mkSigmaTy, mkTyVarTys, mkFunTys, mkDictTy,
172 applyTyCon, instantiateTy,
173 tyVarsOfType, applyTypeEnvToTy, typePrimRep,
174 GenType, SYN_IE(ThetaType), SYN_IE(TauType), SYN_IE(Type)
176 import TyVar ( alphaTyVars, isEmptyTyVarSet, SYN_IE(TyVarEnv) )
178 import UniqSet -- practically all of it
179 import Unique ( getBuiltinUniques, pprUnique, showUnique,
181 Unique{-instance Ord3-}
183 import Util ( mapAccumL, nOfThem, zipEqual,
184 panic, panic#, pprPanic, assertPanic
188 Here are the @Id@ and @IdDetails@ datatypes; also see the notes that
191 Every @Id@ has a @Unique@, to uniquify it and for fast comparison, a
192 @Type@, and an @IdInfo@ (non-essential info about it, e.g.,
193 strictness). The essential info about different kinds of @Ids@ is
196 ToDo: possibly cache other stuff in the single-constructor @Id@ type.
200 Unique -- Key for fast comparison
202 ty -- Id's type; used all the time;
203 IdDetails -- Stuff about individual kinds of Ids.
204 PragmaInfo -- Properties of this Id requested by programmer
205 -- eg specialise-me, inline-me
206 IdInfo -- Properties of this Id deduced by compiler
210 data StrictnessMark = MarkedStrict | NotMarkedStrict
214 ---------------- Local values
216 = LocalId Bool -- Local name; mentioned by the user
217 -- True <=> no free type vars
219 | SysLocalId Bool -- Local name; made up by the compiler
222 | SpecPragmaId -- Local name; introduced by the compiler
223 (Maybe Id) -- for explicit specid in pragma
224 Bool -- as for LocalId
226 ---------------- Global values
228 | ImportedId -- Global name (Imported or Implicit); Id imported from an interface
230 | TopLevId -- Global name (LocalDef); Top-level in the orig source pgm
231 -- (not moved there by transformations).
233 -- a TopLevId's type may contain free type variables, if
234 -- the monomorphism restriction applies.
236 ---------------- Data constructors
239 [StrictnessMark] -- Strict args; length = arity
240 [FieldLabel] -- Field labels for this constructor
242 [TyVar] [(Class,Type)] [Type] TyCon
244 -- forall tyvars . theta_ty =>
245 -- unitype_1 -> ... -> unitype_n -> tycon tyvars
247 | TupleConId Int -- Its arity
249 | RecordSelId FieldLabel
251 ---------------- Things to do with overloading
253 | SuperDictSelId -- Selector for superclass dictionary
254 Class -- The class (input dict)
255 Class -- The superclass (result dict)
257 | MethodSelId Class -- An overloaded class operation, with
258 -- a fully polymorphic type. Its code
259 -- just selects a method from the
260 -- dictionary. The class.
261 ClassOp -- The operation
263 -- NB: The IdInfo for a MethodSelId has all the info about its
264 -- related "constant method Ids", which are just
265 -- specialisations of this general one.
267 | DefaultMethodId -- Default method for a particular class op
268 Class -- same class, <blah-blah> info as MethodSelId
269 ClassOp -- (surprise, surprise)
270 Bool -- True <=> I *know* this default method Id
271 -- is a generated one that just says
272 -- `error "No default method for <op>"'.
275 | DictFunId Class -- A DictFun is uniquely identified
276 Type -- by its class and type; this type has free type vars,
277 -- whose identity is irrelevant. Eg Class = Eq
279 -- The "a" is irrelevant. As it is too painful to
280 -- actually do comparisons that way, we kindly supply
281 -- a Unique for that purpose.
282 Module -- module where instance came from
285 | ConstMethodId -- A method which depends only on the type of the
286 -- instance, and not on any further dictionaries etc.
287 Class -- Uniquely identified by:
288 Type -- (class, type, classop) triple
290 Module -- module where instance came from
292 | InstId -- An instance of a dictionary, class operation,
293 -- or overloaded value (Local name)
294 Bool -- as for LocalId
296 | SpecId -- A specialisation of another Id
297 Id -- Id of which this is a specialisation
298 [Maybe Type] -- Types at which it is specialised;
299 -- A "Nothing" says this type ain't relevant.
300 Bool -- True <=> no free type vars; it's not enough
301 -- to know about the unspec version, because
302 -- we may specialise to a type w/ free tyvars
303 -- (i.e., in one of the "Maybe Type" dudes).
305 | WorkerId -- A "worker" for some other Id
306 Id -- Id for which this is a worker
314 DictFunIds are generated from instance decls.
319 instance Foo a => Foo [a] where
322 generates the dict fun id decl
324 dfun.Foo.[*] = \d -> ...
326 The dfun id is uniquely named by the (class, type) pair. Notice, it
327 isn't a (class,tycon) pair any more, because we may get manually or
328 automatically generated specialisations of the instance decl:
330 instance Foo [Int] where
337 The type variables in the name are irrelevant; we print them as stars.
340 Constant method ids are generated from instance decls where
341 there is no context; that is, no dictionaries are needed to
342 construct the method. Example
344 instance Foo Int where
347 Then we get a constant method
352 It is possible, albeit unusual, to have a constant method
353 for an instance decl which has type vars:
355 instance Foo [a] where
359 We get the constant method
363 So a constant method is identified by a class/op/type triple.
364 The type variables in the type are irrelevant.
367 For Ids whose names must be known/deducible in other modules, we have
368 to conjure up their worker's names (and their worker's worker's
369 names... etc) in a known systematic way.
372 %************************************************************************
374 \subsection[Id-documentation]{Documentation}
376 %************************************************************************
380 The @Id@ datatype describes {\em values}. The basic things we want to
381 know: (1)~a value's {\em type} (@idType@ is a very common
382 operation in the compiler); and (2)~what ``flavour'' of value it might
383 be---for example, it can be terribly useful to know that a value is a
387 %----------------------------------------------------------------------
388 \item[@DataConId@:] For the data constructors declared by a @data@
389 declaration. Their type is kept in {\em two} forms---as a regular
390 @Type@ (in the usual place), and also in its constituent pieces (in
391 the ``details''). We are frequently interested in those pieces.
393 %----------------------------------------------------------------------
394 \item[@TupleConId@:] This is just a special shorthand for @DataCons@ for
395 the infinite family of tuples.
397 %----------------------------------------------------------------------
398 \item[@ImportedId@:] These are values defined outside this module.
399 {\em Everything} we want to know about them must be stored here (or in
402 %----------------------------------------------------------------------
403 \item[@TopLevId@:] These are values defined at the top-level in this
404 module; i.e., those which {\em might} be exported (hence, a
405 @Name@). It does {\em not} include those which are moved to the
406 top-level through program transformations.
408 We also guarantee that @TopLevIds@ will {\em stay} at top-level.
409 Theoretically, they could be floated inwards, but there's no known
410 advantage in doing so. This way, we can keep them with the same
411 @Unique@ throughout (no cloning), and, in general, we don't have to be
412 so paranoid about them.
414 In particular, we had the following problem generating an interface:
415 We have to ``stitch together'' info (1)~from the typechecker-produced
416 global-values list (GVE) and (2)~from the STG code [which @Ids@ have
417 what arities]. If the @Uniques@ on the @TopLevIds@ can {\em change}
418 between (1) and (2), you're sunk!
420 %----------------------------------------------------------------------
421 \item[@MethodSelId@:] A selector from a dictionary; it may select either
422 a method or a dictionary for one of the class's superclasses.
424 %----------------------------------------------------------------------
427 @mkDictFunId [a,b..] theta C T@ is the function derived from the
430 instance theta => C (T a b ..) where
433 It builds function @Id@ which maps dictionaries for theta,
434 to a dictionary for C (T a b ..).
436 *Note* that with the ``Mark Jones optimisation'', the theta may
437 include dictionaries for the immediate superclasses of C at the type
440 %----------------------------------------------------------------------
443 %----------------------------------------------------------------------
446 %----------------------------------------------------------------------
449 %----------------------------------------------------------------------
450 \item[@LocalId@:] A purely-local value, e.g., a function argument,
451 something defined in a @where@ clauses, ... --- but which appears in
452 the original program text.
454 %----------------------------------------------------------------------
455 \item[@SysLocalId@:] Same as a @LocalId@, except does {\em not} appear in
456 the original program text; these are introduced by the compiler in
459 %----------------------------------------------------------------------
460 \item[@SpecPragmaId@:] Introduced by the compiler to record
461 Specialisation pragmas. It is dead code which MUST NOT be removed
462 before specialisation.
467 %----------------------------------------------------------------------
470 @DataCons@ @TupleCons@, @Importeds@, @TopLevIds@, @SuperDictSelIds@,
471 @MethodSelIds@, @DictFunIds@, and @DefaultMethodIds@ have the following
475 They have no free type variables, so if you are making a
476 type-variable substitution you don't need to look inside them.
478 They are constants, so they are not free variables. (When the STG
479 machine makes a closure, it puts all the free variables in the
480 closure; the above are not required.)
482 Note that @InstIds@, @Locals@ and @SysLocals@ {\em may} have the above
483 properties, but they may not.
486 %************************************************************************
488 \subsection[Id-general-funs]{General @Id@-related functions}
490 %************************************************************************
493 unsafeGenId2Id :: GenId ty -> Id
494 unsafeGenId2Id (Id u n ty d p i) = Id u n (panic "unsafeGenId2Id:ty") d p i
496 isDataCon id = is_data (unsafeGenId2Id id)
498 is_data (Id _ _ _ (DataConId _ _ _ _ _ _ _) _ _) = True
499 is_data (Id _ _ _ (TupleConId _) _ _) = True
500 is_data (Id _ _ _ (SpecId unspec _ _) _ _) = is_data unspec
501 is_data other = False
504 isTupleCon id = is_tuple (unsafeGenId2Id id)
506 is_tuple (Id _ _ _ (TupleConId _) _ _) = True
507 is_tuple (Id _ _ _ (SpecId unspec _ _) _ _) = is_tuple unspec
508 is_tuple other = False
511 isSpecId_maybe (Id _ _ _ (SpecId unspec ty_maybes _) _ _)
512 = ASSERT(not (maybeToBool (isSpecId_maybe unspec)))
513 Just (unspec, ty_maybes)
514 isSpecId_maybe other_id
517 isSpecPragmaId_maybe (Id _ _ _ (SpecPragmaId specid _) _ _)
519 isSpecPragmaId_maybe other_id
524 @toplevelishId@ tells whether an @Id@ {\em may} be defined in a nested
525 @let(rec)@ (returns @False@), or whether it is {\em sure} to be
526 defined at top level (returns @True@). This is used to decide whether
527 the @Id@ is a candidate free variable. NB: you are only {\em sure}
528 about something if it returns @True@!
531 toplevelishId :: Id -> Bool
532 idHasNoFreeTyVars :: Id -> Bool
534 toplevelishId (Id _ _ _ details _ _)
537 chk (DataConId _ _ _ _ _ _ _) = True
538 chk (TupleConId _) = True
539 chk (RecordSelId _) = True
540 chk ImportedId = True
541 chk TopLevId = True -- NB: see notes
542 chk (SuperDictSelId _ _) = True
543 chk (MethodSelId _ _) = True
544 chk (DefaultMethodId _ _ _) = True
545 chk (DictFunId _ _ _) = True
546 chk (ConstMethodId _ _ _ _) = True
547 chk (SpecId unspec _ _) = toplevelishId unspec
548 -- depends what the unspecialised thing is
549 chk (WorkerId unwrkr) = toplevelishId unwrkr
550 chk (InstId _) = False -- these are local
551 chk (LocalId _) = False
552 chk (SysLocalId _) = False
553 chk (SpecPragmaId _ _) = False
555 idHasNoFreeTyVars (Id _ _ _ details _ info)
558 chk (DataConId _ _ _ _ _ _ _) = True
559 chk (TupleConId _) = True
560 chk (RecordSelId _) = True
561 chk ImportedId = True
563 chk (SuperDictSelId _ _) = True
564 chk (MethodSelId _ _) = True
565 chk (DefaultMethodId _ _ _) = True
566 chk (DictFunId _ _ _) = True
567 chk (ConstMethodId _ _ _ _) = True
568 chk (WorkerId unwrkr) = idHasNoFreeTyVars unwrkr
569 chk (SpecId _ _ no_free_tvs) = no_free_tvs
570 chk (InstId no_free_tvs) = no_free_tvs
571 chk (LocalId no_free_tvs) = no_free_tvs
572 chk (SysLocalId no_free_tvs) = no_free_tvs
573 chk (SpecPragmaId _ no_free_tvs) = no_free_tvs
577 isTopLevId (Id _ _ _ TopLevId _ _) = True
578 isTopLevId other = False
580 isImportedId (Id _ _ _ ImportedId _ _) = True
581 isImportedId other = False
583 isBottomingId (Id _ _ _ _ _ info) = bottomIsGuaranteed (getInfo info)
585 isSysLocalId (Id _ _ _ (SysLocalId _) _ _) = True
586 isSysLocalId other = False
588 isSpecPragmaId (Id _ _ _ (SpecPragmaId _ _) _ _) = True
589 isSpecPragmaId other = False
591 isMethodSelId (Id _ _ _ (MethodSelId _ _) _ _) = True
592 isMethodSelId _ = False
594 isDefaultMethodId (Id _ _ _ (DefaultMethodId _ _ _) _ _) = True
595 isDefaultMethodId other = False
597 isDefaultMethodId_maybe (Id _ _ _ (DefaultMethodId cls clsop err) _ _)
598 = Just (cls, clsop, err)
599 isDefaultMethodId_maybe other = Nothing
601 isDictFunId (Id _ _ _ (DictFunId _ _ _) _ _) = True
602 isDictFunId other = False
604 isConstMethodId (Id _ _ _ (ConstMethodId _ _ _ _) _ _) = True
605 isConstMethodId other = False
607 isConstMethodId_maybe (Id _ _ _ (ConstMethodId cls ty clsop _) _ _)
608 = Just (cls, ty, clsop)
609 isConstMethodId_maybe other = Nothing
611 isSuperDictSelId_maybe (Id _ _ _ (SuperDictSelId c sc) _ _) = Just (c, sc)
612 isSuperDictSelId_maybe other_id = Nothing
614 isWorkerId (Id _ _ _ (WorkerId _) _ _) = True
615 isWorkerId other = False
617 isWrapperId id = workerExists (getIdStrictness id)
622 pprIdInUnfolding :: IdSet -> Id -> Pretty
624 pprIdInUnfolding in_scopes v
629 if v `elementOfUniqSet` in_scopes then
630 pprUnique (idUnique v)
632 -- ubiquitous Ids with special syntax:
633 else if v == nilDataCon then
635 else if isTupleCon v then
636 ppBeside (ppPStr SLIT("_TUP_")) (ppInt (dataConArity v))
638 -- ones to think about:
641 (Id _ _ _ v_details _ _) = v
644 -- these ones must have been exported by their original module
645 ImportedId -> pp_full_name
647 -- these ones' exportedness checked later...
648 TopLevId -> pp_full_name
649 DataConId _ _ _ _ _ _ _ -> pp_full_name
651 RecordSelId lbl -> ppr sty lbl
653 -- class-ish things: class already recorded as "mentioned"
655 -> ppCat [ppPStr SLIT("_SDSEL_"), pp_class c, pp_class sc]
657 -> ppCat [ppPStr SLIT("_METH_"), pp_class c, pp_class_op o]
658 DefaultMethodId c o _
659 -> ppCat [ppPStr SLIT("_DEFM_"), pp_class c, pp_class_op o]
661 -- instance-ish things: should we try to figure out
662 -- *exactly* which extra instances have to be exported? (ToDo)
664 -> ppCat [ppPStr SLIT("_DFUN_"), pp_class c, pp_type t]
665 ConstMethodId c t o _
666 -> ppCat [ppPStr SLIT("_CONSTM_"), pp_class c, pp_class_op o, pp_type t]
668 -- specialisations and workers
669 SpecId unspec ty_maybes _
671 pp = pprIdInUnfolding in_scopes unspec
673 ppCat [ppPStr SLIT("_SPEC_"), pp, ppLbrack,
674 ppIntersperse pp'SP{-'-} (map pp_ty_maybe ty_maybes),
679 pp = pprIdInUnfolding in_scopes unwrkr
681 ppBeside (ppPStr SLIT("_WRKR_ ")) pp
683 -- anything else? we're nae interested
684 other_id -> panic "pprIdInUnfolding:mystery Id"
686 ppr_Unfolding = PprUnfolding (panic "Id:ppr_Unfolding")
690 (OrigName m_str n_str) = origName "Id:ppr_Unfolding" v
693 if isLexSym n_str && not (isLexSpecialSym n_str) then
694 ppBesides [ppLparen, ppPStr n_str, ppRparen]
698 if isPreludeDefined v then
701 ppCat [ppPStr SLIT("_ORIG_"), ppPStr m_str, pp_n]
703 pp_class :: Class -> Pretty
704 pp_class_op :: ClassOp -> Pretty
705 pp_type :: Type -> Pretty
706 pp_ty_maybe :: Maybe Type -> Pretty
708 pp_class clas = ppr ppr_Unfolding clas
709 pp_class_op op = ppr ppr_Unfolding op
711 pp_type t = ppBesides [ppLparen, ppr ppr_Unfolding t, ppRparen]
713 pp_ty_maybe Nothing = ppPStr SLIT("_N_")
714 pp_ty_maybe (Just t) = pp_type t
718 @whatsMentionedInId@ ferrets out the types/classes/instances on which
719 this @Id@ depends. If this Id is to appear in an interface, then
720 those entities had Jolly Well be in scope. Someone else up the
721 call-tree decides that.
726 :: IdSet -- Ids known to be in scope
727 -> Id -- Id being processed
728 -> (Bag Id, Bag TyCon, Bag Class) -- mentioned Ids/TyCons/etc.
730 whatsMentionedInId in_scopes v
735 = getMentionedTyConsAndClassesFromType v_ty
737 result0 id_bag = (id_bag, tycons, clss)
740 = (ids `unionBags` unitBag v, -- we add v to "mentioned"...
741 tcs `unionBags` tycons,
745 if v `elementOfUniqSet` in_scopes then
746 result0 emptyBag -- v not added to "mentioned"
748 -- ones to think about:
751 (Id _ _ _ v_details _ _) = v
754 -- specialisations and workers
755 SpecId unspec ty_maybes _
757 (ids2, tcs2, cs2) = whatsMentionedInId in_scopes unspec
759 result1 ids2 tcs2 cs2
763 (ids2, tcs2, cs2) = whatsMentionedInId in_scopes unwrkr
765 result1 ids2 tcs2 cs2
767 anything_else -> result0 (unitBag v) -- v is added to "mentioned"
771 Tell them who my wrapper function is.
774 myWrapperMaybe :: Id -> Maybe Id
776 myWrapperMaybe (Id _ _ _ (WorkerId my_wrapper) _ _) = Just my_wrapper
777 myWrapperMaybe other_id = Nothing
782 unfoldingUnfriendlyId -- return True iff it is definitely a bad
783 :: Id -- idea to export an unfolding that
784 -> Bool -- mentions this Id. Reason: it cannot
785 -- possibly be seen in another module.
787 unfoldingUnfriendlyId id = not (externallyVisibleId id)
790 @externallyVisibleId@: is it true that another module might be
791 able to ``see'' this Id?
793 We need the @toplevelishId@ check as well as @isExported@ for when we
794 compile instance declarations in the prelude. @DictFunIds@ are
795 ``exported'' if either their class or tycon is exported, but, in
796 compiling the prelude, the compiler may not recognise that as true.
799 externallyVisibleId :: Id -> Bool
801 externallyVisibleId id@(Id _ _ _ details _ _)
802 = if isLocallyDefined id then
803 toplevelishId id && (isExported id || isDataCon id)
804 -- NB: the use of "isExported" is most dodgy;
805 -- We may eventually move to a situation where
806 -- every Id is "externallyVisible", even if the
807 -- module system's namespace control renders it
811 -- if visible here, it must be visible elsewhere, too.
815 idWantsToBeINLINEd :: Id -> Bool
817 idWantsToBeINLINEd (Id _ _ _ _ IWantToBeINLINEd _) = True
818 idWantsToBeINLINEd _ = False
821 For @unlocaliseId@: See the brief commentary in
822 \tr{simplStg/SimplStg.lhs}.
826 unlocaliseId :: FAST_STRING{-modulename-} -> Id -> Maybe Id
828 unlocaliseId mod (Id u fn ty info TopLevId)
829 = Just (Id u (unlocaliseFullName fn) ty info TopLevId)
831 unlocaliseId mod (Id u sn ty info (LocalId no_ftvs))
832 = --false?: ASSERT(no_ftvs)
834 full_name = unlocaliseShortName mod u sn
836 Just (Id u full_name ty info TopLevId)
838 unlocaliseId mod (Id u sn ty info (SysLocalId no_ftvs))
839 = --false?: on PreludeGlaST: ASSERT(no_ftvs)
841 full_name = unlocaliseShortName mod u sn
843 Just (Id u full_name ty info TopLevId)
845 unlocaliseId mod (Id u n ty info (SpecId unspec ty_maybes no_ftvs))
846 = case unlocalise_parent mod u unspec of
848 Just xx -> Just (Id u n ty info (SpecId xx ty_maybes no_ftvs))
850 unlocaliseId mod (Id u n ty info (WorkerId unwrkr))
851 = case unlocalise_parent mod u unwrkr of
853 Just xx -> Just (Id u n ty info (WorkerId xx))
855 unlocaliseId mod (Id u name ty info (InstId no_ftvs))
856 = Just (Id u full_name ty info TopLevId)
857 -- type might be wrong, but it hardly matters
858 -- at this stage (just before printing C) ToDo
860 name = nameOf (origName "Id.unlocaliseId" name)
861 full_name = mkFullName mod name InventedInThisModule ExportAll mkGeneratedSrcLoc
863 unlocaliseId mod other_id = Nothing
866 -- we have to be Very Careful for workers/specs of
869 unlocalise_parent mod uniq (Id _ sn ty info (LocalId no_ftvs))
870 = --false?: ASSERT(no_ftvs)
872 full_name = unlocaliseShortName mod uniq sn
874 Just (Id uniq full_name ty info TopLevId)
876 unlocalise_parent mod uniq (Id _ sn ty info (SysLocalId no_ftvs))
877 = --false?: ASSERT(no_ftvs)
879 full_name = unlocaliseShortName mod uniq sn
881 Just (Id uniq full_name ty info TopLevId)
883 unlocalise_parent mod uniq other_id = unlocaliseId mod other_id
884 -- we're OK otherwise
888 CLAIM (not ASSERTed) for @applyTypeEnvToId@ and @applySubstToId@:
889 `Top-levelish Ids'' cannot have any free type variables, so applying
890 the type-env cannot have any effect. (NB: checked in CoreLint?)
892 The special casing is in @applyTypeEnvToId@, not @apply_to_Id@, as the
893 former ``should be'' the usual crunch point.
896 type TypeEnv = TyVarEnv Type
898 applyTypeEnvToId :: TypeEnv -> Id -> Id
900 applyTypeEnvToId type_env id@(Id _ _ ty _ _ _)
901 | idHasNoFreeTyVars id
904 = apply_to_Id ( \ ty ->
905 applyTypeEnvToTy type_env ty
910 apply_to_Id :: (Type -> Type) -> Id -> Id
912 apply_to_Id ty_fn (Id u n ty details prag info)
916 Id u n new_ty (apply_to_details details) prag (apply_to_IdInfo ty_fn info)
918 apply_to_details (SpecId unspec ty_maybes no_ftvs)
920 new_unspec = apply_to_Id ty_fn unspec
921 new_maybes = map apply_to_maybe ty_maybes
923 SpecId new_unspec new_maybes (no_free_tvs ty)
924 -- ToDo: gratuitous recalc no_ftvs???? (also InstId)
926 apply_to_maybe Nothing = Nothing
927 apply_to_maybe (Just ty) = Just (ty_fn ty)
929 apply_to_details (WorkerId unwrkr)
931 new_unwrkr = apply_to_Id ty_fn unwrkr
935 apply_to_details other = other
938 Sadly, I don't think the one using the magic typechecker substitution
939 can be done with @apply_to_Id@. Here we go....
941 Strictness is very important here. We can't leave behind thunks
942 with pointers to the substitution: it {\em must} be single-threaded.
946 applySubstToId :: Subst -> Id -> (Subst, Id)
948 applySubstToId subst id@(Id u n ty info details)
949 -- *cannot* have a "idHasNoFreeTyVars" get-out clause
950 -- because, in the typechecker, we are still
951 -- *concocting* the types.
952 = case (applySubstToTy subst ty) of { (s2, new_ty) ->
953 case (applySubstToIdInfo s2 info) of { (s3, new_info) ->
954 case (apply_to_details s3 new_ty details) of { (s4, new_details) ->
955 (s4, Id u n new_ty new_info new_details) }}}
957 apply_to_details subst _ (InstId inst no_ftvs)
958 = case (applySubstToInst subst inst) of { (s2, new_inst) ->
959 (s2, InstId new_inst no_ftvs{-ToDo:right???-}) }
961 apply_to_details subst new_ty (SpecId unspec ty_maybes _)
962 = case (applySubstToId subst unspec) of { (s2, new_unspec) ->
963 case (mapAccumL apply_to_maybe s2 ty_maybes) of { (s3, new_maybes) ->
964 (s3, SpecId new_unspec new_maybes (no_free_tvs new_ty)) }}
965 -- NB: recalc no_ftvs (I think it's necessary (?) WDP 95/04)
967 apply_to_maybe subst Nothing = (subst, Nothing)
968 apply_to_maybe subst (Just ty)
969 = case (applySubstToTy subst ty) of { (s2, new_ty) ->
972 apply_to_details subst _ (WorkerId unwrkr)
973 = case (applySubstToId subst unwrkr) of { (s2, new_unwrkr) ->
974 (s2, WorkerId new_unwrkr) }
976 apply_to_details subst _ other = (subst, other)
980 %************************************************************************
982 \subsection[Id-type-funs]{Type-related @Id@ functions}
984 %************************************************************************
987 idType :: GenId ty -> ty
989 idType (Id _ _ ty _ _ _) = ty
994 getMentionedTyConsAndClassesFromId :: Id -> (Bag TyCon, Bag Class)
996 getMentionedTyConsAndClassesFromId id
997 = getMentionedTyConsAndClassesFromType (idType id)
1002 idPrimRep i = typePrimRep (idType i)
1007 getInstIdModule (Id _ _ _ (DictFunId _ _ mod)) = mod
1008 getInstIdModule (Id _ _ _ (ConstMethodId _ _ _ mod)) = mod
1009 getInstIdModule other = panic "Id:getInstIdModule"
1013 %************************************************************************
1015 \subsection[Id-overloading]{Functions related to overloading}
1017 %************************************************************************
1020 mkSuperDictSelId u c sc ty info
1021 = mk_classy_id (SuperDictSelId c sc) SLIT("sdsel") (Left (origName "mkSuperDictSelId" sc)) u c ty info
1023 mkMethodSelId u rec_c op ty info
1024 = mk_classy_id (MethodSelId rec_c op) SLIT("meth") (Right (classOpString op)) u rec_c ty info
1026 mkDefaultMethodId u rec_c op gen ty info
1027 = mk_classy_id (DefaultMethodId rec_c op gen) SLIT("defm") (Right (classOpString op)) u rec_c ty info
1029 mk_classy_id details str op_str u rec_c ty info
1030 = Id u n ty details NoPragmaInfo info
1032 cname = getName rec_c -- we get other info out of here
1033 cname_orig = origName "mk_classy_id" cname
1034 cmod = moduleOf cname_orig
1036 n = mkCompoundName u cmod str [Left cname_orig, op_str] cname
1038 mkDictFunId u c ity full_ty from_here locn mod info
1039 = Id u n full_ty (DictFunId c ity mod) NoPragmaInfo info
1041 n = mkCompoundName2 u mod SLIT("dfun") (Left (origName "mkDictFunId" c) : renum_type_string full_ty ity) from_here locn
1043 mkConstMethodId u c op ity full_ty from_here locn mod info
1044 = Id u n full_ty (ConstMethodId c ity op mod) NoPragmaInfo info
1046 n = mkCompoundName2 u mod SLIT("const") (Left (origName "mkConstMethodId" c) : Right (classOpString op) : renum_type_string full_ty ity) from_here locn
1048 renum_type_string full_ty ity
1050 nmbrType full_ty `thenNmbr` \ _ -> -- so all the tyvars get added to renumbering...
1051 nmbrType ity `thenNmbr` \ rn_ity ->
1052 returnNmbr (getTypeString rn_ity)
1055 mkWorkerId u unwrkr ty info
1056 = Id u n ty (WorkerId unwrkr) NoPragmaInfo info
1058 unwrkr_name = getName unwrkr
1059 unwrkr_orig = origName "mkWorkerId" unwrkr_name
1060 umod = moduleOf unwrkr_orig
1062 n = mkCompoundName u umod SLIT("wrk") [Left unwrkr_orig] unwrkr_name
1064 mkInstId u ty name = Id u (changeUnique name u) ty (InstId (no_free_tvs ty)) NoPragmaInfo noIdInfo
1067 getConstMethodId clas op ty
1068 = -- constant-method info is hidden in the IdInfo of
1069 -- the class-op id (as mentioned up above).
1071 sel_id = getMethodSelId clas op
1073 case (lookupConstMethodId (getIdSpecialisation sel_id) ty) of
1075 Nothing -> pprError "ERROR: getConstMethodId:" (ppAboves [
1076 ppCat [ppr PprDebug ty, ppr PprDebug ops, ppr PprDebug op_ids,
1077 ppr PprDebug sel_id],
1078 ppStr "(This can arise if an interface pragma refers to an instance",
1079 ppStr "but there is no imported interface which *defines* that instance.",
1080 ppStr "The info above, however ugly, should indicate what else you need to import."
1085 %************************************************************************
1087 \subsection[local-funs]{@LocalId@-related functions}
1089 %************************************************************************
1092 mkImported n ty info = Id (nameUnique n) n ty ImportedId NoPragmaInfo info
1095 updateIdType :: Id -> Type -> Id
1096 updateIdType (Id u n _ info details) ty = Id u n ty info details
1101 type MyTy a b = GenType (GenTyVar a) b
1102 type MyId a b = GenId (MyTy a b)
1104 no_free_tvs ty = isEmptyTyVarSet (tyVarsOfType ty)
1106 -- SysLocal: for an Id being created by the compiler out of thin air...
1107 -- UserLocal: an Id with a name the user might recognize...
1108 mkSysLocal, mkUserLocal :: FAST_STRING -> Unique -> MyTy a b -> SrcLoc -> MyId a b
1110 mkSysLocal str uniq ty loc
1111 = Id uniq (mkLocalName uniq str True{-emph uniq-} loc) ty (SysLocalId (no_free_tvs ty)) NoPragmaInfo noIdInfo
1113 mkUserLocal str uniq ty loc
1114 = Id uniq (mkLocalName uniq str False{-emph name-} loc) ty (LocalId (no_free_tvs ty)) NoPragmaInfo noIdInfo
1116 -- mkUserId builds a local or top-level Id, depending on the name given
1117 mkUserId :: Name -> MyTy a b -> PragmaInfo -> MyId a b
1118 mkUserId name ty pragma_info
1120 = Id (nameUnique name) name ty (LocalId (no_free_tvs ty)) pragma_info noIdInfo
1122 = Id (nameUnique name) name ty
1123 (if isLocallyDefinedName name then TopLevId else ImportedId)
1124 pragma_info noIdInfo
1131 -- for a SpecPragmaId being created by the compiler out of thin air...
1132 mkSpecPragmaId :: FAST_STRING -> Unique -> Type -> Maybe Id -> SrcLoc -> Id
1133 mkSpecPragmaId str uniq ty specid loc
1134 = Id uniq (mkShortName str loc) ty noIdInfo (SpecPragmaId specid (no_free_tvs ty))
1137 mkSpecId u unspec ty_maybes ty info
1138 = ASSERT(not (maybeToBool (isSpecId_maybe unspec)))
1139 Id u n ty info (SpecId unspec ty_maybes (no_free_tvs ty))
1141 -- Specialised version of constructor: only used in STG and code generation
1142 -- Note: The specialsied Id has the same unique as the unspeced Id
1144 mkSameSpecCon ty_maybes unspec@(Id u n ty info details)
1145 = ASSERT(isDataCon unspec)
1146 ASSERT(not (maybeToBool (isSpecId_maybe unspec)))
1147 Id u n new_ty info (SpecId unspec ty_maybes (no_free_tvs new_ty))
1149 new_ty = specialiseTy ty ty_maybes 0
1151 localiseId :: Id -> Id
1152 localiseId id@(Id u n ty info details)
1153 = Id u (mkShortName name loc) ty info (LocalId (no_free_tvs ty))
1155 name = getOccName id
1159 mkIdWithNewUniq :: Id -> Unique -> Id
1161 mkIdWithNewUniq (Id _ n ty details prag info) u
1162 = Id u (changeUnique n u) ty details prag info
1165 Make some local @Ids@ for a template @CoreExpr@. These have bogus
1166 @Uniques@, but that's OK because the templates are supposed to be
1167 instantiated before use.
1169 mkTemplateLocals :: [Type] -> [Id]
1170 mkTemplateLocals tys
1171 = zipWith (\ u -> \ ty -> mkSysLocal SLIT("tpl") u ty mkBuiltinSrcLoc)
1172 (getBuiltinUniques (length tys))
1177 getIdInfo :: GenId ty -> IdInfo
1178 getPragmaInfo :: GenId ty -> PragmaInfo
1180 getIdInfo (Id _ _ _ _ _ info) = info
1181 getPragmaInfo (Id _ _ _ _ info _) = info
1183 replaceIdInfo :: Id -> IdInfo -> Id
1185 replaceIdInfo (Id u n ty details pinfo _) info = Id u n ty details pinfo info
1188 selectIdInfoForSpecId :: Id -> IdInfo
1189 selectIdInfoForSpecId unspec
1190 = ASSERT(not (maybeToBool (isSpecId_maybe unspec)))
1191 noIdInfo `addInfo_UF` getIdUnfolding unspec
1195 %************************************************************************
1197 \subsection[Id-arities]{Arity-related functions}
1199 %************************************************************************
1201 For locally-defined Ids, the code generator maintains its own notion
1202 of their arities; so it should not be asking... (but other things
1203 besides the code-generator need arity info!)
1206 getIdArity :: Id -> ArityInfo
1207 getIdArity id@(Id _ _ _ _ _ id_info)
1208 = --ASSERT( not (isDataCon id))
1211 dataConArity, dataConNumFields :: DataCon -> Int
1213 dataConArity id@(Id _ _ _ _ _ id_info)
1214 = ASSERT(isDataCon id)
1215 case (arityMaybe (getInfo id_info)) of
1217 Nothing -> pprPanic "dataConArity:Nothing:" (pprId PprDebug id)
1220 = ASSERT(isDataCon id)
1221 case (dataConSig id) of { (_, _, arg_tys, _) ->
1224 isNullaryDataCon con = dataConNumFields con == 0 -- function of convenience
1226 addIdArity :: Id -> Int -> Id
1227 addIdArity (Id u n ty details pinfo info) arity
1228 = Id u n ty details pinfo (info `addInfo` (mkArityInfo arity))
1231 %************************************************************************
1233 \subsection[constructor-funs]{@DataCon@-related functions (incl.~tuples)}
1235 %************************************************************************
1239 -> [StrictnessMark] -> [FieldLabel]
1240 -> [TyVar] -> ThetaType -> [TauType] -> TyCon
1243 -- can get the tag and all the pieces of the type from the Type
1245 mkDataCon n stricts fields tvs ctxt args_tys tycon
1246 = ASSERT(length stricts == length args_tys)
1249 -- NB: data_con self-recursion; should be OK as tags are not
1250 -- looked at until late in the game.
1255 (DataConId data_con_tag stricts fields tvs ctxt args_tys tycon)
1256 IWantToBeINLINEd -- Always inline constructors if possible
1259 data_con_tag = position_within fIRST_TAG data_con_family
1261 data_con_family = tyConDataCons tycon
1263 position_within :: Int -> [Id] -> Int
1265 position_within acc (c:cs)
1266 = if c == data_con then acc else position_within (acc+1) cs
1268 position_within acc []
1269 = panic "mkDataCon: con not found in family"
1273 = mkSigmaTy tvs ctxt
1274 (mkFunTys args_tys (applyTyCon tycon (mkTyVarTys tvs)))
1276 datacon_info = noIdInfo `addInfo_UF` unfolding
1277 `addInfo` mkArityInfo arity
1278 --ToDo: `addInfo` specenv
1280 arity = length ctxt + length args_tys
1287 -- else -- do some business...
1289 (tyvars, dict_vars, vars) = mk_uf_bits tvs ctxt args_tys tycon
1290 tyvar_tys = mkTyVarTys tyvars
1292 case (Con data_con tyvar_tys [VarArg v | v <- vars]) of { plain_Con ->
1294 mkUnfolding EssentialUnfolding -- for data constructors
1295 (mkLam tyvars (dict_vars ++ vars) plain_Con)
1298 mk_uf_bits tvs ctxt arg_tys tycon
1300 (inst_env, tyvars, tyvar_tys)
1301 = instantiateTyVarTemplates tvs
1304 -- the "context" and "arg_tys" have TyVarTemplates in them, so
1305 -- we instantiate those types to have the right TyVars in them
1307 case (map (instantiateTauTy inst_env) (map ctxt_ty ctxt))
1308 of { inst_dict_tys ->
1309 case (map (instantiateTauTy inst_env) arg_tys) of { inst_arg_tys ->
1311 -- We can only have **ONE** call to mkTemplateLocals here;
1312 -- otherwise, we get two blobs of locals w/ mixed-up Uniques
1313 -- (Mega-Sigh) [ToDo]
1314 case (mkTemplateLocals (inst_dict_tys ++ inst_arg_tys)) of { all_vars ->
1316 case (splitAt (length ctxt) all_vars) of { (dict_vars, vars) ->
1318 (tyvars, dict_vars, vars)
1321 -- these are really dubious Types, but they are only to make the
1322 -- binders for the lambdas for tossed-away dicts.
1323 ctxt_ty (clas, ty) = mkDictTy clas ty
1328 mkTupleCon :: Arity -> Id
1331 = Id unique n ty (TupleConId arity) NoPragmaInfo tuplecon_info
1333 n = mkTupleDataConName arity
1335 ty = mkSigmaTy tyvars []
1336 (mkFunTys tyvar_tys (applyTyCon tycon tyvar_tys))
1337 tycon = mkTupleTyCon arity
1338 tyvars = take arity alphaTyVars
1339 tyvar_tys = mkTyVarTys tyvars
1342 = noIdInfo `addInfo_UF` unfolding
1343 `addInfo` mkArityInfo arity
1344 --LATER:? `addInfo` panic "Id:mkTupleCon:pcGenerateTupleSpecs arity ty"
1351 -- else -- do some business...
1353 (tyvars, dict_vars, vars) = mk_uf_bits arity
1354 tyvar_tys = mkTyVarTys tyvars
1356 case (Con data_con tyvar_tys [VarArg v | v <- vars]) of { plain_Con ->
1358 EssentialUnfolding -- data constructors
1359 (mkLam tyvars (dict_vars ++ vars) plain_Con) }
1362 = case (mkTemplateLocals tyvar_tys) of { vars ->
1363 (tyvars, [], vars) }
1365 tyvar_tmpls = take arity alphaTyVars
1366 (_, tyvars, tyvar_tys) = instantiateTyVarTemplates tyvar_tmpls (map uniqueOf tyvar_tmpls)
1370 fIRST_TAG = 1 -- Tags allocated from here for real constructors
1374 dataConTag :: DataCon -> ConTag -- will panic if not a DataCon
1375 dataConTag (Id _ _ _ (DataConId tag _ _ _ _ _ _) _ _) = tag
1376 dataConTag (Id _ _ _ (TupleConId _) _ _) = fIRST_TAG
1377 dataConTag (Id _ _ _ (SpecId unspec _ _) _ _) = dataConTag unspec
1379 dataConTyCon :: DataCon -> TyCon -- will panic if not a DataCon
1380 dataConTyCon (Id _ _ _ (DataConId _ _ _ _ _ _ tycon) _ _) = tycon
1381 dataConTyCon (Id _ _ _ (TupleConId a) _ _) = mkTupleTyCon a
1383 dataConSig :: DataCon -> ([TyVar], ThetaType, [TauType], TyCon)
1384 -- will panic if not a DataCon
1386 dataConSig (Id _ _ _ (DataConId _ _ _ tyvars theta_ty arg_tys tycon) _ _)
1387 = (tyvars, theta_ty, arg_tys, tycon)
1389 dataConSig (Id _ _ _ (TupleConId arity) _ _)
1390 = (tyvars, [], tyvar_tys, mkTupleTyCon arity)
1392 tyvars = take arity alphaTyVars
1393 tyvar_tys = mkTyVarTys tyvars
1395 dataConFieldLabels :: DataCon -> [FieldLabel]
1396 dataConFieldLabels (Id _ _ _ (DataConId _ _ fields _ _ _ _) _ _) = fields
1397 dataConFieldLabels (Id _ _ _ (TupleConId _) _ _) = []
1399 dataConStrictMarks :: DataCon -> [StrictnessMark]
1400 dataConStrictMarks (Id _ _ _ (DataConId _ stricts _ _ _ _ _) _ _) = stricts
1401 dataConStrictMarks (Id _ _ _ (TupleConId arity) _ _)
1402 = nOfThem arity NotMarkedStrict
1404 dataConRawArgTys :: DataCon -> [TauType] -- a function of convenience
1405 dataConRawArgTys con = case (dataConSig con) of { (_,_, arg_tys,_) -> arg_tys }
1407 dataConArgTys :: DataCon
1408 -> [Type] -- Instantiated at these types
1409 -> [Type] -- Needs arguments of these types
1410 dataConArgTys con_id inst_tys
1411 = map (instantiateTy tenv) arg_tys
1413 (tyvars, _, arg_tys, _) = dataConSig con_id
1414 tenv = zipEqual "dataConArgTys" tyvars inst_tys
1418 mkRecordSelId field_label selector_ty
1419 = Id (nameUnique name)
1422 (RecordSelId field_label)
1426 name = fieldLabelName field_label
1428 recordSelectorFieldLabel :: Id -> FieldLabel
1429 recordSelectorFieldLabel (Id _ _ _ (RecordSelId lbl) _ _) = lbl
1433 Data type declarations are of the form:
1435 data Foo a b = C1 ... | C2 ... | ... | Cn ...
1437 For each constructor @Ci@, we want to generate a curried function; so, e.g., for
1438 @C1 x y z@, we want a function binding:
1440 fun_C1 = /\ a -> /\ b -> \ [x, y, z] -> Con C1 [a, b] [x, y, z]
1442 Notice the ``big lambdas'' and type arguments to @Con@---we are producing
1443 2nd-order polymorphic lambda calculus with explicit types.
1445 %************************************************************************
1447 \subsection[unfolding-Ids]{Functions related to @Ids@' unfoldings}
1449 %************************************************************************
1451 @getIdUnfolding@ takes a @Id@ (we are discussing the @DataCon@ case)
1452 and generates an @Unfolding@. The @Ids@ and @TyVars@ don't really
1453 have to be new, because we are only producing a template.
1455 ToDo: what if @DataConId@'s type has a context (haven't thought about it
1458 Note: @getDataConUnfolding@ is a ``poor man's'' version---it is NOT
1459 EXPORTED. It just returns the binders (@TyVars@ and @Ids@) [in the
1460 example above: a, b, and x, y, z], which is enough (in the important
1461 \tr{DsExpr} case). (The middle set of @Ids@ is binders for any
1462 dictionaries, in the even of an overloaded data-constructor---none at
1466 getIdUnfolding :: Id -> Unfolding
1468 getIdUnfolding (Id _ _ _ _ _ info) = getInfo_UF info
1471 addIdUnfolding :: Id -> Unfolding -> Id
1472 addIdUnfolding id@(Id u n ty info details) unfold_details
1474 case (isLocallyDefined id, unfold_details) of
1475 (_, NoUnfolding) -> True
1476 (True, IWantToBeINLINEd _) -> True
1477 (False, IWantToBeINLINEd _) -> False -- v bad
1481 Id u n ty (info `addInfo_UF` unfold_details) details
1485 In generating selector functions (take a dictionary, give back one
1486 component...), we need to what out for the nothing-to-select cases (in
1487 which case the ``selector'' is just an identity function):
1489 class Eq a => Foo a { } # the superdict selector for "Eq"
1491 class Foo a { op :: Complex b => c -> b -> a }
1492 # the method selector for "op";
1493 # note local polymorphism...
1496 %************************************************************************
1498 \subsection[IdInfo-funs]{Functions related to @Ids@' @IdInfos@}
1500 %************************************************************************
1503 getIdDemandInfo :: Id -> DemandInfo
1504 getIdDemandInfo (Id _ _ _ _ _ info) = getInfo info
1506 addIdDemandInfo :: Id -> DemandInfo -> Id
1507 addIdDemandInfo (Id u n ty details prags info) demand_info
1508 = Id u n ty details prags (info `addInfo` demand_info)
1512 getIdUpdateInfo :: Id -> UpdateInfo
1513 getIdUpdateInfo (Id _ _ _ _ _ info) = getInfo info
1515 addIdUpdateInfo :: Id -> UpdateInfo -> Id
1516 addIdUpdateInfo (Id u n ty details prags info) upd_info
1517 = Id u n ty details prags (info `addInfo` upd_info)
1522 getIdArgUsageInfo :: Id -> ArgUsageInfo
1523 getIdArgUsageInfo (Id u n ty info details) = getInfo info
1525 addIdArgUsageInfo :: Id -> ArgUsageInfo -> Id
1526 addIdArgUsageInfo (Id u n ty info details) au_info
1527 = Id u n ty (info `addInfo` au_info) details
1533 getIdFBTypeInfo :: Id -> FBTypeInfo
1534 getIdFBTypeInfo (Id u n ty info details) = getInfo info
1536 addIdFBTypeInfo :: Id -> FBTypeInfo -> Id
1537 addIdFBTypeInfo (Id u n ty info details) upd_info
1538 = Id u n ty (info `addInfo` upd_info) details
1543 getIdSpecialisation :: Id -> SpecEnv
1544 getIdSpecialisation (Id _ _ _ _ _ info) = getInfo info
1546 addIdSpecialisation :: Id -> SpecEnv -> Id
1547 addIdSpecialisation (Id u n ty details prags info) spec_info
1548 = 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 :: (a -> a) -> IdEnv 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 mangle_fn env key
1708 = case (lookupIdEnv env key) of
1710 Just xx -> addOneToIdEnv env key (mangle_fn xx)
1712 modifyIdEnv_Directly mangle_fn env key
1713 = case (lookupUFM_Directly env key) of
1715 Just xx -> addToUFM_Directly env key (mangle_fn xx)
1719 type GenIdSet ty = UniqSet (GenId ty)
1720 type IdSet = UniqSet (GenId Type)
1722 emptyIdSet :: GenIdSet ty
1723 intersectIdSets :: GenIdSet ty -> GenIdSet ty -> GenIdSet ty
1724 unionIdSets :: GenIdSet ty -> GenIdSet ty -> GenIdSet ty
1725 unionManyIdSets :: [GenIdSet ty] -> GenIdSet ty
1726 idSetToList :: GenIdSet ty -> [GenId ty]
1727 unitIdSet :: GenId ty -> GenIdSet ty
1728 addOneToIdSet :: GenIdSet ty -> GenId ty -> GenIdSet ty
1729 elementOfIdSet :: GenId ty -> GenIdSet ty -> Bool
1730 minusIdSet :: GenIdSet ty -> GenIdSet ty -> GenIdSet ty
1731 isEmptyIdSet :: GenIdSet ty -> Bool
1732 mkIdSet :: [GenId ty] -> GenIdSet ty
1734 emptyIdSet = emptyUniqSet
1735 unitIdSet = unitUniqSet
1736 addOneToIdSet = addOneToUniqSet
1737 intersectIdSets = intersectUniqSets
1738 unionIdSets = unionUniqSets
1739 unionManyIdSets = unionManyUniqSets
1740 idSetToList = uniqSetToList
1741 elementOfIdSet = elementOfUniqSet
1742 minusIdSet = minusUniqSet
1743 isEmptyIdSet = isEmptyUniqSet
1748 addId, nmbrId, nmbrDataCon :: Id -> NmbrM Id
1750 addId id@(Id u n ty det prag info) nenv@(NmbrEnv ui ut uu idenv tvenv uvenv)
1751 = case (lookupUFM_Directly idenv u) of
1752 Just xx -> trace "addId: already in map!" $
1755 if toplevelishId id then
1756 trace "addId: can't add toplevelish!" $
1758 else -- alloc a new unique for this guy
1759 -- and add an entry in the idenv
1760 -- NB: *** KNOT-TYING ***
1762 nenv_plus_id = NmbrEnv (incrUnique ui) ut uu
1763 (addToUFM_Directly idenv u new_id)
1766 (nenv2, new_ty) = nmbrType ty nenv_plus_id
1767 (nenv3, new_det) = nmbr_details det nenv2
1769 new_id = Id ui n new_ty new_det prag info
1773 nmbrId id@(Id u n ty det prag info) nenv@(NmbrEnv ui ut uu idenv tvenv uvenv)
1774 = case (lookupUFM_Directly idenv u) of
1775 Just xx -> (nenv, xx)
1777 if not (toplevelishId id) then
1778 trace "nmbrId: lookup failed" $
1782 (nenv2, new_ty) = nmbrType ty nenv
1783 (nenv3, new_det) = nmbr_details det nenv2
1785 new_id = Id u n new_ty new_det prag info
1789 -- used when renumbering TyCons to produce data decls...
1790 nmbrDataCon id@(Id _ _ _ (TupleConId _) _ _) nenv
1791 = (nenv, id) -- nothing to do for tuples
1793 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)
1794 = case (lookupUFM_Directly idenv u) of
1795 Just xx -> trace "nmbrDataCon: in env???\n" (nenv, xx)
1798 (nenv2, new_fields) = (mapNmbr nmbrField fields) nenv
1799 (nenv3, new_arg_tys) = (mapNmbr nmbrType arg_tys) nenv2
1801 new_det = DataConId tag marks new_fields (bottom "tvs") (bottom "theta") new_arg_tys tc
1802 new_id = Id u n (bottom "ty") new_det prag info
1806 bottom msg = panic ("nmbrDataCon"++msg)
1809 nmbr_details :: IdDetails -> NmbrM IdDetails
1811 nmbr_details (DataConId tag marks fields tvs theta arg_tys tc)
1812 = mapNmbr nmbrTyVar tvs `thenNmbr` \ new_tvs ->
1813 mapNmbr nmbrField fields `thenNmbr` \ new_fields ->
1814 mapNmbr nmbr_theta theta `thenNmbr` \ new_theta ->
1815 mapNmbr nmbrType arg_tys `thenNmbr` \ new_arg_tys ->
1816 returnNmbr (DataConId tag marks new_fields new_tvs new_theta new_arg_tys tc)
1819 = --nmbrClass c `thenNmbr` \ new_c ->
1820 nmbrType t `thenNmbr` \ new_t ->
1821 returnNmbr (c, new_t)
1823 -- ToDo:add more cases as needed
1824 nmbr_details other_details = returnNmbr other_details
1827 nmbrField (FieldLabel n ty tag)
1828 = nmbrType ty `thenNmbr` \ new_ty ->
1829 returnNmbr (FieldLabel n new_ty tag)