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