[project @ 2000-08-02 14:13:26 by rrt]
[ghc-hetmet.git] / ghc / compiler / basicTypes / Name.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[Name]{@Name@: to transmit name info from renamer to typechecker}
5
6 \begin{code}
7 module Name (
8         -- Re-export the OccName stuff
9         module OccName,
10
11         -- The Name type
12         Name,                                   -- Abstract
13         mkLocalName, mkImportedLocalName, mkSysLocalName, mkCCallName,
14         mkTopName, mkIPName,
15         mkDerivedName, mkGlobalName, mkKnownKeyGlobal,
16         mkWiredInIdName,   mkWiredInTyConName,
17         mkUnboundName, isUnboundName,
18
19         maybeWiredInIdName, maybeWiredInTyConName,
20         isWiredInName, hashName,
21
22         nameUnique, setNameUnique, setNameProvenance, getNameProvenance, setNameImportReason,
23         tidyTopName, 
24         nameOccName, nameModule, setNameOcc, nameRdrName, setNameModule, toRdrName,
25
26         isUserExportedName, isUserImportedName, isUserImportedExplicitlyName, 
27         maybeUserImportedFrom,
28         nameSrcLoc, isLocallyDefinedName, isDllName,
29
30         isSystemName, isLocalName, isGlobalName, isExternallyVisibleName,
31         
32         -- Environment
33         NameEnv, mkNameEnv,
34         emptyNameEnv, unitNameEnv, nameEnvElts, 
35         extendNameEnv_C, extendNameEnv, 
36         plusNameEnv, plusNameEnv_C, extendNameEnv, extendNameEnvList,
37         lookupNameEnv, lookupNameEnv_NF, delFromNameEnv, elemNameEnv, 
38
39
40         -- Provenance
41         Provenance(..), ImportReason(..), pprProvenance,
42         ExportFlag(..), PrintUnqualified,
43         pprNameProvenance, hasBetterProv,
44
45         -- Class NamedThing and overloaded friends
46         NamedThing(..),
47         getSrcLoc, isLocallyDefined, getOccString, toRdrName
48     ) where
49
50 #include "HsVersions.h"
51
52 import {-# SOURCE #-} Var   ( Id, setIdName )
53 import {-# SOURCE #-} TyCon ( TyCon, setTyConName )
54
55 import OccName          -- All of it
56 import Module           ( Module, moduleName, pprModule, mkVanillaModule, isLocalModule )
57 import RdrName          ( RdrName, mkRdrQual, mkRdrUnqual, rdrNameOcc, rdrNameModule )
58 import CmdLineOpts      ( opt_Static, opt_PprStyle_NoPrags, opt_OmitInterfacePragmas, opt_EnsureSplittableC )
59
60 import SrcLoc           ( noSrcLoc, mkBuiltinSrcLoc, SrcLoc )
61 import Unique           ( pprUnique, Unique, Uniquable(..), hasKey, unboundKey, u2i )
62 import Maybes           ( expectJust )
63 import UniqFM
64 import Outputable
65 import GlaExts
66 \end{code}
67
68
69 %************************************************************************
70 %*                                                                      *
71 \subsection[Name-datatype]{The @Name@ datatype, and name construction}
72 %*                                                                      *
73 %************************************************************************
74  
75 \begin{code}
76 data Name = Name {
77                 n_sort :: NameSort,     -- What sort of name it is
78                 n_uniq :: Unique,
79                 n_occ  :: OccName,      -- Its occurrence name
80                 n_prov :: Provenance    -- How it was made
81             }
82
83 data NameSort
84   = Local
85   | Global Module
86   | WiredInId Module Id
87   | WiredInTyCon Module TyCon
88 \end{code}
89
90 Things with a @Global@ name are given C static labels, so they finally
91 appear in the .o file's symbol table.  They appear in the symbol table
92 in the form M.n.  If originally-local things have this property they
93 must be made @Global@ first.
94
95 \begin{code}
96 mkLocalName :: Unique -> OccName -> SrcLoc -> Name
97 mkLocalName uniq occ loc = Name { n_uniq = uniq, n_sort = Local, n_occ = occ, 
98                                   n_prov = LocalDef loc NotExported }
99         -- NB: You might worry that after lots of huffing and
100         -- puffing we might end up with two local names with distinct
101         -- uniques, but the same OccName.  Indeed we can, but that's ok
102         --      * the insides of the compiler don't care: they use the Unique
103         --      * when printing for -ddump-xxx you can switch on -dppr-debug to get the
104         --        uniques if you get confused
105         --      * for interface files we tidyCore first, which puts the uniques
106         --        into the print name (see setNameVisibility below)
107
108 mkImportedLocalName :: Unique -> OccName -> SrcLoc -> Name
109         -- Just the same as mkLocalName, except the provenance is different
110         -- Reason: this flags the name as one that came in from an interface file.
111         -- This is useful when trying to decide which of two type variables
112         -- should 'win' when unifying them.
113         -- NB: this is only for non-top-level names, so we use ImplicitImport
114 mkImportedLocalName uniq occ loc = Name { n_uniq = uniq, n_sort = Local, n_occ = occ, 
115                                           n_prov = NonLocalDef ImplicitImport True }
116
117
118 mkGlobalName :: Unique -> Module -> OccName -> Provenance -> Name
119 mkGlobalName uniq mod occ prov = Name { n_uniq = uniq, n_sort = Global mod,
120                                         n_occ = occ, n_prov = prov }
121                                 
122
123 mkKnownKeyGlobal :: (RdrName, Unique) -> Name
124 mkKnownKeyGlobal (rdr_name, uniq)
125   = mkGlobalName uniq (mkVanillaModule (rdrNameModule rdr_name))
126                       (rdrNameOcc rdr_name)
127                       systemProvenance
128
129 mkSysLocalName :: Unique -> UserFS -> Name
130 mkSysLocalName uniq fs = Name { n_uniq = uniq, n_sort = Local, 
131                                 n_occ = mkSrcVarOcc fs, n_prov = systemProvenance }
132
133 mkCCallName :: Unique -> EncodedString -> Name
134         -- The encoded string completely describes the ccall
135 mkCCallName uniq str =  Name { n_uniq = uniq, n_sort = Local, 
136                                n_occ = mkCCallOcc str, 
137                                n_prov = NonLocalDef ImplicitImport True }
138
139 mkTopName :: Unique -> Module -> FAST_STRING -> Name
140         -- Make a top-level name; make it Global if top-level
141         -- things should be externally visible; Local otherwise
142         -- This chap is only used *after* the tidyCore phase
143         -- Notably, it is used during STG lambda lifting
144         --
145         -- We have to make sure that the name is globally unique
146         -- and we don't have tidyCore to help us. So we append
147         -- the unique.  Hack!  Hack!
148 mkTopName uniq mod fs
149   = Name { n_uniq = uniq, 
150            n_sort = mk_top_sort mod,
151            n_occ  = mkSrcVarOcc (_PK_ ((_UNPK_ fs) ++ show uniq)),
152            n_prov = LocalDef noSrcLoc NotExported }
153
154 mkIPName :: Unique -> OccName -> Name
155 mkIPName uniq occ
156   = Name { n_uniq = uniq,
157            n_sort = Local,
158            n_occ  = occ,
159            -- ZZ is this an appropriate provinence?
160            n_prov = SystemProv }
161
162 ------------------------- Wired in names -------------------------
163
164 mkWiredInIdName :: Unique -> Module -> OccName -> Id -> Name
165 mkWiredInIdName uniq mod occ id = Name { n_uniq = uniq, n_sort = WiredInId mod id,
166                                          n_occ = occ, n_prov = SystemProv }
167
168 -- mkWiredInTyConName takes a FAST_STRING instead of
169 -- an OccName, which is a bit yukky but that's what the 
170 -- clients find easiest.
171 mkWiredInTyConName :: Unique -> Module -> FAST_STRING -> TyCon -> Name
172 mkWiredInTyConName uniq mod fs tycon
173   = Name { n_uniq = uniq, n_sort = WiredInTyCon mod tycon,
174            n_occ = mkSrcOccFS tcName fs, n_prov = SystemProv }
175
176
177 ---------------------------------------------------------------------
178 mkDerivedName :: (OccName -> OccName)
179               -> Name           -- Base name
180               -> Unique         -- New unique
181               -> Name           -- Result is always a value name
182
183 mkDerivedName f name uniq = name {n_uniq = uniq, n_occ = f (n_occ name)}
184
185 -- mkUnboundName makes a place-holder Name; it shouldn't be looked at except possibly
186 -- during compiler debugging.
187 mkUnboundName :: RdrName -> Name
188 mkUnboundName rdr_name = mkLocalName unboundKey (rdrNameOcc rdr_name) noSrcLoc
189
190 isUnboundName :: Name -> Bool
191 isUnboundName name = name `hasKey` unboundKey
192 \end{code}
193
194 \begin{code}
195 -- When we renumber/rename things, we need to be
196 -- able to change a Name's Unique to match the cached
197 -- one in the thing it's the name of.  If you know what I mean.
198 setNameUnique name uniq = name {n_uniq = uniq}
199
200 setNameOcc :: Name -> OccName -> Name
201         -- Give the thing a new OccName, *and*
202         -- record that it's no longer a sys-local
203         -- This is used by the tidy-up pass
204 setNameOcc name occ = name {n_occ = occ}
205
206 setNameModule :: Name -> Module -> Name
207 setNameModule name mod = name {n_sort = set (n_sort name)}
208                        where
209                          set (Global _)             = Global mod
210                          set (WiredInId _ id)       = WiredInId mod id
211                          set (WiredInTyCon _ tycon) = WiredInTyCon mod tycon
212 \end{code}
213
214
215 %************************************************************************
216 %*                                                                      *
217 \subsection{Setting provenance and visibility
218 %*                                                                      *
219 %************************************************************************
220
221 tidyTopName is applied to top-level names in the final program
222
223 For top-level things, it globalises Local names 
224                                 (if all top-level things should be visible)
225                          and localises non-exported Global names
226                                  (if only exported things should be visible)
227
228 In all cases except an exported global, it gives it a new occurrence name.
229
230 The "visibility" here concerns whether the .o file's symbol table
231 mentions the thing; if so, it needs a module name in its symbol.
232 The Global things are "visible" and the Local ones are not
233
234 Why should things be "visible"?  Certainly they must be if they
235 are exported.  But also:
236
237 (a) In certain (prelude only) modules we split up the .hc file into
238     lots of separate little files, which are separately compiled by the C
239     compiler.  That gives lots of little .o files.  The idea is that if
240     you happen to mention one of them you don't necessarily pull them all
241     in.  (Pulling in a piece you don't need can be v bad, because it may
242     mention other pieces you don't need either, and so on.)
243     
244     Sadly, splitting up .hc files means that local names (like s234) are
245     now globally visible, which can lead to clashes between two .hc
246     files. So unlocaliseWhatnot goes through making all the local things
247     into global things, essentially by giving them full names so when they
248     are printed they'll have their module name too.  Pretty revolting
249     really.
250
251 (b) When optimisation is on we want to make all the internal
252     top-level defns externally visible
253
254 \begin{code}
255 tidyTopName :: Module -> TidyOccEnv -> Name -> (TidyOccEnv, Name)
256 tidyTopName mod env name
257   = (env', name')
258   where
259     (env', occ') = tidyOccName env (n_occ name)
260
261     name'        = Name { n_uniq = n_uniq name, n_sort = mk_top_sort mod,
262                           n_occ = occ', n_prov = LocalDef noSrcLoc NotExported }
263
264 mk_top_sort mod | all_toplev_ids_visible = Global mod
265                 | otherwise              = Local
266
267 all_toplev_ids_visible = 
268         not opt_OmitInterfacePragmas ||  -- Pragmas can make them visible
269         opt_EnsureSplittableC            -- Splitting requires visiblilty
270 \end{code}
271
272
273 \begin{code}
274 setNameProvenance :: Name -> Provenance -> Name 
275         -- setNameProvenance used to only change the provenance of 
276         -- Implicit-provenance things, but that gives bad error messages 
277         -- for names defined twice in the same module, so I changed it to 
278         -- set the provenance of *any* global (SLPJ Jun 97)
279 setNameProvenance name prov = name {n_prov = prov}
280
281 getNameProvenance :: Name -> Provenance
282 getNameProvenance name = n_prov name
283
284 setNameImportReason :: Name -> ImportReason -> Name
285 setNameImportReason name reason
286   = name { n_prov = new_prov }
287   where
288         -- It's important that we don't do the pattern matching
289         -- in the top-level clause, else we get a black hole in 
290         -- the renamer.  Rather a yukky constraint.  There's only
291         -- one call, in RnNames
292     old_prov = n_prov name
293     new_prov = case old_prov of
294                   NonLocalDef _ omit -> NonLocalDef reason omit
295                   other              -> old_prov
296 \end{code}
297
298
299 %************************************************************************
300 %*                                                                      *
301 \subsection{Provenance and export info}
302 %*                                                                      *
303 %************************************************************************
304
305 \begin{code}
306 data Provenance
307   = LocalDef                    -- Defined locally
308         SrcLoc                  -- Defn site
309         ExportFlag              -- Whether it's exported
310
311   | NonLocalDef                 -- Defined non-locally
312         ImportReason
313         PrintUnqualified
314
315   | SystemProv                  -- Either (a) a system-generated local with 
316                                 --            a v short name OccName
317                                 -- or     (b) a known-key global which should have a proper
318                                 --            provenance attached by the renamer
319 \end{code}
320
321 Sys-provs are only used internally.  When the compiler generates (say)
322 a fresh desguar variable it always calls it "ds", and of course it gets
323 a fresh unique.  But when printing -ddump-xx dumps, we must print it with
324 its unique, because there'll be a lot of "ds" variables.
325
326 Names with SystemProv differ in the following ways:
327         a) locals have unique attached when printing dumps
328         b) unifier eliminates sys tyvars in favour of user provs where possible
329         c) renamer replaces SystemProv with a better one
330
331 Before anything gets printed in interface files or output code, it's
332 fed through a 'tidy' processor, which zaps the OccNames to have
333 unique names; and converts all sys-locals to user locals
334 If any desugarer sys-locals have survived that far, they get changed to
335 "ds1", "ds2", etc.
336
337 \begin{code}
338 data ImportReason
339   = UserImport Module SrcLoc Bool       -- Imported from module M on line L
340                                         -- Note the M may well not be the defining module
341                                         -- for this thing!
342         -- The Bool is true iff the thing was named *explicitly* in the import spec,
343         -- rather than being imported as part of a group; e.g.
344         --      import B
345         --      import C( T(..) )
346         -- Here, everything imported by B, and the constructors of T
347         -- are not named explicitly; only T is named explicitly.
348         -- This info is used when warning of unused names.
349
350   | ImplicitImport                      -- Imported implicitly for some other reason
351                         
352
353 type PrintUnqualified = Bool    -- True <=> the unqualified name of this thing is
354                                 -- in scope in this module, so print it 
355                                 -- unqualified in error messages
356
357 data ExportFlag = Exported  | NotExported
358 \end{code}
359
360 Something is "Exported" if it may be mentioned by another module without
361 warning.  The crucial thing about Exported things is that they must
362 never be dropped as dead code, even if they aren't used in this module.
363 Furthermore, being Exported means that we can't see all call sites of the thing.
364
365 Exported things include:
366
367         - explicitly exported Ids, including data constructors, 
368           class method selectors
369
370         - dfuns from instance decls
371
372 Being Exported is *not* the same as finally appearing in the .o file's 
373 symbol table.  For example, a local Id may be mentioned in an Exported
374 Id's unfolding in the interface file, in which case the local Id goes
375 out too.
376
377
378 \begin{code}
379 systemProvenance :: Provenance
380 systemProvenance = SystemProv
381
382 -- pprNameProvenance is used in error messages to say where a name came from
383 pprNameProvenance :: Name -> SDoc
384 pprNameProvenance name = pprProvenance (getNameProvenance name)
385
386 pprProvenance :: Provenance -> SDoc
387 pprProvenance SystemProv             = ptext SLIT("System")
388 pprProvenance (LocalDef loc _)       = ptext SLIT("defined at")    <+> ppr loc
389 pprProvenance (NonLocalDef ImplicitImport _)
390   = ptext SLIT("implicitly imported")
391 pprProvenance (NonLocalDef (UserImport mod loc _) _) 
392   =  ptext SLIT("imported from") <+> ppr mod <+> ptext SLIT("at") <+> ppr loc
393 \end{code}
394
395
396 %************************************************************************
397 %*                                                                      *
398 \subsection{Predicates and selectors}
399 %*                                                                      *
400 %************************************************************************
401
402 \begin{code}
403 nameUnique              :: Name -> Unique
404 nameOccName             :: Name -> OccName 
405 nameModule              :: Name -> Module
406 nameSrcLoc              :: Name -> SrcLoc
407 isLocallyDefinedName    :: Name -> Bool
408 isUserExportedName      :: Name -> Bool
409 isWiredInName           :: Name -> Bool
410 isLocalName             :: Name -> Bool
411 isGlobalName            :: Name -> Bool
412 isExternallyVisibleName :: Name -> Bool
413
414
415
416 hashName :: Name -> Int
417 hashName name = IBOX( u2i (nameUnique name) )
418
419 nameUnique name = n_uniq name
420 nameOccName name = n_occ name
421
422 nameModule name =
423   case n_sort name of
424     Local -> pprPanic "nameModule" (ppr name)
425     x     -> nameSortModule x
426
427 nameSortModule (Global       mod)   = mod
428 nameSortModule (WiredInId    mod _) = mod
429 nameSortModule (WiredInTyCon mod _) = mod
430
431 nameRdrName :: Name -> RdrName
432 -- Makes a qualified name for top-level (Global) names, whether locally defined or not
433 -- and an unqualified name just for Locals
434 nameRdrName (Name { n_sort = Local, n_occ = occ }) = mkRdrUnqual occ
435 nameRdrName (Name { n_sort = sort,  n_occ = occ }) = mkRdrQual (moduleName (nameSortModule sort)) occ
436
437 ifaceNameRdrName :: Name -> RdrName
438 -- Makes a qualified naem for imported things, 
439 -- and an unqualified one for local things
440 ifaceNameRdrName n | isLocallyDefined n = mkRdrUnqual (nameOccName n)
441                    | otherwise          = mkRdrQual   (moduleName (nameModule n)) (nameOccName n) 
442
443 isUserExportedName (Name { n_prov = LocalDef _ Exported }) = True
444 isUserExportedName other                                   = False
445
446 isUserImportedExplicitlyName (Name { n_prov = NonLocalDef (UserImport _ _ explicit) _ }) = explicit
447 isUserImportedExplicitlyName other                                                       = False
448
449 isUserImportedName (Name { n_prov = NonLocalDef (UserImport _ _ _) _ }) = True
450 isUserImportedName other                                                = False
451
452 maybeUserImportedFrom (Name { n_prov = NonLocalDef (UserImport m _ _) _ }) = Just m
453 maybeUserImportedFrom other                                                = Nothing
454
455 isDllName :: Name -> Bool
456         -- Does this name refer to something in a different DLL?
457 isDllName nm = not opt_Static &&
458                not (isLocallyDefinedName nm) && 
459                not (isLocalModule (nameModule nm))
460 -- Why is the isLocallyDefinedName test needed?
461
462 nameSrcLoc name = provSrcLoc (n_prov name)
463
464 provSrcLoc (LocalDef loc _)                     = loc        
465 provSrcLoc (NonLocalDef (UserImport _ loc _) _) = loc
466 provSrcLoc other                                = noSrcLoc   
467   
468 isLocallyDefinedName (Name {n_sort = Local})        = True      -- Local (might have SystemProv)
469 isLocallyDefinedName (Name {n_prov = LocalDef _ _}) = True      -- Global, but defined here
470 isLocallyDefinedName other                          = False     -- Other
471
472 -- Things the compiler "knows about" are in some sense
473 -- "imported".  When we are compiling the module where
474 -- the entities are defined, we need to be able to pick
475 -- them out, often in combination with isLocallyDefined.
476 isWiredInName (Name {n_sort = WiredInTyCon _ _}) = True
477 isWiredInName (Name {n_sort = WiredInId    _ _}) = True
478 isWiredInName _                                  = False
479
480 maybeWiredInIdName :: Name -> Maybe Id
481 maybeWiredInIdName (Name {n_sort = WiredInId _ id}) = Just id
482 maybeWiredInIdName other                            = Nothing
483
484 maybeWiredInTyConName :: Name -> Maybe TyCon
485 maybeWiredInTyConName (Name {n_sort = WiredInTyCon _ tc}) = Just tc
486 maybeWiredInTyConName other                               = Nothing
487
488
489 isLocalName (Name {n_sort = Local}) = True
490 isLocalName _                       = False
491
492 isGlobalName (Name {n_sort = Local}) = False
493 isGlobalName other                   = True
494
495 -- Global names are by definition those that are visible
496 -- outside the module, *as seen by the linker*.  Externally visible
497 -- does not mean visible at the source level (that's isExported).
498 isExternallyVisibleName name = isGlobalName name
499
500 hasBetterProv :: Name -> Name -> Bool
501 -- Choose 
502 --      a local thing                 over an   imported thing
503 --      a user-imported thing         over a    non-user-imported thing
504 --      an explicitly-imported thing  over an   implicitly imported thing
505 hasBetterProv n1 n2
506   = case (n_prov n1, n_prov n2) of
507         (LocalDef _ _,                        _                           ) -> True
508         (NonLocalDef (UserImport _ _ True) _, _                           ) -> True
509         (NonLocalDef (UserImport _ _ _   ) _, NonLocalDef ImplicitImport _) -> True
510         other                                                               -> False
511
512 isSystemName (Name {n_prov = SystemProv}) = True
513 isSystemName other                        = False
514 \end{code}
515
516
517 %************************************************************************
518 %*                                                                      *
519 \subsection[Name-instances]{Instance declarations}
520 %*                                                                      *
521 %************************************************************************
522
523 \begin{code}
524 cmpName n1 n2 = n_uniq n1 `compare` n_uniq n2
525 \end{code}
526
527 \begin{code}
528 instance Eq Name where
529     a == b = case (a `compare` b) of { EQ -> True;  _ -> False }
530     a /= b = case (a `compare` b) of { EQ -> False; _ -> True }
531
532 instance Ord Name where
533     a <= b = case (a `compare` b) of { LT -> True;  EQ -> True;  GT -> False }
534     a <  b = case (a `compare` b) of { LT -> True;  EQ -> False; GT -> False }
535     a >= b = case (a `compare` b) of { LT -> False; EQ -> True;  GT -> True  }
536     a >  b = case (a `compare` b) of { LT -> False; EQ -> False; GT -> True  }
537     compare a b = cmpName a b
538
539 instance Uniquable Name where
540     getUnique = nameUnique
541
542 instance NamedThing Name where
543     getName n = n
544 \end{code}
545
546
547 %************************************************************************
548 %*                                                                      *
549 \subsection{Name environment}
550 %*                                                                      *
551 %************************************************************************
552
553 \begin{code}
554 type NameEnv a = UniqFM a       -- Domain is Name
555
556 emptyNameEnv     :: NameEnv a
557 mkNameEnv        :: [(Name,a)] -> NameEnv a
558 nameEnvElts      :: NameEnv a -> [a]
559 extendNameEnv_C  :: (a->a->a) -> NameEnv a -> Name -> a -> NameEnv a
560 extendNameEnv    :: NameEnv a -> Name -> a -> NameEnv a
561 plusNameEnv      :: NameEnv a -> NameEnv a -> NameEnv a
562 plusNameEnv_C    :: (a->a->a) -> NameEnv a -> NameEnv a -> NameEnv a
563 extendNameEnvList:: NameEnv a -> [(Name,a)] -> NameEnv a
564 delFromNameEnv   :: NameEnv a -> Name -> NameEnv a
565 elemNameEnv      :: Name -> NameEnv a -> Bool
566 unitNameEnv      :: Name -> a -> NameEnv a
567 lookupNameEnv    :: NameEnv a -> Name -> Maybe a
568 lookupNameEnv_NF :: NameEnv a -> Name -> a
569
570 emptyNameEnv     = emptyUFM
571 mkNameEnv        = listToUFM
572 nameEnvElts      = eltsUFM
573 extendNameEnv_C  = addToUFM_C
574 extendNameEnv    = addToUFM
575 plusNameEnv      = plusUFM
576 plusNameEnv_C    = plusUFM_C
577 extendNameEnvList= addListToUFM
578 delFromNameEnv   = delFromUFM
579 elemNameEnv      = elemUFM
580 unitNameEnv      = unitUFM
581
582 lookupNameEnv          = lookupUFM
583 lookupNameEnv_NF env n = expectJust "lookupNameEnv_NF" (lookupUFM env n)
584 \end{code}
585
586
587 %************************************************************************
588 %*                                                                      *
589 \subsection{Pretty printing}
590 %*                                                                      *
591 %************************************************************************
592
593 \begin{code}
594 instance Outputable Name where
595         -- When printing interfaces, all Locals have been given nice print-names
596     ppr name = pprName name
597
598 pprName (Name {n_sort = Local, n_uniq = uniq, n_occ = occ, n_prov = prov})
599         -- Locals
600   = getPprStyle $ \ sty ->
601     if codeStyle sty then
602         pprUnique uniq          -- When printing in code we required all names to 
603                                 -- be globally unique; for example, we use this identifier
604                                 -- for the closure name.  So we just print the unique alone.
605     else
606         pprOccName occ <> pp_local_extra sty uniq
607   where
608     sys_local = case prov of
609                   SystemProv -> True
610                   other      -> False
611
612     pp_local_extra sty uniq
613         | sys_local      = underscore <> pprUnique uniq         -- Must print uniques for sys_locals
614         | debugStyle sty = text "{-" <> pprUnique uniq <> text "-}"
615         | otherwise      = empty
616
617
618 pprName (Name {n_sort = sort, n_uniq = uniq, n_occ = occ, n_prov = prov})
619         -- Globals, and wired in things
620   = getPprStyle $ \ sty ->
621     if codeStyle sty then
622         ppr mod <> underscore <> ppr occ
623     else
624         pp_mod_dot sty <> ppr occ <> pp_global_debug sty uniq prov
625   where
626     mod = nameSortModule sort
627
628     pp_mod_dot sty
629       = case prov of
630            SystemProv                                -> pp_qual mod user_sty
631                 -- Hack alert!  Omit the qualifier on SystemProv things in user style
632                 -- I claim such SystemProv things will also be WiredIn things.
633                 -- We can't get the omit flag right
634                 -- on wired in tycons etc (sigh) so we just leave it out in user style, 
635                 -- and hope that leaving it out isn't too consfusing.
636                 -- (e.g. if the programmer hides Bool and  redefines it.  If so, use -dppr-debug.)
637
638            LocalDef _ _                              -> pp_qual mod (user_sty || iface_sty)
639
640            NonLocalDef (UserImport imp_mod _ _) omit 
641                 | user_sty                           -> pp_qual imp_mod omit
642                 | otherwise                          -> pp_qual mod     False
643            NonLocalDef ImplicitImport           omit -> pp_qual mod     (user_sty && omit)
644       where
645         user_sty  = userStyle sty
646         iface_sty = ifaceStyle sty
647     
648     pp_qual mod omit_qual
649         | omit_qual  = empty
650         | otherwise  = pprModule mod <> dot
651     
652     pp_global_debug sty uniq prov
653       | debugStyle sty = hcat [text "{-", pprUnique uniq, prov_p prov, text "-}"]
654       | otherwise      = empty
655
656     prov_p prov | opt_PprStyle_NoPrags = empty
657                 | otherwise            = comma <> pp_prov prov
658
659 pp_prov (LocalDef _ Exported)          = char 'x'
660 pp_prov (LocalDef _ NotExported)       = char 'l'
661 pp_prov (NonLocalDef ImplicitImport _) = char 'j'
662 pp_prov (NonLocalDef (UserImport _ _ True ) _) = char 'I'       -- Imported by name
663 pp_prov (NonLocalDef (UserImport _ _ False) _) = char 'i'       -- Imported by ..
664 pp_prov SystemProv                     = char 's'
665 \end{code}
666
667
668 %************************************************************************
669 %*                                                                      *
670 \subsection{Overloaded functions related to Names}
671 %*                                                                      *
672 %************************************************************************
673
674 \begin{code}
675 class NamedThing a where
676     getOccName :: a -> OccName
677     getName    :: a -> Name
678
679     getOccName n = nameOccName (getName n)      -- Default method
680 \end{code}
681
682 \begin{code}
683 getSrcLoc           :: NamedThing a => a -> SrcLoc
684 isLocallyDefined    :: NamedThing a => a -> Bool
685 getOccString        :: NamedThing a => a -> String
686 toRdrName           :: NamedThing a => a -> RdrName
687
688 getSrcLoc           = nameSrcLoc           . getName
689 isLocallyDefined    = isLocallyDefinedName . getName
690 getOccString x      = occNameString (getOccName x)
691 toRdrName           = ifaceNameRdrName     . getName
692 \end{code}
693
694 \begin{code}
695 {-# SPECIALIZE isLocallyDefined :: Name -> Bool #-}
696 \end{code}