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