d1fd37f432637e9f7aae124b36d62e42aca9e8b4
[ghc-hetmet.git] / ghc / compiler / basicTypes / Name.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
3 %
4 \section[Name]{@Name@: to transmit name info from renamer to typechecker}
5
6 \begin{code}
7 module Name (
8         -- Re-export the Module type
9         Module,
10         pprModule, moduleString,
11
12         -- The OccName type
13         OccName(..),
14         pprOccName, occNameString, occNameFlavour, 
15         isTvOcc, isTCOcc, isVarOcc, prefixOccName,
16         uniqToOccName,
17
18         -- The Name type
19         Name,                                   -- Abstract
20         mkLocalName, mkSysLocalName, 
21
22         mkCompoundName, mkGlobalName,
23
24         mkWiredInIdName,   mkWiredInTyConName,
25         maybeWiredInIdName, maybeWiredInTyConName,
26         isWiredInName,
27
28         nameUnique, changeUnique, setNameProvenance, getNameProvenance,
29         setNameVisibility, mkNameVisible,
30         nameOccName, nameString, nameModule,
31
32         isExportedName, nameSrcLoc,
33         isLocallyDefinedName,
34
35         isLocalName, 
36
37         pprNameProvenance,
38
39         -- Sets of Names
40         NameSet,
41         emptyNameSet, unitNameSet, mkNameSet, unionNameSets, unionManyNameSets,
42         minusNameSet, elemNameSet, nameSetToList, addOneToNameSet, addListToNameSet, isEmptyNameSet,
43
44         -- Misc
45         Provenance(..), pprProvenance,
46         ExportFlag(..), 
47         PrintUnqualified,
48
49         -- Class NamedThing and overloaded friends
50         NamedThing(..),
51         modAndOcc, isExported, 
52         getSrcLoc, isLocallyDefined, getOccString
53     ) where
54
55 #include "HsVersions.h"
56
57 import {-# SOURCE #-} Id    ( Id )
58 import {-# SOURCE #-} TyCon ( TyCon )
59
60 import CStrings         ( identToC )
61 import CmdLineOpts      ( opt_PprStyle_All, opt_OmitInterfacePragmas, opt_EnsureSplittableC )
62 import BasicTypes       ( Module, IfaceFlavour(..), moduleString, pprModule )
63
64 import Lex              ( isLexConId )
65 import SrcLoc           ( noSrcLoc, mkBuiltinSrcLoc, SrcLoc )
66 import Unique           ( pprUnique, showUnique, Unique, Uniquable(..) )
67 import UniqSet          ( UniqSet,
68                              emptyUniqSet, unitUniqSet, unionUniqSets, uniqSetToList, 
69                              isEmptyUniqSet, unionManyUniqSets, minusUniqSet, mkUniqSet, 
70                              elementOfUniqSet, addListToUniqSet, addOneToUniqSet
71                         )
72 import UniqFM           ( UniqFM )
73 import Outputable
74 \end{code}
75
76
77 %************************************************************************
78 %*                                                                      *
79 \subsection[Name-pieces-datatypes]{The @OccName@ datatypes}
80 %*                                                                      *
81 %************************************************************************
82
83 \begin{code}
84 data OccName  = VarOcc  FAST_STRING     -- Variables and data constructors
85               | TvOcc   FAST_STRING     -- Type variables
86               | TCOcc   FAST_STRING     -- Type constructors and classes
87
88 pprOccName :: OccName -> SDoc
89 pprOccName n = getPprStyle $ \ sty ->
90                if codeStyle sty 
91                then identToC (occNameString n)
92                else ptext (occNameString n)
93
94 occNameString :: OccName -> FAST_STRING
95 occNameString (VarOcc s)  = s
96 occNameString (TvOcc s)   = s
97 occNameString (TCOcc s)   = s
98
99 prefixOccName :: FAST_STRING -> OccName -> OccName
100 prefixOccName prefix (VarOcc s) = VarOcc (prefix _APPEND_ s)
101 prefixOccName prefix (TvOcc s)  = TvOcc (prefix _APPEND_ s)
102 prefixOccName prefix (TCOcc s) = TCOcc (prefix _APPEND_ s)
103
104 -- occNameFlavour is used only to generate good error messages, so it doesn't matter
105 -- that the VarOcc case isn't mega-efficient.  We could have different Occ constructors for
106 -- data constructors and values, but that makes everything else a bit more complicated.
107 occNameFlavour :: OccName -> String
108 occNameFlavour (VarOcc s) | isLexConId s = "Data constructor"
109                           | otherwise    = "Value"
110 occNameFlavour (TvOcc s)  = "Type variable"
111 occNameFlavour (TCOcc s)  = "Type constructor or class"
112
113 isVarOcc, isTCOcc, isTvOcc :: OccName -> Bool
114 isVarOcc (VarOcc s) = True
115 isVarOcc other     = False
116
117 isTvOcc (TvOcc s) = True
118 isTvOcc other     = False
119
120 isTCOcc (TCOcc s) = True
121 isTCOcc other     = False
122
123 instance Eq OccName where
124     a == b = case (a `compare` b) of { EQ -> True;  _ -> False }
125     a /= b = case (a `compare` b) of { EQ -> False; _ -> True }
126
127 instance Ord OccName where
128     a <= b = case (a `compare` b) of { LT -> True;  EQ -> True;  GT -> False }
129     a <  b = case (a `compare` b) of { LT -> True;  EQ -> False; GT -> False }
130     a >= b = case (a `compare` b) of { LT -> False; EQ -> True;  GT -> True  }
131     a >  b = case (a `compare` b) of { LT -> False; EQ -> False; GT -> True  }
132     compare a b = cmpOcc a b
133
134 (VarOcc s1) `cmpOcc` (VarOcc s2) = s1 `compare` s2
135 (VarOcc s1) `cmpOcc` other2      = LT
136
137 (TvOcc s1)  `cmpOcc` (VarOcc s2) = GT
138 (TvOcc s1)  `cmpOcc` (TvOcc s2)  = s1 `compare` s2
139 (TvOcc s1)  `cmpOcc` other       = LT
140
141 (TCOcc s1) `cmpOcc` (TCOcc s2) = s1 `compare` s2
142 (TCOcc s1) `cmpOcc` other      = GT
143
144 instance Outputable OccName where
145   ppr = pprOccName
146 \end{code}
147
148
149 %************************************************************************
150 %*                                                                      *
151 \subsection[Name-datatype]{The @Name@ datatype, and name construction}
152 %*                                                                      *
153 %************************************************************************
154  
155 \begin{code}
156 data Name
157   = Local    Unique
158              OccName
159              SrcLoc
160
161   | Global   Unique
162              Module             -- The defining module
163              OccName            -- Its name in that module
164              Provenance         -- How it was defined
165 \end{code}
166
167 Things with a @Global@ name are given C static labels, so they finally
168 appear in the .o file's symbol table.  They appear in the symbol table
169 in the form M.n.  If originally-local things have this property they
170 must be made @Global@ first.
171
172 \begin{code}
173 data Provenance
174   = NoProvenance
175
176   | LocalDef                    -- Defined locally
177         SrcLoc                  -- Defn site
178         ExportFlag              -- Whether it's exported
179
180   | NonLocalDef                 -- Defined non-locally
181         SrcLoc                  -- Defined non-locally; src-loc gives defn site
182         IfaceFlavour            -- Whether the defn site is an .hi-boot file or not
183         PrintUnqualified
184
185   | WiredInTyCon TyCon                  -- There's a wired-in version
186   | WiredInId    Id                     -- ...ditto...
187
188 type PrintUnqualified = Bool            -- True <=> the unqualified name of this thing is
189                                         -- in scope in this module, so print it unqualified
190                                         -- in error messages
191 \end{code}
192
193 Something is "Exported" if it may be mentioned by another module without
194 warning.  The crucial thing about Exported things is that they must
195 never be dropped as dead code, even if they aren't used in this module.
196 Furthermore, being Exported means that we can't see all call sites of the thing.
197
198 Exported things include:
199         - explicitly exported Ids, including data constructors, class method selectors
200         - dfuns from instance decls
201
202 Being Exported is *not* the same as finally appearing in the .o file's 
203 symbol table.  For example, a local Id may be mentioned in an Exported
204 Id's unfolding in the interface file, in which case the local Id goes
205 out too.
206
207 \begin{code}
208 data ExportFlag = Exported  | NotExported
209 \end{code}
210
211 \begin{code}
212 mkLocalName    :: Unique -> OccName -> SrcLoc -> Name
213 mkLocalName = Local
214
215 mkGlobalName :: Unique -> Module -> OccName -> Provenance -> Name
216 mkGlobalName = Global
217
218 mkSysLocalName :: Unique -> FAST_STRING -> SrcLoc -> Name
219 mkSysLocalName uniq str loc = Local uniq (VarOcc str) loc
220
221 mkWiredInIdName :: Unique -> Module -> FAST_STRING -> Id -> Name
222 mkWiredInIdName uniq mod occ id 
223   = Global uniq mod (VarOcc occ) (WiredInId id)
224
225 mkWiredInTyConName :: Unique -> Module -> FAST_STRING -> TyCon -> Name
226 mkWiredInTyConName uniq mod occ tycon
227   = Global uniq mod (TCOcc occ) (WiredInTyCon tycon)
228
229
230 mkCompoundName :: (FAST_STRING -> FAST_STRING)  -- Occurrence-name modifier
231                -> Unique                        -- New unique
232                -> Name                          -- Base name (must be a Global)
233                -> Name          -- Result is always a value name
234
235 mkCompoundName str_fn uniq (Global _ mod occ prov)
236   = Global uniq mod new_occ prov
237   where    
238     new_occ = VarOcc (str_fn (occNameString occ))               -- Always a VarOcc
239
240 mkCompoundName str_fn uniq (Local _ occ loc)
241   = Local uniq (VarOcc (str_fn (occNameString occ))) loc
242
243
244 setNameProvenance :: Name -> Provenance -> Name 
245         -- setNameProvenance used to only change the provenance of Implicit-provenance things,
246         -- but that gives bad error messages for names defined twice in the same
247         -- module, so I changed it to set the provenance of *any* global (SLPJ Jun 97)
248 setNameProvenance (Global uniq mod occ _) prov = Global uniq mod occ prov
249 setNameProvenance other_name              prov = other_name
250
251 getNameProvenance :: Name -> Provenance
252 getNameProvenance (Global uniq mod occ prov) = prov
253 getNameProvenance (Local uniq occ locn)      = LocalDef locn NotExported
254
255 -- When we renumber/rename things, we need to be
256 -- able to change a Name's Unique to match the cached
257 -- one in the thing it's the name of.  If you know what I mean.
258 changeUnique (Local      _ n l)  u = Local u n l
259 changeUnique (Global   _ mod occ  prov) u = Global u mod occ prov
260 \end{code}
261
262 setNameVisibility is applied to names in the final program
263
264 The Maybe Module argument is (Just mod) for top-level values,
265 and Nothing for all others (local values and type variables)
266
267 For top-level things, it globalises Local names 
268                                 (if all top-level things should be visible)
269                          and localises non-exported Global names
270                                  (if only exported things should be visible)
271
272 For nested things it localises Global names.
273
274 In all cases except an exported global, it gives it a new occurrence name.
275
276 The "visibility" here concerns whether the .o file's symbol table
277 mentions the thing; if so, it needs a module name in its symbol.
278 The Global things are "visible" and the Local ones are not
279
280 Why should things be "visible"?  Certainly they must be if they
281 are exported.  But also:
282
283 (a) In certain (prelude only) modules we split up the .hc file into
284     lots of separate little files, which are separately compiled by the C
285     compiler.  That gives lots of little .o files.  The idea is that if
286     you happen to mention one of them you don't necessarily pull them all
287     in.  (Pulling in a piece you don't need can be v bad, because it may
288     mention other pieces you don't need either, and so on.)
289     
290     Sadly, splitting up .hc files means that local names (like s234) are
291     now globally visible, which can lead to clashes between two .hc
292     files. So unlocaliseWhatnot goes through making all the local things
293     into global things, essentially by giving them full names so when they
294     are printed they'll have their module name too.  Pretty revolting
295     really.
296
297 (b) When optimisation is on we want to make all the internal
298     top-level defns externally visible
299
300 \begin{code}
301 setNameVisibility :: Maybe Module -> Unique -> Name -> Name
302
303 setNameVisibility maybe_mod occ_uniq name@(Global uniq mod occ (LocalDef loc NotExported))
304   | not all_toplev_ids_visible || not_top_level maybe_mod
305   = Local uniq (uniqToOccName occ_uniq) loc     -- Localise Global name
306
307 setNameVisibility maybe_mod occ_uniq name@(Global _ _ _ _)
308   = name                                        -- Otherwise don't fiddle with Global
309
310 setNameVisibility (Just mod) occ_uniq (Local uniq occ loc)
311   | all_toplev_ids_visible
312   = Global uniq mod                             -- Globalise Local name
313            (uniqToOccName occ_uniq)
314            (LocalDef loc NotExported)
315
316 setNameVisibility maybe_mod occ_uniq (Local uniq occ loc)
317   = Local uniq (uniqToOccName occ_uniq) loc     -- New OccName for Local
318
319 -- make the Name globally visible regardless.
320 mkNameVisible :: Module -> Unique -> Name -> Name
321 mkNameVisible mod occ_uniq nm@(Global _ _ _ _) = nm
322 mkNameVisible mod occ_uniq nm@(Local uniq occ loc)
323  = Global uniq mod (uniqToOccName occ_uniq) (LocalDef loc Exported)
324
325
326 uniqToOccName uniq = VarOcc (_PK_ ('$':showUnique uniq))
327         -- The "$" is to make sure that this OccName is distinct from all user-defined ones
328
329 not_top_level (Just m) = False
330 not_top_level Nothing  = True
331
332 all_toplev_ids_visible = not opt_OmitInterfacePragmas ||  -- Pragmas can make them visible
333                          opt_EnsureSplittableC            -- Splitting requires visiblilty
334 \end{code}
335
336 %************************************************************************
337 %*                                                                      *
338 \subsection{Predicates and selectors}
339 %*                                                                      *
340 %************************************************************************
341
342 \begin{code}
343 nameUnique              :: Name -> Unique
344 nameModAndOcc           :: Name -> (Module, OccName)    -- Globals only
345 nameOccName             :: Name -> OccName 
346 nameModule              :: Name -> Module
347 nameString              :: Name -> FAST_STRING          -- A.b form
348 nameSrcLoc              :: Name -> SrcLoc
349 isLocallyDefinedName    :: Name -> Bool
350 isExportedName          :: Name -> Bool
351 isWiredInName           :: Name -> Bool
352 isLocalName             :: Name -> Bool
353
354
355
356 nameUnique (Local  u _ _)   = u
357 nameUnique (Global u _ _ _) = u
358
359 nameOccName (Local _ occ _)    = occ
360 nameOccName (Global _ _ occ _) = occ
361
362 nameModule (Global _ mod occ _) = mod
363
364 nameModAndOcc (Global _ mod occ _) = (mod,occ)
365
366 nameString (Local _ occ _)      = occNameString occ
367 nameString (Global _ mod occ _) = mod _APPEND_ SLIT(".") _APPEND_ occNameString occ
368
369 isExportedName (Global _ _ _ (LocalDef _ Exported)) = True
370 isExportedName other                                = False
371
372 nameSrcLoc (Local _ _ loc)     = loc
373 nameSrcLoc (Global _ _ _ (LocalDef loc _))      = loc
374 nameSrcLoc (Global _ _ _ (NonLocalDef loc _ _)) = loc
375 nameSrcLoc (Global _ _ _ (WiredInTyCon _))      = mkBuiltinSrcLoc
376 nameSrcLoc (Global _ _ _ (WiredInId _))         = mkBuiltinSrcLoc
377 nameSrcLoc other                                = noSrcLoc
378   
379 isLocallyDefinedName (Local  _ _ _)                = True
380 isLocallyDefinedName (Global _ _ _ (LocalDef _ _)) = True
381 isLocallyDefinedName other                         = False
382
383 -- Things the compiler "knows about" are in some sense
384 -- "imported".  When we are compiling the module where
385 -- the entities are defined, we need to be able to pick
386 -- them out, often in combination with isLocallyDefined.
387 isWiredInName (Global _ _ _ (WiredInTyCon _)) = True
388 isWiredInName (Global _ _ _ (WiredInId    _)) = True
389 isWiredInName _                               = False
390
391 maybeWiredInIdName :: Name -> Maybe Id
392 maybeWiredInIdName (Global _ _ _ (WiredInId id)) = Just id
393 maybeWiredInIdName other                         = Nothing
394
395 maybeWiredInTyConName :: Name -> Maybe TyCon
396 maybeWiredInTyConName (Global _ _ _ (WiredInTyCon tc)) = Just tc
397 maybeWiredInTyConName other                            = Nothing
398
399
400 isLocalName (Local _ _ _) = True
401 isLocalName _             = False
402 \end{code}
403
404
405 %************************************************************************
406 %*                                                                      *
407 \subsection[Name-instances]{Instance declarations}
408 %*                                                                      *
409 %************************************************************************
410
411 \begin{code}
412 cmpName n1 n2 = c n1 n2
413   where
414     c (Local  u1 _ _)   (Local  u2 _ _)   = compare u1 u2
415     c (Local   _ _ _)     _               = LT
416     c (Global u1 _ _ _) (Global u2 _ _ _) = compare u1 u2
417     c (Global  _ _ _ _)   _               = GT
418 \end{code}
419
420 \begin{code}
421 instance Eq Name where
422     a == b = case (a `compare` b) of { EQ -> True;  _ -> False }
423     a /= b = case (a `compare` b) of { EQ -> False; _ -> True }
424
425 instance Ord Name where
426     a <= b = case (a `compare` b) of { LT -> True;      EQ -> True;  GT -> False }
427     a <  b = case (a `compare` b) of { LT -> True;      EQ -> False; GT -> False }
428     a >= b = case (a `compare` b) of { LT -> False; EQ -> True;  GT -> True  }
429     a >  b = case (a `compare` b) of { LT -> False; EQ -> False; GT -> True  }
430     compare a b = cmpName a b
431
432 instance Uniquable Name where
433     uniqueOf = nameUnique
434
435 instance NamedThing Name where
436     getName n = n
437 \end{code}
438
439
440
441 %************************************************************************
442 %*                                                                      *
443 \subsection{Pretty printing}
444 %*                                                                      *
445 %************************************************************************
446
447 \begin{code}
448 instance Outputable Name where
449         -- When printing interfaces, all Locals have been given nice print-names
450     ppr name = pprName name
451
452 pprName name
453   = getPprStyle $ \ sty ->
454     let
455        ppr (Local u n _) 
456          |  userStyle sty 
457          || ifaceStyle sty = ptext (occNameString n)
458          |  codeStyle sty  = pprUnique u
459          |  otherwise      = hcat [ptext (occNameString n), ptext SLIT("_"), pprUnique u]
460    
461        ppr name@(Global u m n prov)
462          | codeStyle sty
463          = identToC (m _APPEND_ SLIT(".") _APPEND_ occNameString n)
464    
465          | otherwise  
466          = hcat [pp_mod_dot, ptext (occNameString n), pp_debug sty name]
467          where
468            pp_mod_dot 
469                 = case prov of          -- Omit home module qualifier if its in scope 
470                            LocalDef _ _           -> pp_qual dot (user_sty || iface_sty)
471                            NonLocalDef _ hif omit -> pp_qual (pp_hif hif) (omit && user_sty)
472                            WiredInTyCon _         -> pp_qual dot user_sty -- Hack: omit qualifers on wired in things
473                            WiredInId _            -> pp_qual dot user_sty -- in user style only
474                            NoProvenance           -> pp_qual dot False
475    
476            pp_qual sep omit_qual
477             | omit_qual  = empty
478             | otherwise  = pprModule m <> sep
479
480            dot = text "."
481            pp_hif HiFile     = dot       -- Vanilla case
482            pp_hif HiBootFile = text "!"  -- M!t indicates a name imported from a .hi-boot interface
483
484            user_sty  = userStyle sty
485            iface_sty = ifaceStyle sty
486     in
487     ppr name
488    
489    
490 pp_debug sty (Global uniq m n prov) 
491   | debugStyle sty = hcat [text "{-", pprUnique uniq, prov_p, text "-}"]
492   | otherwise      = empty
493                    where
494                      prov_p | opt_PprStyle_All = comma <> pp_prov prov
495                             | otherwise        = empty
496
497 pp_prov (LocalDef _ Exported)    = char 'x'
498 pp_prov (LocalDef _ NotExported) = char 'l'
499 pp_prov (NonLocalDef _ _ _)      = char 'n'
500 pp_prov (WiredInTyCon _)         = char 'W'
501 pp_prov (WiredInId _)            = char 'w'
502 pp_prov NoProvenance             = char '?'
503
504 -- pprNameProvenance is used in error messages to say where a name came from
505 pprNameProvenance :: Name -> SDoc
506 pprNameProvenance (Local _ _ loc)     = pprProvenance (LocalDef loc NotExported)
507 pprNameProvenance (Global _ _ _ prov) = pprProvenance prov
508
509 pprProvenance :: Provenance -> SDoc
510 pprProvenance (LocalDef loc _)      = ptext SLIT("Locally defined at")     <+> ppr loc
511 pprProvenance (NonLocalDef loc _ _) = ptext SLIT("Non-locally defined at") <+> ppr loc
512 pprProvenance (WiredInTyCon tc)     = ptext SLIT("Wired-in tycon")
513 pprProvenance (WiredInId id)        = ptext SLIT("Wired-in id")
514 pprProvenance NoProvenance          = ptext SLIT("No provenance")
515 \end{code}
516
517
518 %************************************************************************
519 %*                                                                      *
520 \subsection[Sets of names}
521 %*                                                                      *
522 %************************************************************************
523
524 \begin{code}
525 type NameSet = UniqSet Name
526 emptyNameSet      :: NameSet
527 unitNameSet       :: Name -> NameSet
528 addListToNameSet  :: NameSet -> [Name] -> NameSet
529 addOneToNameSet   :: NameSet -> Name -> NameSet
530 mkNameSet         :: [Name] -> NameSet
531 unionNameSets     :: NameSet -> NameSet -> NameSet
532 unionManyNameSets :: [NameSet] -> NameSet
533 minusNameSet      :: NameSet -> NameSet -> NameSet
534 elemNameSet       :: Name -> NameSet -> Bool
535 nameSetToList     :: NameSet -> [Name]
536 isEmptyNameSet    :: NameSet -> Bool
537
538 isEmptyNameSet    = isEmptyUniqSet
539 emptyNameSet      = emptyUniqSet
540 unitNameSet       = unitUniqSet
541 mkNameSet         = mkUniqSet
542 addListToNameSet  = addListToUniqSet
543 addOneToNameSet   = addOneToUniqSet
544 unionNameSets     = unionUniqSets
545 unionManyNameSets = unionManyUniqSets
546 minusNameSet      = minusUniqSet
547 elemNameSet       = elementOfUniqSet
548 nameSetToList     = uniqSetToList
549 \end{code}
550
551
552
553 %************************************************************************
554 %*                                                                      *
555 \subsection{Overloaded functions related to Names}
556 %*                                                                      *
557 %************************************************************************
558
559 \begin{code}
560 class NamedThing a where
561     getOccName :: a -> OccName          -- Even RdrNames can do this!
562     getName    :: a -> Name
563
564     getOccName n = nameOccName (getName n)      -- Default method
565 \end{code}
566
567 \begin{code}
568 modAndOcc           :: NamedThing a => a -> (Module, OccName)
569 getSrcLoc           :: NamedThing a => a -> SrcLoc
570 isLocallyDefined    :: NamedThing a => a -> Bool
571 isExported          :: NamedThing a => a -> Bool
572 getOccString        :: NamedThing a => a -> String
573
574 modAndOcc           = nameModAndOcc        . getName
575 isExported          = isExportedName       . getName
576 getSrcLoc           = nameSrcLoc           . getName
577 isLocallyDefined    = isLocallyDefinedName . getName
578 getOccString x      = _UNPK_ (occNameString (getOccName x))
579 \end{code}
580
581 \begin{code}
582 {-# SPECIALIZE isLocallyDefined
583         :: Name     -> Bool
584   #-}
585 \end{code}