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