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