[project @ 2000-10-16 08:24:18 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, mkCCallName,
14         mkTopName, mkIPName,
15         mkDerivedName, mkGlobalName, mkKnownKeyGlobal, mkWiredInName,
16
17         nameUnique, setNameUnique, setLocalNameSort,
18         tidyTopName, 
19         nameOccName, nameModule, setNameOcc, nameRdrName, setNameModuleAndLoc, 
20         toRdrName, hashName,
21
22         isUserExportedName, isUserImportedName, isUserImportedExplicitlyName, 
23         maybeUserImportedFrom,
24         nameSrcLoc, isLocallyDefinedName, isDllName,
25
26         isSystemName, isLocalName, isGlobalName, isExternallyVisibleName,
27         isTyVarName,
28         
29         -- Environment
30         NameEnv, mkNameEnv,
31         emptyNameEnv, unitNameEnv, nameEnvElts, 
32         extendNameEnv_C, extendNameEnv, 
33         plusNameEnv, plusNameEnv_C, extendNameEnv, extendNameEnvList,
34         lookupNameEnv, lookupNameEnv_NF, delFromNameEnv, elemNameEnv, 
35
36
37         -- Class NamedThing and overloaded friends
38         NamedThing(..),
39         getSrcLoc, isLocallyDefined, getOccString, toRdrName
40     ) where
41
42 #include "HsVersions.h"
43
44 import OccName          -- All of it
45 import Module           ( Module, moduleName, pprModule, mkVanillaModule, 
46                           isLocalModule )
47 import RdrName          ( RdrName, mkRdrQual, mkRdrUnqual, rdrNameOcc, 
48                           rdrNameModule )
49 import CmdLineOpts      ( opt_Static, opt_PprStyle_NoPrags, 
50                           opt_OmitInterfacePragmas, opt_EnsureSplittableC )
51
52 import SrcLoc           ( noSrcLoc, SrcLoc )
53 import Unique           ( Unique, Uniquable(..), u2i, pprUnique )
54 import Maybes           ( expectJust )
55 import FastTypes
56 import UniqFM
57 import Outputable
58 \end{code}
59
60 %************************************************************************
61 %*                                                                      *
62 \subsection[Name-datatype]{The @Name@ datatype, and name construction}
63 %*                                                                      *
64 %************************************************************************
65  
66 \begin{code}
67 data Name = Name {
68                 n_sort :: NameSort,     -- What sort of name it is
69                 n_occ  :: OccName,      -- Its occurrence name
70                 n_uniq :: Unique,
71                 n_loc  :: SrcLoc        -- Definition site
72             }
73
74 data NameSort
75   = Global Module       -- (a) TyCon, Class, their derived Ids, dfun Id
76                         -- (b) imported Id
77
78   | Exported            -- An exported Ids defined in the module being compiled
79
80   | Local               -- A user-defined, but non-exported Id or TyVar,
81                         -- defined in the module being compiled
82
83   | System              -- A system-defined Id or TyVar.  Typically the
84                         -- OccName is very uninformative (like 's')
85 \end{code}
86
87 Notes about the NameSorts:
88
89 1.  An Exported Id is changed to Global right at the
90     end in the tidyCore pass, so that an importer sees a Global
91     Similarly, Local Ids that are visible to an importer (e.g. when 
92     optimisation is on) are changed to Globals.
93
94 2.  Things with a @Global@ name are given C static labels, so they finally
95     appear in the .o file's symbol table.  They appear in the symbol table
96     in the form M.n.  If originally-local things have this property they
97     must be made @Global@ first.
98
99 3.  A System Name differs in the following ways:
100         a) has unique attached when printing dumps
101         b) unifier eliminates sys tyvars in favour of user provs where possible
102
103     Before anything gets printed in interface files or output code, it's
104     fed through a 'tidy' processor, which zaps the OccNames to have
105     unique names; and converts all sys-locals to user locals
106     If any desugarer sys-locals have survived that far, they get changed to
107     "ds1", "ds2", etc.
108
109 \begin{code}
110 nameUnique              :: Name -> Unique
111 nameOccName             :: Name -> OccName 
112 nameModule              :: Name -> Module
113 nameSrcLoc              :: Name -> SrcLoc
114
115 nameUnique  name = n_uniq name
116 nameOccName name = n_occ  name
117 nameSrcLoc  name = n_loc  name
118 nameModule (Name { n_sort = Global mod }) = mod
119 nameModule name                           = pprPanic "nameModule" (ppr name)
120 \end{code}
121
122 \begin{code}
123 isLocallyDefinedName    :: Name -> Bool
124 isUserExportedName      :: Name -> Bool
125 isLocalName             :: Name -> Bool         -- Not globala
126 isGlobalName            :: Name -> Bool
127 isSystemName            :: Name -> Bool
128 isExternallyVisibleName :: Name -> Bool
129
130 isGlobalName (Name {n_sort = Global _}) = True
131 isGlobalName other                      = False
132
133 isLocalName name = not (isGlobalName name)
134
135 isLocallyDefinedName name = isLocalName name
136
137 -- Global names are by definition those that are visible
138 -- outside the module, *as seen by the linker*.  Externally visible
139 -- does not mean visible at the source level (that's isExported).
140 isExternallyVisibleName name = isGlobalName name
141
142 isUserExportedName (Name { n_sort = Exported }) = True
143 isUserExportedName other                        = False
144
145 isSystemName (Name {n_sort = System}) = True
146 isSystemName other                    = False
147 \end{code}
148
149
150 %************************************************************************
151 %*                                                                      *
152 \subsection{Making names}
153 %*                                                                      *
154 %************************************************************************
155
156 \begin{code}
157 mkLocalName :: Unique -> OccName -> SrcLoc -> Name
158 mkLocalName uniq occ loc = Name { n_uniq = uniq, n_sort = Local, n_occ = occ, n_loc = loc }
159         -- NB: You might worry that after lots of huffing and
160         -- puffing we might end up with two local names with distinct
161         -- uniques, but the same OccName.  Indeed we can, but that's ok
162         --      * the insides of the compiler don't care: they use the Unique
163         --      * when printing for -ddump-xxx you can switch on -dppr-debug to get the
164         --        uniques if you get confused
165         --      * for interface files we tidyCore first, which puts the uniques
166         --        into the print name (see setNameVisibility below)
167
168 mkImportedLocalName :: Unique -> OccName -> SrcLoc -> Name
169         -- Just the same as mkLocalName, except the provenance is different
170         -- Reason: this flags the name as one that came in from an interface 
171         -- file. This is useful when trying to decide which of two type
172         -- variables should 'win' when unifying them.
173         -- NB: this is only for non-top-level names, so we use ImplicitImport
174         --
175         -- Oct 00: now that Names lack Provenances, mkImportedLocalName doesn't make
176         --         sense any more, so it's just the same as mkLocalName
177 mkImportedLocalName uniq occ loc = mkLocalName uniq occ loc
178
179
180 mkGlobalName :: Unique -> Module -> OccName -> SrcLoc -> Name
181 mkGlobalName uniq mod occ prov = Name { n_uniq = uniq, n_sort = Global mod,
182                                         n_occ = occ, n_loc = loc }
183                                 
184
185 mkKnownKeyGlobal :: RdrName -> Unique -> Name
186 mkKnownKeyGlobal rdr_name uniq
187   = mkGlobalName uniq (mkVanillaModule (rdrNameModule rdr_name))
188                       (rdrNameOcc rdr_name)
189                       builtinSrcLoc
190
191 mkWiredInName :: Module -> OccName -> Unique -> Name
192 mkWiredInName mod occ uniq = mkGlobalName uniq mod occ builtinSrcLoc
193
194 mkSysLocalName :: Unique -> UserFS -> Name
195 mkSysLocalName uniq fs = Name { n_uniq = uniq, n_sort = System, 
196                                 n_occ = mkVarOcc fs, n_loc = noSrcLoc }
197
198 mkCCallName :: Unique -> EncodedString -> Name
199         -- The encoded string completely describes the ccall
200 mkCCallName uniq str =  Name { n_uniq = uniq, n_sort = Local, 
201                                n_occ = mkCCallOcc str, 
202                                n_prov = noSrcLoc }
203
204 mkTopName :: Unique -> Module -> FAST_STRING -> Name
205         -- Make a top-level name; make it Global if top-level
206         -- things should be externally visible; Local otherwise
207         -- This chap is only used *after* the tidyCore phase
208         -- Notably, it is used during STG lambda lifting
209         --
210         -- We have to make sure that the name is globally unique
211         -- and we don't have tidyCore to help us. So we append
212         -- the unique.  Hack!  Hack!
213         -- (Used only by the STG lambda lifter.)
214 mkTopName uniq mod fs
215   = Name { n_uniq = uniq, 
216            n_sort = mk_top_sort mod,
217            n_occ  = mkVarOcc (_PK_ ((_UNPK_ fs) ++ show uniq)),
218            n_loc = noSrcLoc }
219
220 mkIPName :: Unique -> OccName -> Name
221 mkIPName uniq occ
222   = Name { n_uniq = uniq,
223            n_sort = Local,
224            n_occ  = occ,
225            -- ZZ is this an appropriate provinence?
226            n_prov = SystemProv }
227
228 ---------------------------------------------------------------------
229 mkDerivedName :: (OccName -> OccName)
230               -> Name           -- Base name
231               -> Unique         -- New unique
232               -> Name           -- Result is always a value name
233
234 mkDerivedName f name uniq = name {n_uniq = uniq, n_occ = f (n_occ name)}
235 \end{code}
236
237 \begin{code}
238 -- When we renumber/rename things, we need to be
239 -- able to change a Name's Unique to match the cached
240 -- one in the thing it's the name of.  If you know what I mean.
241 setNameUnique name uniq = name {n_uniq = uniq}
242
243 setNameOcc :: Name -> OccName -> Name
244         -- Give the thing a new OccName, *and*
245         -- record that it's no longer a sys-local
246         -- This is used by the tidy-up pass
247 setNameOcc name occ = name {n_occ = occ}
248
249 setNameModuleAndLoc :: Name -> Module -> SrcLoc -> Name
250 setNameModuleAndLoc name mod loc = name {n_sort = set (n_sort name), n_loc = loc}
251                        where
252                          set (Global _) = Global mod
253
254 setLocalNameSort :: Name -> Bool -> Name
255   -- Set the name's sort to Local or Exported, depending on the boolean
256 setLocalNameSort name is_exported = name { n_sort = if is_exported then Exported
257                                                                    else Local }
258 \end{code}
259
260
261 %************************************************************************
262 %*                                                                      *
263 \subsection{Tidying a name}
264 %*                                                                      *
265 %************************************************************************
266
267 tidyTopName is applied to top-level names in the final program
268
269 For top-level things, 
270         it globalises Local names 
271                 (if all top-level things should be visible)
272         and localises non-exported Global names
273                  (if only exported things should be visible)
274
275 In all cases except an exported global, it gives it a new occurrence name.
276
277 The "visibility" here concerns whether the .o file's symbol table
278 mentions the thing; if so, it needs a module name in its symbol.
279 The Global things are "visible" and the Local ones are not
280
281 Why should things be "visible"?  Certainly they must be if they
282 are exported.  But also:
283
284 (a) In certain (prelude only) modules we split up the .hc file into
285     lots of separate little files, which are separately compiled by the C
286     compiler.  That gives lots of little .o files.  The idea is that if
287     you happen to mention one of them you don't necessarily pull them all
288     in.  (Pulling in a piece you don't need can be v bad, because it may
289     mention other pieces you don't need either, and so on.)
290     
291     Sadly, splitting up .hc files means that local names (like s234) are
292     now globally visible, which can lead to clashes between two .hc
293     files. So unlocaliseWhatnot goes through making all the local things
294     into global things, essentially by giving them full names so when they
295     are printed they'll have their module name too.  Pretty revolting
296     really.
297
298 (b) When optimisation is on we want to make all the internal
299     top-level defns externally visible
300
301 \begin{code}
302 tidyTopName :: Module -> TidyOccEnv -> Name -> (TidyOccEnv, Name)
303 tidyTopName mod env name
304   = (env', name')
305   where
306     (env', occ') = tidyOccName env (n_occ name)
307
308     name'        = Name { n_uniq = n_uniq name, n_sort = mk_top_sort mod,
309                           n_occ = occ', n_loc = n_loc name }
310
311 mk_top_sort mod | all_toplev_ids_visible = Global mod
312                 | otherwise              = Local
313
314 all_toplev_ids_visible = 
315         not opt_OmitInterfacePragmas ||  -- Pragmas can make them visible
316         opt_EnsureSplittableC            -- Splitting requires visiblilty
317 \end{code}
318
319
320
321 %************************************************************************
322 %*                                                                      *
323 \subsection{Predicates and selectors}
324 %*                                                                      *
325 %************************************************************************
326
327 \begin{code}
328 hashName :: Name -> Int
329 hashName name = iBox (u2i (nameUnique name))
330
331
332 nameRdrName :: Name -> RdrName
333 -- Makes a qualified name for top-level (Global) names, whether locally defined or not
334 -- and an unqualified name just for Locals
335 nameRdrName (Name { n_occ = occ, n_sort = Global mod }) = mkRdrQual (moduleName mod) occ
336 nameRdrName (Name { n_occ = occ })                      = mkRdrUnqual occ
337
338 ifaceNameRdrName :: Name -> RdrName
339 -- Makes a qualified naem for imported things, 
340 -- and an unqualified one for local things
341 ifaceNameRdrName n | isLocallyDefined n = mkRdrUnqual (nameOccName n)
342                    | otherwise          = mkRdrQual   (moduleName (nameModule n)) (nameOccName n) 
343
344 isDllName :: Name -> Bool
345         -- Does this name refer to something in a different DLL?
346 isDllName nm = not opt_Static &&
347                not (isLocallyDefinedName nm) &&         -- isLocallyDefinedName test needed 'cos
348                not (isLocalModule (nameModule nm))      -- nameModule won't work on local names
349
350
351
352 isTyVarName :: Name -> Bool
353 isTyVarName name = isTvOcc (nameOccName name)
354
355 \end{code}
356
357
358 %************************************************************************
359 %*                                                                      *
360 \subsection[Name-instances]{Instance declarations}
361 %*                                                                      *
362 %************************************************************************
363
364 \begin{code}
365 cmpName n1 n2 = n_uniq n1 `compare` n_uniq n2
366 \end{code}
367
368 \begin{code}
369 instance Eq Name where
370     a == b = case (a `compare` b) of { EQ -> True;  _ -> False }
371     a /= b = case (a `compare` b) of { EQ -> False; _ -> True }
372
373 instance Ord Name where
374     a <= b = case (a `compare` b) of { LT -> True;  EQ -> True;  GT -> False }
375     a <  b = case (a `compare` b) of { LT -> True;  EQ -> False; GT -> False }
376     a >= b = case (a `compare` b) of { LT -> False; EQ -> True;  GT -> True  }
377     a >  b = case (a `compare` b) of { LT -> False; EQ -> False; GT -> True  }
378     compare a b = cmpName a b
379
380 instance Uniquable Name where
381     getUnique = nameUnique
382
383 instance NamedThing Name where
384     getName n = n
385 \end{code}
386
387
388 %************************************************************************
389 %*                                                                      *
390 \subsection{Name environment}
391 %*                                                                      *
392 %************************************************************************
393
394 \begin{code}
395 type NameEnv a = UniqFM a       -- Domain is Name
396
397 emptyNameEnv     :: NameEnv a
398 mkNameEnv        :: [(Name,a)] -> NameEnv a
399 nameEnvElts      :: NameEnv a -> [a]
400 extendNameEnv_C  :: (a->a->a) -> NameEnv a -> Name -> a -> NameEnv a
401 extendNameEnv    :: NameEnv a -> Name -> a -> NameEnv a
402 plusNameEnv      :: NameEnv a -> NameEnv a -> NameEnv a
403 plusNameEnv_C    :: (a->a->a) -> NameEnv a -> NameEnv a -> NameEnv a
404 extendNameEnvList:: NameEnv a -> [(Name,a)] -> NameEnv a
405 delFromNameEnv   :: NameEnv a -> Name -> NameEnv a
406 elemNameEnv      :: Name -> NameEnv a -> Bool
407 unitNameEnv      :: Name -> a -> NameEnv a
408 lookupNameEnv    :: NameEnv a -> Name -> Maybe a
409 lookupNameEnv_NF :: NameEnv a -> Name -> a
410 mapNameEnv       :: (a->b) -> NameEnv a -> NameEnv b
411
412 emptyNameEnv     = emptyUFM
413 mkNameEnv        = listToUFM
414 nameEnvElts      = eltsUFM
415 extendNameEnv_C  = addToUFM_C
416 extendNameEnv    = addToUFM
417 plusNameEnv      = plusUFM
418 plusNameEnv_C    = plusUFM_C
419 extendNameEnvList= addListToUFM
420 delFromNameEnv   = delFromUFM
421 elemNameEnv      = elemUFM
422 mapNameEnv       = mapUFM
423 unitNameEnv      = unitUFM
424
425 lookupNameEnv          = lookupUFM
426 lookupNameEnv_NF env n = expectJust "lookupNameEnv_NF" (lookupUFM env n)
427 \end{code}
428
429
430 %************************************************************************
431 %*                                                                      *
432 \subsection{Pretty printing}
433 %*                                                                      *
434 %************************************************************************
435
436 \begin{code}
437 instance Outputable Name where
438         -- When printing interfaces, all Locals have been given nice print-names
439     ppr name = pprName name
440
441 pprName (Name {n_sort = Local, n_uniq = uniq, n_occ = occ, n_prov = prov})
442         -- Locals
443   = getPprStyle $ \ sty ->
444     if codeStyle sty then
445         pprUnique uniq          -- When printing in code we required all names to 
446                                 -- be globally unique; for example, we use this identifier
447                                 -- for the closure name.  So we just print the unique alone.
448     else
449         pprOccName occ <> pp_local_extra sty uniq
450   where
451     sys_local = case prov of
452                   SystemProv -> True
453                   other      -> False
454
455     pp_local_extra sty uniq
456         | sys_local      = underscore <> pprUnique uniq         -- Must print uniques for sys_locals
457         | debugStyle sty = text "{-" <> pprUnique uniq <> text "-}"
458         | otherwise      = empty
459
460
461 pprName (Name {n_sort = sort, n_uniq = uniq, n_occ = occ, n_prov = prov})
462         -- Globals, and wired in things
463   = getPprStyle $ \ sty ->
464     if codeStyle sty then
465         ppr mod <> underscore <> ppr occ
466     else
467         pp_mod_dot sty <> ppr occ <> pp_global_debug sty uniq prov
468   where
469     mod = nameSortModule sort
470
471     pp_mod_dot sty
472       = case prov of
473            SystemProv -> pp_qual mod user_sty
474                 -- ToDo (SDM): the following comment is out of date - do
475                 -- we need to do anything different now that WiredInNames
476                 -- don't exist any more?
477
478                 -- Hack alert!  Omit the qualifier on SystemProv things in 
479                 -- user style.  I claim such SystemProv things will also be 
480                 -- WiredIn things. We can't get the omit flag right
481                 -- on wired in tycons etc (sigh) so we just leave it out in 
482                 -- user style, and hope that leaving it out isn't too 
483                 -- consfusing. (e.g. if the programmer hides Bool and  
484                 -- redefines it.  If so, use -dppr-debug.)
485
486            LocalDef _ _ -> pp_qual mod (user_sty || iface_sty)
487
488            NonLocalDef (UserImport imp_mod _ _) omit 
489                 | user_sty                           -> pp_qual imp_mod omit
490                 | otherwise                          -> pp_qual mod     False
491            NonLocalDef ImplicitImport           omit -> pp_qual mod     (user_sty && omit)
492       where
493         user_sty  = userStyle sty
494         iface_sty = ifaceStyle sty
495     
496     pp_qual mod omit_qual
497         | omit_qual  = empty
498         | otherwise  = pprModule mod <> dot
499     
500     pp_global_debug sty uniq prov
501       | debugStyle sty = hcat [text "{-", pprUnique uniq, prov_p prov, text "-}"]
502       | otherwise      = empty
503
504     prov_p prov | opt_PprStyle_NoPrags = empty
505                 | otherwise            = comma <> pp_prov prov
506
507 pp_prov (LocalDef _ Exported)          = char 'x'
508 pp_prov (LocalDef _ NotExported)       = char 'l'
509 pp_prov (NonLocalDef ImplicitImport _) = char 'j'
510 pp_prov (NonLocalDef (UserImport _ _ True ) _) = char 'I'       -- Imported by name
511 pp_prov (NonLocalDef (UserImport _ _ False) _) = char 'i'       -- Imported by ..
512 pp_prov SystemProv                     = char 's'
513 \end{code}
514
515
516 %************************************************************************
517 %*                                                                      *
518 \subsection{Overloaded functions related to Names}
519 %*                                                                      *
520 %************************************************************************
521
522 \begin{code}
523 class NamedThing a where
524     getOccName :: a -> OccName
525     getName    :: a -> Name
526
527     getOccName n = nameOccName (getName n)      -- Default method
528 \end{code}
529
530 \begin{code}
531 getSrcLoc           :: NamedThing a => a -> SrcLoc
532 isLocallyDefined    :: NamedThing a => a -> Bool
533 getOccString        :: NamedThing a => a -> String
534 toRdrName           :: NamedThing a => a -> RdrName
535
536 getSrcLoc           = nameSrcLoc           . getName
537 isLocallyDefined    = isLocallyDefinedName . getName
538 getOccString x      = occNameString (getOccName x)
539 toRdrName           = ifaceNameRdrName     . getName
540 \end{code}
541
542 \begin{code}
543 {-# SPECIALIZE isLocallyDefined :: Name -> Bool #-}
544 \end{code}