[project @ 1998-02-03 17:13:54 by simonm]
[ghc-hetmet.git] / ghc / compiler / basicTypes / Id.lhs
1
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
3 %
4 \section[Id]{@Ids@: Value and constructor identifiers}
5
6 \begin{code}
7 module Id (
8         -- TYPES
9         GenId(..), -- *naughtily* used in some places (e.g., TcHsSyn)
10         Id, IdDetails,
11         StrictnessMark(..),
12         ConTag, fIRST_TAG,
13         DataCon, DictFun, DictVar,
14
15         -- CONSTRUCTION
16         mkDataCon,
17         mkDefaultMethodId,
18         mkDictFunId,
19         mkIdWithNewUniq, mkIdWithNewName, mkIdWithNewType,
20         mkImported,
21         mkMethodSelId,
22         mkRecordSelId,
23         mkSuperDictSelId,
24         mkSysLocal,
25         mkTemplateLocals,
26         mkTupleCon,
27         mkUserId,
28         mkUserLocal,
29         mkPrimitiveId, 
30         mkWorkerId,
31         setIdVisibility,
32
33         -- DESTRUCTION (excluding pragmatic info)
34         idPrimRep,
35         idType,
36         idUnique,
37         idName,
38
39         dataConRepType,
40         dataConArgTys,
41         dataConNumFields,
42         dataConFieldLabels,
43         dataConRawArgTys,
44         dataConSig,
45         dataConStrictMarks,
46         dataConTag,
47         dataConTyCon,
48
49         recordSelectorFieldLabel,
50
51         -- PREDICATES
52         omitIfaceSigForId,
53         cmpEqDataCon,
54         cmpId,
55         cmpId_withSpecDataCon,
56         externallyVisibleId,
57         idHasNoFreeTyVars,
58         idWantsToBeINLINEd, getInlinePragma, 
59         idMustBeINLINEd, idMustNotBeINLINEd,
60         isBottomingId,
61         isDataCon, isAlgCon, isNewCon,
62         isDefaultMethodId,
63         isDefaultMethodId_maybe,
64         isDictFunId,
65         isImportedId,
66         isRecordSelector,
67         isMethodSelId_maybe,
68         isNullaryDataCon,
69         isSpecPragmaId,
70         isSuperDictSelId_maybe,
71         isPrimitiveId_maybe,
72         isSysLocalId,
73         isTupleCon,
74         isWrapperId,
75         toplevelishId,
76         unfoldingUnfriendlyId,
77
78         -- SUBSTITUTION
79         applyTypeEnvToId,
80         apply_to_Id,
81         
82         -- PRINTING and RENUMBERING
83         pprId,
84 --      pprIdInUnfolding,
85         showId,
86
87         -- Specialialisation
88         getIdSpecialisation,
89         addIdSpecialisation,
90
91         -- UNFOLDING, ARITY, UPDATE, AND STRICTNESS STUFF (etc)
92         addIdUnfolding,
93         addIdArity,
94         addIdDemandInfo,
95         addIdStrictness,
96         addIdUpdateInfo,
97         getIdArity,
98         getIdDemandInfo,
99         getIdInfo,
100         getIdStrictness,
101         getIdUnfolding,
102         getIdUpdateInfo,
103         getPragmaInfo,
104         replaceIdInfo, replacePragmaInfo,
105         addInlinePragma, nukeNoInlinePragma, addNoInlinePragma,
106
107         -- IdEnvs AND IdSets
108         IdEnv, GenIdSet, IdSet,
109         addOneToIdEnv,
110         addOneToIdSet,
111         combineIdEnvs,
112         delManyFromIdEnv,
113         delOneFromIdEnv,
114         elementOfIdSet,
115         emptyIdSet,
116         growIdEnv,
117         growIdEnvList,
118         idSetToList,
119         intersectIdSets,
120         isEmptyIdSet,
121         isNullIdEnv,
122         lookupIdEnv,
123         lookupNoFailIdEnv,
124         mapIdEnv,
125         minusIdSet,
126         mkIdEnv,
127         mkIdSet,
128         modifyIdEnv,
129         modifyIdEnv_Directly,
130         nullIdEnv,
131         rngIdEnv,
132         unionIdSets,
133         unionManyIdSets,
134         unitIdEnv,
135         unitIdSet
136     ) where
137
138 #include "HsVersions.h"
139
140 import {-# SOURCE #-} CoreUnfold ( Unfolding )
141 import {-# SOURCE #-} StdIdInfo  ( addStandardIdInfo )
142
143 import CmdLineOpts      ( opt_PprStyle_All )
144 import SpecEnv          ( SpecEnv   )
145 import Bag
146 import Class            ( Class )
147 import BasicTypes       ( Arity )
148 import IdInfo
149 import Maybes           ( maybeToBool )
150 import Name             ( nameUnique, mkLocalName, mkSysLocalName, isLocalName,
151                           mkCompoundName, occNameString, modAndOcc,
152                           changeUnique, isWiredInName, setNameVisibility,
153                           ExportFlag(..), Provenance,
154                           OccName(..), Name, Module,
155                           NamedThing(..)
156                         ) 
157 import PrimOp           ( PrimOp )
158 import PrelMods         ( pREL_TUP, pREL_BASE )
159 import FieldLabel       ( fieldLabelName, FieldLabel(..){-instances-} )
160 import PragmaInfo       ( PragmaInfo(..) )
161 import SrcLoc           ( mkBuiltinSrcLoc )
162 import TysWiredIn       ( tupleTyCon )
163 import TyCon            ( TyCon, tyConDataCons, isDataTyCon, isNewTyCon, mkSpecTyCon )
164 import Type             ( mkSigmaTy, mkTyVarTys, mkFunTys,
165                           mkTyConApp, instantiateTy, mkForAllTys,
166                           tyVarsOfType, instantiateTy, typePrimRep,
167                           instantiateTauTy,
168                           GenType, ThetaType, TauType, Type
169                         )
170 import TyVar            ( TyVar, alphaTyVars, isEmptyTyVarSet, 
171                           TyVarEnv, zipTyVarEnv, mkTyVarEnv
172                         )
173 import UniqFM
174 import UniqSet          -- practically all of it
175 import Unique           ( getBuiltinUniques, Unique, Uniquable(..) )
176 import Outputable
177 import SrcLoc           ( SrcLoc )
178 import Util             ( nOfThem, assoc )
179 import GlaExts          ( Int# )
180 \end{code}
181
182 Here are the @Id@ and @IdDetails@ datatypes; also see the notes that
183 follow.
184
185 Every @Id@ has a @Unique@, to uniquify it and for fast comparison, a
186 @Type@, and an @IdInfo@ (non-essential info about it, e.g.,
187 strictness).  The essential info about different kinds of @Ids@ is
188 in its @IdDetails@.
189
190 ToDo: possibly cache other stuff in the single-constructor @Id@ type.
191
192 \begin{code}
193 data GenId ty = Id
194         Unique          -- Key for fast comparison
195         Name
196         ty              -- Id's type; used all the time;
197         IdDetails       -- Stuff about individual kinds of Ids.
198         PragmaInfo      -- Properties of this Id requested by programmer
199                         -- eg specialise-me, inline-me
200         IdInfo          -- Properties of this Id deduced by compiler
201                                    
202 type Id            = GenId Type
203
204 data StrictnessMark = MarkedStrict | NotMarkedStrict
205
206 data IdDetails
207
208   ---------------- Local values
209
210   = LocalId     Bool            -- Local name; mentioned by the user
211                                 -- True <=> no free type vars
212
213   | SysLocalId  Bool            -- Local name; made up by the compiler
214                                 -- as for LocalId
215
216   | PrimitiveId PrimOp          -- The Id for a primitive operation
217
218   | SpecPragmaId                -- Local name; introduced by the compiler
219                  (Maybe Id)     -- for explicit specid in pragma
220                  Bool           -- as for LocalId
221
222   ---------------- Global values
223
224   | ImportedId                  -- Global name (Imported or Implicit); Id imported from an interface
225
226   ---------------- Data constructors
227
228   | AlgConId                    -- Used for both data and newtype constructors.
229                                 -- You can tell the difference by looking at the TyCon
230                 ConTag
231                 [StrictnessMark] -- Strict args; length = arity
232                 [FieldLabel]    -- Field labels for this constructor; 
233                                 --length = 0 (not a record) or arity
234
235                 [TyVar] ThetaType       -- Type vars and context for the data type decl
236                 [TyVar] ThetaType       -- Ditto for the context of the constructor, 
237                                         -- the existentially quantified stuff
238                 [Type] TyCon            -- Args and result tycon
239                                 -- the type is:
240                                 -- forall tyvars1 ++ tyvars2. theta1 ++ theta2 =>
241                                 --    unitype_1 -> ... -> unitype_n -> tycon tyvars
242
243   | TupleConId  Int             -- Its arity
244
245   | RecordSelId FieldLabel
246
247   ---------------- Things to do with overloading
248
249   | SuperDictSelId              -- Selector for superclass dictionary
250                 Class           -- The class (input dict)
251                 Class           -- The superclass (result dict)
252
253   | MethodSelId Class           -- An overloaded class operation, with
254                                 -- a fully polymorphic type.  Its code
255                                 -- just selects a method from the
256                                 -- dictionary.
257
258         -- NB: The IdInfo for a MethodSelId has all the info about its
259         -- related "constant method Ids", which are just
260         -- specialisations of this general one.
261
262   | DefaultMethodId             -- Default method for a particular class op
263                 Class           -- same class, <blah-blah> info as MethodSelId
264
265                                 -- see below
266   | DictFunId   Class           -- A DictFun is uniquely identified
267                 [Type]          -- by its class and type; this type has free type vars,
268                                 -- whose identity is irrelevant.  Eg Class = Eq
269                                 --                                   Type  = Tree a
270                                 -- The "a" is irrelevant.  As it is too painful to
271                                 -- actually do comparisons that way, we kindly supply
272                                 -- a Unique for that purpose.
273
274   | SpecId                      -- A specialisation of another Id
275                 Id              -- Id of which this is a specialisation
276                 [Maybe Type]    -- Types at which it is specialised;
277                                 -- A "Nothing" says this type ain't relevant.
278                 Bool            -- True <=> no free type vars; it's not enough
279                                 -- to know about the unspec version, because
280                                 -- we may specialise to a type w/ free tyvars
281                                 -- (i.e., in one of the "Maybe Type" dudes).
282
283 type ConTag     = Int
284 type DictVar    = Id
285 type DictFun    = Id
286 type DataCon    = Id
287 \end{code}
288
289 DictFunIds are generated from instance decls.
290 \begin{verbatim}
291         class Foo a where
292           op :: a -> a -> Bool
293
294         instance Foo a => Foo [a] where
295           op = ...
296 \end{verbatim}
297 generates the dict fun id decl
298 \begin{verbatim}
299         dfun.Foo.[*] = \d -> ...
300 \end{verbatim}
301 The dfun id is uniquely named by the (class, type) pair.  Notice, it
302 isn't a (class,tycon) pair any more, because we may get manually or
303 automatically generated specialisations of the instance decl:
304 \begin{verbatim}
305         instance Foo [Int] where
306           op = ...
307 \end{verbatim}
308 generates
309 \begin{verbatim}
310         dfun.Foo.[Int] = ...
311 \end{verbatim}
312 The type variables in the name are irrelevant; we print them as stars.
313
314
315 Constant method ids are generated from instance decls where
316 there is no context; that is, no dictionaries are needed to
317 construct the method.  Example
318 \begin{verbatim}
319         instance Foo Int where
320           op = ...
321 \end{verbatim}
322 Then we get a constant method
323 \begin{verbatim}
324         Foo.op.Int = ...
325 \end{verbatim}
326
327 It is possible, albeit unusual, to have a constant method
328 for an instance decl which has type vars:
329 \begin{verbatim}
330         instance Foo [a] where
331           op []     ys = True
332           op (x:xs) ys = False
333 \end{verbatim}
334 We get the constant method
335 \begin{verbatim}
336         Foo.op.[*] = ...
337 \end{verbatim}
338 So a constant method is identified by a class/op/type triple.
339 The type variables in the type are irrelevant.
340
341
342 For Ids whose names must be known/deducible in other modules, we have
343 to conjure up their worker's names (and their worker's worker's
344 names... etc) in a known systematic way.
345
346
347 %************************************************************************
348 %*                                                                      *
349 \subsection[Id-documentation]{Documentation}
350 %*                                                                      *
351 %************************************************************************
352
353 [A BIT DATED [WDP]]
354
355 The @Id@ datatype describes {\em values}.  The basic things we want to
356 know: (1)~a value's {\em type} (@idType@ is a very common
357 operation in the compiler); and (2)~what ``flavour'' of value it might
358 be---for example, it can be terribly useful to know that a value is a
359 class method.
360
361 \begin{description}
362 %----------------------------------------------------------------------
363 \item[@AlgConId@:] For the data constructors declared by a @data@
364 declaration.  Their type is kept in {\em two} forms---as a regular
365 @Type@ (in the usual place), and also in its constituent pieces (in
366 the ``details''). We are frequently interested in those pieces.
367
368 %----------------------------------------------------------------------
369 \item[@TupleConId@:] This is just a special shorthand for @DataCons@ for
370 the infinite family of tuples.
371
372 %----------------------------------------------------------------------
373 \item[@ImportedId@:] These are values defined outside this module.
374 {\em Everything} we want to know about them must be stored here (or in
375 their @IdInfo@).
376
377 %----------------------------------------------------------------------
378 \item[@MethodSelId@:] A selector from a dictionary; it may select either
379 a method or a dictionary for one of the class's superclasses.
380
381 %----------------------------------------------------------------------
382 \item[@DictFunId@:]
383
384 @mkDictFunId [a,b..] theta C T@ is the function derived from the
385 instance declaration
386
387         instance theta => C (T a b ..) where
388                 ...
389
390 It builds function @Id@ which maps dictionaries for theta,
391 to a dictionary for C (T a b ..).
392
393 *Note* that with the ``Mark Jones optimisation'', the theta may
394 include dictionaries for the immediate superclasses of C at the type
395 (T a b ..).
396
397 %----------------------------------------------------------------------
398 \item[@SpecId@:]
399
400 %----------------------------------------------------------------------
401 \item[@LocalId@:] A purely-local value, e.g., a function argument,
402 something defined in a @where@ clauses, ... --- but which appears in
403 the original program text.
404
405 %----------------------------------------------------------------------
406 \item[@SysLocalId@:] Same as a @LocalId@, except does {\em not} appear in
407 the original program text; these are introduced by the compiler in
408 doing its thing.
409
410 %----------------------------------------------------------------------
411 \item[@SpecPragmaId@:] Introduced by the compiler to record
412 Specialisation pragmas. It is dead code which MUST NOT be removed
413 before specialisation.
414 \end{description}
415
416 Further remarks:
417 \begin{enumerate}
418 %----------------------------------------------------------------------
419 \item
420
421 @DataCons@ @TupleCons@, @Importeds@, @SuperDictSelIds@,
422 @MethodSelIds@, @DictFunIds@, and @DefaultMethodIds@ have the following
423 properties:
424 \begin{itemize}
425 \item
426 They have no free type variables, so if you are making a
427 type-variable substitution you don't need to look inside them.
428 \item
429 They are constants, so they are not free variables.  (When the STG
430 machine makes a closure, it puts all the free variables in the
431 closure; the above are not required.)
432 \end{itemize}
433 Note that @Locals@ and @SysLocals@ {\em may} have the above
434 properties, but they may not.
435 \end{enumerate}
436
437 %************************************************************************
438 %*                                                                      *
439 \subsection[Id-general-funs]{General @Id@-related functions}
440 %*                                                                      *
441 %************************************************************************
442
443 \begin{code}
444 -- isDataCon returns False for @newtype@ constructors
445 isDataCon (Id _ _ _ (AlgConId _ _ _ _ _ _ _ _ tc) _ _) = isDataTyCon tc
446 isDataCon (Id _ _ _ (TupleConId _) _ _)                 = True
447 isDataCon (Id _ _ _ (SpecId unspec _ _) _ _)            = isDataCon unspec
448 isDataCon other                                         = False
449
450 isNewCon (Id _ _ _ (AlgConId _ _ _ _ _ _ _ _ tc) _ _) = isNewTyCon tc
451 isNewCon other                                         = False
452
453 -- isAlgCon returns True for @data@ or @newtype@ constructors
454 isAlgCon (Id _ _ _ (AlgConId _ _ _ _ _ _ _ _ _) _ _) = True
455 isAlgCon (Id _ _ _ (TupleConId _) _ _)                = True
456 isAlgCon (Id _ _ _ (SpecId unspec _ _) _ _)           = isAlgCon unspec
457 isAlgCon other                                        = False
458
459 isTupleCon (Id _ _ _ (TupleConId _) _ _)         = True
460 isTupleCon (Id _ _ _ (SpecId unspec _ _) _ _)    = isTupleCon unspec
461 isTupleCon other                                 = False
462 \end{code}
463
464 @toplevelishId@ tells whether an @Id@ {\em may} be defined in a nested
465 @let(rec)@ (returns @False@), or whether it is {\em sure} to be
466 defined at top level (returns @True@). This is used to decide whether
467 the @Id@ is a candidate free variable. NB: you are only {\em sure}
468 about something if it returns @True@!
469
470 \begin{code}
471 toplevelishId     :: Id -> Bool
472 idHasNoFreeTyVars :: Id -> Bool
473
474 toplevelishId (Id _ _ _ details _ _)
475   = chk details
476   where
477     chk (AlgConId _ __ _ _ _ _ _ _)   = True
478     chk (TupleConId _)              = True
479     chk (RecordSelId _)             = True
480     chk ImportedId                  = True
481     chk (SuperDictSelId _ _)        = True
482     chk (MethodSelId _)             = True
483     chk (DefaultMethodId _)         = True
484     chk (DictFunId     _ _)         = True
485     chk (SpecId unspec _ _)         = toplevelishId unspec
486                                     -- depends what the unspecialised thing is
487     chk (LocalId      _)            = False
488     chk (SysLocalId   _)            = False
489     chk (SpecPragmaId _ _)          = False
490     chk (PrimitiveId _)             = True
491
492 idHasNoFreeTyVars (Id _ _ _ details _ info)
493   = chk details
494   where
495     chk (AlgConId _ _ _ _ _ _ _ _ _) = True
496     chk (TupleConId _)            = True
497     chk (RecordSelId _)           = True
498     chk ImportedId                = True
499     chk (SuperDictSelId _ _)      = True
500     chk (MethodSelId _)           = True
501     chk (DefaultMethodId _)       = True
502     chk (DictFunId     _ _)       = True
503     chk (SpecId _     _   no_free_tvs) = no_free_tvs
504     chk (LocalId        no_free_tvs) = no_free_tvs
505     chk (SysLocalId     no_free_tvs) = no_free_tvs
506     chk (SpecPragmaId _ no_free_tvs) = no_free_tvs
507     chk (PrimitiveId _)             = True
508
509 -- omitIfaceSigForId tells whether an Id's info is implied by other declarations,
510 -- so we don't need to put its signature in an interface file, even if it's mentioned
511 -- in some other interface unfolding.
512
513 omitIfaceSigForId
514         :: Id
515         -> Bool
516
517 omitIfaceSigForId (Id _ name _ details _ _)
518   | isWiredInName name
519   = True
520
521   | otherwise
522   = case details of
523         ImportedId        -> True               -- Never put imports in interface file
524         (PrimitiveId _)   -> True               -- Ditto, for primitives
525
526         -- This group is Ids that are implied by their type or class decl;
527         -- remember that all type and class decls appear in the interface file.
528         -- The dfun id must *not* be omitted, because it carries version info for
529         -- the instance decl
530         (AlgConId _ _ _ _ _ _ _ _ _) -> True
531         (TupleConId _)            -> True
532         (RecordSelId _)           -> True
533         (SuperDictSelId _ _)      -> True
534         (MethodSelId _)           -> True
535
536         other                     -> False      -- Don't omit!
537                 -- NB DefaultMethodIds are not omitted
538 \end{code}
539
540 \begin{code}
541 isImportedId (Id _ _ _ ImportedId _ _) = True
542 isImportedId other                     = False
543
544 isBottomingId (Id _ _ _ _ _ info) = bottomIsGuaranteed (strictnessInfo info)
545
546 isSysLocalId (Id _ _ _ (SysLocalId _) _ _) = True
547 isSysLocalId other                         = False
548
549 isSpecPragmaId (Id _ _ _ (SpecPragmaId _ _) _ _) = True
550 isSpecPragmaId other                             = False
551
552 isSpecId_maybe (Id _ _ _ (SpecId unspec ty_maybes _) _ _)
553   = ASSERT(not (maybeToBool (isSpecId_maybe unspec)))
554     Just (unspec, ty_maybes)
555 isSpecId_maybe other_id
556   = Nothing
557
558 isMethodSelId_maybe (Id _ _ _ (MethodSelId cls) _ _) = Just cls
559 isMethodSelId_maybe _                                = Nothing
560
561 isDefaultMethodId (Id _ _ _ (DefaultMethodId _) _ _) = True
562 isDefaultMethodId other                              = False
563
564 isDefaultMethodId_maybe (Id _ _ _ (DefaultMethodId cls) _ _)
565   = Just cls
566 isDefaultMethodId_maybe other = Nothing
567
568 isDictFunId (Id _ _ _ (DictFunId _ _) _ _) = True
569 isDictFunId other                          = False
570
571 isSuperDictSelId_maybe (Id _ _ _ (SuperDictSelId c sc) _ _) = Just (c, sc)
572 isSuperDictSelId_maybe other_id                           = Nothing
573
574 isWrapperId id = workerExists (getIdStrictness id)
575
576 isPrimitiveId_maybe (Id _ _ _ (PrimitiveId primop) _ _) = Just primop
577 isPrimitiveId_maybe other                               = Nothing
578 \end{code}
579
580 \begin{code}
581 unfoldingUnfriendlyId   -- return True iff it is definitely a bad
582         :: Id           -- idea to export an unfolding that
583         -> Bool         -- mentions this Id.  Reason: it cannot
584                         -- possibly be seen in another module.
585
586 unfoldingUnfriendlyId id = not (externallyVisibleId id)
587 \end{code}
588
589 @externallyVisibleId@: is it true that another module might be
590 able to ``see'' this Id in a code generation sense. That
591 is, another .o file might refer to this Id.
592
593 In tidyCorePgm (SimplCore.lhs) we carefully set each top level thing's
594 local-ness precisely so that the test here would be easy
595
596 \begin{code}
597 externallyVisibleId :: Id -> Bool
598 externallyVisibleId id@(Id _ name _ _ _ _) = not (isLocalName name)
599                      -- not local => global => externally visible
600 \end{code}
601
602 CLAIM (not ASSERTed) for @applyTypeEnvToId@ and @applySubstToId@:
603 `Top-levelish Ids'' cannot have any free type variables, so applying
604 the type-env cannot have any effect.  (NB: checked in CoreLint?)
605
606 \begin{code}
607 type TypeEnv = TyVarEnv Type
608
609 applyTypeEnvToId :: TypeEnv -> Id -> Id
610 applyTypeEnvToId type_env id@(Id _ _ ty _ _ _)
611   = apply_to_Id ( \ ty ->
612         instantiateTy type_env ty
613     ) id
614 \end{code}
615
616 \begin{code}
617 apply_to_Id :: (Type -> Type) -> Id -> Id
618
619 apply_to_Id ty_fn id@(Id u n ty details prag info)
620   | idHasNoFreeTyVars id
621   = id
622   | otherwise
623   = Id u n (ty_fn ty) (apply_to_details details) prag (apply_to_IdInfo ty_fn info)
624   where
625     apply_to_details (SpecId unspec ty_maybes no_ftvs)
626       = let
627             new_unspec = apply_to_Id ty_fn unspec
628             new_maybes = map apply_to_maybe ty_maybes
629         in
630         SpecId new_unspec new_maybes (no_free_tvs ty)
631         -- ToDo: gratuitous recalc no_ftvs????
632       where
633         apply_to_maybe Nothing   = Nothing
634         apply_to_maybe (Just ty) = Just (ty_fn ty)
635
636     apply_to_details other = other
637 \end{code}
638
639
640 %************************************************************************
641 %*                                                                      *
642 \subsection[Id-type-funs]{Type-related @Id@ functions}
643 %*                                                                      *
644 %************************************************************************
645
646 \begin{code}
647 idName :: GenId ty -> Name
648 idName (Id _ n _ _ _ _) = n
649
650 idType :: GenId ty -> ty
651 idType (Id _ _ ty _ _ _) = ty
652
653 idPrimRep i = typePrimRep (idType i)
654 \end{code}
655
656 %************************************************************************
657 %*                                                                      *
658 \subsection[Id-overloading]{Functions related to overloading}
659 %*                                                                      *
660 %************************************************************************
661
662 \begin{code}
663 mkSuperDictSelId u clas sc ty
664   = addStandardIdInfo $
665     Id u name ty details NoPragmaInfo noIdInfo
666   where
667     name    = mkCompoundName name_fn u (getName clas)
668     details = SuperDictSelId clas sc
669     name_fn clas_str = SLIT("scsel_") _APPEND_ clas_str _APPEND_ mod _APPEND_ occNameString occ
670     (mod,occ) = modAndOcc sc
671
672         -- For method selectors the clean thing to do is
673         -- to give the method selector the same name as the class op itself.
674 mkMethodSelId op_name rec_c ty
675   = addStandardIdInfo $
676     Id (uniqueOf op_name) op_name ty (MethodSelId rec_c) NoPragmaInfo noIdInfo
677
678 mkDefaultMethodId dm_name rec_c ty
679   = Id (uniqueOf dm_name) dm_name ty (DefaultMethodId rec_c) NoPragmaInfo noIdInfo
680
681 mkDictFunId dfun_name full_ty clas itys
682   = Id (nameUnique dfun_name) dfun_name full_ty details NoPragmaInfo noIdInfo
683   where
684     details  = DictFunId clas itys
685
686 mkWorkerId u unwrkr ty info
687   = Id u name ty details NoPragmaInfo info
688   where
689     details = LocalId (no_free_tvs ty)
690     name    = mkCompoundName name_fn u (getName unwrkr)
691     name_fn wkr_str = SLIT("$w") _APPEND_ wkr_str
692 \end{code}
693
694 %************************************************************************
695 %*                                                                      *
696 \subsection[local-funs]{@LocalId@-related functions}
697 %*                                                                      *
698 %************************************************************************
699
700 \begin{code}
701 mkImported  n ty info = Id (nameUnique n) n ty ImportedId NoPragmaInfo info
702
703 mkPrimitiveId n ty primop 
704   = addStandardIdInfo $
705     Id (nameUnique n) n ty (PrimitiveId primop) IMustBeINLINEd noIdInfo
706         -- The pragma @IMustBeINLINEd@ says that this Id absolutely must be inlined.
707         -- It's only true for primitives, because we don't want to make a closure for each of them.
708
709 \end{code}
710
711 \begin{code}
712 no_free_tvs ty = isEmptyTyVarSet (tyVarsOfType ty)
713
714 -- SysLocal: for an Id being created by the compiler out of thin air...
715 -- UserLocal: an Id with a name the user might recognize...
716 mkSysLocal  :: FAST_STRING -> Unique -> GenType flexi -> SrcLoc -> GenId (GenType flexi)
717 mkUserLocal :: OccName     -> Unique -> GenType flexi -> SrcLoc -> GenId (GenType flexi)
718
719 mkSysLocal str uniq ty loc
720   = Id uniq (mkSysLocalName uniq str loc) ty (SysLocalId (no_free_tvs ty)) NoPragmaInfo noIdInfo
721
722 mkUserLocal occ uniq ty loc
723   = Id uniq (mkLocalName uniq occ loc) ty (LocalId (no_free_tvs ty)) NoPragmaInfo noIdInfo
724
725 mkUserId :: Name -> GenType flexi -> PragmaInfo -> GenId (GenType flexi)
726 mkUserId name ty pragma_info
727   = Id (nameUnique name) name ty (LocalId (no_free_tvs ty)) pragma_info noIdInfo
728 \end{code}
729
730 \begin{code}
731 -- See notes with setNameVisibility (Name.lhs)
732 setIdVisibility :: Maybe Module -> Unique -> Id -> Id
733 setIdVisibility maybe_mod u (Id uniq name ty details prag info)
734   = Id uniq (setNameVisibility maybe_mod u name) ty details prag info
735
736 mkIdWithNewUniq :: Id -> Unique -> Id
737 mkIdWithNewUniq (Id _ n ty details prag info) u
738   = Id u (changeUnique n u) ty details prag info
739
740 mkIdWithNewName :: Id -> Name -> Id
741 mkIdWithNewName (Id _ _ ty details prag info) new_name
742   = Id (uniqueOf new_name) new_name ty details prag info
743
744 mkIdWithNewType :: Id -> Type -> Id
745 mkIdWithNewType (Id u name _ details pragma info) ty 
746   = Id u name ty details pragma info
747
748 {-
749 -- Specialised version of constructor: only used in STG and code generation
750 -- Note: The specialsied Id has the same unique as the unspeced Id
751
752 mkSameSpecCon ty_maybes unspec@(Id u name ty details pragma info)
753   = ASSERT(isDataCon unspec)
754     ASSERT(not (maybeToBool (isSpecId_maybe unspec)))
755     Id u name new_ty (SpecId unspec ty_maybes (no_free_tvs new_ty)) pragma info
756   where
757     new_ty = specialiseTy ty ty_maybes 0
758
759     -- pprTrace "SameSpecCon:Unique:"
760     --          (ppSep (ppr unspec: [pprMaybeTy ty | ty <- ty_maybes]))
761 -}
762 \end{code}
763
764 Make some local @Ids@ for a template @CoreExpr@.  These have bogus
765 @Uniques@, but that's OK because the templates are supposed to be
766 instantiated before use.
767 \begin{code}
768 mkTemplateLocals :: [Type] -> [Id]
769 mkTemplateLocals tys
770   = zipWith (\ u -> \ ty -> mkSysLocal SLIT("tpl") u ty mkBuiltinSrcLoc)
771             (getBuiltinUniques (length tys))
772             tys
773 \end{code}
774
775 \begin{code}
776 getIdInfo     :: GenId ty -> IdInfo
777 getPragmaInfo :: GenId ty -> PragmaInfo
778
779 getIdInfo     (Id _ _ _ _ _ info) = info
780 getPragmaInfo (Id _ _ _ _ info _) = info
781
782 replaceIdInfo :: Id -> IdInfo -> Id
783 replaceIdInfo (Id u n ty details pinfo _) info = Id u n ty details pinfo info
784
785 replacePragmaInfo :: GenId ty -> PragmaInfo -> GenId ty
786 replacePragmaInfo (Id u sn ty details _ info) prag = Id u sn ty details prag info
787 \end{code}
788
789 %************************************************************************
790 %*                                                                      *
791 \subsection[Id-arities]{Arity-related functions}
792 %*                                                                      *
793 %************************************************************************
794
795 For locally-defined Ids, the code generator maintains its own notion
796 of their arities; so it should not be asking...  (but other things
797 besides the code-generator need arity info!)
798
799 \begin{code}
800 getIdArity :: Id -> ArityInfo
801 getIdArity id@(Id _ _ _ _ _ id_info)
802   = arityInfo id_info
803
804 addIdArity :: Id -> ArityInfo -> Id
805 addIdArity (Id u n ty details pinfo info) arity
806   = Id u n ty details pinfo (info `addArityInfo` arity)
807 \end{code}
808
809 %************************************************************************
810 %*                                                                      *
811 \subsection[constructor-funs]{@DataCon@-related functions (incl.~tuples)}
812 %*                                                                      *
813 %************************************************************************
814
815 \begin{code}
816 mkDataCon :: Name
817           -> [StrictnessMark] -> [FieldLabel]
818           -> [TyVar] -> ThetaType
819           -> [TyVar] -> ThetaType
820           -> [TauType] -> TyCon
821           -> Id
822   -- can get the tag and all the pieces of the type from the Type
823
824 mkDataCon n stricts fields tvs ctxt con_tvs con_ctxt args_tys tycon
825   = ASSERT(length stricts == length args_tys)
826     addStandardIdInfo data_con
827   where
828     -- NB: data_con self-recursion; should be OK as tags are not
829     -- looked at until late in the game.
830     data_con
831       = Id (nameUnique n)
832            n
833            data_con_ty
834            (AlgConId data_con_tag stricts fields tvs ctxt con_tvs con_ctxt args_tys tycon)
835            IWantToBeINLINEd     -- Always inline constructors if possible
836            noIdInfo
837
838     data_con_tag    = assoc "mkDataCon" (data_con_family `zip` [fIRST_TAG..]) data_con
839     data_con_family = tyConDataCons tycon
840
841     data_con_ty
842       = mkSigmaTy (tvs++con_tvs) (ctxt++con_ctxt)
843         (mkFunTys args_tys (mkTyConApp tycon (mkTyVarTys tvs)))
844
845
846 mkTupleCon :: Arity -> Name -> Type -> Id
847 mkTupleCon arity name ty 
848   = addStandardIdInfo tuple_id
849   where
850     tuple_id = Id (nameUnique name) name ty 
851                   (TupleConId arity) 
852                   IWantToBeINLINEd              -- Always inline constructors if possible
853                   noIdInfo
854
855 fIRST_TAG :: ConTag
856 fIRST_TAG =  1  -- Tags allocated from here for real constructors
857 \end{code}
858
859 dataConNumFields gives the number of actual fields in the
860 {\em representation} of the data constructor.  This may be more than appear
861 in the source code; the extra ones are the existentially quantified
862 dictionaries
863
864 \begin{code}
865 dataConNumFields id
866   = ASSERT( if (isDataCon id) then True else
867             pprTrace "dataConNumFields" (ppr id) False )
868     case (dataConSig id) of { (_, _, _, con_theta, arg_tys, _) ->
869     length con_theta + length arg_tys }
870
871 isNullaryDataCon con = dataConNumFields con == 0 -- function of convenience
872
873 \end{code}
874
875
876 \begin{code}
877 dataConTag :: DataCon -> ConTag -- will panic if not a DataCon
878 dataConTag (Id _ _ _ (AlgConId tag _ _ _ _ _ _ _ _) _ _) = tag
879 dataConTag (Id _ _ _ (TupleConId _) _ _)              = fIRST_TAG
880 dataConTag (Id _ _ _ (SpecId unspec _ _) _ _)         = dataConTag unspec
881
882 dataConTyCon :: DataCon -> TyCon        -- will panic if not a DataCon
883 dataConTyCon (Id _ _ _ (AlgConId _ _ _ _ _ _ _ _ tycon) _ _) = tycon
884 dataConTyCon (Id _ _ _ (TupleConId a) _ _)                = tupleTyCon a
885
886 dataConSig :: DataCon -> ([TyVar], ThetaType, [TyVar], ThetaType, [TauType], TyCon)
887                                         -- will panic if not a DataCon
888
889 dataConSig (Id _ _ _ (AlgConId _ _ _ tyvars theta con_tyvars con_theta arg_tys tycon) _ _)
890   = (tyvars, theta, con_tyvars, con_theta, arg_tys, tycon)
891
892 dataConSig (Id _ _ _ (TupleConId arity) _ _)
893   = (tyvars, [], [], [], tyvar_tys, tupleTyCon arity)
894   where
895     tyvars      = take arity alphaTyVars
896     tyvar_tys   = mkTyVarTys tyvars
897
898 dataConSig (Id _ _ _ (SpecId unspec ty_maybes _) _ _)
899   = (spec_tyvars, spec_theta_ty, spec_con_tyvars, spec_con_theta, spec_arg_tys, spec_tycon)
900   where
901     (tyvars, theta_ty, con_tyvars, con_theta, arg_tys, tycon) = dataConSig unspec
902
903     ty_env = tyvars `zip` ty_maybes
904
905     spec_tyvars     = [tyvar | (tyvar, Nothing) <- ty_env]
906     spec_con_tyvars = [tyvar | (tyvar, Nothing) <- con_tyvars `zip` ty_maybes] -- Hmm..
907
908     spec_env = mkTyVarEnv [(tyvar, ty) | (tyvar, Just ty) <- ty_env]
909     spec_arg_tys = map (instantiateTauTy spec_env) arg_tys
910
911     spec_theta_ty  = if null theta_ty then []
912                      else panic "dataConSig:ThetaTy:SpecDataCon1"
913     spec_con_theta = if null con_theta then []
914                      else panic "dataConSig:ThetaTy:SpecDataCon2"
915     spec_tycon     = mkSpecTyCon tycon ty_maybes
916
917
918 -- dataConRepType returns the type of the representation of a contructor
919 -- This may differ from the type of the contructor Id itself for two reasons:
920 --      a) the constructor Id may be overloaded, but the dictionary isn't stored
921 --         e.g.    data Eq a => T a = MkT a a
922 --
923 --      b) the constructor may store an unboxed version of a strict field.
924 --
925 -- Here's an example illustrating both:
926 --      data Ord a => T a = MkT Int! a
927 -- Here
928 --      T :: Ord a => Int -> a -> T a
929 -- but the rep type is
930 --      Trep :: Int# -> a -> T a
931 -- Actually, the unboxed part isn't implemented yet!
932
933 dataConRepType :: Id -> Type
934 dataConRepType (Id _ _ _ (AlgConId _ _ _ tyvars theta con_tyvars con_theta arg_tys tycon) _ _)
935   = mkForAllTys (tyvars++con_tyvars) 
936                 (mkFunTys arg_tys (mkTyConApp tycon (mkTyVarTys tyvars)))
937 dataConRepType other_id
938   = ASSERT( isDataCon other_id )
939     idType other_id
940
941 dataConFieldLabels :: DataCon -> [FieldLabel]
942 dataConFieldLabels (Id _ _ _ (AlgConId _ _ fields _ _ _ _ _ _) _ _) = fields
943 dataConFieldLabels (Id _ _ _ (TupleConId _)                 _ _) = []
944 #ifdef DEBUG
945 dataConFieldLabels x@(Id _ _ _ idt _ _) = 
946   panic ("dataConFieldLabel: " ++
947     (case idt of
948       LocalId _    -> "l"
949       SysLocalId _ -> "sl"
950       PrimitiveId _ -> "p"
951       SpecPragmaId _  _ -> "sp"
952       ImportedId -> "i"
953       RecordSelId _ -> "r"
954       SuperDictSelId _ _ -> "sc"
955       MethodSelId _ -> "m"
956       DefaultMethodId _ -> "d"
957       DictFunId _ _ -> "di"
958       SpecId _ _ _ -> "spec"))
959 #endif
960
961 dataConStrictMarks :: DataCon -> [StrictnessMark]
962 dataConStrictMarks (Id _ _ _ (AlgConId _ stricts _ _ _ _ _ _ _) _ _) = stricts
963 dataConStrictMarks (Id _ _ _ (TupleConId arity)              _ _) 
964   = nOfThem arity NotMarkedStrict
965
966 dataConRawArgTys :: DataCon -> [TauType] -- a function of convenience
967 dataConRawArgTys con = case (dataConSig con) of { (_,_, _, _, arg_tys,_) -> arg_tys }
968
969 dataConArgTys :: DataCon 
970               -> [Type]         -- Instantiated at these types
971               -> [Type]         -- Needs arguments of these types
972 dataConArgTys con_id inst_tys
973  = map (instantiateTy tenv) arg_tys
974  where
975     (tyvars, _, _, _, arg_tys, _) = dataConSig con_id
976     tenv                          = zipTyVarEnv tyvars inst_tys
977 \end{code}
978
979 \begin{code}
980 mkRecordSelId field_label selector_ty
981   = addStandardIdInfo $         -- Record selectors have a standard unfolding
982     Id (nameUnique name)
983        name
984        selector_ty
985        (RecordSelId field_label)
986        NoPragmaInfo
987        noIdInfo
988   where
989     name = fieldLabelName field_label
990
991 recordSelectorFieldLabel :: Id -> FieldLabel
992 recordSelectorFieldLabel (Id _ _ _ (RecordSelId lbl) _ _) = lbl
993
994 isRecordSelector (Id _ _ _ (RecordSelId lbl) _ _) = True
995 isRecordSelector other                            = False
996 \end{code}
997
998
999 Data type declarations are of the form:
1000 \begin{verbatim}
1001 data Foo a b = C1 ... | C2 ... | ... | Cn ...
1002 \end{verbatim}
1003 For each constructor @Ci@, we want to generate a curried function; so, e.g., for
1004 @C1 x y z@, we want a function binding:
1005 \begin{verbatim}
1006 fun_C1 = /\ a -> /\ b -> \ [x, y, z] -> Con C1 [a, b] [x, y, z]
1007 \end{verbatim}
1008 Notice the ``big lambdas'' and type arguments to @Con@---we are producing
1009 2nd-order polymorphic lambda calculus with explicit types.
1010
1011 %************************************************************************
1012 %*                                                                      *
1013 \subsection[unfolding-Ids]{Functions related to @Ids@' unfoldings}
1014 %*                                                                      *
1015 %************************************************************************
1016
1017 \begin{code}
1018 getIdUnfolding :: Id -> Unfolding
1019
1020 getIdUnfolding (Id _ _ _ _ _ info) = unfoldInfo info
1021
1022 addIdUnfolding :: Id -> Unfolding -> Id
1023 addIdUnfolding id@(Id u n ty details prag info) unfolding
1024   = Id u n ty details prag (info `addUnfoldInfo` unfolding)
1025 \end{code}
1026
1027 The inline pragma tells us to be very keen to inline this Id, but it's still
1028 OK not to if optimisation is switched off.
1029
1030 \begin{code}
1031 getInlinePragma :: Id -> PragmaInfo
1032 getInlinePragma (Id _ _ _ _ prag _) = prag
1033
1034 idWantsToBeINLINEd :: Id -> Bool
1035
1036 idWantsToBeINLINEd (Id _ _ _ _ IWantToBeINLINEd _) = True
1037 idWantsToBeINLINEd (Id _ _ _ _ IMustBeINLINEd   _) = True
1038 idWantsToBeINLINEd _                               = False
1039
1040 idMustNotBeINLINEd (Id _ _ _ _ IMustNotBeINLINEd _) = True
1041 idMustNotBeINLINEd _                                = False
1042
1043 idMustBeINLINEd (Id _ _ _ _ IMustBeINLINEd _) = True
1044 idMustBeINLINEd _                             = False
1045
1046 addInlinePragma :: Id -> Id
1047 addInlinePragma (Id u sn ty details _ info)
1048   = Id u sn ty details IWantToBeINLINEd info
1049
1050 nukeNoInlinePragma :: Id -> Id
1051 nukeNoInlinePragma id@(Id u sn ty details IMustNotBeINLINEd info)
1052   = Id u sn ty details NoPragmaInfo info
1053 nukeNoInlinePragma id@(Id u sn ty details _ info) = id          -- Otherwise no-op
1054
1055 addNoInlinePragma :: Id -> Id
1056 addNoInlinePragma id@(Id u sn ty details _ info)
1057   = Id u sn ty details IMustNotBeINLINEd info
1058 \end{code}
1059
1060
1061
1062 %************************************************************************
1063 %*                                                                      *
1064 \subsection[IdInfo-funs]{Functions related to @Ids@' @IdInfos@}
1065 %*                                                                      *
1066 %************************************************************************
1067
1068 \begin{code}
1069 getIdDemandInfo :: Id -> DemandInfo
1070 getIdDemandInfo (Id _ _ _ _ _ info) = demandInfo info
1071
1072 addIdDemandInfo :: Id -> DemandInfo -> Id
1073 addIdDemandInfo (Id u n ty details prags info) demand_info
1074   = Id u n ty details prags (info `addDemandInfo` demand_info)
1075 \end{code}
1076
1077 \begin{code}
1078 getIdUpdateInfo :: Id -> UpdateInfo
1079 getIdUpdateInfo (Id _ _ _ _ _ info) = updateInfo info
1080
1081 addIdUpdateInfo :: Id -> UpdateInfo -> Id
1082 addIdUpdateInfo (Id u n ty details prags info) upd_info
1083   = Id u n ty details prags (info `addUpdateInfo` upd_info)
1084 \end{code}
1085
1086 \begin{code}
1087 {- LATER:
1088 getIdArgUsageInfo :: Id -> ArgUsageInfo
1089 getIdArgUsageInfo (Id u n ty info details) = argUsageInfo info
1090
1091 addIdArgUsageInfo :: Id -> ArgUsageInfo -> Id
1092 addIdArgUsageInfo (Id u n ty info details) au_info
1093   = Id u n ty (info `addArgusageInfo` au_info) details
1094 -}
1095 \end{code}
1096
1097 \begin{code}
1098 {- LATER:
1099 getIdFBTypeInfo :: Id -> FBTypeInfo
1100 getIdFBTypeInfo (Id u n ty info details) = fbTypeInfo info
1101
1102 addIdFBTypeInfo :: Id -> FBTypeInfo -> Id
1103 addIdFBTypeInfo (Id u n ty info details) upd_info
1104   = Id u n ty (info `addFBTypeInfo` upd_info) details
1105 -}
1106 \end{code}
1107
1108 \begin{code}
1109 getIdSpecialisation :: Id -> IdSpecEnv
1110 getIdSpecialisation (Id _ _ _ _ _ info) = specInfo info
1111
1112 addIdSpecialisation :: Id -> IdSpecEnv -> Id
1113 addIdSpecialisation (Id u n ty details prags info) spec_info
1114   = Id u n ty details prags (info `addSpecInfo` spec_info)
1115 \end{code}
1116
1117 Strictness: we snaffle the info out of the IdInfo.
1118
1119 \begin{code}
1120 getIdStrictness :: Id -> StrictnessInfo
1121
1122 getIdStrictness (Id _ _ _ _ _ info) = strictnessInfo info
1123
1124 addIdStrictness :: Id -> StrictnessInfo -> Id
1125 addIdStrictness (Id u n ty details prags info) strict_info
1126   = Id u n ty details prags (info `addStrictnessInfo` strict_info)
1127 \end{code}
1128
1129 %************************************************************************
1130 %*                                                                      *
1131 \subsection[Id-comparison]{Comparison functions for @Id@s}
1132 %*                                                                      *
1133 %************************************************************************
1134
1135 Comparison: equality and ordering---this stuff gets {\em hammered}.
1136
1137 \begin{code}
1138 cmpId (Id u1 _ _ _ _ _) (Id u2 _ _ _ _ _) = compare u1 u2
1139 -- short and very sweet
1140 \end{code}
1141
1142 \begin{code}
1143 instance Eq (GenId ty) where
1144     a == b = case (a `compare` b) of { EQ -> True;  _ -> False }
1145     a /= b = case (a `compare` b) of { EQ -> False; _ -> True  }
1146
1147 instance Ord (GenId ty) where
1148     a <= b = case (a `compare` b) of { LT -> True;  EQ -> True;  GT -> False }
1149     a <  b = case (a `compare` b) of { LT -> True;  EQ -> False; GT -> False }
1150     a >= b = case (a `compare` b) of { LT -> False; EQ -> True;  GT -> True  }
1151     a >  b = case (a `compare` b) of { LT -> False; EQ -> False; GT -> True  }
1152     compare a b = cmpId a b
1153 \end{code}
1154
1155 @cmpId_withSpecDataCon@ ensures that any spectys are taken into
1156 account when comparing two data constructors. We need to do this
1157 because a specialised data constructor has the same Unique as its
1158 unspecialised counterpart.
1159
1160 \begin{code}
1161 cmpId_withSpecDataCon :: Id -> Id -> Ordering
1162
1163 cmpId_withSpecDataCon id1 id2
1164   | eq_ids && isDataCon id1 && isDataCon id2
1165   = cmpEqDataCon id1 id2
1166
1167   | otherwise
1168   = cmp_ids
1169   where
1170     cmp_ids = cmpId id1 id2
1171     eq_ids  = case cmp_ids of { EQ -> True; other -> False }
1172
1173 cmpEqDataCon (Id _ _ _ (SpecId _ mtys1 _) _ _) (Id _ _ _ (SpecId _ mtys2 _) _ _)
1174   = panic "Id.cmpEqDataCon:cmpUniTypeMaybeList mtys1 mtys2"
1175
1176 cmpEqDataCon _ (Id _ _ _ (SpecId _ _ _) _ _) = LT
1177 cmpEqDataCon (Id _ _ _ (SpecId _ _ _) _ _) _ = GT
1178 cmpEqDataCon _                             _ = EQ
1179 \end{code}
1180
1181 %************************************************************************
1182 %*                                                                      *
1183 \subsection[Id-other-instances]{Other instance declarations for @Id@s}
1184 %*                                                                      *
1185 %************************************************************************
1186
1187 \begin{code}
1188 instance Outputable ty => Outputable (GenId ty) where
1189     ppr id = pprId id
1190
1191 showId :: Id -> String
1192 showId id = showSDoc (pprId id)
1193 \end{code}
1194
1195 Default printing code (not used for interfaces):
1196 \begin{code}
1197 pprId :: Outputable ty => GenId ty -> SDoc
1198
1199 pprId (Id u n _ _ prags _)
1200   = hcat [ppr n, pp_prags]
1201   where
1202     pp_prags | opt_PprStyle_All = case prags of
1203                                      IMustNotBeINLINEd -> text "{n}"
1204                                      IWantToBeINLINEd  -> text "{i}"
1205                                      IMustBeINLINEd    -> text "{I}"
1206                                      other             -> empty
1207              | otherwise        = empty
1208
1209   -- WDP 96/05/06: We can re-elaborate this as we go along...
1210 \end{code}
1211
1212 \begin{code}
1213 idUnique (Id u _ _ _ _ _) = u
1214
1215 instance Uniquable (GenId ty) where
1216     uniqueOf = idUnique
1217
1218 instance NamedThing (GenId ty) where
1219     getName this_id@(Id u n _ details _ _) = n
1220 \end{code}
1221
1222 Note: The code generator doesn't carry a @UniqueSupply@, so it uses
1223 the @Uniques@ out of local @Ids@ given to it.
1224
1225 %************************************************************************
1226 %*                                                                      *
1227 \subsection{@IdEnv@s and @IdSet@s}
1228 %*                                                                      *
1229 %************************************************************************
1230
1231 \begin{code}
1232 type IdEnv elt = UniqFM elt
1233
1234 nullIdEnv         :: IdEnv a
1235                   
1236 mkIdEnv           :: [(GenId ty, a)] -> IdEnv a
1237 unitIdEnv         :: GenId ty -> a -> IdEnv a
1238 addOneToIdEnv     :: IdEnv a -> GenId ty -> a -> IdEnv a
1239 growIdEnv         :: IdEnv a -> IdEnv a -> IdEnv a
1240 growIdEnvList     :: IdEnv a -> [(GenId ty, a)] -> IdEnv a
1241                   
1242 delManyFromIdEnv  :: IdEnv a -> [GenId ty] -> IdEnv a
1243 delOneFromIdEnv   :: IdEnv a -> GenId ty -> IdEnv a
1244 combineIdEnvs     :: (a -> a -> a) -> IdEnv a -> IdEnv a -> IdEnv a
1245 mapIdEnv          :: (a -> b) -> IdEnv a -> IdEnv b
1246 modifyIdEnv       :: (a -> a) -> IdEnv a -> GenId ty -> IdEnv a
1247 rngIdEnv          :: IdEnv a -> [a]
1248                   
1249 isNullIdEnv       :: IdEnv a -> Bool
1250 lookupIdEnv       :: IdEnv a -> GenId ty -> Maybe a
1251 lookupNoFailIdEnv :: IdEnv a -> GenId ty -> a
1252 \end{code}
1253
1254 \begin{code}
1255 addOneToIdEnv    = addToUFM
1256 combineIdEnvs    = plusUFM_C
1257 delManyFromIdEnv = delListFromUFM
1258 delOneFromIdEnv  = delFromUFM
1259 growIdEnv        = plusUFM
1260 lookupIdEnv      = lookupUFM
1261 mapIdEnv         = mapUFM
1262 mkIdEnv          = listToUFM
1263 nullIdEnv        = emptyUFM
1264 rngIdEnv         = eltsUFM
1265 unitIdEnv        = unitUFM
1266
1267 growIdEnvList     env pairs = plusUFM env (listToUFM pairs)
1268 isNullIdEnv       env       = sizeUFM env == 0
1269 lookupNoFailIdEnv env id    = case (lookupIdEnv env id) of { Just xx -> xx }
1270
1271 -- modifyIdEnv: Look up a thing in the IdEnv, then mash it with the
1272 -- modify function, and put it back.
1273
1274 modifyIdEnv mangle_fn env key
1275   = case (lookupIdEnv env key) of
1276       Nothing -> env
1277       Just xx -> addOneToIdEnv env key (mangle_fn xx)
1278
1279 modifyIdEnv_Directly mangle_fn env key
1280   = case (lookupUFM_Directly env key) of
1281       Nothing -> env
1282       Just xx -> addToUFM_Directly env key (mangle_fn xx)
1283 \end{code}
1284
1285 \begin{code}
1286 type GenIdSet ty = UniqSet (GenId ty)
1287 type IdSet       = UniqSet (GenId Type)
1288
1289 emptyIdSet      :: GenIdSet ty
1290 intersectIdSets :: GenIdSet ty -> GenIdSet ty -> GenIdSet ty
1291 unionIdSets     :: GenIdSet ty -> GenIdSet ty -> GenIdSet ty
1292 unionManyIdSets :: [GenIdSet ty] -> GenIdSet ty
1293 idSetToList     :: GenIdSet ty -> [GenId ty]
1294 unitIdSet       :: GenId ty -> GenIdSet ty
1295 addOneToIdSet   :: GenIdSet ty -> GenId ty -> GenIdSet ty
1296 elementOfIdSet  :: GenId ty -> GenIdSet ty -> Bool
1297 minusIdSet      :: GenIdSet ty -> GenIdSet ty -> GenIdSet ty
1298 isEmptyIdSet    :: GenIdSet ty -> Bool
1299 mkIdSet         :: [GenId ty] -> GenIdSet ty
1300
1301 emptyIdSet      = emptyUniqSet
1302 unitIdSet       = unitUniqSet
1303 addOneToIdSet   = addOneToUniqSet
1304 intersectIdSets = intersectUniqSets
1305 unionIdSets     = unionUniqSets
1306 unionManyIdSets = unionManyUniqSets
1307 idSetToList     = uniqSetToList
1308 elementOfIdSet  = elementOfUniqSet
1309 minusIdSet      = minusUniqSet
1310 isEmptyIdSet    = isEmptyUniqSet
1311 mkIdSet         = mkUniqSet
1312 \end{code}