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