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