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