remove empty dir
[ghc-hetmet.git] / compiler / basicTypes / RdrName.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4
5 \section[RdrName]{@RdrName@}
6
7 \begin{code}
8 module RdrName (
9         RdrName(..),    -- Constructors exported only to BinIface
10
11         -- Construction
12         mkRdrUnqual, mkRdrQual, 
13         mkUnqual, mkVarUnqual, mkQual, mkOrig,
14         nameRdrName, getRdrName, 
15         mkDerivedRdrName, 
16
17         -- Destruction
18         rdrNameModule, rdrNameOcc, setRdrNameSpace,
19         isRdrDataCon, isRdrTyVar, isRdrTc, isQual, isUnqual, 
20         isOrig, isOrig_maybe, isExact, isExact_maybe, isSrcRdrName,
21
22         -- Printing;    instance Outputable RdrName
23
24         -- LocalRdrEnv
25         LocalRdrEnv, emptyLocalRdrEnv, extendLocalRdrEnv,
26         lookupLocalRdrEnv, elemLocalRdrEnv,
27
28         -- GlobalRdrEnv
29         GlobalRdrEnv, emptyGlobalRdrEnv, mkGlobalRdrEnv, plusGlobalRdrEnv, 
30         lookupGlobalRdrEnv, extendGlobalRdrEnv,
31         pprGlobalRdrEnv, globalRdrEnvElts,
32         lookupGRE_RdrName, lookupGRE_Name,
33
34         -- GlobalRdrElt, Provenance, ImportSpec
35         GlobalRdrElt(..), isLocalGRE, unQualOK, 
36         Provenance(..), pprNameProvenance,
37         ImportSpec(..), ImpDeclSpec(..), ImpItemSpec(..), 
38         importSpecLoc, importSpecModule
39   ) where 
40
41 #include "HsVersions.h"
42
43 import OccName
44 import Module   ( Module, mkModuleFS )
45 import Name     ( Name, NamedThing(getName), nameModule, nameParent_maybe,
46                   nameOccName, isExternalName, nameSrcLoc )
47 import Maybes   ( mapCatMaybes )
48 import SrcLoc   ( isGoodSrcLoc, SrcSpan )
49 import FastString ( FastString )
50 import Outputable
51 import Util     ( thenCmp )
52 \end{code}
53
54 %************************************************************************
55 %*                                                                      *
56 \subsection{The main data type}
57 %*                                                                      *
58 %************************************************************************
59
60 \begin{code}
61 data RdrName 
62   = Unqual OccName
63         -- Used for ordinary, unqualified occurrences 
64
65   | Qual Module OccName
66         -- A qualified name written by the user in 
67         --  *source* code.  The module isn't necessarily 
68         -- the module where the thing is defined; 
69         -- just the one from which it is imported
70
71   | Orig Module OccName
72         -- An original name; the module is the *defining* module.
73         -- This is used when GHC generates code that will be fed
74         -- into the renamer (e.g. from deriving clauses), but where
75         -- we want to say "Use Prelude.map dammit".  
76  
77   | Exact Name
78         -- We know exactly the Name. This is used 
79         --  (a) when the parser parses built-in syntax like "[]" 
80         --      and "(,)", but wants a RdrName from it
81         --  (b) when converting names to the RdrNames in IfaceTypes
82         --      Here an Exact RdrName always contains an External Name
83         --      (Internal Names are converted to simple Unquals)
84         --  (c) by Template Haskell, when TH has generated a unique name
85 \end{code}
86
87
88 %************************************************************************
89 %*                                                                      *
90 \subsection{Simple functions}
91 %*                                                                      *
92 %************************************************************************
93
94 \begin{code}
95 rdrNameModule :: RdrName -> Module
96 rdrNameModule (Qual m _) = m
97 rdrNameModule (Orig m _) = m
98 rdrNameModule (Exact n)  = nameModule n
99 rdrNameModule (Unqual n) = pprPanic "rdrNameModule" (ppr n)
100
101 rdrNameOcc :: RdrName -> OccName
102 rdrNameOcc (Qual _ occ) = occ
103 rdrNameOcc (Unqual occ) = occ
104 rdrNameOcc (Orig _ occ) = occ
105 rdrNameOcc (Exact name) = nameOccName name
106
107 setRdrNameSpace :: RdrName -> NameSpace -> RdrName
108 -- This rather gruesome function is used mainly by the parser
109 -- When parsing         data T a = T | T1 Int
110 -- we parse the data constructors as *types* because of parser ambiguities,
111 -- so then we need to change the *type constr* to a *data constr*
112 --
113 -- The original-name case *can* occur when parsing
114 --              data [] a = [] | a : [a]
115 -- For the orig-name case we return an unqualified name.
116 setRdrNameSpace (Unqual occ) ns = Unqual (setOccNameSpace ns occ)
117 setRdrNameSpace (Qual m occ) ns = Qual m (setOccNameSpace ns occ)
118 setRdrNameSpace (Orig m occ) ns = Orig m (setOccNameSpace ns occ)
119 setRdrNameSpace (Exact n)    ns = Orig (nameModule n)
120                                        (setOccNameSpace ns (nameOccName n))
121 \end{code}
122
123 \begin{code}
124         -- These two are the basic constructors
125 mkRdrUnqual :: OccName -> RdrName
126 mkRdrUnqual occ = Unqual occ
127
128 mkRdrQual :: Module -> OccName -> RdrName
129 mkRdrQual mod occ = Qual mod occ
130
131 mkOrig :: Module -> OccName -> RdrName
132 mkOrig mod occ = Orig mod occ
133
134 ---------------
135 mkDerivedRdrName :: Name -> (OccName -> OccName) -> (RdrName)
136 mkDerivedRdrName parent mk_occ
137   = mkOrig (nameModule parent) (mk_occ (nameOccName parent))
138
139 ---------------
140         -- These two are used when parsing source files
141         -- They do encode the module and occurrence names
142 mkUnqual :: NameSpace -> FastString -> RdrName
143 mkUnqual sp n = Unqual (mkOccNameFS sp n)
144
145 mkVarUnqual :: FastString -> RdrName
146 mkVarUnqual n = Unqual (mkVarOccFS n)
147
148 mkQual :: NameSpace -> (FastString, FastString) -> RdrName
149 mkQual sp (m, n) = Qual (mkModuleFS m) (mkOccNameFS sp n)
150
151 getRdrName :: NamedThing thing => thing -> RdrName
152 getRdrName name = nameRdrName (getName name)
153
154 nameRdrName :: Name -> RdrName
155 nameRdrName name = Exact name
156 -- Keep the Name even for Internal names, so that the
157 -- unique is still there for debug printing, particularly
158 -- of Types (which are converted to IfaceTypes before printing)
159
160 nukeExact :: Name -> RdrName
161 nukeExact n 
162   | isExternalName n = Orig (nameModule n) (nameOccName n)
163   | otherwise        = Unqual (nameOccName n)
164 \end{code}
165
166 \begin{code}
167 isRdrDataCon rn = isDataOcc (rdrNameOcc rn)
168 isRdrTyVar   rn = isTvOcc   (rdrNameOcc rn)
169 isRdrTc      rn = isTcOcc   (rdrNameOcc rn)
170
171 isSrcRdrName (Unqual _) = True
172 isSrcRdrName (Qual _ _) = True
173 isSrcRdrName _          = False
174
175 isUnqual (Unqual _) = True
176 isUnqual other      = False
177
178 isQual (Qual _ _) = True
179 isQual _          = False
180
181 isOrig (Orig _ _) = True
182 isOrig _          = False
183
184 isOrig_maybe (Orig m n) = Just (m,n)
185 isOrig_maybe _          = Nothing
186
187 isExact (Exact _) = True
188 isExact other   = False
189
190 isExact_maybe (Exact n) = Just n
191 isExact_maybe other     = Nothing
192 \end{code}
193
194
195 %************************************************************************
196 %*                                                                      *
197 \subsection{Instances}
198 %*                                                                      *
199 %************************************************************************
200
201 \begin{code}
202 instance Outputable RdrName where
203     ppr (Exact name)   = ppr name
204     ppr (Unqual occ)   = ppr occ <+> ppr_name_space occ
205     ppr (Qual mod occ) = ppr mod <> dot <> ppr occ <+> ppr_name_space occ
206     ppr (Orig mod occ) = ppr mod <> dot <> ppr occ <+> ppr_name_space occ
207
208 ppr_name_space occ = ifPprDebug (parens (pprNonVarNameSpace (occNameSpace occ)))
209
210 instance OutputableBndr RdrName where
211     pprBndr _ n 
212         | isTvOcc (rdrNameOcc n) = char '@' <+> ppr n
213         | otherwise              = ppr n
214
215 instance Eq RdrName where
216     (Exact n1)    == (Exact n2)    = n1==n2
217         -- Convert exact to orig
218     (Exact n1)    == r2@(Orig _ _) = nukeExact n1 == r2
219     r1@(Orig _ _) == (Exact n2)    = r1 == nukeExact n2
220
221     (Orig m1 o1)  == (Orig m2 o2)  = m1==m2 && o1==o2
222     (Qual m1 o1)  == (Qual m2 o2)  = m1==m2 && o1==o2
223     (Unqual o1)   == (Unqual o2)   = o1==o2
224     r1 == r2 = False
225
226 instance Ord RdrName where
227     a <= b = case (a `compare` b) of { LT -> True;  EQ -> True;  GT -> False }
228     a <  b = case (a `compare` b) of { LT -> True;  EQ -> False; GT -> False }
229     a >= b = case (a `compare` b) of { LT -> False; EQ -> True;  GT -> True  }
230     a >  b = case (a `compare` b) of { LT -> False; EQ -> False; GT -> True  }
231
232         -- Exact < Unqual < Qual < Orig
233         -- [Note: Apr 2004] We used to use nukeExact to convert Exact to Orig 
234         --      before comparing so that Prelude.map == the exact Prelude.map, but 
235         --      that meant that we reported duplicates when renaming bindings 
236         --      generated by Template Haskell; e.g 
237         --      do { n1 <- newName "foo"; n2 <- newName "foo"; 
238         --           <decl involving n1,n2> }
239         --      I think we can do without this conversion
240     compare (Exact n1) (Exact n2) = n1 `compare` n2
241     compare (Exact n1) n2         = LT
242
243     compare (Unqual _)   (Exact _)    = GT
244     compare (Unqual o1)  (Unqual  o2) = o1 `compare` o2
245     compare (Unqual _)   _            = LT
246
247     compare (Qual _ _)   (Exact _)    = GT
248     compare (Qual _ _)   (Unqual _)   = GT
249     compare (Qual m1 o1) (Qual m2 o2) = (o1 `compare` o2) `thenCmp` (m1 `compare` m2) 
250     compare (Qual _ _)   (Orig _ _)   = LT
251
252     compare (Orig m1 o1) (Orig m2 o2) = (o1 `compare` o2) `thenCmp` (m1 `compare` m2) 
253     compare (Orig _ _)   _            = GT
254 \end{code}
255
256
257
258 %************************************************************************
259 %*                                                                      *
260                         LocalRdrEnv
261 %*                                                                      *
262 %************************************************************************
263
264 A LocalRdrEnv is used for local bindings (let, where, lambda, case)
265 It is keyed by OccName, because we never use it for qualified names.
266
267 \begin{code}
268 type LocalRdrEnv = OccEnv Name
269
270 emptyLocalRdrEnv = emptyOccEnv
271
272 extendLocalRdrEnv :: LocalRdrEnv -> [Name] -> LocalRdrEnv
273 extendLocalRdrEnv env names
274   = extendOccEnvList env [(nameOccName n, n) | n <- names]
275
276 lookupLocalRdrEnv :: LocalRdrEnv -> RdrName -> Maybe Name
277 lookupLocalRdrEnv env (Exact name) = Just name
278 lookupLocalRdrEnv env (Unqual occ) = lookupOccEnv env occ
279 lookupLocalRdrEnv env other        = Nothing
280
281 elemLocalRdrEnv :: RdrName -> LocalRdrEnv -> Bool
282 elemLocalRdrEnv rdr_name env 
283   | isUnqual rdr_name = rdrNameOcc rdr_name `elemOccEnv` env
284   | otherwise         = False
285 \end{code}
286
287
288 %************************************************************************
289 %*                                                                      *
290                         GlobalRdrEnv
291 %*                                                                      *
292 %************************************************************************
293
294 \begin{code}
295 type GlobalRdrEnv = OccEnv [GlobalRdrElt]
296         -- Keyed by OccName; when looking up a qualified name
297         -- we look up the OccName part, and then check the Provenance
298         -- to see if the appropriate qualification is valid.  This
299         -- saves routinely doubling the size of the env by adding both
300         -- qualified and unqualified names to the domain.
301         --
302         -- The list in the range is reqd because there may be name clashes
303         -- These only get reported on lookup, not on construction
304
305         -- INVARIANT: All the members of the list have distinct 
306         --            gre_name fields; that is, no duplicate Names
307
308 emptyGlobalRdrEnv = emptyOccEnv
309
310 globalRdrEnvElts :: GlobalRdrEnv -> [GlobalRdrElt]
311 globalRdrEnvElts env = foldOccEnv (++) [] env
312
313 data GlobalRdrElt 
314   = GRE { gre_name   :: Name,
315           gre_prov   :: Provenance      -- Why it's in scope
316     }
317
318 instance Outputable GlobalRdrElt where
319   ppr gre = ppr name <+> pp_parent (nameParent_maybe name)
320                 <+> parens (pprNameProvenance gre)
321           where
322             name = gre_name gre
323             pp_parent (Just p) = brackets (text "parent:" <+> ppr p)
324             pp_parent Nothing  = empty
325
326 pprGlobalRdrEnv :: GlobalRdrEnv -> SDoc
327 pprGlobalRdrEnv env
328   = vcat (map pp (occEnvElts env))
329   where
330     pp gres = ppr (nameOccName (gre_name (head gres))) <> colon <+> 
331               vcat [ ppr (gre_name gre) <+> pprNameProvenance gre
332                    | gre <- gres]
333 \end{code}
334
335 \begin{code}
336 lookupGlobalRdrEnv :: GlobalRdrEnv -> OccName -> [GlobalRdrElt]
337 lookupGlobalRdrEnv env rdr_name = case lookupOccEnv env rdr_name of
338                                         Nothing   -> []
339                                         Just gres -> gres
340
341 extendGlobalRdrEnv :: GlobalRdrEnv -> GlobalRdrElt -> GlobalRdrEnv
342 extendGlobalRdrEnv env gre = extendOccEnv_C add env occ [gre]
343   where
344     occ = nameOccName (gre_name gre)
345     add gres _ = gre:gres
346
347 lookupGRE_RdrName :: RdrName -> GlobalRdrEnv -> [GlobalRdrElt]
348 lookupGRE_RdrName rdr_name env
349   = case lookupOccEnv env (rdrNameOcc rdr_name) of
350         Nothing   -> []
351         Just gres -> pickGREs rdr_name gres
352
353 lookupGRE_Name :: GlobalRdrEnv -> Name -> [GlobalRdrElt]
354 lookupGRE_Name env name
355   = [ gre | gre <- lookupGlobalRdrEnv env (nameOccName name),
356             gre_name gre == name ]
357
358
359 pickGREs :: RdrName -> [GlobalRdrElt] -> [GlobalRdrElt]
360 -- Take a list of GREs which have the right OccName
361 -- Pick those GREs that are suitable for this RdrName
362 -- And for those, keep only only the Provenances that are suitable
363 -- 
364 -- Consider
365 --       module A ( f ) where
366 --       import qualified Foo( f )
367 --       import Baz( f )
368 --       f = undefined
369 -- Let's suppose that Foo.f and Baz.f are the same entity really.
370 -- The export of f is ambiguous because it's in scope from the local def
371 -- and the import.  The lookup of (Unqual f) should return a GRE for
372 -- the locally-defined f, and a GRE for the imported f, with a *single* 
373 -- provenance, namely the one for Baz(f).
374 pickGREs rdr_name gres
375   = mapCatMaybes pick gres
376   where
377     is_unqual = isUnqual rdr_name
378     mod       = rdrNameModule rdr_name
379
380     pick :: GlobalRdrElt -> Maybe GlobalRdrElt
381     pick gre@(GRE {gre_prov = LocalDef, gre_name = n})  -- Local def
382         | is_unqual || nameModule n == mod = Just gre
383         | otherwise                        = Nothing
384     pick gre@(GRE {gre_prov = Imported [is]})   -- Single import (efficiency)
385         | is_unqual     = if not (is_qual (is_decl is)) then Just gre
386                                                         else Nothing
387         | otherwise     = if mod == is_as (is_decl is)  then Just gre
388                                                         else Nothing
389     pick gre@(GRE {gre_prov = Imported is})     -- Multiple import
390         | null filtered_is = Nothing
391         | otherwise        = Just (gre {gre_prov = Imported filtered_is})
392         where
393           filtered_is | is_unqual = filter (not . is_qual    . is_decl) is
394                       | otherwise = filter ((== mod) . is_as . is_decl) is
395
396 isLocalGRE :: GlobalRdrElt -> Bool
397 isLocalGRE (GRE {gre_prov = LocalDef}) = True
398 isLocalGRE other                       = False
399
400 unQualOK :: GlobalRdrElt -> Bool
401 -- An unqualifed version of this thing is in scope
402 unQualOK (GRE {gre_prov = LocalDef})    = True
403 unQualOK (GRE {gre_prov = Imported is}) = not (all (is_qual . is_decl) is)
404
405 plusGlobalRdrEnv :: GlobalRdrEnv -> GlobalRdrEnv -> GlobalRdrEnv
406 plusGlobalRdrEnv env1 env2 = plusOccEnv_C (foldr insertGRE) env1 env2
407
408 mkGlobalRdrEnv :: [GlobalRdrElt] -> GlobalRdrEnv
409 mkGlobalRdrEnv gres
410   = foldr add emptyGlobalRdrEnv gres
411   where
412     add gre env = extendOccEnv_C (foldr insertGRE) env 
413                                  (nameOccName (gre_name gre)) 
414                                  [gre]
415
416 insertGRE :: GlobalRdrElt -> [GlobalRdrElt] -> [GlobalRdrElt]
417 insertGRE new_g [] = [new_g]
418 insertGRE new_g (old_g : old_gs)
419         | gre_name new_g == gre_name old_g
420         = new_g `plusGRE` old_g : old_gs
421         | otherwise
422         = old_g : insertGRE new_g old_gs
423
424 plusGRE :: GlobalRdrElt -> GlobalRdrElt -> GlobalRdrElt
425 -- Used when the gre_name fields match
426 plusGRE g1 g2
427   = GRE { gre_name = gre_name g1,
428           gre_prov = gre_prov g1 `plusProv` gre_prov g2 }
429 \end{code}
430
431
432 %************************************************************************
433 %*                                                                      *
434                         Provenance
435 %*                                                                      *
436 %************************************************************************
437
438 The "provenance" of something says how it came to be in scope.
439 It's quite elaborate so that we can give accurate unused-name warnings.
440
441 \begin{code}
442 data Provenance
443   = LocalDef            -- Defined locally
444   | Imported            -- Imported
445         [ImportSpec]    -- INVARIANT: non-empty
446
447 data ImportSpec = ImpSpec { is_decl :: ImpDeclSpec,
448                             is_item ::  ImpItemSpec }
449                 deriving( Eq, Ord )
450
451 data ImpDeclSpec        -- Describes a particular import declaration
452                         -- Shared among all the Provenaces for that decl
453   = ImpDeclSpec {
454         is_mod      :: Module,  -- 'import Muggle'
455                                 -- Note the Muggle may well not be 
456                                 -- the defining module for this thing!
457         is_as       :: Module,  -- 'as M' (or 'Muggle' if there is no 'as' clause)
458         is_qual     :: Bool,    -- True <=> qualified (only)
459         is_dloc     :: SrcSpan  -- Location of import declaration
460     }
461
462 data ImpItemSpec  -- Describes import info a particular Name
463   = ImpAll              -- The import had no import list, 
464                         -- or  had a hiding list
465
466   | ImpSome {           -- The import had an import list
467         is_explicit :: Bool,
468         is_iloc     :: SrcSpan  -- Location of the import item
469     }
470         -- The is_explicit field is True iff the thing was named 
471         -- *explicitly* in the import specs rather 
472         -- than being imported as part of a "..." group 
473         -- e.g.         import C( T(..) )
474         -- Here the constructors of T are not named explicitly; 
475         -- only T is named explicitly.
476
477 importSpecLoc :: ImportSpec -> SrcSpan
478 importSpecLoc (ImpSpec decl ImpAll) = is_dloc decl
479 importSpecLoc (ImpSpec _    item)   = is_iloc item
480
481 importSpecModule :: ImportSpec -> Module
482 importSpecModule is = is_mod (is_decl is)
483
484 -- Note [Comparing provenance]
485 -- Comparison of provenance is just used for grouping 
486 -- error messages (in RnEnv.warnUnusedBinds)
487 instance Eq Provenance where
488   p1 == p2 = case p1 `compare` p2 of EQ -> True; _ -> False
489
490 instance Eq ImpDeclSpec where
491   p1 == p2 = case p1 `compare` p2 of EQ -> True; _ -> False
492
493 instance Eq ImpItemSpec where
494   p1 == p2 = case p1 `compare` p2 of EQ -> True; _ -> False
495
496 instance Ord Provenance where
497    compare LocalDef      LocalDef        = EQ
498    compare LocalDef      (Imported _)    = LT
499    compare (Imported _ ) LocalDef        = GT
500    compare (Imported is1) (Imported is2) = compare (head is1) 
501         {- See Note [Comparing provenance] -}      (head is2)
502
503 instance Ord ImpDeclSpec where
504    compare is1 is2 = (is_mod is1 `compare` is_mod is2) `thenCmp` 
505                      (is_dloc is1 `compare` is_dloc is2)
506
507 instance Ord ImpItemSpec where
508    compare is1 is2 = is_iloc is1 `compare` is_iloc is2
509 \end{code}
510
511 \begin{code}
512 plusProv :: Provenance -> Provenance -> Provenance
513 -- Choose LocalDef over Imported
514 -- There is an obscure bug lurking here; in the presence
515 -- of recursive modules, something can be imported *and* locally
516 -- defined, and one might refer to it with a qualified name from
517 -- the import -- but I'm going to ignore that because it makes
518 -- the isLocalGRE predicate so much nicer this way
519 plusProv LocalDef        LocalDef        = panic "plusProv"
520 plusProv LocalDef        p2              = LocalDef
521 plusProv p1              LocalDef        = LocalDef
522 plusProv (Imported is1)  (Imported is2)  = Imported (is1++is2)
523
524 pprNameProvenance :: GlobalRdrElt -> SDoc
525 -- Print out the place where the name was imported
526 pprNameProvenance (GRE {gre_name = name, gre_prov = LocalDef})
527   = ptext SLIT("defined at") <+> ppr (nameSrcLoc name)
528 pprNameProvenance (GRE {gre_name = name, gre_prov = Imported (why:whys)})
529   = sep [ppr why, nest 2 (ppr_defn (nameSrcLoc name))]
530
531 -- If we know the exact definition point (which we may do with GHCi)
532 -- then show that too.  But not if it's just "imported from X".
533 ppr_defn loc | isGoodSrcLoc loc = parens (ptext SLIT("defined at") <+> ppr loc)
534              | otherwise        = empty
535
536 instance Outputable ImportSpec where
537    ppr imp_spec@(ImpSpec imp_decl _)
538      = ptext SLIT("imported from") <+> ppr (is_mod imp_decl) 
539         <+> ptext SLIT("at") <+> ppr (importSpecLoc imp_spec)
540 \end{code}