Refactor (again) the handling of default methods
[ghc-hetmet.git] / compiler / basicTypes / RdrName.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 %
5
6 \begin{code}
7 {-# LANGUAGE DeriveDataTypeable #-}
8
9 -- |
10 -- #name_types#
11 -- GHC uses several kinds of name internally:
12 --
13 -- * 'OccName.OccName': see "OccName#name_types"
14 --
15 -- * 'RdrName.RdrName' is the type of names that come directly from the parser. They
16 --   have not yet had their scoping and binding resolved by the renamer and can be
17 --   thought of to a first approximation as an 'OccName.OccName' with an optional module
18 --   qualifier
19 --
20 -- * 'Name.Name': see "Name#name_types"
21 --
22 -- * 'Id.Id': see "Id#name_types"
23 --
24 -- * 'Var.Var': see "Var#name_types"
25 module RdrName (
26         -- * The main type
27         RdrName(..),    -- Constructors exported only to BinIface
28
29         -- ** Construction
30         mkRdrUnqual, mkRdrQual, 
31         mkUnqual, mkVarUnqual, mkQual, mkOrig,
32         nameRdrName, getRdrName, 
33
34         -- ** Destruction
35         rdrNameOcc, rdrNameSpace, setRdrNameSpace,
36         isRdrDataCon, isRdrTyVar, isRdrTc, isQual, isQual_maybe, isUnqual, 
37         isOrig, isOrig_maybe, isExact, isExact_maybe, isSrcRdrName,
38
39         -- ** Printing
40         showRdrName,
41
42         -- * Local mapping of 'RdrName' to 'Name.Name'
43         LocalRdrEnv, emptyLocalRdrEnv, extendLocalRdrEnv, extendLocalRdrEnvList,
44         lookupLocalRdrEnv, lookupLocalRdrOcc, elemLocalRdrEnv,
45
46         -- * Global mapping of 'RdrName' to 'GlobalRdrElt's
47         GlobalRdrEnv, emptyGlobalRdrEnv, mkGlobalRdrEnv, plusGlobalRdrEnv, 
48         lookupGlobalRdrEnv, extendGlobalRdrEnv,
49         pprGlobalRdrEnv, globalRdrEnvElts,
50         lookupGRE_RdrName, lookupGRE_Name, getGRE_NameQualifier_maybes,
51         hideSomeUnquals, findLocalDupsRdrEnv, pickGREs,
52
53         -- ** Global 'RdrName' mapping elements: 'GlobalRdrElt', 'Provenance', 'ImportSpec'
54         GlobalRdrElt(..), isLocalGRE, unQualOK, qualSpecOK, unQualSpecOK,
55         Provenance(..), pprNameProvenance,
56         Parent(..), 
57         ImportSpec(..), ImpDeclSpec(..), ImpItemSpec(..), 
58         importSpecLoc, importSpecModule, isExplicitItem
59   ) where 
60
61 #include "HsVersions.h"
62
63 import Module
64 import Name
65 import Maybes
66 import SrcLoc
67 import FastString
68 import Outputable
69 import Util
70
71 import Data.Data
72 \end{code}
73
74 %************************************************************************
75 %*                                                                      *
76 \subsection{The main data type}
77 %*                                                                      *
78 %************************************************************************
79
80 \begin{code}
81 -- | Do not use the data constructors of RdrName directly: prefer the family
82 -- of functions that creates them, such as 'mkRdrUnqual'
83 data RdrName
84   = Unqual OccName
85         -- ^ Used for ordinary, unqualified occurrences, e.g. @x@, @y@ or @Foo@.
86         -- Create such a 'RdrName' with 'mkRdrUnqual'
87
88   | Qual ModuleName OccName
89         -- ^ A qualified name written by the user in 
90         -- /source/ code.  The module isn't necessarily 
91         -- the module where the thing is defined; 
92         -- just the one from which it is imported.
93         -- Examples are @Bar.x@, @Bar.y@ or @Bar.Foo@.
94         -- Create such a 'RdrName' with 'mkRdrQual'
95
96   | Orig Module OccName
97         -- ^ An original name; the module is the /defining/ module.
98         -- This is used when GHC generates code that will be fed
99         -- into the renamer (e.g. from deriving clauses), but where
100         -- we want to say \"Use Prelude.map dammit\". One of these
101         -- can be created with 'mkOrig'
102  
103   | Exact Name
104         -- ^ We know exactly the 'Name'. This is used:
105         --
106         --  (1) When the parser parses built-in syntax like @[]@
107         --      and @(,)@, but wants a 'RdrName' from it
108         --
109         --  (2) By Template Haskell, when TH has generated a unique name
110         --
111         -- Such a 'RdrName' can be created by using 'getRdrName' on a 'Name'
112   deriving (Data, Typeable)
113 \end{code}
114
115
116 %************************************************************************
117 %*                                                                      *
118 \subsection{Simple functions}
119 %*                                                                      *
120 %************************************************************************
121
122 \begin{code}
123 rdrNameOcc :: RdrName -> OccName
124 rdrNameOcc (Qual _ occ) = occ
125 rdrNameOcc (Unqual occ) = occ
126 rdrNameOcc (Orig _ occ) = occ
127 rdrNameOcc (Exact name) = nameOccName name
128
129 rdrNameSpace :: RdrName -> NameSpace
130 rdrNameSpace = occNameSpace . rdrNameOcc
131
132 setRdrNameSpace :: RdrName -> NameSpace -> RdrName
133 -- ^ This rather gruesome function is used mainly by the parser.
134 -- When parsing:
135 --
136 -- > data T a = T | T1 Int
137 --
138 -- we parse the data constructors as /types/ because of parser ambiguities,
139 -- so then we need to change the /type constr/ to a /data constr/
140 --
141 -- The exact-name case /can/ occur when parsing:
142 --
143 -- > data [] a = [] | a : [a]
144 --
145 -- For the exact-name case we return an original name.
146 setRdrNameSpace (Unqual occ) ns = Unqual (setOccNameSpace ns occ)
147 setRdrNameSpace (Qual m occ) ns = Qual m (setOccNameSpace ns occ)
148 setRdrNameSpace (Orig m occ) ns = Orig m (setOccNameSpace ns occ)
149 setRdrNameSpace (Exact n)    ns = ASSERT( isExternalName n ) 
150                                   Orig (nameModule n)
151                                        (setOccNameSpace ns (nameOccName n))
152 \end{code}
153
154 \begin{code}
155         -- These two are the basic constructors
156 mkRdrUnqual :: OccName -> RdrName
157 mkRdrUnqual occ = Unqual occ
158
159 mkRdrQual :: ModuleName -> OccName -> RdrName
160 mkRdrQual mod occ = Qual mod occ
161
162 mkOrig :: Module -> OccName -> RdrName
163 mkOrig mod occ = Orig mod occ
164
165 ---------------
166         -- These two are used when parsing source files
167         -- They do encode the module and occurrence names
168 mkUnqual :: NameSpace -> FastString -> RdrName
169 mkUnqual sp n = Unqual (mkOccNameFS sp n)
170
171 mkVarUnqual :: FastString -> RdrName
172 mkVarUnqual n = Unqual (mkVarOccFS n)
173
174 -- | Make a qualified 'RdrName' in the given namespace and where the 'ModuleName' and
175 -- the 'OccName' are taken from the first and second elements of the tuple respectively
176 mkQual :: NameSpace -> (FastString, FastString) -> RdrName
177 mkQual sp (m, n) = Qual (mkModuleNameFS m) (mkOccNameFS sp n)
178
179 getRdrName :: NamedThing thing => thing -> RdrName
180 getRdrName name = nameRdrName (getName name)
181
182 nameRdrName :: Name -> RdrName
183 nameRdrName name = Exact name
184 -- Keep the Name even for Internal names, so that the
185 -- unique is still there for debug printing, particularly
186 -- of Types (which are converted to IfaceTypes before printing)
187
188 nukeExact :: Name -> RdrName
189 nukeExact n 
190   | isExternalName n = Orig (nameModule n) (nameOccName n)
191   | otherwise        = Unqual (nameOccName n)
192 \end{code}
193
194 \begin{code}
195 isRdrDataCon :: RdrName -> Bool
196 isRdrTyVar   :: RdrName -> Bool
197 isRdrTc      :: RdrName -> Bool
198
199 isRdrDataCon rn = isDataOcc (rdrNameOcc rn)
200 isRdrTyVar   rn = isTvOcc   (rdrNameOcc rn)
201 isRdrTc      rn = isTcOcc   (rdrNameOcc rn)
202
203 isSrcRdrName :: RdrName -> Bool
204 isSrcRdrName (Unqual _) = True
205 isSrcRdrName (Qual _ _) = True
206 isSrcRdrName _          = False
207
208 isUnqual :: RdrName -> Bool
209 isUnqual (Unqual _) = True
210 isUnqual _          = False
211
212 isQual :: RdrName -> Bool
213 isQual (Qual _ _) = True
214 isQual _          = False
215
216 isQual_maybe :: RdrName -> Maybe (ModuleName, OccName)
217 isQual_maybe (Qual m n) = Just (m,n)
218 isQual_maybe _          = Nothing
219
220 isOrig :: RdrName -> Bool
221 isOrig (Orig _ _) = True
222 isOrig _          = False
223
224 isOrig_maybe :: RdrName -> Maybe (Module, OccName)
225 isOrig_maybe (Orig m n) = Just (m,n)
226 isOrig_maybe _          = Nothing
227
228 isExact :: RdrName -> Bool
229 isExact (Exact _) = True
230 isExact _         = False
231
232 isExact_maybe :: RdrName -> Maybe Name
233 isExact_maybe (Exact n) = Just n
234 isExact_maybe _         = Nothing
235 \end{code}
236
237
238 %************************************************************************
239 %*                                                                      *
240 \subsection{Instances}
241 %*                                                                      *
242 %************************************************************************
243
244 \begin{code}
245 instance Outputable RdrName where
246     ppr (Exact name)   = ppr name
247     ppr (Unqual occ)   = ppr occ
248     ppr (Qual mod occ) = ppr mod <> dot <> ppr occ
249     ppr (Orig mod occ) = getPprStyle (\sty -> pprModulePrefix sty mod occ <> ppr occ)
250
251 instance OutputableBndr RdrName where
252     pprBndr _ n 
253         | isTvOcc (rdrNameOcc n) = char '@' <+> ppr n
254         | otherwise              = ppr n
255
256 showRdrName :: RdrName -> String
257 showRdrName r = showSDoc (ppr r)
258
259 instance Eq RdrName where
260     (Exact n1)    == (Exact n2)    = n1==n2
261         -- Convert exact to orig
262     (Exact n1)    == r2@(Orig _ _) = nukeExact n1 == r2
263     r1@(Orig _ _) == (Exact n2)    = r1 == nukeExact n2
264
265     (Orig m1 o1)  == (Orig m2 o2)  = m1==m2 && o1==o2
266     (Qual m1 o1)  == (Qual m2 o2)  = m1==m2 && o1==o2
267     (Unqual o1)   == (Unqual o2)   = o1==o2
268     _             == _             = False
269
270 instance Ord RdrName where
271     a <= b = case (a `compare` b) of { LT -> True;  EQ -> True;  GT -> False }
272     a <  b = case (a `compare` b) of { LT -> True;  EQ -> False; GT -> False }
273     a >= b = case (a `compare` b) of { LT -> False; EQ -> True;  GT -> True  }
274     a >  b = case (a `compare` b) of { LT -> False; EQ -> False; GT -> True  }
275
276         -- Exact < Unqual < Qual < Orig
277         -- [Note: Apr 2004] We used to use nukeExact to convert Exact to Orig 
278         --      before comparing so that Prelude.map == the exact Prelude.map, but 
279         --      that meant that we reported duplicates when renaming bindings 
280         --      generated by Template Haskell; e.g 
281         --      do { n1 <- newName "foo"; n2 <- newName "foo"; 
282         --           <decl involving n1,n2> }
283         --      I think we can do without this conversion
284     compare (Exact n1) (Exact n2) = n1 `compare` n2
285     compare (Exact _)  _          = LT
286
287     compare (Unqual _)   (Exact _)    = GT
288     compare (Unqual o1)  (Unqual  o2) = o1 `compare` o2
289     compare (Unqual _)   _            = LT
290
291     compare (Qual _ _)   (Exact _)    = GT
292     compare (Qual _ _)   (Unqual _)   = GT
293     compare (Qual m1 o1) (Qual m2 o2) = (o1 `compare` o2) `thenCmp` (m1 `compare` m2) 
294     compare (Qual _ _)   (Orig _ _)   = LT
295
296     compare (Orig m1 o1) (Orig m2 o2) = (o1 `compare` o2) `thenCmp` (m1 `compare` m2) 
297     compare (Orig _ _)   _            = GT
298 \end{code}
299
300 %************************************************************************
301 %*                                                                      *
302                         LocalRdrEnv
303 %*                                                                      *
304 %************************************************************************
305
306 \begin{code}
307 -- | This environment is used to store local bindings (@let@, @where@, lambda, @case@).
308 -- It is keyed by OccName, because we never use it for qualified names
309 type LocalRdrEnv = OccEnv Name
310
311 emptyLocalRdrEnv :: LocalRdrEnv
312 emptyLocalRdrEnv = emptyOccEnv
313
314 extendLocalRdrEnv :: LocalRdrEnv -> Name -> LocalRdrEnv
315 extendLocalRdrEnv env name
316   = extendOccEnv env (nameOccName name) name
317
318 extendLocalRdrEnvList :: LocalRdrEnv -> [Name] -> LocalRdrEnv
319 extendLocalRdrEnvList env names
320   = extendOccEnvList env [(nameOccName n, n) | n <- names]
321
322 lookupLocalRdrEnv :: LocalRdrEnv -> RdrName -> Maybe Name
323 lookupLocalRdrEnv _   (Exact name) = Just name
324 lookupLocalRdrEnv env (Unqual occ) = lookupOccEnv env occ
325 lookupLocalRdrEnv _   _            = Nothing
326
327 lookupLocalRdrOcc :: LocalRdrEnv -> OccName -> Maybe Name
328 lookupLocalRdrOcc env occ = lookupOccEnv env occ
329
330 elemLocalRdrEnv :: RdrName -> LocalRdrEnv -> Bool
331 elemLocalRdrEnv rdr_name env 
332   | isUnqual rdr_name = rdrNameOcc rdr_name `elemOccEnv` env
333   | otherwise         = False
334 \end{code}
335
336 %************************************************************************
337 %*                                                                      *
338                         GlobalRdrEnv
339 %*                                                                      *
340 %************************************************************************
341
342 \begin{code}
343 type GlobalRdrEnv = OccEnv [GlobalRdrElt]
344 -- ^ Keyed by 'OccName'; when looking up a qualified name
345 -- we look up the 'OccName' part, and then check the 'Provenance'
346 -- to see if the appropriate qualification is valid.  This
347 -- saves routinely doubling the size of the env by adding both
348 -- qualified and unqualified names to the domain.
349 --
350 -- The list in the codomain is required because there may be name clashes
351 -- These only get reported on lookup, not on construction
352 --
353 -- INVARIANT: All the members of the list have distinct 
354 --            'gre_name' fields; that is, no duplicate Names
355 --
356 -- INVARIANT: Imported provenance => Name is an ExternalName
357 --            However LocalDefs can have an InternalName.  This
358 --            happens only when type-checking a [d| ... |] Template
359 --            Haskell quotation; see this note in RnNames
360 --            Note [Top-level Names in Template Haskell decl quotes]
361
362 -- | An element of the 'GlobalRdrEnv'
363 data GlobalRdrElt 
364   = GRE { gre_name :: Name,
365           gre_par  :: Parent,
366           gre_prov :: Provenance        -- ^ Why it's in scope
367     }
368
369 -- | The children of a Name are the things that are abbreviated by the ".."
370 --   notation in export lists.  Specifically:
371 --      TyCon   Children are * data constructors
372 --                           * record field ids
373 --      Class   Children are * class operations
374 -- Each child has the parent thing as its Parent
375 data Parent = NoParent | ParentIs Name
376               deriving (Eq)
377
378 instance Outputable Parent where
379    ppr NoParent     = empty
380    ppr (ParentIs n) = ptext (sLit "parent:") <> ppr n
381    
382
383 plusParent :: Parent -> Parent -> Parent
384 plusParent p1 p2 = ASSERT2( p1 == p2, parens (ppr p1) <+> parens (ppr p2) )
385                    p1
386
387 {- Why so complicated? -=chak
388 plusParent :: Parent -> Parent -> Parent
389 plusParent NoParent     rel = 
390   ASSERT2( case rel of { NoParent -> True; other -> False }, 
391            ptext (sLit "plusParent[NoParent]: ") <+> ppr rel )    
392   NoParent
393 plusParent (ParentIs n) rel = 
394   ASSERT2( case rel of { ParentIs m -> n==m;  other -> False }, 
395            ptext (sLit "plusParent[ParentIs]:") <+> ppr n <> comma <+> ppr rel )
396   ParentIs n
397  -}
398
399 emptyGlobalRdrEnv :: GlobalRdrEnv
400 emptyGlobalRdrEnv = emptyOccEnv
401
402 globalRdrEnvElts :: GlobalRdrEnv -> [GlobalRdrElt]
403 globalRdrEnvElts env = foldOccEnv (++) [] env
404
405 instance Outputable GlobalRdrElt where
406   ppr gre = ppr name <+> parens (ppr (gre_par gre) <+> pprNameProvenance gre)
407           where
408             name = gre_name gre
409
410 pprGlobalRdrEnv :: GlobalRdrEnv -> SDoc
411 pprGlobalRdrEnv env
412   = vcat (map pp (occEnvElts env))
413   where
414     pp gres = ppr (nameOccName (gre_name (head gres))) <> colon <+> 
415               vcat [ ppr (gre_name gre) <+> pprNameProvenance gre
416                    | gre <- gres]
417 \end{code}
418
419 \begin{code}
420 lookupGlobalRdrEnv :: GlobalRdrEnv -> OccName -> [GlobalRdrElt]
421 lookupGlobalRdrEnv env occ_name = case lookupOccEnv env occ_name of
422                                         Nothing   -> []
423                                         Just gres -> gres
424
425 extendGlobalRdrEnv :: GlobalRdrEnv -> GlobalRdrElt -> GlobalRdrEnv
426 extendGlobalRdrEnv env gre = extendOccEnv_Acc (:) singleton env occ gre
427   where
428     occ = nameOccName (gre_name gre)
429
430 lookupGRE_RdrName :: RdrName -> GlobalRdrEnv -> [GlobalRdrElt]
431 lookupGRE_RdrName rdr_name env
432   = case lookupOccEnv env (rdrNameOcc rdr_name) of
433         Nothing   -> []
434         Just gres -> pickGREs rdr_name gres
435
436 lookupGRE_Name :: GlobalRdrEnv -> Name -> [GlobalRdrElt]
437 lookupGRE_Name env name
438   = [ gre | gre <- lookupGlobalRdrEnv env (nameOccName name),
439             gre_name gre == name ]
440
441 getGRE_NameQualifier_maybes :: GlobalRdrEnv -> Name -> [Maybe [ModuleName]]
442 getGRE_NameQualifier_maybes env
443   = map qualifier_maybe . map gre_prov . lookupGRE_Name env
444   where qualifier_maybe LocalDef       = Nothing
445         qualifier_maybe (Imported iss) = Just $ map (is_as . is_decl) iss 
446
447 pickGREs :: RdrName -> [GlobalRdrElt] -> [GlobalRdrElt]
448 -- ^ Take a list of GREs which have the right OccName
449 -- Pick those GREs that are suitable for this RdrName
450 -- And for those, keep only only the Provenances that are suitable
451 -- 
452 -- Consider:
453 --
454 -- @
455 --       module A ( f ) where
456 --       import qualified Foo( f )
457 --       import Baz( f )
458 --       f = undefined
459 -- @
460 --
461 -- Let's suppose that @Foo.f@ and @Baz.f@ are the same entity really.
462 -- The export of @f@ is ambiguous because it's in scope from the local def
463 -- and the import.  The lookup of @Unqual f@ should return a GRE for
464 -- the locally-defined @f@, and a GRE for the imported @f@, with a /single/ 
465 -- provenance, namely the one for @Baz(f)@.
466 pickGREs rdr_name gres
467   = mapCatMaybes pick gres
468   where
469     rdr_is_unqual = isUnqual rdr_name
470     rdr_is_qual   = isQual_maybe rdr_name
471
472     pick :: GlobalRdrElt -> Maybe GlobalRdrElt
473     pick gre@(GRE {gre_prov = LocalDef, gre_name = n})  -- Local def
474         | rdr_is_unqual                    = Just gre
475         | Just (mod,_) <- rdr_is_qual        -- Qualified name
476         , Just n_mod <- nameModule_maybe n   -- Binder is External
477         , mod == moduleName n_mod          = Just gre
478         | otherwise                        = Nothing
479     pick gre@(GRE {gre_prov = Imported [is]})   -- Single import (efficiency)
480         | rdr_is_unqual,
481           not (is_qual (is_decl is))    = Just gre
482         | Just (mod,_) <- rdr_is_qual, 
483           mod == is_as (is_decl is)     = Just gre
484         | otherwise                     = Nothing
485     pick gre@(GRE {gre_prov = Imported is})     -- Multiple import
486         | null filtered_is = Nothing
487         | otherwise        = Just (gre {gre_prov = Imported filtered_is})
488         where
489           filtered_is | rdr_is_unqual
490                       = filter (not . is_qual    . is_decl) is
491                       | Just (mod,_) <- rdr_is_qual 
492                       = filter ((== mod) . is_as . is_decl) is
493                       | otherwise
494                       = []
495
496 isLocalGRE :: GlobalRdrElt -> Bool
497 isLocalGRE (GRE {gre_prov = LocalDef}) = True
498 isLocalGRE _                           = False
499
500 unQualOK :: GlobalRdrElt -> Bool
501 -- ^ Test if an unqualifed version of this thing would be in scope
502 unQualOK (GRE {gre_prov = LocalDef})    = True
503 unQualOK (GRE {gre_prov = Imported is}) = any unQualSpecOK is
504
505 plusGlobalRdrEnv :: GlobalRdrEnv -> GlobalRdrEnv -> GlobalRdrEnv
506 plusGlobalRdrEnv env1 env2 = plusOccEnv_C (foldr insertGRE) env1 env2
507
508 mkGlobalRdrEnv :: [GlobalRdrElt] -> GlobalRdrEnv
509 mkGlobalRdrEnv gres
510   = foldr add emptyGlobalRdrEnv gres
511   where
512     add gre env = extendOccEnv_Acc insertGRE singleton env 
513                                    (nameOccName (gre_name gre)) 
514                                    gre
515
516 findLocalDupsRdrEnv :: GlobalRdrEnv -> [OccName] -> (GlobalRdrEnv, [[Name]])
517 -- ^ For each 'OccName', see if there are multiple local definitions
518 -- for it.  If so, remove all but one (to suppress subsequent error messages)
519 -- and return a list of the duplicate bindings
520 findLocalDupsRdrEnv rdr_env occs 
521   = go rdr_env [] occs
522   where
523     go rdr_env dups [] = (rdr_env, dups)
524     go rdr_env dups (occ:occs)
525       = case filter isLocalGRE gres of
526           []       -> WARN( True, ppr occ <+> ppr rdr_env ) 
527                       go rdr_env dups occs      -- Weird!  No binding for occ
528           [_]      -> go rdr_env dups occs      -- The common case
529           dup_gres -> go (extendOccEnv rdr_env occ (head dup_gres : nonlocal_gres))
530                          (map gre_name dup_gres : dups)
531                          occs
532       where
533         gres = lookupOccEnv rdr_env occ `orElse` []
534         nonlocal_gres = filterOut isLocalGRE gres
535
536
537 insertGRE :: GlobalRdrElt -> [GlobalRdrElt] -> [GlobalRdrElt]
538 insertGRE new_g [] = [new_g]
539 insertGRE new_g (old_g : old_gs)
540         | gre_name new_g == gre_name old_g
541         = new_g `plusGRE` old_g : old_gs
542         | otherwise
543         = old_g : insertGRE new_g old_gs
544
545 plusGRE :: GlobalRdrElt -> GlobalRdrElt -> GlobalRdrElt
546 -- Used when the gre_name fields match
547 plusGRE g1 g2
548   = GRE { gre_name = gre_name g1,
549           gre_prov = gre_prov g1 `plusProv`   gre_prov g2,
550           gre_par  = gre_par  g1 `plusParent` gre_par  g2 }
551
552 hideSomeUnquals :: GlobalRdrEnv -> [OccName] -> GlobalRdrEnv
553 -- ^ Hide any unqualified bindings for the specified OccNames
554 -- This is used in TH, when renaming a declaration bracket
555 --
556 -- > [d| foo = ... |]
557 --
558 -- We want unqualified @foo@ in "..." to mean this @foo@, not
559 -- the one from the enclosing module.  But the /qualified/ name
560 -- from the enclosing module must certainly still be available
561
562 --      Seems like 5 times as much work as it deserves!
563 hideSomeUnquals rdr_env occs
564   = foldr hide rdr_env occs
565   where
566     hide occ env 
567         | Just gres <- lookupOccEnv env occ = extendOccEnv env occ (map qual_gre gres)
568         | otherwise                         = env
569     qual_gre gre@(GRE { gre_name = name, gre_prov = LocalDef })
570         = gre { gre_prov = Imported [imp_spec] }
571         where   -- Local defs get transfomed to (fake) imported things
572           mod = ASSERT2( isExternalName name, ppr name) moduleName (nameModule name)
573           imp_spec = ImpSpec { is_item = ImpAll, is_decl = decl_spec }
574           decl_spec = ImpDeclSpec { is_mod = mod, is_as = mod, 
575                                     is_qual = True, 
576                                     is_dloc = srcLocSpan (nameSrcLoc name) }
577
578     qual_gre gre@(GRE { gre_prov = Imported specs })
579         = gre { gre_prov = Imported (map qual_spec specs) }
580
581     qual_spec spec@(ImpSpec { is_decl = decl_spec })
582         = spec { is_decl = decl_spec { is_qual = True } }
583 \end{code}
584
585 %************************************************************************
586 %*                                                                      *
587                         Provenance
588 %*                                                                      *
589 %************************************************************************
590
591 \begin{code}
592 -- | The 'Provenance' of something says how it came to be in scope.
593 -- It's quite elaborate so that we can give accurate unused-name warnings.
594 data Provenance
595   = LocalDef            -- ^ The thing was defined locally
596   | Imported            
597         [ImportSpec]    -- ^ The thing was imported.
598                         -- 
599                         -- INVARIANT: the list of 'ImportSpec' is non-empty
600
601 data ImportSpec = ImpSpec { is_decl :: ImpDeclSpec,
602                             is_item ::  ImpItemSpec }
603                 deriving( Eq, Ord )
604
605 -- | Describes a particular import declaration and is
606 -- shared among all the 'Provenance's for that decl
607 data ImpDeclSpec
608   = ImpDeclSpec {
609         is_mod      :: ModuleName, -- ^ Module imported, e.g. @import Muggle@
610                                    -- Note the @Muggle@ may well not be 
611                                    -- the defining module for this thing!
612
613                                    -- TODO: either should be Module, or there
614                                    -- should be a Maybe PackageId here too.
615         is_as       :: ModuleName, -- ^ Import alias, e.g. from @as M@ (or @Muggle@ if there is no @as@ clause)
616         is_qual     :: Bool,       -- ^ Was this import qualified?
617         is_dloc     :: SrcSpan     -- ^ The location of the entire import declaration
618     }
619
620 -- | Describes import info a particular Name
621 data ImpItemSpec
622   = ImpAll              -- ^ The import had no import list, 
623                         -- or had a hiding list
624
625   | ImpSome {
626         is_explicit :: Bool,
627         is_iloc     :: SrcSpan  -- Location of the import item
628     }   -- ^ The import had an import list.
629         -- The 'is_explicit' field is @True@ iff the thing was named 
630         -- /explicitly/ in the import specs rather
631         -- than being imported as part of a "..." group. Consider:
632         --
633         -- > import C( T(..) )
634         --
635         -- Here the constructors of @T@ are not named explicitly; 
636         -- only @T@ is named explicitly.
637
638 unQualSpecOK :: ImportSpec -> Bool
639 -- ^ Is in scope unqualified?
640 unQualSpecOK is = not (is_qual (is_decl is))
641
642 qualSpecOK :: ModuleName -> ImportSpec -> Bool
643 -- ^ Is in scope qualified with the given module?
644 qualSpecOK mod is = mod == is_as (is_decl is)
645
646 importSpecLoc :: ImportSpec -> SrcSpan
647 importSpecLoc (ImpSpec decl ImpAll) = is_dloc decl
648 importSpecLoc (ImpSpec _    item)   = is_iloc item
649
650 importSpecModule :: ImportSpec -> ModuleName
651 importSpecModule is = is_mod (is_decl is)
652
653 isExplicitItem :: ImpItemSpec -> Bool
654 isExplicitItem ImpAll                        = False
655 isExplicitItem (ImpSome {is_explicit = exp}) = exp
656
657 -- Note [Comparing provenance]
658 -- Comparison of provenance is just used for grouping 
659 -- error messages (in RnEnv.warnUnusedBinds)
660 instance Eq Provenance where
661   p1 == p2 = case p1 `compare` p2 of EQ -> True; _ -> False
662
663 instance Eq ImpDeclSpec where
664   p1 == p2 = case p1 `compare` p2 of EQ -> True; _ -> False
665
666 instance Eq ImpItemSpec where
667   p1 == p2 = case p1 `compare` p2 of EQ -> True; _ -> False
668
669 instance Ord Provenance where
670    compare LocalDef      LocalDef        = EQ
671    compare LocalDef      (Imported _)    = LT
672    compare (Imported _ ) LocalDef        = GT
673    compare (Imported is1) (Imported is2) = compare (head is1) 
674         {- See Note [Comparing provenance] -}      (head is2)
675
676 instance Ord ImpDeclSpec where
677    compare is1 is2 = (is_mod is1 `compare` is_mod is2) `thenCmp` 
678                      (is_dloc is1 `compare` is_dloc is2)
679
680 instance Ord ImpItemSpec where
681    compare is1 is2 = is_iloc is1 `compare` is_iloc is2
682 \end{code}
683
684 \begin{code}
685 plusProv :: Provenance -> Provenance -> Provenance
686 -- Choose LocalDef over Imported
687 -- There is an obscure bug lurking here; in the presence
688 -- of recursive modules, something can be imported *and* locally
689 -- defined, and one might refer to it with a qualified name from
690 -- the import -- but I'm going to ignore that because it makes
691 -- the isLocalGRE predicate so much nicer this way
692 plusProv LocalDef        LocalDef        = panic "plusProv"
693 plusProv LocalDef        _               = LocalDef
694 plusProv _               LocalDef        = LocalDef
695 plusProv (Imported is1)  (Imported is2)  = Imported (is1++is2)
696
697 pprNameProvenance :: GlobalRdrElt -> SDoc
698 -- ^ Print out the place where the name was imported
699 pprNameProvenance (GRE {gre_name = name, gre_prov = LocalDef})
700   = ptext (sLit "defined at") <+> ppr (nameSrcLoc name)
701 pprNameProvenance (GRE {gre_name = name, gre_prov = Imported whys})
702   = case whys of
703         (why:_) -> sep [ppr why, nest 2 (ppr_defn (nameSrcLoc name))]
704         [] -> panic "pprNameProvenance"
705
706 -- If we know the exact definition point (which we may do with GHCi)
707 -- then show that too.  But not if it's just "imported from X".
708 ppr_defn :: SrcLoc -> SDoc
709 ppr_defn loc | isGoodSrcLoc loc = parens (ptext (sLit "defined at") <+> ppr loc)
710              | otherwise        = empty
711
712 instance Outputable ImportSpec where
713    ppr imp_spec
714      = ptext (sLit "imported from") <+> ppr (importSpecModule imp_spec) 
715         <+> if isGoodSrcSpan loc then ptext (sLit "at") <+> ppr loc
716                                  else empty
717      where
718        loc = importSpecLoc imp_spec
719 \end{code}