[project @ 1998-01-08 18:03:08 by simonm]
[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,
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, modnameToC, cSEP )
61 import CmdLineOpts      ( opt_PprStyle_All, opt_OmitInterfacePragmas, opt_EnsureSplittableC )
62 import BasicTypes       ( Module, IfaceFlavour(..), moduleString, pprModule )
63
64 import PrelMods         ( gHC__ )
65 import Lex              ( isLexSym, isLexConId )
66 import SrcLoc           ( noSrcLoc, mkBuiltinSrcLoc, SrcLoc )
67 import Unique           ( pprUnique, showUnique, Unique, Uniquable(..) )
68 import UniqSet          ( UniqSet(..), 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 uniqToOccName uniq = VarOcc (_PK_ ('$':showUnique uniq))
320         -- The "$" is to make sure that this OccName is distinct from all user-defined ones
321
322 not_top_level (Just m) = False
323 not_top_level Nothing  = True
324
325 all_toplev_ids_visible = not opt_OmitInterfacePragmas ||  -- Pragmas can make them visible
326                          opt_EnsureSplittableC            -- Splitting requires visiblilty
327 \end{code}
328
329 %************************************************************************
330 %*                                                                      *
331 \subsection{Predicates and selectors}
332 %*                                                                      *
333 %************************************************************************
334
335 \begin{code}
336 nameUnique              :: Name -> Unique
337 nameModAndOcc           :: Name -> (Module, OccName)    -- Globals only
338 nameOccName             :: Name -> OccName 
339 nameModule              :: Name -> Module
340 nameString              :: Name -> FAST_STRING          -- A.b form
341 nameSrcLoc              :: Name -> SrcLoc
342 isLocallyDefinedName    :: Name -> Bool
343 isExportedName          :: Name -> Bool
344 isWiredInName           :: Name -> Bool
345 isLocalName             :: Name -> Bool
346
347
348
349 nameUnique (Local  u _ _)   = u
350 nameUnique (Global u _ _ _) = u
351
352 nameOccName (Local _ occ _)    = occ
353 nameOccName (Global _ _ occ _) = occ
354
355 nameModule (Global _ mod occ _) = mod
356
357 nameModAndOcc (Global _ mod occ _) = (mod,occ)
358
359 nameString (Local _ occ _)      = occNameString occ
360 nameString (Global _ mod occ _) = mod _APPEND_ SLIT(".") _APPEND_ occNameString occ
361
362 isExportedName (Global _ _ _ (LocalDef _ Exported)) = True
363 isExportedName other                                = False
364
365 nameSrcLoc (Local _ _ loc)     = loc
366 nameSrcLoc (Global _ _ _ (LocalDef loc _))      = loc
367 nameSrcLoc (Global _ _ _ (NonLocalDef loc _ _)) = loc
368 nameSrcLoc (Global _ _ _ (WiredInTyCon _))      = mkBuiltinSrcLoc
369 nameSrcLoc (Global _ _ _ (WiredInId _))         = mkBuiltinSrcLoc
370 nameSrcLoc other                                = noSrcLoc
371   
372 isLocallyDefinedName (Local  _ _ _)                = True
373 isLocallyDefinedName (Global _ _ _ (LocalDef _ _)) = True
374 isLocallyDefinedName other                         = False
375
376 -- Things the compiler "knows about" are in some sense
377 -- "imported".  When we are compiling the module where
378 -- the entities are defined, we need to be able to pick
379 -- them out, often in combination with isLocallyDefined.
380 isWiredInName (Global _ _ _ (WiredInTyCon _)) = True
381 isWiredInName (Global _ _ _ (WiredInId    _)) = True
382 isWiredInName _                               = False
383
384 maybeWiredInIdName :: Name -> Maybe Id
385 maybeWiredInIdName (Global _ _ _ (WiredInId id)) = Just id
386 maybeWiredInIdName other                         = Nothing
387
388 maybeWiredInTyConName :: Name -> Maybe TyCon
389 maybeWiredInTyConName (Global _ _ _ (WiredInTyCon tc)) = Just tc
390 maybeWiredInTyConName other                            = Nothing
391
392
393 isLocalName (Local _ _ _) = True
394 isLocalName _             = False
395 \end{code}
396
397
398 %************************************************************************
399 %*                                                                      *
400 \subsection[Name-instances]{Instance declarations}
401 %*                                                                      *
402 %************************************************************************
403
404 \begin{code}
405 cmpName n1 n2 = c n1 n2
406   where
407     c (Local  u1 _ _)   (Local  u2 _ _)   = compare u1 u2
408     c (Local   _ _ _)     _               = LT
409     c (Global u1 _ _ _) (Global u2 _ _ _) = compare u1 u2
410     c (Global  _ _ _ _)   _               = GT
411 \end{code}
412
413 \begin{code}
414 instance Eq Name where
415     a == b = case (a `compare` b) of { EQ -> True;  _ -> False }
416     a /= b = case (a `compare` b) of { EQ -> False; _ -> True }
417
418 instance Ord Name where
419     a <= b = case (a `compare` b) of { LT -> True;      EQ -> True;  GT -> False }
420     a <  b = case (a `compare` b) of { LT -> True;      EQ -> False; GT -> False }
421     a >= b = case (a `compare` b) of { LT -> False; EQ -> True;  GT -> True  }
422     a >  b = case (a `compare` b) of { LT -> False; EQ -> False; GT -> True  }
423     compare a b = cmpName a b
424
425 instance Uniquable Name where
426     uniqueOf = nameUnique
427
428 instance NamedThing Name where
429     getName n = n
430 \end{code}
431
432
433
434 %************************************************************************
435 %*                                                                      *
436 \subsection{Pretty printing}
437 %*                                                                      *
438 %************************************************************************
439
440 \begin{code}
441 instance Outputable Name where
442         -- When printing interfaces, all Locals have been given nice print-names
443     ppr name = pprName name
444
445 pprName name
446   = getPprStyle $ \ sty ->
447     let
448        ppr (Local u n _) 
449          |  userStyle sty 
450          || ifaceStyle sty = ptext (occNameString n)
451          |  codeStyle sty  = pprUnique u
452          |  otherwise      = hcat [ptext (occNameString n), ptext SLIT("_"), pprUnique u]
453    
454        ppr name@(Global u m n prov)
455          | codeStyle sty
456          = identToC (m _APPEND_ SLIT(".") _APPEND_ occNameString n)
457    
458          | otherwise  
459          = hcat [pp_mod_dot, ptext (occNameString n), pp_debug sty name]
460          where
461            pp_mod_dot 
462                 = case prov of          -- Omit home module qualifier if its in scope 
463                            LocalDef _ _           -> pp_qual dot (user_sty || iface_sty)
464                            NonLocalDef _ hif omit -> pp_qual (pp_hif hif) (omit && user_sty)
465                            WiredInTyCon _         -> pp_qual dot user_sty -- Hack: omit qualifers on wired in things
466                            WiredInId _            -> pp_qual dot user_sty -- in user style only
467                            NoProvenance           -> pp_qual dot False
468    
469            pp_qual sep omit_qual
470             | omit_qual  = empty
471             | otherwise  = pprModule m <> sep
472
473            dot = text "."
474            pp_hif HiFile     = dot       -- Vanilla case
475            pp_hif HiBootFile = text "!"  -- M!t indicates a name imported from a .hi-boot interface
476
477            user_sty  = userStyle sty
478            iface_sty = ifaceStyle sty
479     in
480     ppr name
481    
482    
483 pp_debug sty (Global uniq m n prov) 
484   | debugStyle sty = hcat [text "{-", pprUnique uniq, prov_p, text "-}"]
485   | otherwise      = empty
486                    where
487                      prov_p | opt_PprStyle_All = comma <> pp_prov prov
488                             | otherwise        = empty
489
490 pp_prov (LocalDef _ Exported)    = char 'x'
491 pp_prov (LocalDef _ NotExported) = char 'l'
492 pp_prov (NonLocalDef _ _ _)      = char 'n'
493 pp_prov (WiredInTyCon _)         = char 'W'
494 pp_prov (WiredInId _)            = char 'w'
495 pp_prov NoProvenance             = char '?'
496
497 -- pprNameProvenance is used in error messages to say where a name came from
498 pprNameProvenance :: Name -> SDoc
499 pprNameProvenance (Local _ _ loc)     = pprProvenance (LocalDef loc NotExported)
500 pprNameProvenance (Global _ _ _ prov) = pprProvenance prov
501
502 pprProvenance :: Provenance -> SDoc
503 pprProvenance (LocalDef loc _)      = ptext SLIT("Locally defined at")     <+> ppr loc
504 pprProvenance (NonLocalDef loc _ _) = ptext SLIT("Non-locally defined at") <+> ppr loc
505 pprProvenance (WiredInTyCon tc)     = ptext SLIT("Wired-in tycon")
506 pprProvenance (WiredInId id)        = ptext SLIT("Wired-in id")
507 pprProvenance NoProvenance          = ptext SLIT("No provenance")
508 \end{code}
509
510
511 %************************************************************************
512 %*                                                                      *
513 \subsection[Sets of names}
514 %*                                                                      *
515 %************************************************************************
516
517 \begin{code}
518 type NameSet = UniqSet Name
519 emptyNameSet      :: NameSet
520 unitNameSet       :: Name -> NameSet
521 addListToNameSet  :: NameSet -> [Name] -> NameSet
522 addOneToNameSet   :: NameSet -> Name -> NameSet
523 mkNameSet         :: [Name] -> NameSet
524 unionNameSets     :: NameSet -> NameSet -> NameSet
525 unionManyNameSets :: [NameSet] -> NameSet
526 minusNameSet      :: NameSet -> NameSet -> NameSet
527 elemNameSet       :: Name -> NameSet -> Bool
528 nameSetToList     :: NameSet -> [Name]
529 isEmptyNameSet    :: NameSet -> Bool
530
531 isEmptyNameSet    = isEmptyUniqSet
532 emptyNameSet      = emptyUniqSet
533 unitNameSet       = unitUniqSet
534 mkNameSet         = mkUniqSet
535 addListToNameSet  = addListToUniqSet
536 addOneToNameSet   = addOneToUniqSet
537 unionNameSets     = unionUniqSets
538 unionManyNameSets = unionManyUniqSets
539 minusNameSet      = minusUniqSet
540 elemNameSet       = elementOfUniqSet
541 nameSetToList     = uniqSetToList
542 \end{code}
543
544
545
546 %************************************************************************
547 %*                                                                      *
548 \subsection{Overloaded functions related to Names}
549 %*                                                                      *
550 %************************************************************************
551
552 \begin{code}
553 class NamedThing a where
554     getOccName :: a -> OccName          -- Even RdrNames can do this!
555     getName    :: a -> Name
556
557     getOccName n = nameOccName (getName n)      -- Default method
558 \end{code}
559
560 \begin{code}
561 modAndOcc           :: NamedThing a => a -> (Module, OccName)
562 getModule           :: NamedThing a => a -> Module
563 getSrcLoc           :: NamedThing a => a -> SrcLoc
564 isLocallyDefined    :: NamedThing a => a -> Bool
565 isExported          :: NamedThing a => a -> Bool
566 getOccString        :: NamedThing a => a -> String
567
568 modAndOcc           = nameModAndOcc        . getName
569 getModule           = nameModule           . getName
570 isExported          = isExportedName       . getName
571 getSrcLoc           = nameSrcLoc           . getName
572 isLocallyDefined    = isLocallyDefinedName . getName
573 getOccString x      = _UNPK_ (occNameString (getOccName x))
574 \end{code}
575
576 \begin{code}
577 {-# SPECIALIZE isLocallyDefined
578         :: Name     -> Bool
579   #-}
580 \end{code}