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