fix haddock submodule pointer
[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         transformGREs, 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 emptyGlobalRdrEnv :: GlobalRdrEnv
388 emptyGlobalRdrEnv = emptyOccEnv
389
390 globalRdrEnvElts :: GlobalRdrEnv -> [GlobalRdrElt]
391 globalRdrEnvElts env = foldOccEnv (++) [] env
392
393 instance Outputable GlobalRdrElt where
394   ppr gre = ppr name <+> parens (ppr (gre_par gre) <+> pprNameProvenance gre)
395           where
396             name = gre_name gre
397
398 pprGlobalRdrEnv :: GlobalRdrEnv -> SDoc
399 pprGlobalRdrEnv env
400   = vcat (map pp (occEnvElts env))
401   where
402     pp gres = ppr (nameOccName (gre_name (head gres))) <> colon <+> 
403               vcat [ ppr (gre_name gre) <+> pprNameProvenance gre
404                    | gre <- gres]
405 \end{code}
406
407 \begin{code}
408 lookupGlobalRdrEnv :: GlobalRdrEnv -> OccName -> [GlobalRdrElt]
409 lookupGlobalRdrEnv env occ_name = case lookupOccEnv env occ_name of
410                                         Nothing   -> []
411                                         Just gres -> gres
412
413 extendGlobalRdrEnv :: GlobalRdrEnv -> GlobalRdrElt -> GlobalRdrEnv
414 extendGlobalRdrEnv env gre = extendOccEnv_Acc (:) singleton env occ gre
415   where
416     occ = nameOccName (gre_name gre)
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 -- Returns all the qualifiers by which 'x' is in scope
431 -- Nothing means "the unqualified version is in scope"
432 getGRE_NameQualifier_maybes env
433   = map qualifier_maybe . map gre_prov . lookupGRE_Name env
434   where
435     qualifier_maybe LocalDef       = Nothing
436     qualifier_maybe (Imported iss) = Just $ map (is_as . is_decl) iss
437
438 pickGREs :: RdrName -> [GlobalRdrElt] -> [GlobalRdrElt]
439 -- ^ Take a list of GREs which have the right OccName
440 -- Pick those GREs that are suitable for this RdrName
441 -- And for those, keep only only the Provenances that are suitable
442 -- 
443 -- Consider:
444 --
445 -- @
446 --       module A ( f ) where
447 --       import qualified Foo( f )
448 --       import Baz( f )
449 --       f = undefined
450 -- @
451 --
452 -- Let's suppose that @Foo.f@ and @Baz.f@ are the same entity really.
453 -- The export of @f@ is ambiguous because it's in scope from the local def
454 -- and the import.  The lookup of @Unqual f@ should return a GRE for
455 -- the locally-defined @f@, and a GRE for the imported @f@, with a /single/ 
456 -- provenance, namely the one for @Baz(f)@.
457 pickGREs rdr_name gres
458   = mapCatMaybes pick gres
459   where
460     rdr_is_unqual = isUnqual rdr_name
461     rdr_is_qual   = isQual_maybe rdr_name
462
463     pick :: GlobalRdrElt -> Maybe GlobalRdrElt
464     pick gre@(GRE {gre_prov = LocalDef, gre_name = n})  -- Local def
465         | rdr_is_unqual                    = Just gre
466         | Just (mod,_) <- rdr_is_qual        -- Qualified name
467         , Just n_mod <- nameModule_maybe n   -- Binder is External
468         , mod == moduleName n_mod          = Just gre
469         | otherwise                        = Nothing
470     pick gre@(GRE {gre_prov = Imported [is]})   -- Single import (efficiency)
471         | rdr_is_unqual,
472           not (is_qual (is_decl is))    = Just gre
473         | Just (mod,_) <- rdr_is_qual, 
474           mod == is_as (is_decl is)     = Just gre
475         | otherwise                     = Nothing
476     pick gre@(GRE {gre_prov = Imported is})     -- Multiple import
477         | null filtered_is = Nothing
478         | otherwise        = Just (gre {gre_prov = Imported filtered_is})
479         where
480           filtered_is | rdr_is_unqual
481                       = filter (not . is_qual    . is_decl) is
482                       | Just (mod,_) <- rdr_is_qual 
483                       = filter ((== mod) . is_as . is_decl) is
484                       | otherwise
485                       = []
486
487 isLocalGRE :: GlobalRdrElt -> Bool
488 isLocalGRE (GRE {gre_prov = LocalDef}) = True
489 isLocalGRE _                           = False
490
491 unQualOK :: GlobalRdrElt -> Bool
492 -- ^ Test if an unqualifed version of this thing would be in scope
493 unQualOK (GRE {gre_prov = LocalDef})    = True
494 unQualOK (GRE {gre_prov = Imported is}) = any unQualSpecOK is
495
496 plusGlobalRdrEnv :: GlobalRdrEnv -> GlobalRdrEnv -> GlobalRdrEnv
497 plusGlobalRdrEnv env1 env2 = plusOccEnv_C (foldr insertGRE) env1 env2
498
499 mkGlobalRdrEnv :: [GlobalRdrElt] -> GlobalRdrEnv
500 mkGlobalRdrEnv gres
501   = foldr add emptyGlobalRdrEnv gres
502   where
503     add gre env = extendOccEnv_Acc insertGRE singleton env 
504                                    (nameOccName (gre_name gre)) 
505                                    gre
506
507 findLocalDupsRdrEnv :: GlobalRdrEnv -> [OccName] -> (GlobalRdrEnv, [[Name]])
508 -- ^ For each 'OccName', see if there are multiple local definitions
509 -- for it.  If so, remove all but one (to suppress subsequent error messages)
510 -- and return a list of the duplicate bindings
511 findLocalDupsRdrEnv rdr_env occs 
512   = go rdr_env [] occs
513   where
514     go rdr_env dups [] = (rdr_env, dups)
515     go rdr_env dups (occ:occs)
516       = case filter isLocalGRE gres of
517           []       -> WARN( True, ppr occ <+> ppr rdr_env ) 
518                       go rdr_env dups occs      -- Weird!  No binding for occ
519           [_]      -> go rdr_env dups occs      -- The common case
520           dup_gres -> go (extendOccEnv rdr_env occ (head dup_gres : nonlocal_gres))
521                          (map gre_name dup_gres : dups)
522                          occs
523       where
524         gres = lookupOccEnv rdr_env occ `orElse` []
525         nonlocal_gres = filterOut isLocalGRE gres
526
527
528 insertGRE :: GlobalRdrElt -> [GlobalRdrElt] -> [GlobalRdrElt]
529 insertGRE new_g [] = [new_g]
530 insertGRE new_g (old_g : old_gs)
531         | gre_name new_g == gre_name old_g
532         = new_g `plusGRE` old_g : old_gs
533         | otherwise
534         = old_g : insertGRE new_g old_gs
535
536 plusGRE :: GlobalRdrElt -> GlobalRdrElt -> GlobalRdrElt
537 -- Used when the gre_name fields match
538 plusGRE g1 g2
539   = GRE { gre_name = gre_name g1,
540           gre_prov = gre_prov g1 `plusProv`   gre_prov g2,
541           gre_par  = gre_par  g1 `plusParent` gre_par  g2 }
542
543 transformGREs :: (GlobalRdrElt -> GlobalRdrElt)
544               -> [OccName] 
545               -> GlobalRdrEnv -> GlobalRdrEnv
546 -- ^ Apply a transformation function to the GREs for these OccNames
547 transformGREs trans_gre occs rdr_env
548   = foldr trans rdr_env occs
549   where
550     trans occ env 
551       = case lookupOccEnv env occ of 
552            Just gres -> extendOccEnv env occ (map trans_gre gres)
553            Nothing   -> env
554 \end{code}
555
556 %************************************************************************
557 %*                                                                      *
558                         Provenance
559 %*                                                                      *
560 %************************************************************************
561
562 \begin{code}
563 -- | The 'Provenance' of something says how it came to be in scope.
564 -- It's quite elaborate so that we can give accurate unused-name warnings.
565 data Provenance
566   = LocalDef            -- ^ The thing was defined locally
567   | Imported            
568         [ImportSpec]    -- ^ The thing was imported.
569                         -- 
570                         -- INVARIANT: the list of 'ImportSpec' is non-empty
571
572 data ImportSpec = ImpSpec { is_decl :: ImpDeclSpec,
573                             is_item :: ImpItemSpec }
574                 deriving( Eq, Ord )
575
576 -- | Describes a particular import declaration and is
577 -- shared among all the 'Provenance's for that decl
578 data ImpDeclSpec
579   = ImpDeclSpec {
580         is_mod      :: ModuleName, -- ^ Module imported, e.g. @import Muggle@
581                                    -- Note the @Muggle@ may well not be 
582                                    -- the defining module for this thing!
583
584                                    -- TODO: either should be Module, or there
585                                    -- should be a Maybe PackageId here too.
586         is_as       :: ModuleName, -- ^ Import alias, e.g. from @as M@ (or @Muggle@ if there is no @as@ clause)
587         is_qual     :: Bool,       -- ^ Was this import qualified?
588         is_dloc     :: SrcSpan     -- ^ The location of the entire import declaration
589     }
590
591 -- | Describes import info a particular Name
592 data ImpItemSpec
593   = ImpAll              -- ^ The import had no import list, 
594                         -- or had a hiding list
595
596   | ImpSome {
597         is_explicit :: Bool,
598         is_iloc     :: SrcSpan  -- Location of the import item
599     }   -- ^ The import had an import list.
600         -- The 'is_explicit' field is @True@ iff the thing was named 
601         -- /explicitly/ in the import specs rather
602         -- than being imported as part of a "..." group. Consider:
603         --
604         -- > import C( T(..) )
605         --
606         -- Here the constructors of @T@ are not named explicitly; 
607         -- only @T@ is named explicitly.
608
609 unQualSpecOK :: ImportSpec -> Bool
610 -- ^ Is in scope unqualified?
611 unQualSpecOK is = not (is_qual (is_decl is))
612
613 qualSpecOK :: ModuleName -> ImportSpec -> Bool
614 -- ^ Is in scope qualified with the given module?
615 qualSpecOK mod is = mod == is_as (is_decl is)
616
617 importSpecLoc :: ImportSpec -> SrcSpan
618 importSpecLoc (ImpSpec decl ImpAll) = is_dloc decl
619 importSpecLoc (ImpSpec _    item)   = is_iloc item
620
621 importSpecModule :: ImportSpec -> ModuleName
622 importSpecModule is = is_mod (is_decl is)
623
624 isExplicitItem :: ImpItemSpec -> Bool
625 isExplicitItem ImpAll                        = False
626 isExplicitItem (ImpSome {is_explicit = exp}) = exp
627
628 -- Note [Comparing provenance]
629 -- Comparison of provenance is just used for grouping 
630 -- error messages (in RnEnv.warnUnusedBinds)
631 instance Eq Provenance where
632   p1 == p2 = case p1 `compare` p2 of EQ -> True; _ -> False
633
634 instance Eq ImpDeclSpec where
635   p1 == p2 = case p1 `compare` p2 of EQ -> True; _ -> False
636
637 instance Eq ImpItemSpec where
638   p1 == p2 = case p1 `compare` p2 of EQ -> True; _ -> False
639
640 instance Ord Provenance where
641    compare LocalDef      LocalDef        = EQ
642    compare LocalDef      (Imported _)    = LT
643    compare (Imported _ ) LocalDef        = GT
644    compare (Imported is1) (Imported is2) = compare (head is1) 
645         {- See Note [Comparing provenance] -}      (head is2)
646
647 instance Ord ImpDeclSpec where
648    compare is1 is2 = (is_mod is1 `compare` is_mod is2) `thenCmp` 
649                      (is_dloc is1 `compare` is_dloc is2)
650
651 instance Ord ImpItemSpec where
652    compare is1 is2 = is_iloc is1 `compare` is_iloc is2
653 \end{code}
654
655 \begin{code}
656 plusProv :: Provenance -> Provenance -> Provenance
657 -- Choose LocalDef over Imported
658 -- There is an obscure bug lurking here; in the presence
659 -- of recursive modules, something can be imported *and* locally
660 -- defined, and one might refer to it with a qualified name from
661 -- the import -- but I'm going to ignore that because it makes
662 -- the isLocalGRE predicate so much nicer this way
663 plusProv LocalDef        LocalDef        = panic "plusProv"
664 plusProv LocalDef        _               = LocalDef
665 plusProv _               LocalDef        = LocalDef
666 plusProv (Imported is1)  (Imported is2)  = Imported (is1++is2)
667
668 pprNameProvenance :: GlobalRdrElt -> SDoc
669 -- ^ Print out the place where the name was imported
670 pprNameProvenance (GRE {gre_name = name, gre_prov = LocalDef})
671   = ptext (sLit "defined at") <+> ppr (nameSrcLoc name)
672 pprNameProvenance (GRE {gre_name = name, gre_prov = Imported whys})
673   = case whys of
674         (why:_) -> sep [ppr why, nest 2 (ppr_defn (nameSrcLoc name))]
675         [] -> panic "pprNameProvenance"
676
677 -- If we know the exact definition point (which we may do with GHCi)
678 -- then show that too.  But not if it's just "imported from X".
679 ppr_defn :: SrcLoc -> SDoc
680 ppr_defn (RealSrcLoc loc) = parens (ptext (sLit "defined at") <+> ppr loc)
681 ppr_defn (UnhelpfulLoc _) = empty
682
683 instance Outputable ImportSpec where
684    ppr imp_spec
685      = ptext (sLit "imported from") <+> ppr (importSpecModule imp_spec) 
686         <+> pprLoc
687      where
688        loc = importSpecLoc imp_spec
689        pprLoc = case loc of
690                 RealSrcSpan s -> ptext (sLit "at") <+> ppr s
691                 UnhelpfulSpan _ -> empty
692 \end{code}