a84e626f98820c157a1534cbc5319c440d1fe62f
[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, mkSysLocalName, mkTopName,
14         mkDerivedName, mkGlobalName,
15         mkWiredInIdName,   mkWiredInTyConName,
16         maybeWiredInIdName, maybeWiredInTyConName,
17         isWiredInName,
18
19         nameUnique, setNameUnique, setNameProvenance, getNameProvenance,
20         tidyTopName, mkNameVisible,
21         nameOccName, nameModule, setNameOcc,
22
23         isExportedName, nameSrcLoc,
24         isLocallyDefinedName,
25
26         isSysLocalName, isLocalName, isGlobalName, isExternallyVisibleName,
27
28         pprNameProvenance,
29
30         -- Misc
31         Provenance(..), ImportReason(..), pprProvenance,
32         ExportFlag(..), PrintUnqualified,
33
34         -- Class NamedThing and overloaded friends
35         NamedThing(..),
36         modAndOcc, isExported, 
37         getSrcLoc, isLocallyDefined, getOccString
38     ) where
39
40 #include "HsVersions.h"
41
42 import {-# SOURCE #-} Var   ( Id )
43 import {-# SOURCE #-} TyCon ( TyCon )
44
45 import OccName          -- All of it
46 import CmdLineOpts      ( opt_PprStyle_NoPrags, opt_OmitInterfacePragmas, opt_EnsureSplittableC )
47 import BasicTypes       ( IfaceFlavour(..) )
48
49 import SrcLoc           ( noSrcLoc, mkBuiltinSrcLoc, SrcLoc )
50 import Unique           ( pprUnique, Unique, Uniquable(..) )
51 import Outputable
52 import GlaExts
53 \end{code}
54
55
56 %************************************************************************
57 %*                                                                      *
58 \subsection[Name-datatype]{The @Name@ datatype, and name construction}
59 %*                                                                      *
60 %************************************************************************
61  
62 \begin{code}
63 data Name
64   = Local    Unique
65              OccName            -- How to print it
66              Bool               -- True <=> this is a "sys-local"
67                                 -- see notes just below
68
69
70   | Global   Unique
71              Module             -- The defining module
72              OccName            -- Its name in that module
73              Provenance         -- How it was defined
74 \end{code}
75
76 Sys-locals are only used internally.  When the compiler generates (say)
77 a fresh desguar variable it always calls it "ds", and of course it gets
78 a fresh unique.  But when printing -ddump-xx dumps, we must print it with
79 its unique, because there'll be a lot of "ds" variables.  That debug
80 printing issue is the ONLY way in which sys-locals are different.  I think.
81
82 Before anything gets printed in interface files or output code, it's
83 fed through a 'tidy' processor, which zaps the OccNames to have
84 unique names; and converts all sys-locals to ordinary locals
85 If any desugarer sys-locals have survived that far, they get changed to
86 "ds1", "ds2", etc.
87
88 Things with a @Global@ name are given C static labels, so they finally
89 appear in the .o file's symbol table.  They appear in the symbol table
90 in the form M.n.  If originally-local things have this property they
91 must be made @Global@ first.
92
93
94 \begin{code}
95 mkLocalName    :: Unique -> OccName -> Name
96 mkLocalName uniq occ = Local uniq occ False
97         -- NB: You might worry that after lots of huffing and
98         -- puffing we might end up with two local names with distinct
99         -- uniques, but the same OccName.  Indeed we can, but that's ok
100         --      * the insides of the compiler don't care: they use the Unique
101         --      * when printing for -ddump-xxx you can switch on -dppr-debug to get the
102         --        uniques if you get confused
103         --      * for interface files we tidyCore first, which puts the uniques
104         --        into the print name (see setNameVisibility below)
105
106 mkGlobalName :: Unique -> Module -> OccName -> Provenance -> Name
107 mkGlobalName = Global
108
109 mkSysLocalName :: Unique -> FAST_STRING -> Name
110 mkSysLocalName uniq fs = Local uniq (varOcc fs) True
111
112 mkTopName :: Unique -> Module -> FAST_STRING -> Name
113         -- Make a top-level name; make it Global if top-level
114         -- things should be externally visible; Local otherwise
115         -- This chap is only used *after* the tidyCore phase
116         -- Notably, it is used during STG lambda lifting
117         --
118         -- We have to make sure that the name is globally unique
119         -- and we don't have tidyCore to help us. So we append
120         -- the unique.  Hack!  Hack!
121 mkTopName uniq mod fs 
122   | all_toplev_ids_visible = Global uniq mod occ (LocalDef noSrcLoc NotExported)
123   | otherwise              = Local uniq occ False
124   where
125     occ = varOcc (_PK_ ((_UNPK_ fs) ++ show uniq))
126
127 mkWiredInIdName :: Unique -> Module -> OccName -> Id -> Name
128 mkWiredInIdName uniq mod occ id = Global uniq mod occ (WiredInId id)
129
130 -- mkWiredInTyConName takes a FAST_STRING instead of
131 -- an OccName, which is a bit yukky but that's what the 
132 -- clients find easiest.
133 mkWiredInTyConName :: Unique -> Module -> FAST_STRING -> TyCon -> Name
134 mkWiredInTyConName uniq mod occ tycon
135   = Global uniq mod (tcOcc occ) (WiredInTyCon tycon)
136
137 mkDerivedName :: (OccName -> OccName)
138               -> Name           -- Base name
139               -> Unique         -- New unique
140               -> Name           -- Result is always a value name
141
142 mkDerivedName f (Global _ mod occ prov) uniq = Global uniq mod (f occ) prov
143 mkDerivedName f (Local _ occ sys)       uniq = Local uniq (f occ) sys
144
145 -- When we renumber/rename things, we need to be
146 -- able to change a Name's Unique to match the cached
147 -- one in the thing it's the name of.  If you know what I mean.
148 setNameUnique (Local _ occ sys)        u = Local u occ sys
149 setNameUnique (Global  _ mod occ prov) u = Global u mod occ prov
150
151 setNameOcc :: Name -> OccName -> Name
152         -- Give the thing a new OccName, *and*
153         -- record that it's no longer a sys-local
154         -- This is used by the tidy-up pass
155 setNameOcc (Global uniq mod _ prov) occ = Global uniq mod occ prov
156 setNameOcc (Local uniq _ sys)       occ = Local uniq occ False
157 \end{code}
158
159
160 %************************************************************************
161 %*                                                                      *
162 \subsection{Setting provenance and visibility
163 %*                                                                      *
164 %************************************************************************
165
166 tidyTopName is applied to top-level names in the final program
167
168 For top-level things, it globalises Local names 
169                                 (if all top-level things should be visible)
170                          and localises non-exported Global names
171                                  (if only exported things should be visible)
172
173 In all cases except an exported global, it gives it a new occurrence name.
174
175 The "visibility" here concerns whether the .o file's symbol table
176 mentions the thing; if so, it needs a module name in its symbol.
177 The Global things are "visible" and the Local ones are not
178
179 Why should things be "visible"?  Certainly they must be if they
180 are exported.  But also:
181
182 (a) In certain (prelude only) modules we split up the .hc file into
183     lots of separate little files, which are separately compiled by the C
184     compiler.  That gives lots of little .o files.  The idea is that if
185     you happen to mention one of them you don't necessarily pull them all
186     in.  (Pulling in a piece you don't need can be v bad, because it may
187     mention other pieces you don't need either, and so on.)
188     
189     Sadly, splitting up .hc files means that local names (like s234) are
190     now globally visible, which can lead to clashes between two .hc
191     files. So unlocaliseWhatnot goes through making all the local things
192     into global things, essentially by giving them full names so when they
193     are printed they'll have their module name too.  Pretty revolting
194     really.
195
196 (b) When optimisation is on we want to make all the internal
197     top-level defns externally visible
198
199 \begin{code}
200 tidyTopName :: Module -> TidyOccEnv -> Name -> (TidyOccEnv, Name)
201 tidyTopName mod env name
202   | isExported name = (env, name)       -- Don't fiddle with an exported name
203                                         -- It should be in the TidyOccEnv already
204   | otherwise       = (env', name')
205   where
206     prov         = getNameProvenance name
207     uniq         = nameUnique name
208     (env', occ') = tidyOccName env (nameOccName name)
209
210     name' | all_toplev_ids_visible = Global uniq mod occ' prov
211           | otherwise              = Local uniq occ' False
212
213 all_toplev_ids_visible = 
214         not opt_OmitInterfacePragmas ||  -- Pragmas can make them visible
215         opt_EnsureSplittableC            -- Splitting requires visiblilty
216 \end{code}
217
218 \begin{code}
219 setNameProvenance :: Name -> Provenance -> Name 
220         -- setNameProvenance used to only change the provenance of 
221         -- Implicit-provenance things, but that gives bad error messages 
222         -- for names defined twice in the same module, so I changed it to 
223         -- set the provenance of *any* global (SLPJ Jun 97)
224 setNameProvenance (Global uniq mod occ _) prov = Global uniq mod occ prov
225 setNameProvenance other_name              prov = other_name
226
227 getNameProvenance :: Name -> Provenance
228 getNameProvenance (Global uniq mod occ prov) = prov
229 getNameProvenance (Local _ _ _)              = LocalDef noSrcLoc NotExported
230 \end{code}
231
232 \begin{code}
233 -- make the Name globally visible regardless.
234 mkNameVisible :: Module -> Unique -> Name -> Name
235 mkNameVisible mod occ_uniq nm@(Global _ _ _ _) = nm
236 mkNameVisible mod occ_uniq nm@(Local uniq occ _)
237  = Global uniq mod occ (LocalDef noSrcLoc Exported)
238 \end{code}
239
240
241 %************************************************************************
242 %*                                                                      *
243 \subsection{Provenance and export info}
244 %*                                                                      *
245 %************************************************************************
246
247 \begin{code}
248 data Provenance
249   = NoProvenance 
250
251   | LocalDef                    -- Defined locally
252         SrcLoc                  -- Defn site
253         ExportFlag              -- Whether it's exported
254
255   | NonLocalDef                 -- Defined non-locally
256         ImportReason
257         IfaceFlavour            -- Whether the defn site is an .hi-boot file
258         PrintUnqualified
259
260   | WiredInTyCon TyCon                  -- There's a wired-in version
261   | WiredInId    Id                     -- ...ditto...
262
263 data ImportReason
264   = UserImport Module SrcLoc Bool       -- Imported from module M on line L
265                                         -- Note the M may well not be the defining module
266                                         -- for this thing!
267         -- The Bool is true iff the thing was named *explicitly* in the import spec,
268         -- rather than being imported as part of a group; e.g.
269         --      import B
270         --      import C( T(..) )
271         -- Here, everything imported by B, and the constructors of T
272         -- are not named explicitly; only T is named explicitly.
273         -- This info is used when warning of unused names.
274
275   | ImplicitImport                      -- Imported implicitly for some other reason
276                         
277
278 type PrintUnqualified = Bool    -- True <=> the unqualified name of this thing is
279                                 -- in scope in this module, so print it 
280                                 -- unqualified in error messages
281
282 data ExportFlag = Exported  | NotExported
283 \end{code}
284
285 Something is "Exported" if it may be mentioned by another module without
286 warning.  The crucial thing about Exported things is that they must
287 never be dropped as dead code, even if they aren't used in this module.
288 Furthermore, being Exported means that we can't see all call sites of the thing.
289
290 Exported things include:
291
292         - explicitly exported Ids, including data constructors, 
293           class method selectors
294
295         - dfuns from instance decls
296
297 Being Exported is *not* the same as finally appearing in the .o file's 
298 symbol table.  For example, a local Id may be mentioned in an Exported
299 Id's unfolding in the interface file, in which case the local Id goes
300 out too.
301
302
303 \begin{code}
304 -- pprNameProvenance is used in error messages to say where a name came from
305 pprNameProvenance :: Name -> SDoc
306 pprNameProvenance name = pprProvenance (getNameProvenance name)
307
308 pprProvenance :: Provenance -> SDoc
309 pprProvenance NoProvenance           = ptext SLIT("No provenance")
310 pprProvenance (LocalDef loc _)       = ptext SLIT("defined at")    <+> ppr loc
311 pprProvenance (WiredInTyCon tc)      = ptext SLIT("Wired-in tycon")
312 pprProvenance (WiredInId id)         = ptext SLIT("Wired-in id")
313 pprProvenance (NonLocalDef ImplicitImport _ _)
314   = ptext SLIT("implicitly imported")
315 pprProvenance (NonLocalDef (UserImport mod loc _) _ _) 
316   =  ptext SLIT("imported from") <+> ppr mod <+> ptext SLIT("at") <+> ppr loc
317 \end{code}
318
319
320 %************************************************************************
321 %*                                                                      *
322 \subsection{Predicates and selectors}
323 %*                                                                      *
324 %************************************************************************
325
326 \begin{code}
327 nameUnique              :: Name -> Unique
328 nameModAndOcc           :: Name -> (Module, OccName)    -- Globals only
329 nameOccName             :: Name -> OccName 
330 nameModule              :: Name -> Module
331 nameSrcLoc              :: Name -> SrcLoc
332 isLocallyDefinedName    :: Name -> Bool
333 isExportedName          :: Name -> Bool
334 isWiredInName           :: Name -> Bool
335 isLocalName             :: Name -> Bool
336 isGlobalName            :: Name -> Bool
337 isExternallyVisibleName :: Name -> Bool
338
339
340
341 nameUnique (Local  u _ _)   = u
342 nameUnique (Global u _ _ _) = u
343
344 nameOccName (Local _ occ _)    = occ
345 nameOccName (Global _ _ occ _) = occ
346
347 nameModule (Global _ mod occ _) = mod
348
349 nameModAndOcc (Global _ mod occ _) = (mod,occ)
350
351 isExportedName (Global _ _ _ (LocalDef _ Exported)) = True
352 isExportedName other                                = False
353
354 nameSrcLoc (Global _ _ _ (LocalDef loc _))                       = loc        
355 nameSrcLoc (Global _ _ _ (NonLocalDef (UserImport _ loc _) _ _)) = loc
356 nameSrcLoc (Global _ _ _ (WiredInTyCon _))                       = mkBuiltinSrcLoc
357 nameSrcLoc (Global _ _ _ (WiredInId _))                          = mkBuiltinSrcLoc
358 nameSrcLoc other                                                 = noSrcLoc   
359   
360 isLocallyDefinedName (Local  _ _ _)                = True
361 isLocallyDefinedName (Global _ _ _ (LocalDef _ _)) = True
362 isLocallyDefinedName other                         = False
363
364 -- Things the compiler "knows about" are in some sense
365 -- "imported".  When we are compiling the module where
366 -- the entities are defined, we need to be able to pick
367 -- them out, often in combination with isLocallyDefined.
368 isWiredInName (Global _ _ _ (WiredInTyCon _)) = True
369 isWiredInName (Global _ _ _ (WiredInId    _)) = True
370 isWiredInName _                               = False
371
372 maybeWiredInIdName :: Name -> Maybe Id
373 maybeWiredInIdName (Global _ _ _ (WiredInId id)) = Just id
374 maybeWiredInIdName other                         = Nothing
375
376 maybeWiredInTyConName :: Name -> Maybe TyCon
377 maybeWiredInTyConName (Global _ _ _ (WiredInTyCon tc)) = Just tc
378 maybeWiredInTyConName other                            = Nothing
379
380
381 isLocalName (Local _ _ _) = True
382 isLocalName _             = False
383
384 isSysLocalName (Local _ _ sys) = sys
385 isSysLocalName other           = False
386
387 isGlobalName (Global _ _ _ _) = True
388 isGlobalName other            = False
389
390 -- Global names are by definition those that are visible
391 -- outside the module, *as seen by the linker*.  Externally visible
392 -- does not mean visible at the source level (that's isExported).
393 isExternallyVisibleName name = isGlobalName name
394 \end{code}
395
396
397 %************************************************************************
398 %*                                                                      *
399 \subsection[Name-instances]{Instance declarations}
400 %*                                                                      *
401 %************************************************************************
402
403 \begin{code}
404 cmpName n1 n2 = c n1 n2
405   where
406     c (Local  u1 _ _)   (Local  u2 _ _)   = compare u1 u2
407     c (Local   _ _ _)   _                 = LT
408     c (Global u1 _ _ _) (Global u2 _ _ _) = compare u1 u2
409     c (Global  _ _ _ _) _                 = GT
410 \end{code}
411
412 \begin{code}
413 instance Eq Name where
414     a == b = case (a `compare` b) of { EQ -> True;  _ -> False }
415     a /= b = case (a `compare` b) of { EQ -> False; _ -> True }
416
417 instance Ord Name where
418     a <= b = case (a `compare` b) of { LT -> True;      EQ -> True;  GT -> False }
419     a <  b = case (a `compare` b) of { LT -> True;      EQ -> False; GT -> False }
420     a >= b = case (a `compare` b) of { LT -> False; EQ -> True;  GT -> True  }
421     a >  b = case (a `compare` b) of { LT -> False; EQ -> False; GT -> True  }
422     compare a b = cmpName a b
423
424 instance Uniquable Name where
425     getUnique = nameUnique
426
427 instance NamedThing Name where
428     getName n = n
429 \end{code}
430
431
432 %************************************************************************
433 %*                                                                      *
434 \subsection{Pretty printing}
435 %*                                                                      *
436 %************************************************************************
437
438 \begin{code}
439 instance Outputable Name where
440         -- When printing interfaces, all Locals have been given nice print-names
441     ppr name = pprName name
442
443 pprName (Local uniq occ sys_local)
444   = getPprStyle $ \ sty ->
445     if codeStyle sty then
446         pprUnique uniq          -- When printing in code we required all names to 
447                                 -- be globally unique; for example, we use this identifier
448                                 -- for the closure name.  So we just print the unique alone.
449     else
450         pprOccName occ <> pp_local_extra sty uniq
451   where
452     pp_local_extra sty uniq
453         | sys_local      = underscore <> pprUnique uniq         -- Must print uniques for sys_locals
454         | debugStyle sty = text "{-" <> pprUnique uniq <> text "-}"
455         | otherwise      = empty
456
457
458 pprName (Global uniq mod occ prov)
459   = getPprStyle $ \ sty ->
460     if codeStyle sty then
461         ppr mod <> underscore <> ppr occ
462     else
463         pp_mod_dot sty <> ppr occ <> pp_global_debug sty uniq prov
464   where
465     pp_mod_dot sty
466       = case prov of   -- Omit home module qualifier if in scope 
467            LocalDef _ _           -> pp_qual dot (user_sty || iface_sty)
468            NonLocalDef _ hif omit -> pp_qual (pp_hif hif) (omit && user_sty)
469                          -- Hack: omit qualifers on wired in things
470                          -- in user style only
471            WiredInTyCon _       -> pp_qual dot user_sty
472            WiredInId _          -> pp_qual dot user_sty
473            NoProvenance         -> pp_qual dot False
474       where
475         user_sty  = userStyle sty
476         iface_sty = ifaceStyle sty
477     
478     pp_qual sep omit_qual
479         | omit_qual  = empty
480         | otherwise      = pprModule mod <> sep
481     
482     pp_hif HiFile     = dot      -- Vanilla case
483     pp_hif HiBootFile = text "!"  -- M!t indicates a name imported from a .hi-boot interface
484    
485     pp_global_debug sty uniq prov
486       | debugStyle sty = hcat [text "{-", pprUnique uniq, prov_p prov, text "-}"]
487       | otherwise      = empty
488
489     prov_p prov | opt_PprStyle_NoPrags = empty
490                 | otherwise            = comma <> pp_prov prov
491
492 pp_prov (LocalDef _ Exported)            = char 'x'
493 pp_prov (LocalDef _ NotExported)         = char 'l'
494 pp_prov (NonLocalDef ImplicitImport _ _) = char 'i'
495 pp_prov (NonLocalDef explicitimport _ _) = char 'I'
496 pp_prov (WiredInTyCon _)                 = char 'W'
497 pp_prov (WiredInId _)                    = char 'w'
498 pp_prov NoProvenance                     = char '?'
499 \end{code}
500
501
502 %************************************************************************
503 %*                                                                      *
504 \subsection{Overloaded functions related to Names}
505 %*                                                                      *
506 %************************************************************************
507
508 \begin{code}
509 class NamedThing a where
510     getOccName :: a -> OccName          -- Even RdrNames can do this!
511     getName    :: a -> Name
512
513     getOccName n = nameOccName (getName n)      -- Default method
514 \end{code}
515
516 \begin{code}
517 modAndOcc           :: NamedThing a => a -> (Module, OccName)
518 getSrcLoc           :: NamedThing a => a -> SrcLoc
519 isLocallyDefined    :: NamedThing a => a -> Bool
520 isExported          :: NamedThing a => a -> Bool
521 getOccString        :: NamedThing a => a -> String
522
523 modAndOcc           = nameModAndOcc        . getName
524 isExported          = isExportedName       . getName
525 getSrcLoc           = nameSrcLoc           . getName
526 isLocallyDefined    = isLocallyDefinedName . getName
527 getOccString x      = occNameString (getOccName x)
528 \end{code}
529
530 \begin{code}
531 {-# SPECIALIZE isLocallyDefined :: Name -> Bool #-}
532 \end{code}