Rename package key to unit ID, and installed package ID to component ID.
[ghc.git] / compiler / basicTypes / RdrName.hs
1 {-
2 (c) The University of Glasgow 2006
3 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 -}
5
6 {-# LANGUAGE CPP, DeriveDataTypeable #-}
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
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, demoteRdrName,
36 isRdrDataCon, isRdrTyVar, isRdrTc, isQual, isQual_maybe, isUnqual,
37 isOrig, isOrig_maybe, isExact, isExact_maybe, isSrcRdrName,
38
39 -- * Local mapping of 'RdrName' to 'Name.Name'
40 LocalRdrEnv, emptyLocalRdrEnv, extendLocalRdrEnv, extendLocalRdrEnvList,
41 lookupLocalRdrEnv, lookupLocalRdrOcc,
42 elemLocalRdrEnv, inLocalRdrEnvScope,
43 localRdrEnvElts, delLocalRdrEnvList,
44
45 -- * Global mapping of 'RdrName' to 'GlobalRdrElt's
46 GlobalRdrEnv, emptyGlobalRdrEnv, mkGlobalRdrEnv, plusGlobalRdrEnv,
47 lookupGlobalRdrEnv, extendGlobalRdrEnv, shadowNames,
48 pprGlobalRdrEnv, globalRdrEnvElts,
49 lookupGRE_RdrName, lookupGRE_Name, getGRE_NameQualifier_maybes,
50 transformGREs, pickGREs,
51
52 -- * GlobalRdrElts
53 gresFromAvails, gresFromAvail, localGREsFromAvail, availFromGRE,
54 greUsedRdrName, greRdrNames, greSrcSpan, greQualModName,
55
56 -- ** Global 'RdrName' mapping elements: 'GlobalRdrElt', 'Provenance', 'ImportSpec'
57 GlobalRdrElt(..), isLocalGRE, unQualOK, qualSpecOK, unQualSpecOK,
58 pprNameProvenance,
59 Parent(..),
60 ImportSpec(..), ImpDeclSpec(..), ImpItemSpec(..),
61 importSpecLoc, importSpecModule, isExplicitItem
62 ) where
63
64 #include "HsVersions.h"
65
66 import Module
67 import Name
68 import Avail
69 import NameSet
70 import Maybes
71 import SrcLoc
72 import FastString
73 import Outputable
74 import Unique
75 import Util
76 import StaticFlags( opt_PprStyle_Debug )
77
78 import Data.Data
79
80 {-
81 ************************************************************************
82 * *
83 \subsection{The main data type}
84 * *
85 ************************************************************************
86 -}
87
88 -- | Do not use the data constructors of RdrName directly: prefer the family
89 -- of functions that creates them, such as 'mkRdrUnqual'
90 --
91 -- - Note: A Located RdrName will only have API Annotations if it is a
92 -- compound one,
93 -- e.g.
94 --
95 -- > `bar`
96 -- > ( ~ )
97 --
98 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnType',
99 -- 'ApiAnnotation.AnnOpen' @'('@ or @'['@ or @'[:'@,
100 -- 'ApiAnnotation.AnnClose' @')'@ or @']'@ or @':]'@,,
101 -- 'ApiAnnotation.AnnBackquote' @'`'@,
102 -- 'ApiAnnotation.AnnVal','ApiAnnotation.AnnTildehsh',
103 -- 'ApiAnnotation.AnnTilde',
104
105 -- For details on above see note [Api annotations] in ApiAnnotation
106 data RdrName
107 = Unqual OccName
108 -- ^ Used for ordinary, unqualified occurrences, e.g. @x@, @y@ or @Foo@.
109 -- Create such a 'RdrName' with 'mkRdrUnqual'
110
111 | Qual ModuleName OccName
112 -- ^ A qualified name written by the user in
113 -- /source/ code. The module isn't necessarily
114 -- the module where the thing is defined;
115 -- just the one from which it is imported.
116 -- Examples are @Bar.x@, @Bar.y@ or @Bar.Foo@.
117 -- Create such a 'RdrName' with 'mkRdrQual'
118
119 | Orig Module OccName
120 -- ^ An original name; the module is the /defining/ module.
121 -- This is used when GHC generates code that will be fed
122 -- into the renamer (e.g. from deriving clauses), but where
123 -- we want to say \"Use Prelude.map dammit\". One of these
124 -- can be created with 'mkOrig'
125
126 | Exact Name
127 -- ^ We know exactly the 'Name'. This is used:
128 --
129 -- (1) When the parser parses built-in syntax like @[]@
130 -- and @(,)@, but wants a 'RdrName' from it
131 --
132 -- (2) By Template Haskell, when TH has generated a unique name
133 --
134 -- Such a 'RdrName' can be created by using 'getRdrName' on a 'Name'
135 deriving (Data, Typeable)
136
137 {-
138 ************************************************************************
139 * *
140 \subsection{Simple functions}
141 * *
142 ************************************************************************
143 -}
144
145 instance HasOccName RdrName where
146 occName = rdrNameOcc
147
148 rdrNameOcc :: RdrName -> OccName
149 rdrNameOcc (Qual _ occ) = occ
150 rdrNameOcc (Unqual occ) = occ
151 rdrNameOcc (Orig _ occ) = occ
152 rdrNameOcc (Exact name) = nameOccName name
153
154 rdrNameSpace :: RdrName -> NameSpace
155 rdrNameSpace = occNameSpace . rdrNameOcc
156
157 -- demoteRdrName lowers the NameSpace of RdrName.
158 -- see Note [Demotion] in OccName
159 demoteRdrName :: RdrName -> Maybe RdrName
160 demoteRdrName (Unqual occ) = fmap Unqual (demoteOccName occ)
161 demoteRdrName (Qual m occ) = fmap (Qual m) (demoteOccName occ)
162 demoteRdrName (Orig _ _) = panic "demoteRdrName"
163 demoteRdrName (Exact _) = panic "demoteRdrName"
164
165 -- These two are the basic constructors
166 mkRdrUnqual :: OccName -> RdrName
167 mkRdrUnqual occ = Unqual occ
168
169 mkRdrQual :: ModuleName -> OccName -> RdrName
170 mkRdrQual mod occ = Qual mod occ
171
172 mkOrig :: Module -> OccName -> RdrName
173 mkOrig mod occ = Orig mod occ
174
175 ---------------
176 -- These two are used when parsing source files
177 -- They do encode the module and occurrence names
178 mkUnqual :: NameSpace -> FastString -> RdrName
179 mkUnqual sp n = Unqual (mkOccNameFS sp n)
180
181 mkVarUnqual :: FastString -> RdrName
182 mkVarUnqual n = Unqual (mkVarOccFS n)
183
184 -- | Make a qualified 'RdrName' in the given namespace and where the 'ModuleName' and
185 -- the 'OccName' are taken from the first and second elements of the tuple respectively
186 mkQual :: NameSpace -> (FastString, FastString) -> RdrName
187 mkQual sp (m, n) = Qual (mkModuleNameFS m) (mkOccNameFS sp n)
188
189 getRdrName :: NamedThing thing => thing -> RdrName
190 getRdrName name = nameRdrName (getName name)
191
192 nameRdrName :: Name -> RdrName
193 nameRdrName name = Exact name
194 -- Keep the Name even for Internal names, so that the
195 -- unique is still there for debug printing, particularly
196 -- of Types (which are converted to IfaceTypes before printing)
197
198 nukeExact :: Name -> RdrName
199 nukeExact n
200 | isExternalName n = Orig (nameModule n) (nameOccName n)
201 | otherwise = Unqual (nameOccName n)
202
203 isRdrDataCon :: RdrName -> Bool
204 isRdrTyVar :: RdrName -> Bool
205 isRdrTc :: RdrName -> Bool
206
207 isRdrDataCon rn = isDataOcc (rdrNameOcc rn)
208 isRdrTyVar rn = isTvOcc (rdrNameOcc rn)
209 isRdrTc rn = isTcOcc (rdrNameOcc rn)
210
211 isSrcRdrName :: RdrName -> Bool
212 isSrcRdrName (Unqual _) = True
213 isSrcRdrName (Qual _ _) = True
214 isSrcRdrName _ = False
215
216 isUnqual :: RdrName -> Bool
217 isUnqual (Unqual _) = True
218 isUnqual _ = False
219
220 isQual :: RdrName -> Bool
221 isQual (Qual _ _) = True
222 isQual _ = False
223
224 isQual_maybe :: RdrName -> Maybe (ModuleName, OccName)
225 isQual_maybe (Qual m n) = Just (m,n)
226 isQual_maybe _ = Nothing
227
228 isOrig :: RdrName -> Bool
229 isOrig (Orig _ _) = True
230 isOrig _ = False
231
232 isOrig_maybe :: RdrName -> Maybe (Module, OccName)
233 isOrig_maybe (Orig m n) = Just (m,n)
234 isOrig_maybe _ = Nothing
235
236 isExact :: RdrName -> Bool
237 isExact (Exact _) = True
238 isExact _ = False
239
240 isExact_maybe :: RdrName -> Maybe Name
241 isExact_maybe (Exact n) = Just n
242 isExact_maybe _ = Nothing
243
244 {-
245 ************************************************************************
246 * *
247 \subsection{Instances}
248 * *
249 ************************************************************************
250 -}
251
252 instance Outputable RdrName where
253 ppr (Exact name) = ppr name
254 ppr (Unqual occ) = ppr occ
255 ppr (Qual mod occ) = ppr mod <> dot <> ppr occ
256 ppr (Orig mod occ) = getPprStyle (\sty -> pprModulePrefix sty mod occ <> ppr occ)
257
258 instance OutputableBndr RdrName where
259 pprBndr _ n
260 | isTvOcc (rdrNameOcc n) = char '@' <+> ppr n
261 | otherwise = ppr n
262
263 pprInfixOcc rdr = pprInfixVar (isSymOcc (rdrNameOcc rdr)) (ppr rdr)
264 pprPrefixOcc rdr
265 | Just name <- isExact_maybe rdr = pprPrefixName name
266 -- pprPrefixName has some special cases, so
267 -- we delegate to them rather than reproduce them
268 | otherwise = pprPrefixVar (isSymOcc (rdrNameOcc rdr)) (ppr rdr)
269
270 instance Eq RdrName where
271 (Exact n1) == (Exact n2) = n1==n2
272 -- Convert exact to orig
273 (Exact n1) == r2@(Orig _ _) = nukeExact n1 == r2
274 r1@(Orig _ _) == (Exact n2) = r1 == nukeExact n2
275
276 (Orig m1 o1) == (Orig m2 o2) = m1==m2 && o1==o2
277 (Qual m1 o1) == (Qual m2 o2) = m1==m2 && o1==o2
278 (Unqual o1) == (Unqual o2) = o1==o2
279 _ == _ = False
280
281 instance Ord RdrName where
282 a <= b = case (a `compare` b) of { LT -> True; EQ -> True; GT -> False }
283 a < b = case (a `compare` b) of { LT -> True; EQ -> False; GT -> False }
284 a >= b = case (a `compare` b) of { LT -> False; EQ -> True; GT -> True }
285 a > b = case (a `compare` b) of { LT -> False; EQ -> False; GT -> True }
286
287 -- Exact < Unqual < Qual < Orig
288 -- [Note: Apr 2004] We used to use nukeExact to convert Exact to Orig
289 -- before comparing so that Prelude.map == the exact Prelude.map, but
290 -- that meant that we reported duplicates when renaming bindings
291 -- generated by Template Haskell; e.g
292 -- do { n1 <- newName "foo"; n2 <- newName "foo";
293 -- <decl involving n1,n2> }
294 -- I think we can do without this conversion
295 compare (Exact n1) (Exact n2) = n1 `compare` n2
296 compare (Exact _) _ = LT
297
298 compare (Unqual _) (Exact _) = GT
299 compare (Unqual o1) (Unqual o2) = o1 `compare` o2
300 compare (Unqual _) _ = LT
301
302 compare (Qual _ _) (Exact _) = GT
303 compare (Qual _ _) (Unqual _) = GT
304 compare (Qual m1 o1) (Qual m2 o2) = (o1 `compare` o2) `thenCmp` (m1 `compare` m2)
305 compare (Qual _ _) (Orig _ _) = LT
306
307 compare (Orig m1 o1) (Orig m2 o2) = (o1 `compare` o2) `thenCmp` (m1 `compare` m2)
308 compare (Orig _ _) _ = GT
309
310 {-
311 ************************************************************************
312 * *
313 LocalRdrEnv
314 * *
315 ************************************************************************
316 -}
317
318 -- | This environment is used to store local bindings (@let@, @where@, lambda, @case@).
319 -- It is keyed by OccName, because we never use it for qualified names
320 -- We keep the current mapping, *and* the set of all Names in scope
321 -- Reason: see Note [Splicing Exact Names] in RnEnv
322 data LocalRdrEnv = LRE { lre_env :: OccEnv Name
323 , lre_in_scope :: NameSet }
324
325 instance Outputable LocalRdrEnv where
326 ppr (LRE {lre_env = env, lre_in_scope = ns})
327 = hang (ptext (sLit "LocalRdrEnv {"))
328 2 (vcat [ ptext (sLit "env =") <+> pprOccEnv ppr_elt env
329 , ptext (sLit "in_scope =") <+> braces (pprWithCommas ppr (nameSetElems ns))
330 ] <+> char '}')
331 where
332 ppr_elt name = parens (ppr (getUnique (nameOccName name))) <+> ppr name
333 -- So we can see if the keys line up correctly
334
335 emptyLocalRdrEnv :: LocalRdrEnv
336 emptyLocalRdrEnv = LRE { lre_env = emptyOccEnv, lre_in_scope = emptyNameSet }
337
338 extendLocalRdrEnv :: LocalRdrEnv -> Name -> LocalRdrEnv
339 -- The Name should be a non-top-level thing
340 extendLocalRdrEnv (LRE { lre_env = env, lre_in_scope = ns }) name
341 = WARN( isExternalName name, ppr name )
342 LRE { lre_env = extendOccEnv env (nameOccName name) name
343 , lre_in_scope = extendNameSet ns name }
344
345 extendLocalRdrEnvList :: LocalRdrEnv -> [Name] -> LocalRdrEnv
346 extendLocalRdrEnvList (LRE { lre_env = env, lre_in_scope = ns }) names
347 = WARN( any isExternalName names, ppr names )
348 LRE { lre_env = extendOccEnvList env [(nameOccName n, n) | n <- names]
349 , lre_in_scope = extendNameSetList ns names }
350
351 lookupLocalRdrEnv :: LocalRdrEnv -> RdrName -> Maybe Name
352 lookupLocalRdrEnv (LRE { lre_env = env }) (Unqual occ) = lookupOccEnv env occ
353 lookupLocalRdrEnv _ _ = Nothing
354
355 lookupLocalRdrOcc :: LocalRdrEnv -> OccName -> Maybe Name
356 lookupLocalRdrOcc (LRE { lre_env = env }) occ = lookupOccEnv env occ
357
358 elemLocalRdrEnv :: RdrName -> LocalRdrEnv -> Bool
359 elemLocalRdrEnv rdr_name (LRE { lre_env = env, lre_in_scope = ns })
360 = case rdr_name of
361 Unqual occ -> occ `elemOccEnv` env
362 Exact name -> name `elemNameSet` ns -- See Note [Local bindings with Exact Names]
363 Qual {} -> False
364 Orig {} -> False
365
366 localRdrEnvElts :: LocalRdrEnv -> [Name]
367 localRdrEnvElts (LRE { lre_env = env }) = occEnvElts env
368
369 inLocalRdrEnvScope :: Name -> LocalRdrEnv -> Bool
370 -- This is the point of the NameSet
371 inLocalRdrEnvScope name (LRE { lre_in_scope = ns }) = name `elemNameSet` ns
372
373 delLocalRdrEnvList :: LocalRdrEnv -> [OccName] -> LocalRdrEnv
374 delLocalRdrEnvList (LRE { lre_env = env, lre_in_scope = ns }) occs
375 = LRE { lre_env = delListFromOccEnv env occs
376 , lre_in_scope = ns }
377
378 {-
379 Note [Local bindings with Exact Names]
380 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
381 With Template Haskell we can make local bindings that have Exact Names.
382 Computing shadowing etc may use elemLocalRdrEnv (at least it certainly
383 does so in RnTpes.bindHsTyVars), so for an Exact Name we must consult
384 the in-scope-name-set.
385
386
387 ************************************************************************
388 * *
389 GlobalRdrEnv
390 * *
391 ************************************************************************
392 -}
393
394 type GlobalRdrEnv = OccEnv [GlobalRdrElt]
395 -- ^ Keyed by 'OccName'; when looking up a qualified name
396 -- we look up the 'OccName' part, and then check the 'Provenance'
397 -- to see if the appropriate qualification is valid. This
398 -- saves routinely doubling the size of the env by adding both
399 -- qualified and unqualified names to the domain.
400 --
401 -- The list in the codomain is required because there may be name clashes
402 -- These only get reported on lookup, not on construction
403 --
404 -- INVARIANT 1: All the members of the list have distinct
405 -- 'gre_name' fields; that is, no duplicate Names
406 --
407 -- INVARIANT 2: Imported provenance => Name is an ExternalName
408 -- However LocalDefs can have an InternalName. This
409 -- happens only when type-checking a [d| ... |] Template
410 -- Haskell quotation; see this note in RnNames
411 -- Note [Top-level Names in Template Haskell decl quotes]
412
413 -- | An element of the 'GlobalRdrEnv'
414 data GlobalRdrElt
415 = GRE { gre_name :: Name
416 , gre_par :: Parent
417 , gre_lcl :: Bool -- ^ True <=> the thing was defined locally
418 , gre_imp :: [ImportSpec] -- ^ In scope through these imports
419 } -- INVARIANT: either gre_lcl = True or gre_imp is non-empty
420 -- See Note [GlobalRdrElt provenance]
421
422 -- | The children of a Name are the things that are abbreviated by the ".."
423 -- notation in export lists. See Note [Parents]
424 data Parent = NoParent | ParentIs Name
425 deriving (Eq)
426
427 instance Outputable Parent where
428 ppr NoParent = empty
429 ppr (ParentIs n) = ptext (sLit "parent:") <> ppr n
430
431 plusParent :: Parent -> Parent -> Parent
432 -- See Note [Combining parents]
433 plusParent (ParentIs n) p2 = hasParent n p2
434 plusParent p1 (ParentIs n) = hasParent n p1
435 plusParent _ _ = NoParent
436
437 hasParent :: Name -> Parent -> Parent
438 #ifdef DEBUG
439 hasParent n (ParentIs n')
440 | n /= n' = pprPanic "hasParent" (ppr n <+> ppr n') -- Parents should agree
441 #endif
442 hasParent n _ = ParentIs n
443
444 {- Note [GlobalRdrElt provenance]
445 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
446 The gre_lcl and gre_imp fields of a GlobalRdrElt describe its "provenance",
447 i.e. how the Name came to be in scope. It can be in scope two ways:
448 - gre_lcl = True: it is bound in this module
449 - gre_imp: a list of all the imports that brought it into scope
450
451 It's an INVARIANT that you have one or the other; that is, either
452 gre_lcl is True, or gre_imp is non-empty.
453
454 It is just possible to have *both* if there is a module loop: a Name
455 is defined locally in A, and also brought into scope by importing a
456 module that SOURCE-imported A. Exapmle (Trac #7672):
457
458 A.hs-boot module A where
459 data T
460
461 B.hs module B(Decl.T) where
462 import {-# SOURCE #-} qualified A as Decl
463
464 A.hs module A where
465 import qualified B
466 data T = Z | S B.T
467
468 In A.hs, 'T' is locally bound, *and* imported as B.T.
469
470 Note [Parents]
471 ~~~~~~~~~~~~~~~~~
472 Parent Children
473 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
474 data T Data constructors
475 Record-field ids
476
477 data family T Data constructors and record-field ids
478 of all visible data instances of T
479
480 class C Class operations
481 Associated type constructors
482
483 Note [Combining parents]
484 ~~~~~~~~~~~~~~~~~~~~~~~~
485 With an associated type we might have
486 module M where
487 class C a where
488 data T a
489 op :: T a -> a
490 instance C Int where
491 data T Int = TInt
492 instance C Bool where
493 data T Bool = TBool
494
495 Then: C is the parent of T
496 T is the parent of TInt and TBool
497 So: in an export list
498 C(..) is short for C( op, T )
499 T(..) is short for T( TInt, TBool )
500
501 Module M exports everything, so its exports will be
502 AvailTC C [C,T,op]
503 AvailTC T [T,TInt,TBool]
504 On import we convert to GlobalRdrElt and then combine
505 those. For T that will mean we have
506 one GRE with Parent C
507 one GRE with NoParent
508 That's why plusParent picks the "best" case.
509 -}
510
511 -- | make a 'GlobalRdrEnv' where all the elements point to the same
512 -- Provenance (useful for "hiding" imports, or imports with no details).
513 gresFromAvails :: Maybe ImportSpec -> [AvailInfo] -> [GlobalRdrElt]
514 -- prov = Nothing => locally bound
515 -- Just spec => imported as described by spec
516 gresFromAvails prov avails
517 = concatMap (gresFromAvail (const prov)) avails
518
519 localGREsFromAvail :: AvailInfo -> [GlobalRdrElt]
520 -- Turn an Avail into a list of LocalDef GlobalRdrElts
521 localGREsFromAvail = gresFromAvail (const Nothing)
522
523 gresFromAvail :: (Name -> Maybe ImportSpec) -> AvailInfo -> [GlobalRdrElt]
524 gresFromAvail prov_fn avail
525 = map mk_gre (availNames avail)
526 where
527 mk_gre n
528 = case prov_fn n of -- Nothing => bound locally
529 -- Just is => imported from 'is'
530 Nothing -> GRE { gre_name = n, gre_par = mkParent n avail
531 , gre_lcl = True, gre_imp = [] }
532 Just is -> GRE { gre_name = n, gre_par = mkParent n avail
533 , gre_lcl = False, gre_imp = [is] }
534
535 greQualModName :: GlobalRdrElt -> ModuleName
536 -- Get a suitable module qualifier for the GRE
537 -- (used in mkPrintUnqualified)
538 -- Prerecondition: the gre_name is always External
539 greQualModName gre@(GRE { gre_name = name, gre_lcl = lcl, gre_imp = iss })
540 | lcl, Just mod <- nameModule_maybe name = moduleName mod
541 | (is:_) <- iss = is_as (is_decl is)
542 | otherwise = pprPanic "greQualModName" (ppr gre)
543
544 greUsedRdrName :: GlobalRdrElt -> RdrName
545 -- For imported things, return a RdrName to add to the
546 -- used-RdrName set, which is used to generate
547 -- unused-import-decl warnings
548 -- Return an Unqual if possible, otherwise any Qual
549 greUsedRdrName GRE{ gre_name = name, gre_lcl = lcl, gre_imp = iss }
550 | lcl = Unqual occ
551 | not (all (is_qual . is_decl) iss) = Unqual occ
552 | (is:_) <- iss = Qual (is_as (is_decl is)) occ
553 | otherwise = pprPanic "greRdrName" (ppr name)
554 where
555 occ = nameOccName name
556
557 greRdrNames :: GlobalRdrElt -> [RdrName]
558 greRdrNames GRE{ gre_name = name, gre_lcl = lcl, gre_imp = iss }
559 = (if lcl then [unqual] else []) ++ concatMap do_spec (map is_decl iss)
560 where
561 occ = nameOccName name
562 unqual = Unqual occ
563 do_spec decl_spec
564 | is_qual decl_spec = [qual]
565 | otherwise = [unqual,qual]
566 where qual = Qual (is_as decl_spec) occ
567
568 -- the SrcSpan that pprNameProvenance prints out depends on whether
569 -- the Name is defined locally or not: for a local definition the
570 -- definition site is used, otherwise the location of the import
571 -- declaration. We want to sort the export locations in
572 -- exportClashErr by this SrcSpan, we need to extract it:
573 greSrcSpan :: GlobalRdrElt -> SrcSpan
574 greSrcSpan gre@(GRE { gre_name = name, gre_lcl = lcl, gre_imp = iss } )
575 | lcl = nameSrcSpan name
576 | (is:_) <- iss = is_dloc (is_decl is)
577 | otherwise = pprPanic "greSrcSpan" (ppr gre)
578
579 mkParent :: Name -> AvailInfo -> Parent
580 mkParent _ (Avail _) = NoParent
581 mkParent n (AvailTC m _) | n == m = NoParent
582 | otherwise = ParentIs m
583
584 availFromGRE :: GlobalRdrElt -> AvailInfo
585 availFromGRE gre
586 = case gre_par gre of
587 ParentIs p -> AvailTC p [me]
588 NoParent | isTyConName me -> AvailTC me [me]
589 | otherwise -> Avail me
590 where
591 me = gre_name gre
592
593 emptyGlobalRdrEnv :: GlobalRdrEnv
594 emptyGlobalRdrEnv = emptyOccEnv
595
596 globalRdrEnvElts :: GlobalRdrEnv -> [GlobalRdrElt]
597 globalRdrEnvElts env = foldOccEnv (++) [] env
598
599 instance Outputable GlobalRdrElt where
600 ppr gre = hang (ppr (gre_name gre) <+> ppr (gre_par gre))
601 2 (pprNameProvenance gre)
602
603 pprGlobalRdrEnv :: Bool -> GlobalRdrEnv -> SDoc
604 pprGlobalRdrEnv locals_only env
605 = vcat [ ptext (sLit "GlobalRdrEnv") <+> ppWhen locals_only (ptext (sLit "(locals only)"))
606 <+> lbrace
607 , nest 2 (vcat [ pp (remove_locals gre_list) | gre_list <- occEnvElts env ]
608 <+> rbrace) ]
609 where
610 remove_locals gres | locals_only = filter isLocalGRE gres
611 | otherwise = gres
612 pp [] = empty
613 pp gres = hang (ppr occ
614 <+> parens (ptext (sLit "unique") <+> ppr (getUnique occ))
615 <> colon)
616 2 (vcat (map ppr gres))
617 where
618 occ = nameOccName (gre_name (head gres))
619
620 lookupGlobalRdrEnv :: GlobalRdrEnv -> OccName -> [GlobalRdrElt]
621 lookupGlobalRdrEnv env occ_name = case lookupOccEnv env occ_name of
622 Nothing -> []
623 Just gres -> gres
624 lookupGRE_RdrName :: RdrName -> GlobalRdrEnv -> [GlobalRdrElt]
625 lookupGRE_RdrName rdr_name env
626 = case lookupOccEnv env (rdrNameOcc rdr_name) of
627 Nothing -> []
628 Just gres -> pickGREs rdr_name gres
629
630 lookupGRE_Name :: GlobalRdrEnv -> Name -> [GlobalRdrElt]
631 lookupGRE_Name env name
632 = [ gre | gre <- lookupGlobalRdrEnv env (nameOccName name),
633 gre_name gre == name ]
634
635 getGRE_NameQualifier_maybes :: GlobalRdrEnv -> Name -> [Maybe [ModuleName]]
636 -- Returns all the qualifiers by which 'x' is in scope
637 -- Nothing means "the unqualified version is in scope"
638 -- [] means the thing is not in scope at all
639 getGRE_NameQualifier_maybes env
640 = map (qualifier_maybe) . lookupGRE_Name env
641 where
642 qualifier_maybe (GRE { gre_lcl = lcl, gre_imp = iss })
643 | lcl = Nothing
644 | otherwise = Just $ map (is_as . is_decl) iss
645
646 isLocalGRE :: GlobalRdrElt -> Bool
647 isLocalGRE (GRE {gre_lcl = lcl }) = lcl
648
649 unQualOK :: GlobalRdrElt -> Bool
650 -- ^ Test if an unqualifed version of this thing would be in scope
651 unQualOK (GRE {gre_lcl = lcl, gre_imp = iss })
652 | lcl = True
653 | otherwise = any unQualSpecOK iss
654
655 pickGREs :: RdrName -> [GlobalRdrElt] -> [GlobalRdrElt]
656 -- ^ Take a list of GREs which have the right OccName
657 -- Pick those GREs that are suitable for this RdrName
658 -- And for those, keep only only the Provenances that are suitable
659 -- Only used for Qual and Unqual, not Orig or Exact
660 --
661 -- Consider:
662 --
663 -- @
664 -- module A ( f ) where
665 -- import qualified Foo( f )
666 -- import Baz( f )
667 -- f = undefined
668 -- @
669 --
670 -- Let's suppose that @Foo.f@ and @Baz.f@ are the same entity really.
671 -- The export of @f@ is ambiguous because it's in scope from the local def
672 -- and the import. The lookup of @Unqual f@ should return a GRE for
673 -- the locally-defined @f@, and a GRE for the imported @f@, with a /single/
674 -- provenance, namely the one for @Baz(f)@, so that the "ambiguous occurrence"
675 -- message mentions the correct candidates
676 pickGREs rdr_name gres
677 = ASSERT2( isSrcRdrName rdr_name, ppr rdr_name )
678 mapMaybe pick gres
679 where
680 rdr_is_unqual = isUnqual rdr_name
681 rdr_is_qual = isQual_maybe rdr_name
682
683 pick :: GlobalRdrElt -> Maybe GlobalRdrElt
684 pick gre@(GRE { gre_name = n, gre_lcl = lcl, gre_imp = iss })
685 | not lcl' && null iss'
686 = Nothing
687
688 | otherwise
689 = Just (gre { gre_lcl = lcl', gre_imp = iss' })
690
691 where
692 lcl' | not lcl = False
693 | rdr_is_unqual = True
694 | Just (mod,_) <- rdr_is_qual -- Qualified name
695 , Just n_mod <- nameModule_maybe n -- Binder is External
696 = mod == moduleName n_mod
697 | otherwise
698 = False
699
700 iss' | rdr_is_unqual
701 = filter (not . is_qual . is_decl) iss
702 | Just (mod,_) <- rdr_is_qual
703 = filter ((== mod) . is_as . is_decl) iss
704 | otherwise
705 = []
706
707 -- Building GlobalRdrEnvs
708
709 plusGlobalRdrEnv :: GlobalRdrEnv -> GlobalRdrEnv -> GlobalRdrEnv
710 plusGlobalRdrEnv env1 env2 = plusOccEnv_C (foldr insertGRE) env1 env2
711
712 mkGlobalRdrEnv :: [GlobalRdrElt] -> GlobalRdrEnv
713 mkGlobalRdrEnv gres
714 = foldr add emptyGlobalRdrEnv gres
715 where
716 add gre env = extendOccEnv_Acc insertGRE singleton env
717 (nameOccName (gre_name gre))
718 gre
719
720 insertGRE :: GlobalRdrElt -> [GlobalRdrElt] -> [GlobalRdrElt]
721 insertGRE new_g [] = [new_g]
722 insertGRE new_g (old_g : old_gs)
723 | gre_name new_g == gre_name old_g
724 = new_g `plusGRE` old_g : old_gs
725 | otherwise
726 = old_g : insertGRE new_g old_gs
727
728 plusGRE :: GlobalRdrElt -> GlobalRdrElt -> GlobalRdrElt
729 -- Used when the gre_name fields match
730 plusGRE g1 g2
731 = GRE { gre_name = gre_name g1
732 , gre_lcl = gre_lcl g1 || gre_lcl g2
733 , gre_imp = gre_imp g1 ++ gre_imp g2
734 , gre_par = gre_par g1 `plusParent` gre_par g2 }
735
736 transformGREs :: (GlobalRdrElt -> GlobalRdrElt)
737 -> [OccName]
738 -> GlobalRdrEnv -> GlobalRdrEnv
739 -- ^ Apply a transformation function to the GREs for these OccNames
740 transformGREs trans_gre occs rdr_env
741 = foldr trans rdr_env occs
742 where
743 trans occ env
744 = case lookupOccEnv env occ of
745 Just gres -> extendOccEnv env occ (map trans_gre gres)
746 Nothing -> env
747
748 extendGlobalRdrEnv :: GlobalRdrEnv -> GlobalRdrElt -> GlobalRdrEnv
749 extendGlobalRdrEnv env gre
750 = extendOccEnv_Acc insertGRE singleton env
751 (nameOccName (gre_name gre)) gre
752
753 shadowNames :: GlobalRdrEnv -> [Name] -> GlobalRdrEnv
754 shadowNames = foldl shadowName
755
756 {- Note [GlobalRdrEnv shadowing]
757 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
758 Before adding new names to the GlobalRdrEnv we nuke some existing entries;
759 this is "shadowing". The actual work is done by RdrEnv.shadowNames.
760 There are two reasons for shadowing:
761
762 * The GHCi REPL
763
764 - Ids bought into scope on the command line (eg let x = True) have
765 External Names, like Ghci4.x. We want a new binding for 'x' (say)
766 to override the existing binding for 'x'.
767 See Note [Interactively-bound Ids in GHCi] in HscTypes
768
769 - Data types also have Extenal Names, like Ghci4.T; but we still want
770 'T' to mean the newly-declared 'T', not an old one.
771
772 * Nested Template Haskell declaration brackets
773 See Note [Top-level Names in Template Haskell decl quotes] in RnNames
774
775 Consider a TH decl quote:
776 module M where
777 f x = h [d| f = 3 |]
778 We must shadow the outer declaration of 'f', else we'll get a
779 complaint when extending the GlobalRdrEnv, saying that there are two
780 bindings for 'f'. There are several tricky points:
781
782 - This shadowing applies even if the binding for 'f' is in a
783 where-clause, and hence is in the *local* RdrEnv not the *global*
784 RdrEnv. This is done in lcl_env_TH in extendGlobalRdrEnvRn.
785
786 - The External Name M.f from the enclosing module must certainly
787 still be available. So we don't nuke it entirely; we just make
788 it seem like qualified import.
789
790 - We only shadow *External* names (which come from the main module),
791 or from earlier GHCi commands. Do not shadow *Internal* names
792 because in the bracket
793 [d| class C a where f :: a
794 f = 4 |]
795 rnSrcDecls will first call extendGlobalRdrEnvRn with C[f] from the
796 class decl, and *separately* extend the envt with the value binding.
797 At that stage, the class op 'f' will have an Internal name.
798 -}
799
800 shadowName :: GlobalRdrEnv -> Name -> GlobalRdrEnv
801 -- Remove certain old GREs that share the same OccName as this new Name.
802 -- See Note [GlobalRdrEnv shadowing] for details
803 shadowName env name
804 = alterOccEnv (fmap alter_fn) env (nameOccName name)
805 where
806 alter_fn :: [GlobalRdrElt] -> [GlobalRdrElt]
807 alter_fn gres = mapMaybe (shadow_with name) gres
808
809 shadow_with :: Name -> GlobalRdrElt -> Maybe GlobalRdrElt
810 shadow_with new_name
811 old_gre@(GRE { gre_name = old_name, gre_lcl = lcl, gre_imp = iss })
812 = case nameModule_maybe old_name of
813 Nothing -> Just old_gre -- Old name is Internal; do not shadow
814 Just old_mod
815 | Just new_mod <- nameModule_maybe new_name
816 , new_mod == old_mod -- Old name same as new name; shadow completely
817 -> Nothing
818
819 | null iss' -- Nothing remains
820 -> Nothing
821
822 | otherwise
823 -> Just (old_gre { gre_lcl = False, gre_imp = iss' })
824
825 where
826 iss' = lcl_imp ++ mapMaybe (shadow_is new_name) iss
827 lcl_imp | lcl = [mk_fake_imp_spec old_name old_mod]
828 | otherwise = []
829
830 mk_fake_imp_spec old_name old_mod -- Urgh!
831 = ImpSpec id_spec ImpAll
832 where
833 old_mod_name = moduleName old_mod
834 id_spec = ImpDeclSpec { is_mod = old_mod_name
835 , is_as = old_mod_name
836 , is_qual = True
837 , is_dloc = nameSrcSpan old_name }
838
839 shadow_is :: Name -> ImportSpec -> Maybe ImportSpec
840 shadow_is new_name is@(ImpSpec { is_decl = id_spec })
841 | Just new_mod <- nameModule_maybe new_name
842 , is_as id_spec == moduleName new_mod
843 = Nothing -- Shadow both qualified and unqualified
844 | otherwise -- Shadow unqualified only
845 = Just (is { is_decl = id_spec { is_qual = True } })
846
847
848 {-
849 ************************************************************************
850 * *
851 Provenance
852 * *
853 ************************************************************************
854 -}
855
856 -- | The 'ImportSpec' of something says how it came to be imported
857 -- It's quite elaborate so that we can give accurate unused-name warnings.
858 data ImportSpec = ImpSpec { is_decl :: ImpDeclSpec,
859 is_item :: ImpItemSpec }
860 deriving( Eq, Ord )
861
862 -- | Describes a particular import declaration and is
863 -- shared among all the 'Provenance's for that decl
864 data ImpDeclSpec
865 = ImpDeclSpec {
866 is_mod :: ModuleName, -- ^ Module imported, e.g. @import Muggle@
867 -- Note the @Muggle@ may well not be
868 -- the defining module for this thing!
869
870 -- TODO: either should be Module, or there
871 -- should be a Maybe UnitId here too.
872 is_as :: ModuleName, -- ^ Import alias, e.g. from @as M@ (or @Muggle@ if there is no @as@ clause)
873 is_qual :: Bool, -- ^ Was this import qualified?
874 is_dloc :: SrcSpan -- ^ The location of the entire import declaration
875 }
876
877 -- | Describes import info a particular Name
878 data ImpItemSpec
879 = ImpAll -- ^ The import had no import list,
880 -- or had a hiding list
881
882 | ImpSome {
883 is_explicit :: Bool,
884 is_iloc :: SrcSpan -- Location of the import item
885 } -- ^ The import had an import list.
886 -- The 'is_explicit' field is @True@ iff the thing was named
887 -- /explicitly/ in the import specs rather
888 -- than being imported as part of a "..." group. Consider:
889 --
890 -- > import C( T(..) )
891 --
892 -- Here the constructors of @T@ are not named explicitly;
893 -- only @T@ is named explicitly.
894
895 instance Eq ImpDeclSpec where
896 p1 == p2 = case p1 `compare` p2 of EQ -> True; _ -> False
897
898 instance Ord ImpDeclSpec where
899 compare is1 is2 = (is_mod is1 `compare` is_mod is2) `thenCmp`
900 (is_dloc is1 `compare` is_dloc is2)
901
902 instance Eq ImpItemSpec where
903 p1 == p2 = case p1 `compare` p2 of EQ -> True; _ -> False
904
905 instance Ord ImpItemSpec where
906 compare is1 is2 = is_iloc is1 `compare` is_iloc is2
907
908 unQualSpecOK :: ImportSpec -> Bool
909 -- ^ Is in scope unqualified?
910 unQualSpecOK is = not (is_qual (is_decl is))
911
912 qualSpecOK :: ModuleName -> ImportSpec -> Bool
913 -- ^ Is in scope qualified with the given module?
914 qualSpecOK mod is = mod == is_as (is_decl is)
915
916 importSpecLoc :: ImportSpec -> SrcSpan
917 importSpecLoc (ImpSpec decl ImpAll) = is_dloc decl
918 importSpecLoc (ImpSpec _ item) = is_iloc item
919
920 importSpecModule :: ImportSpec -> ModuleName
921 importSpecModule is = is_mod (is_decl is)
922
923 isExplicitItem :: ImpItemSpec -> Bool
924 isExplicitItem ImpAll = False
925 isExplicitItem (ImpSome {is_explicit = exp}) = exp
926
927 {-
928 -- Note [Comparing provenance]
929 -- Comparison of provenance is just used for grouping
930 -- error messages (in RnEnv.warnUnusedBinds)
931 instance Eq Provenance where
932 p1 == p2 = case p1 `compare` p2 of EQ -> True; _ -> False
933
934 instance Ord Provenance where
935 compare (Prov l1 i1) (Prov l2 i2)
936 = (l1 `compare` l2) `thenCmp` (i1 `cmp_is` i2)
937 where -- See Note [Comparing provenance]
938 [] `cmp_is` [] = EQ
939 [] `cmp_is` _ = LT
940 (_:_) `cmp_is` [] = GT
941 (i1:_) `cmp_is` (i2:_) = i1 `compare` i2
942 -}
943
944 pprNameProvenance :: GlobalRdrElt -> SDoc
945 -- ^ Print out one place where the name was define/imported
946 -- (With -dppr-debug, print them all)
947 pprNameProvenance (GRE { gre_name = name, gre_lcl = lcl, gre_imp = iss })
948 | opt_PprStyle_Debug = vcat pp_provs
949 | otherwise = head pp_provs
950 where
951 pp_provs = pp_lcl ++ map pp_is iss
952 pp_lcl = if lcl then [ptext (sLit "defined at") <+> ppr (nameSrcLoc name)]
953 else []
954 pp_is is = sep [ppr is, ppr_defn_site is name]
955
956 -- If we know the exact definition point (which we may do with GHCi)
957 -- then show that too. But not if it's just "imported from X".
958 ppr_defn_site :: ImportSpec -> Name -> SDoc
959 ppr_defn_site imp_spec name
960 | same_module && not (isGoodSrcSpan loc)
961 = empty -- Nothing interesting to say
962 | otherwise
963 = parens $ hang (ptext (sLit "and originally defined") <+> pp_mod)
964 2 (pprLoc loc)
965 where
966 loc = nameSrcSpan name
967 defining_mod = nameModule name
968 same_module = importSpecModule imp_spec == moduleName defining_mod
969 pp_mod | same_module = empty
970 | otherwise = ptext (sLit "in") <+> quotes (ppr defining_mod)
971
972
973 instance Outputable ImportSpec where
974 ppr imp_spec
975 = ptext (sLit "imported") <+> qual
976 <+> ptext (sLit "from") <+> quotes (ppr (importSpecModule imp_spec))
977 <+> pprLoc (importSpecLoc imp_spec)
978 where
979 qual | is_qual (is_decl imp_spec) = ptext (sLit "qualified")
980 | otherwise = empty
981
982 pprLoc :: SrcSpan -> SDoc
983 pprLoc (RealSrcSpan s) = ptext (sLit "at") <+> ppr s
984 pprLoc (UnhelpfulSpan {}) = empty