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