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