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