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