Comments only
[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
205     ppr (Qual mod occ) = ppr mod <> dot <> ppr occ
206     ppr (Orig mod occ) = ppr mod <> dot <> ppr occ
207
208 instance OutputableBndr RdrName where
209     pprBndr _ n 
210         | isTvOcc (rdrNameOcc n) = char '@' <+> ppr n
211         | otherwise              = ppr n
212
213 instance Eq RdrName where
214     (Exact n1)    == (Exact n2)    = n1==n2
215         -- Convert exact to orig
216     (Exact n1)    == r2@(Orig _ _) = nukeExact n1 == r2
217     r1@(Orig _ _) == (Exact n2)    = r1 == nukeExact n2
218
219     (Orig m1 o1)  == (Orig m2 o2)  = m1==m2 && o1==o2
220     (Qual m1 o1)  == (Qual m2 o2)  = m1==m2 && o1==o2
221     (Unqual o1)   == (Unqual o2)   = o1==o2
222     r1 == r2 = False
223
224 instance Ord RdrName where
225     a <= b = case (a `compare` b) of { LT -> True;  EQ -> True;  GT -> False }
226     a <  b = case (a `compare` b) of { LT -> True;  EQ -> False; GT -> False }
227     a >= b = case (a `compare` b) of { LT -> False; EQ -> True;  GT -> True  }
228     a >  b = case (a `compare` b) of { LT -> False; EQ -> False; GT -> True  }
229
230         -- Exact < Unqual < Qual < Orig
231         -- [Note: Apr 2004] We used to use nukeExact to convert Exact to Orig 
232         --      before comparing so that Prelude.map == the exact Prelude.map, but 
233         --      that meant that we reported duplicates when renaming bindings 
234         --      generated by Template Haskell; e.g 
235         --      do { n1 <- newName "foo"; n2 <- newName "foo"; 
236         --           <decl involving n1,n2> }
237         --      I think we can do without this conversion
238     compare (Exact n1) (Exact n2) = n1 `compare` n2
239     compare (Exact n1) n2         = LT
240
241     compare (Unqual _)   (Exact _)    = GT
242     compare (Unqual o1)  (Unqual  o2) = o1 `compare` o2
243     compare (Unqual _)   _            = LT
244
245     compare (Qual _ _)   (Exact _)    = GT
246     compare (Qual _ _)   (Unqual _)   = GT
247     compare (Qual m1 o1) (Qual m2 o2) = (o1 `compare` o2) `thenCmp` (m1 `compare` m2) 
248     compare (Qual _ _)   (Orig _ _)   = LT
249
250     compare (Orig m1 o1) (Orig m2 o2) = (o1 `compare` o2) `thenCmp` (m1 `compare` m2) 
251     compare (Orig _ _)   _            = GT
252 \end{code}
253
254
255
256 %************************************************************************
257 %*                                                                      *
258                         LocalRdrEnv
259 %*                                                                      *
260 %************************************************************************
261
262 A LocalRdrEnv is used for local bindings (let, where, lambda, case)
263 It is keyed by OccName, because we never use it for qualified names.
264
265 \begin{code}
266 type LocalRdrEnv = OccEnv Name
267
268 emptyLocalRdrEnv = emptyOccEnv
269
270 extendLocalRdrEnv :: LocalRdrEnv -> [Name] -> LocalRdrEnv
271 extendLocalRdrEnv env names
272   = extendOccEnvList env [(nameOccName n, n) | n <- names]
273
274 lookupLocalRdrEnv :: LocalRdrEnv -> RdrName -> Maybe Name
275 lookupLocalRdrEnv env (Exact name) = Just name
276 lookupLocalRdrEnv env (Unqual occ) = lookupOccEnv env occ
277 lookupLocalRdrEnv env other        = Nothing
278
279 elemLocalRdrEnv :: RdrName -> LocalRdrEnv -> Bool
280 elemLocalRdrEnv rdr_name env 
281   | isUnqual rdr_name = rdrNameOcc rdr_name `elemOccEnv` env
282   | otherwise         = False
283 \end{code}
284
285
286 %************************************************************************
287 %*                                                                      *
288                         GlobalRdrEnv
289 %*                                                                      *
290 %************************************************************************
291
292 \begin{code}
293 type GlobalRdrEnv = OccEnv [GlobalRdrElt]
294         -- Keyed by OccName; when looking up a qualified name
295         -- we look up the OccName part, and then check the Provenance
296         -- to see if the appropriate qualification is valid.  This
297         -- saves routinely doubling the size of the env by adding both
298         -- qualified and unqualified names to the domain.
299         --
300         -- The list in the range is reqd because there may be name clashes
301         -- These only get reported on lookup, not on construction
302
303         -- INVARIANT: All the members of the list have distinct 
304         --            gre_name fields; that is, no duplicate Names
305
306 emptyGlobalRdrEnv = emptyOccEnv
307
308 globalRdrEnvElts :: GlobalRdrEnv -> [GlobalRdrElt]
309 globalRdrEnvElts env = foldOccEnv (++) [] env
310
311 data GlobalRdrElt 
312   = GRE { gre_name   :: Name,
313           gre_prov   :: Provenance      -- Why it's in scope
314     }
315
316 instance Outputable GlobalRdrElt where
317   ppr gre = ppr name <+> pp_parent (nameParent_maybe name)
318                 <+> parens (pprNameProvenance gre)
319           where
320             name = gre_name gre
321             pp_parent (Just p) = brackets (text "parent:" <+> ppr p)
322             pp_parent Nothing  = empty
323
324 pprGlobalRdrEnv :: GlobalRdrEnv -> SDoc
325 pprGlobalRdrEnv env
326   = vcat (map pp (occEnvElts env))
327   where
328     pp gres = ppr (nameOccName (gre_name (head gres))) <> colon <+> 
329               vcat [ ppr (gre_name gre) <+> pprNameProvenance gre
330                    | gre <- gres]
331 \end{code}
332
333 \begin{code}
334 lookupGlobalRdrEnv :: GlobalRdrEnv -> OccName -> [GlobalRdrElt]
335 lookupGlobalRdrEnv env rdr_name = case lookupOccEnv env rdr_name of
336                                         Nothing   -> []
337                                         Just gres -> gres
338
339 extendGlobalRdrEnv :: GlobalRdrEnv -> GlobalRdrElt -> GlobalRdrEnv
340 extendGlobalRdrEnv env gre = extendOccEnv_C add env occ [gre]
341   where
342     occ = nameOccName (gre_name gre)
343     add gres _ = gre:gres
344
345 lookupGRE_RdrName :: RdrName -> GlobalRdrEnv -> [GlobalRdrElt]
346 lookupGRE_RdrName rdr_name env
347   = case lookupOccEnv env (rdrNameOcc rdr_name) of
348         Nothing   -> []
349         Just gres -> pickGREs rdr_name gres
350
351 lookupGRE_Name :: GlobalRdrEnv -> Name -> [GlobalRdrElt]
352 lookupGRE_Name env name
353   = [ gre | gre <- lookupGlobalRdrEnv env (nameOccName name),
354             gre_name gre == name ]
355
356
357 pickGREs :: RdrName -> [GlobalRdrElt] -> [GlobalRdrElt]
358 -- Take a list of GREs which have the right OccName
359 -- Pick those GREs that are suitable for this RdrName
360 -- And for those, keep only only the Provenances that are suitable
361 -- 
362 -- Consider
363 --       module A ( f ) where
364 --       import qualified Foo( f )
365 --       import Baz( f )
366 --       f = undefined
367 -- Let's suppose that Foo.f and Baz.f are the same entity really.
368 -- The export of f is ambiguous because it's in scope from the local def
369 -- and the import.  The lookup of (Unqual f) should return a GRE for
370 -- the locally-defined f, and a GRE for the imported f, with a *single* 
371 -- provenance, namely the one for Baz(f).
372 pickGREs rdr_name gres
373   = mapCatMaybes pick gres
374   where
375     is_unqual = isUnqual rdr_name
376     mod       = rdrNameModule rdr_name
377
378     pick :: GlobalRdrElt -> Maybe GlobalRdrElt
379     pick gre@(GRE {gre_prov = LocalDef, gre_name = n})  -- Local def
380         | is_unqual || nameModule n == mod = Just gre
381         | otherwise                        = Nothing
382     pick gre@(GRE {gre_prov = Imported [is]})   -- Single import (efficiency)
383         | is_unqual     = if not (is_qual (is_decl is)) then Just gre
384                                                         else Nothing
385         | otherwise     = if mod == is_as (is_decl is)  then Just gre
386                                                         else Nothing
387     pick gre@(GRE {gre_prov = Imported is})     -- Multiple import
388         | null filtered_is = Nothing
389         | otherwise        = Just (gre {gre_prov = Imported filtered_is})
390         where
391           filtered_is | is_unqual = filter (not . is_qual    . is_decl) is
392                       | otherwise = filter ((== mod) . is_as . is_decl) is
393
394 isLocalGRE :: GlobalRdrElt -> Bool
395 isLocalGRE (GRE {gre_prov = LocalDef}) = True
396 isLocalGRE other                       = False
397
398 unQualOK :: GlobalRdrElt -> Bool
399 -- An unqualifed version of this thing is in scope
400 unQualOK (GRE {gre_prov = LocalDef})    = True
401 unQualOK (GRE {gre_prov = Imported is}) = not (all (is_qual . is_decl) is)
402
403 plusGlobalRdrEnv :: GlobalRdrEnv -> GlobalRdrEnv -> GlobalRdrEnv
404 plusGlobalRdrEnv env1 env2 = plusOccEnv_C (foldr insertGRE) env1 env2
405
406 mkGlobalRdrEnv :: [GlobalRdrElt] -> GlobalRdrEnv
407 mkGlobalRdrEnv gres
408   = foldr add emptyGlobalRdrEnv gres
409   where
410     add gre env = extendOccEnv_C (foldr insertGRE) env 
411                                  (nameOccName (gre_name gre)) 
412                                  [gre]
413
414 insertGRE :: GlobalRdrElt -> [GlobalRdrElt] -> [GlobalRdrElt]
415 insertGRE new_g [] = [new_g]
416 insertGRE new_g (old_g : old_gs)
417         | gre_name new_g == gre_name old_g
418         = new_g `plusGRE` old_g : old_gs
419         | otherwise
420         = old_g : insertGRE new_g old_gs
421
422 plusGRE :: GlobalRdrElt -> GlobalRdrElt -> GlobalRdrElt
423 -- Used when the gre_name fields match
424 plusGRE g1 g2
425   = GRE { gre_name = gre_name g1,
426           gre_prov = gre_prov g1 `plusProv` gre_prov g2 }
427 \end{code}
428
429
430 %************************************************************************
431 %*                                                                      *
432                         Provenance
433 %*                                                                      *
434 %************************************************************************
435
436 The "provenance" of something says how it came to be in scope.
437 It's quite elaborate so that we can give accurate unused-name warnings.
438
439 \begin{code}
440 data Provenance
441   = LocalDef            -- Defined locally
442   | Imported            -- Imported
443         [ImportSpec]    -- INVARIANT: non-empty
444
445 data ImportSpec = ImpSpec { is_decl :: ImpDeclSpec,
446                             is_item ::  ImpItemSpec }
447                 deriving( Eq, Ord )
448
449 data ImpDeclSpec        -- Describes a particular import declaration
450                         -- Shared among all the Provenaces for that decl
451   = ImpDeclSpec {
452         is_mod      :: Module,  -- 'import Muggle'
453                                 -- Note the Muggle may well not be 
454                                 -- the defining module for this thing!
455         is_as       :: Module,  -- 'as M' (or 'Muggle' if there is no 'as' clause)
456         is_qual     :: Bool,    -- True <=> qualified (only)
457         is_dloc     :: SrcSpan  -- Location of import declaration
458     }
459
460 data ImpItemSpec  -- Describes import info a particular Name
461   = ImpAll              -- The import had no import list, 
462                         -- or  had a hiding list
463
464   | ImpSome {           -- The import had an import list
465         is_explicit :: Bool,
466         is_iloc     :: SrcSpan  -- Location of the import item
467     }
468         -- The is_explicit field is True iff the thing was named 
469         -- *explicitly* in the import specs rather 
470         -- than being imported as part of a "..." group 
471         -- e.g.         import C( T(..) )
472         -- Here the constructors of T are not named explicitly; 
473         -- only T is named explicitly.
474
475 importSpecLoc :: ImportSpec -> SrcSpan
476 importSpecLoc (ImpSpec decl ImpAll) = is_dloc decl
477 importSpecLoc (ImpSpec _    item)   = is_iloc item
478
479 importSpecModule :: ImportSpec -> Module
480 importSpecModule is = is_mod (is_decl is)
481
482 -- Note [Comparing provenance]
483 -- Comparison of provenance is just used for grouping 
484 -- error messages (in RnEnv.warnUnusedBinds)
485 instance Eq Provenance where
486   p1 == p2 = case p1 `compare` p2 of EQ -> True; _ -> False
487
488 instance Eq ImpDeclSpec where
489   p1 == p2 = case p1 `compare` p2 of EQ -> True; _ -> False
490
491 instance Eq ImpItemSpec where
492   p1 == p2 = case p1 `compare` p2 of EQ -> True; _ -> False
493
494 instance Ord Provenance where
495    compare LocalDef      LocalDef        = EQ
496    compare LocalDef      (Imported _)    = LT
497    compare (Imported _ ) LocalDef        = GT
498    compare (Imported is1) (Imported is2) = compare (head is1) 
499         {- See Note [Comparing provenance] -}      (head is2)
500
501 instance Ord ImpDeclSpec where
502    compare is1 is2 = (is_mod is1 `compare` is_mod is2) `thenCmp` 
503                      (is_dloc is1 `compare` is_dloc is2)
504
505 instance Ord ImpItemSpec where
506    compare is1 is2 = is_iloc is1 `compare` is_iloc is2
507 \end{code}
508
509 \begin{code}
510 plusProv :: Provenance -> Provenance -> Provenance
511 -- Choose LocalDef over Imported
512 -- There is an obscure bug lurking here; in the presence
513 -- of recursive modules, something can be imported *and* locally
514 -- defined, and one might refer to it with a qualified name from
515 -- the import -- but I'm going to ignore that because it makes
516 -- the isLocalGRE predicate so much nicer this way
517 plusProv LocalDef        LocalDef        = panic "plusProv"
518 plusProv LocalDef        p2              = LocalDef
519 plusProv p1              LocalDef        = LocalDef
520 plusProv (Imported is1)  (Imported is2)  = Imported (is1++is2)
521
522 pprNameProvenance :: GlobalRdrElt -> SDoc
523 -- Print out the place where the name was imported
524 pprNameProvenance (GRE {gre_name = name, gre_prov = LocalDef})
525   = ptext SLIT("defined at") <+> ppr (nameSrcLoc name)
526 pprNameProvenance (GRE {gre_name = name, gre_prov = Imported (why:whys)})
527   = sep [ppr why, nest 2 (ppr_defn (nameSrcLoc name))]
528
529 -- If we know the exact definition point (which we may do with GHCi)
530 -- then show that too.  But not if it's just "imported from X".
531 ppr_defn loc | isGoodSrcLoc loc = parens (ptext SLIT("defined at") <+> ppr loc)
532              | otherwise        = empty
533
534 instance Outputable ImportSpec where
535    ppr imp_spec@(ImpSpec imp_decl _)
536      = ptext SLIT("imported from") <+> ppr (is_mod imp_decl) 
537         <+> ptext SLIT("at") <+> ppr (importSpecLoc imp_spec)
538 \end{code}