bc90dafa98ec23752589a6260833a5a881e1cd64
[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, isStar,
38 isUniStar,
39
40 -- * Local mapping of 'RdrName' to 'Name.Name'
41 LocalRdrEnv, emptyLocalRdrEnv, extendLocalRdrEnv, extendLocalRdrEnvList,
42 lookupLocalRdrEnv, lookupLocalRdrOcc,
43 elemLocalRdrEnv, inLocalRdrEnvScope,
44 localRdrEnvElts, delLocalRdrEnvList,
45
46 -- * Global mapping of 'RdrName' to 'GlobalRdrElt's
47 GlobalRdrEnv, emptyGlobalRdrEnv, mkGlobalRdrEnv, plusGlobalRdrEnv,
48 lookupGlobalRdrEnv, extendGlobalRdrEnv, greOccName, shadowNames,
49 pprGlobalRdrEnv, globalRdrEnvElts,
50 lookupGRE_RdrName, lookupGRE_Name, lookupGRE_FieldLabel,
51 lookupGRE_Name_OccName,
52 getGRE_NameQualifier_maybes,
53 transformGREs, pickGREs, pickGREsModExp,
54
55 -- * GlobalRdrElts
56 gresFromAvails, gresFromAvail, localGREsFromAvail, availFromGRE,
57 greUsedRdrName, greRdrNames, greSrcSpan, greQualModName,
58 gresToAvailInfo,
59
60 -- ** Global 'RdrName' mapping elements: 'GlobalRdrElt', 'Provenance', 'ImportSpec'
61 GlobalRdrElt(..), isLocalGRE, isRecFldGRE, greLabel,
62 unQualOK, qualSpecOK, unQualSpecOK,
63 pprNameProvenance,
64 Parent(..),
65 ImportSpec(..), ImpDeclSpec(..), ImpItemSpec(..),
66 importSpecLoc, importSpecModule, isExplicitItem, bestImport
67 ) where
68
69 #include "HsVersions.h"
70
71 import GhcPrelude
72
73 import Module
74 import Name
75 import Avail
76 import NameSet
77 import Maybes
78 import SrcLoc
79 import FastString
80 import FieldLabel
81 import Outputable
82 import Unique
83 import UniqFM
84 import UniqSet
85 import Util
86 import NameEnv
87
88 import Data.Data
89 import Data.List( sortBy, foldl', nub )
90
91 {-
92 ************************************************************************
93 * *
94 \subsection{The main data type}
95 * *
96 ************************************************************************
97 -}
98
99 -- | Reader Name
100 --
101 -- Do not use the data constructors of RdrName directly: prefer the family
102 -- of functions that creates them, such as 'mkRdrUnqual'
103 --
104 -- - Note: A Located RdrName will only have API Annotations if it is a
105 -- compound one,
106 -- e.g.
107 --
108 -- > `bar`
109 -- > ( ~ )
110 --
111 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnType',
112 -- 'ApiAnnotation.AnnOpen' @'('@ or @'['@ or @'[:'@,
113 -- 'ApiAnnotation.AnnClose' @')'@ or @']'@ or @':]'@,,
114 -- 'ApiAnnotation.AnnBackquote' @'`'@,
115 -- 'ApiAnnotation.AnnVal'
116 -- 'ApiAnnotation.AnnTilde',
117
118 -- For details on above see note [Api annotations] in ApiAnnotation
119 data RdrName
120 = Unqual OccName
121 -- ^ Unqualified name
122 --
123 -- Used for ordinary, unqualified occurrences, e.g. @x@, @y@ or @Foo@.
124 -- Create such a 'RdrName' with 'mkRdrUnqual'
125
126 | Qual ModuleName OccName
127 -- ^ Qualified name
128 --
129 -- A qualified name written by the user in
130 -- /source/ code. The module isn't necessarily
131 -- the module where the thing is defined;
132 -- just the one from which it is imported.
133 -- Examples are @Bar.x@, @Bar.y@ or @Bar.Foo@.
134 -- Create such a 'RdrName' with 'mkRdrQual'
135
136 | Orig Module OccName
137 -- ^ Original name
138 --
139 -- An original name; the module is the /defining/ module.
140 -- This is used when GHC generates code that will be fed
141 -- into the renamer (e.g. from deriving clauses), but where
142 -- we want to say \"Use Prelude.map dammit\". One of these
143 -- can be created with 'mkOrig'
144
145 | Exact Name
146 -- ^ Exact name
147 --
148 -- We know exactly the 'Name'. This is used:
149 --
150 -- (1) When the parser parses built-in syntax like @[]@
151 -- and @(,)@, but wants a 'RdrName' from it
152 --
153 -- (2) By Template Haskell, when TH has generated a unique name
154 --
155 -- Such a 'RdrName' can be created by using 'getRdrName' on a 'Name'
156 deriving Data
157
158 {-
159 ************************************************************************
160 * *
161 \subsection{Simple functions}
162 * *
163 ************************************************************************
164 -}
165
166 instance HasOccName RdrName where
167 occName = rdrNameOcc
168
169 rdrNameOcc :: RdrName -> OccName
170 rdrNameOcc (Qual _ occ) = occ
171 rdrNameOcc (Unqual occ) = occ
172 rdrNameOcc (Orig _ occ) = occ
173 rdrNameOcc (Exact name) = nameOccName name
174
175 rdrNameSpace :: RdrName -> NameSpace
176 rdrNameSpace = occNameSpace . rdrNameOcc
177
178 -- demoteRdrName lowers the NameSpace of RdrName.
179 -- see Note [Demotion] in OccName
180 demoteRdrName :: RdrName -> Maybe RdrName
181 demoteRdrName (Unqual occ) = fmap Unqual (demoteOccName occ)
182 demoteRdrName (Qual m occ) = fmap (Qual m) (demoteOccName occ)
183 demoteRdrName (Orig _ _) = panic "demoteRdrName"
184 demoteRdrName (Exact _) = panic "demoteRdrName"
185
186 -- These two are the basic constructors
187 mkRdrUnqual :: OccName -> RdrName
188 mkRdrUnqual occ = Unqual occ
189
190 mkRdrQual :: ModuleName -> OccName -> RdrName
191 mkRdrQual mod occ = Qual mod occ
192
193 mkOrig :: Module -> OccName -> RdrName
194 mkOrig mod occ = Orig mod occ
195
196 ---------------
197 -- These two are used when parsing source files
198 -- They do encode the module and occurrence names
199 mkUnqual :: NameSpace -> FastString -> RdrName
200 mkUnqual sp n = Unqual (mkOccNameFS sp n)
201
202 mkVarUnqual :: FastString -> RdrName
203 mkVarUnqual n = Unqual (mkVarOccFS n)
204
205 -- | Make a qualified 'RdrName' in the given namespace and where the 'ModuleName' and
206 -- the 'OccName' are taken from the first and second elements of the tuple respectively
207 mkQual :: NameSpace -> (FastString, FastString) -> RdrName
208 mkQual sp (m, n) = Qual (mkModuleNameFS m) (mkOccNameFS sp n)
209
210 getRdrName :: NamedThing thing => thing -> RdrName
211 getRdrName name = nameRdrName (getName name)
212
213 nameRdrName :: Name -> RdrName
214 nameRdrName name = Exact name
215 -- Keep the Name even for Internal names, so that the
216 -- unique is still there for debug printing, particularly
217 -- of Types (which are converted to IfaceTypes before printing)
218
219 nukeExact :: Name -> RdrName
220 nukeExact n
221 | isExternalName n = Orig (nameModule n) (nameOccName n)
222 | otherwise = Unqual (nameOccName n)
223
224 isRdrDataCon :: RdrName -> Bool
225 isRdrTyVar :: RdrName -> Bool
226 isRdrTc :: RdrName -> Bool
227
228 isRdrDataCon rn = isDataOcc (rdrNameOcc rn)
229 isRdrTyVar rn = isTvOcc (rdrNameOcc rn)
230 isRdrTc rn = isTcOcc (rdrNameOcc rn)
231
232 isSrcRdrName :: RdrName -> Bool
233 isSrcRdrName (Unqual _) = True
234 isSrcRdrName (Qual _ _) = True
235 isSrcRdrName _ = False
236
237 isUnqual :: RdrName -> Bool
238 isUnqual (Unqual _) = True
239 isUnqual _ = False
240
241 isQual :: RdrName -> Bool
242 isQual (Qual _ _) = True
243 isQual _ = False
244
245 isQual_maybe :: RdrName -> Maybe (ModuleName, OccName)
246 isQual_maybe (Qual m n) = Just (m,n)
247 isQual_maybe _ = Nothing
248
249 isOrig :: RdrName -> Bool
250 isOrig (Orig _ _) = True
251 isOrig _ = False
252
253 isOrig_maybe :: RdrName -> Maybe (Module, OccName)
254 isOrig_maybe (Orig m n) = Just (m,n)
255 isOrig_maybe _ = Nothing
256
257 isExact :: RdrName -> Bool
258 isExact (Exact _) = True
259 isExact _ = False
260
261 isExact_maybe :: RdrName -> Maybe Name
262 isExact_maybe (Exact n) = Just n
263 isExact_maybe _ = Nothing
264
265 isStar, isUniStar :: RdrName -> Bool
266 isStar = (fsLit "*" ==) . occNameFS . rdrNameOcc
267 isUniStar = (fsLit "★" ==) . occNameFS . rdrNameOcc
268
269 {-
270 ************************************************************************
271 * *
272 \subsection{Instances}
273 * *
274 ************************************************************************
275 -}
276
277 instance Outputable RdrName where
278 ppr (Exact name) = ppr name
279 ppr (Unqual occ) = ppr occ
280 ppr (Qual mod occ) = ppr mod <> dot <> ppr occ
281 ppr (Orig mod occ) = getPprStyle (\sty -> pprModulePrefix sty mod occ <> ppr occ)
282
283 instance OutputableBndr RdrName where
284 pprBndr _ n
285 | isTvOcc (rdrNameOcc n) = char '@' <+> ppr n
286 | otherwise = ppr n
287
288 pprInfixOcc rdr = pprInfixVar (isSymOcc (rdrNameOcc rdr)) (ppr rdr)
289 pprPrefixOcc rdr
290 | Just name <- isExact_maybe rdr = pprPrefixName name
291 -- pprPrefixName has some special cases, so
292 -- we delegate to them rather than reproduce them
293 | otherwise = pprPrefixVar (isSymOcc (rdrNameOcc rdr)) (ppr rdr)
294
295 instance Eq RdrName where
296 (Exact n1) == (Exact n2) = n1==n2
297 -- Convert exact to orig
298 (Exact n1) == r2@(Orig _ _) = nukeExact n1 == r2
299 r1@(Orig _ _) == (Exact n2) = r1 == nukeExact n2
300
301 (Orig m1 o1) == (Orig m2 o2) = m1==m2 && o1==o2
302 (Qual m1 o1) == (Qual m2 o2) = m1==m2 && o1==o2
303 (Unqual o1) == (Unqual o2) = o1==o2
304 _ == _ = False
305
306 instance Ord RdrName where
307 a <= b = case (a `compare` b) of { LT -> True; EQ -> True; GT -> False }
308 a < b = case (a `compare` b) of { LT -> True; EQ -> False; GT -> False }
309 a >= b = case (a `compare` b) of { LT -> False; EQ -> True; GT -> True }
310 a > b = case (a `compare` b) of { LT -> False; EQ -> False; GT -> True }
311
312 -- Exact < Unqual < Qual < Orig
313 -- [Note: Apr 2004] We used to use nukeExact to convert Exact to Orig
314 -- before comparing so that Prelude.map == the exact Prelude.map, but
315 -- that meant that we reported duplicates when renaming bindings
316 -- generated by Template Haskell; e.g
317 -- do { n1 <- newName "foo"; n2 <- newName "foo";
318 -- <decl involving n1,n2> }
319 -- I think we can do without this conversion
320 compare (Exact n1) (Exact n2) = n1 `compare` n2
321 compare (Exact _) _ = LT
322
323 compare (Unqual _) (Exact _) = GT
324 compare (Unqual o1) (Unqual o2) = o1 `compare` o2
325 compare (Unqual _) _ = LT
326
327 compare (Qual _ _) (Exact _) = GT
328 compare (Qual _ _) (Unqual _) = GT
329 compare (Qual m1 o1) (Qual m2 o2) = (o1 `compare` o2) `thenCmp` (m1 `compare` m2)
330 compare (Qual _ _) (Orig _ _) = LT
331
332 compare (Orig m1 o1) (Orig m2 o2) = (o1 `compare` o2) `thenCmp` (m1 `compare` m2)
333 compare (Orig _ _) _ = GT
334
335 {-
336 ************************************************************************
337 * *
338 LocalRdrEnv
339 * *
340 ************************************************************************
341 -}
342
343 -- | Local Reader Environment
344 --
345 -- This environment is used to store local bindings
346 -- (@let@, @where@, lambda, @case@).
347 -- It is keyed by OccName, because we never use it for qualified names
348 -- We keep the current mapping, *and* the set of all Names in scope
349 -- Reason: see Note [Splicing Exact names] in RnEnv
350 data LocalRdrEnv = LRE { lre_env :: OccEnv Name
351 , lre_in_scope :: NameSet }
352
353 instance Outputable LocalRdrEnv where
354 ppr (LRE {lre_env = env, lre_in_scope = ns})
355 = hang (text "LocalRdrEnv {")
356 2 (vcat [ text "env =" <+> pprOccEnv ppr_elt env
357 , text "in_scope ="
358 <+> pprUFM (getUniqSet ns) (braces . pprWithCommas ppr)
359 ] <+> char '}')
360 where
361 ppr_elt name = parens (ppr (getUnique (nameOccName name))) <+> ppr name
362 -- So we can see if the keys line up correctly
363
364 emptyLocalRdrEnv :: LocalRdrEnv
365 emptyLocalRdrEnv = LRE { lre_env = emptyOccEnv
366 , lre_in_scope = emptyNameSet }
367
368 extendLocalRdrEnv :: LocalRdrEnv -> Name -> LocalRdrEnv
369 -- The Name should be a non-top-level thing
370 extendLocalRdrEnv lre@(LRE { lre_env = env, lre_in_scope = ns }) name
371 = WARN( isExternalName name, ppr name )
372 lre { lre_env = extendOccEnv env (nameOccName name) name
373 , lre_in_scope = extendNameSet ns name }
374
375 extendLocalRdrEnvList :: LocalRdrEnv -> [Name] -> LocalRdrEnv
376 extendLocalRdrEnvList lre@(LRE { lre_env = env, lre_in_scope = ns }) names
377 = WARN( any isExternalName names, ppr names )
378 lre { lre_env = extendOccEnvList env [(nameOccName n, n) | n <- names]
379 , lre_in_scope = extendNameSetList ns names }
380
381 lookupLocalRdrEnv :: LocalRdrEnv -> RdrName -> Maybe Name
382 lookupLocalRdrEnv (LRE { lre_env = env, lre_in_scope = ns }) rdr
383 | Unqual occ <- rdr
384 = lookupOccEnv env occ
385
386 -- See Note [Local bindings with Exact Names]
387 | Exact name <- rdr
388 , name `elemNameSet` ns
389 = Just name
390
391 | otherwise
392 = Nothing
393
394 lookupLocalRdrOcc :: LocalRdrEnv -> OccName -> Maybe Name
395 lookupLocalRdrOcc (LRE { lre_env = env }) occ = lookupOccEnv env occ
396
397 elemLocalRdrEnv :: RdrName -> LocalRdrEnv -> Bool
398 elemLocalRdrEnv rdr_name (LRE { lre_env = env, lre_in_scope = ns })
399 = case rdr_name of
400 Unqual occ -> occ `elemOccEnv` env
401 Exact name -> name `elemNameSet` ns -- See Note [Local bindings with Exact Names]
402 Qual {} -> False
403 Orig {} -> False
404
405 localRdrEnvElts :: LocalRdrEnv -> [Name]
406 localRdrEnvElts (LRE { lre_env = env }) = occEnvElts env
407
408 inLocalRdrEnvScope :: Name -> LocalRdrEnv -> Bool
409 -- This is the point of the NameSet
410 inLocalRdrEnvScope name (LRE { lre_in_scope = ns }) = name `elemNameSet` ns
411
412 delLocalRdrEnvList :: LocalRdrEnv -> [OccName] -> LocalRdrEnv
413 delLocalRdrEnvList lre@(LRE { lre_env = env }) occs
414 = lre { lre_env = delListFromOccEnv env occs }
415
416 {-
417 Note [Local bindings with Exact Names]
418 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
419 With Template Haskell we can make local bindings that have Exact Names.
420 Computing shadowing etc may use elemLocalRdrEnv (at least it certainly
421 does so in RnTpes.bindHsQTyVars), so for an Exact Name we must consult
422 the in-scope-name-set.
423
424
425 ************************************************************************
426 * *
427 GlobalRdrEnv
428 * *
429 ************************************************************************
430 -}
431
432 -- | Global Reader Environment
433 type GlobalRdrEnv = OccEnv [GlobalRdrElt]
434 -- ^ Keyed by 'OccName'; when looking up a qualified name
435 -- we look up the 'OccName' part, and then check the 'Provenance'
436 -- to see if the appropriate qualification is valid. This
437 -- saves routinely doubling the size of the env by adding both
438 -- qualified and unqualified names to the domain.
439 --
440 -- The list in the codomain is required because there may be name clashes
441 -- These only get reported on lookup, not on construction
442 --
443 -- INVARIANT 1: All the members of the list have distinct
444 -- 'gre_name' fields; that is, no duplicate Names
445 --
446 -- INVARIANT 2: Imported provenance => Name is an ExternalName
447 -- However LocalDefs can have an InternalName. This
448 -- happens only when type-checking a [d| ... |] Template
449 -- Haskell quotation; see this note in RnNames
450 -- Note [Top-level Names in Template Haskell decl quotes]
451 --
452 -- INVARIANT 3: If the GlobalRdrEnv maps [occ -> gre], then
453 -- greOccName gre = occ
454 --
455 -- NB: greOccName gre is usually the same as
456 -- nameOccName (gre_name gre), but not always in the
457 -- case of record seectors; see greOccName
458
459 -- | Global Reader Element
460 --
461 -- An element of the 'GlobalRdrEnv'
462 data GlobalRdrElt
463 = GRE { gre_name :: Name
464 , gre_par :: Parent
465 , gre_lcl :: Bool -- ^ True <=> the thing was defined locally
466 , gre_imp :: [ImportSpec] -- ^ In scope through these imports
467 } deriving (Data, Eq)
468 -- INVARIANT: either gre_lcl = True or gre_imp is non-empty
469 -- See Note [GlobalRdrElt provenance]
470
471 -- | The children of a Name are the things that are abbreviated by the ".."
472 -- notation in export lists. See Note [Parents]
473 data Parent = NoParent
474 | ParentIs { par_is :: Name }
475 | FldParent { par_is :: Name, par_lbl :: Maybe FieldLabelString }
476 -- ^ See Note [Parents for record fields]
477 deriving (Eq, Data)
478
479 instance Outputable Parent where
480 ppr NoParent = empty
481 ppr (ParentIs n) = text "parent:" <> ppr n
482 ppr (FldParent n f) = text "fldparent:"
483 <> ppr n <> colon <> ppr f
484
485 plusParent :: Parent -> Parent -> Parent
486 -- See Note [Combining parents]
487 plusParent p1@(ParentIs _) p2 = hasParent p1 p2
488 plusParent p1@(FldParent _ _) p2 = hasParent p1 p2
489 plusParent p1 p2@(ParentIs _) = hasParent p2 p1
490 plusParent p1 p2@(FldParent _ _) = hasParent p2 p1
491 plusParent _ _ = NoParent
492
493 hasParent :: Parent -> Parent -> Parent
494 #if defined(DEBUG)
495 hasParent p NoParent = p
496 hasParent p p'
497 | p /= p' = pprPanic "hasParent" (ppr p <+> ppr p') -- Parents should agree
498 #endif
499 hasParent p _ = p
500
501
502 {- Note [GlobalRdrElt provenance]
503 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
504 The gre_lcl and gre_imp fields of a GlobalRdrElt describe its "provenance",
505 i.e. how the Name came to be in scope. It can be in scope two ways:
506 - gre_lcl = True: it is bound in this module
507 - gre_imp: a list of all the imports that brought it into scope
508
509 It's an INVARIANT that you have one or the other; that is, either
510 gre_lcl is True, or gre_imp is non-empty.
511
512 It is just possible to have *both* if there is a module loop: a Name
513 is defined locally in A, and also brought into scope by importing a
514 module that SOURCE-imported A. Exapmle (Trac #7672):
515
516 A.hs-boot module A where
517 data T
518
519 B.hs module B(Decl.T) where
520 import {-# SOURCE #-} qualified A as Decl
521
522 A.hs module A where
523 import qualified B
524 data T = Z | S B.T
525
526 In A.hs, 'T' is locally bound, *and* imported as B.T.
527
528 Note [Parents]
529 ~~~~~~~~~~~~~~~~~
530 Parent Children
531 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
532 data T Data constructors
533 Record-field ids
534
535 data family T Data constructors and record-field ids
536 of all visible data instances of T
537
538 class C Class operations
539 Associated type constructors
540
541 ~~~~~~~~~~~~~~~~~~~~~~~~~
542 Constructor Meaning
543 ~~~~~~~~~~~~~~~~~~~~~~~~
544 NoParent Can not be bundled with a type constructor.
545 ParentIs n Can be bundled with the type constructor corresponding to
546 n.
547 FldParent See Note [Parents for record fields]
548
549
550
551
552 Note [Parents for record fields]
553 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
554 For record fields, in addition to the Name of the type constructor
555 (stored in par_is), we use FldParent to store the field label. This
556 extra information is used for identifying overloaded record fields
557 during renaming.
558
559 In a definition arising from a normal module (without
560 -XDuplicateRecordFields), par_lbl will be Nothing, meaning that the
561 field's label is the same as the OccName of the selector's Name. The
562 GlobalRdrEnv will contain an entry like this:
563
564 "x" |-> GRE x (FldParent T Nothing) LocalDef
565
566 When -XDuplicateRecordFields is enabled for the module that contains
567 T, the selector's Name will be mangled (see comments in FieldLabel).
568 Thus we store the actual field label in par_lbl, and the GlobalRdrEnv
569 entry looks like this:
570
571 "x" |-> GRE $sel:x:MkT (FldParent T (Just "x")) LocalDef
572
573 Note that the OccName used when adding a GRE to the environment
574 (greOccName) now depends on the parent field: for FldParent it is the
575 field label, if present, rather than the selector name.
576
577 ~~
578
579 Record pattern synonym selectors are treated differently. Their parent
580 information is `NoParent` in the module in which they are defined. This is because
581 a pattern synonym `P` has no parent constructor either.
582
583 However, if `f` is bundled with a type constructor `T` then whenever `f` is
584 imported the parent will use the `Parent` constructor so the parent of `f` is
585 now `T`.
586
587
588 Note [Combining parents]
589 ~~~~~~~~~~~~~~~~~~~~~~~~
590 With an associated type we might have
591 module M where
592 class C a where
593 data T a
594 op :: T a -> a
595 instance C Int where
596 data T Int = TInt
597 instance C Bool where
598 data T Bool = TBool
599
600 Then: C is the parent of T
601 T is the parent of TInt and TBool
602 So: in an export list
603 C(..) is short for C( op, T )
604 T(..) is short for T( TInt, TBool )
605
606 Module M exports everything, so its exports will be
607 AvailTC C [C,T,op]
608 AvailTC T [T,TInt,TBool]
609 On import we convert to GlobalRdrElt and then combine
610 those. For T that will mean we have
611 one GRE with Parent C
612 one GRE with NoParent
613 That's why plusParent picks the "best" case.
614 -}
615
616 -- | make a 'GlobalRdrEnv' where all the elements point to the same
617 -- Provenance (useful for "hiding" imports, or imports with no details).
618 gresFromAvails :: Maybe ImportSpec -> [AvailInfo] -> [GlobalRdrElt]
619 -- prov = Nothing => locally bound
620 -- Just spec => imported as described by spec
621 gresFromAvails prov avails
622 = concatMap (gresFromAvail (const prov)) avails
623
624 localGREsFromAvail :: AvailInfo -> [GlobalRdrElt]
625 -- Turn an Avail into a list of LocalDef GlobalRdrElts
626 localGREsFromAvail = gresFromAvail (const Nothing)
627
628 gresFromAvail :: (Name -> Maybe ImportSpec) -> AvailInfo -> [GlobalRdrElt]
629 gresFromAvail prov_fn avail
630 = map mk_gre (availNonFldNames avail) ++ map mk_fld_gre (availFlds avail)
631 where
632 mk_gre n
633 = case prov_fn n of -- Nothing => bound locally
634 -- Just is => imported from 'is'
635 Nothing -> GRE { gre_name = n, gre_par = mkParent n avail
636 , gre_lcl = True, gre_imp = [] }
637 Just is -> GRE { gre_name = n, gre_par = mkParent n avail
638 , gre_lcl = False, gre_imp = [is] }
639
640 mk_fld_gre (FieldLabel { flLabel = lbl, flIsOverloaded = is_overloaded
641 , flSelector = n })
642 = case prov_fn n of -- Nothing => bound locally
643 -- Just is => imported from 'is'
644 Nothing -> GRE { gre_name = n, gre_par = FldParent (availName avail) mb_lbl
645 , gre_lcl = True, gre_imp = [] }
646 Just is -> GRE { gre_name = n, gre_par = FldParent (availName avail) mb_lbl
647 , gre_lcl = False, gre_imp = [is] }
648 where
649 mb_lbl | is_overloaded = Just lbl
650 | otherwise = Nothing
651
652
653 greQualModName :: GlobalRdrElt -> ModuleName
654 -- Get a suitable module qualifier for the GRE
655 -- (used in mkPrintUnqualified)
656 -- Prerecondition: the gre_name is always External
657 greQualModName gre@(GRE { gre_name = name, gre_lcl = lcl, gre_imp = iss })
658 | lcl, Just mod <- nameModule_maybe name = moduleName mod
659 | (is:_) <- iss = is_as (is_decl is)
660 | otherwise = pprPanic "greQualModName" (ppr gre)
661
662 greUsedRdrName :: GlobalRdrElt -> RdrName
663 -- For imported things, return a RdrName to add to the used-RdrName
664 -- set, which is used to generate unused-import-decl warnings.
665 -- Return a Qual RdrName if poss, so that identifies the most
666 -- specific ImportSpec. See Trac #10890 for some good examples.
667 greUsedRdrName gre@GRE{ gre_name = name, gre_lcl = lcl, gre_imp = iss }
668 | lcl, Just mod <- nameModule_maybe name = Qual (moduleName mod) occ
669 | not (null iss), is <- bestImport iss = Qual (is_as (is_decl is)) occ
670 | otherwise = pprTrace "greUsedRdrName" (ppr gre) (Unqual occ)
671 where
672 occ = greOccName gre
673
674 greRdrNames :: GlobalRdrElt -> [RdrName]
675 greRdrNames gre@GRE{ gre_lcl = lcl, gre_imp = iss }
676 = (if lcl then [unqual] else []) ++ concatMap do_spec (map is_decl iss)
677 where
678 occ = greOccName gre
679 unqual = Unqual occ
680 do_spec decl_spec
681 | is_qual decl_spec = [qual]
682 | otherwise = [unqual,qual]
683 where qual = Qual (is_as decl_spec) occ
684
685 -- the SrcSpan that pprNameProvenance prints out depends on whether
686 -- the Name is defined locally or not: for a local definition the
687 -- definition site is used, otherwise the location of the import
688 -- declaration. We want to sort the export locations in
689 -- exportClashErr by this SrcSpan, we need to extract it:
690 greSrcSpan :: GlobalRdrElt -> SrcSpan
691 greSrcSpan gre@(GRE { gre_name = name, gre_lcl = lcl, gre_imp = iss } )
692 | lcl = nameSrcSpan name
693 | (is:_) <- iss = is_dloc (is_decl is)
694 | otherwise = pprPanic "greSrcSpan" (ppr gre)
695
696 mkParent :: Name -> AvailInfo -> Parent
697 mkParent _ (Avail _) = NoParent
698 mkParent n (AvailTC m _ _) | n == m = NoParent
699 | otherwise = ParentIs m
700
701 greParentName :: GlobalRdrElt -> Maybe Name
702 greParentName gre = case gre_par gre of
703 NoParent -> Nothing
704 ParentIs n -> Just n
705 FldParent n _ -> Just n
706
707 -- | Takes a list of distinct GREs and folds them
708 -- into AvailInfos. This is more efficient than mapping each individual
709 -- GRE to an AvailInfo and the folding using `plusAvail` but needs the
710 -- uniqueness assumption.
711 gresToAvailInfo :: [GlobalRdrElt] -> [AvailInfo]
712 gresToAvailInfo gres
713 = ASSERT( nub gres == gres ) nameEnvElts avail_env
714 where
715 avail_env :: NameEnv AvailInfo -- keyed by the parent
716 avail_env = foldl' add emptyNameEnv gres
717
718 add :: NameEnv AvailInfo -> GlobalRdrElt -> NameEnv AvailInfo
719 add env gre = extendNameEnv_Acc comb availFromGRE env
720 (fromMaybe (gre_name gre)
721 (greParentName gre)) gre
722
723 where
724 -- We want to insert the child `k` into a list of children but
725 -- need to maintain the invariant that the parent is first.
726 --
727 -- We also use the invariant that `k` is not already in `ns`.
728 insertChildIntoChildren :: Name -> [Name] -> Name -> [Name]
729 insertChildIntoChildren _ [] k = [k]
730 insertChildIntoChildren p (n:ns) k
731 | p == k = k:n:ns
732 | otherwise = n:k:ns
733
734 comb :: GlobalRdrElt -> AvailInfo -> AvailInfo
735 comb _ (Avail n) = Avail n -- Duplicated name
736 comb gre (AvailTC m ns fls) =
737 let n = gre_name gre
738 in case gre_par gre of
739 NoParent -> AvailTC m (n:ns) fls -- Not sure this ever happens
740 ParentIs {} -> AvailTC m (insertChildIntoChildren m ns n) fls
741 FldParent _ mb_lbl -> AvailTC m ns (mkFieldLabel n mb_lbl : fls)
742
743 availFromGRE :: GlobalRdrElt -> AvailInfo
744 availFromGRE (GRE { gre_name = me, gre_par = parent })
745 = case parent of
746 ParentIs p -> AvailTC p [me] []
747 NoParent | isTyConName me -> AvailTC me [me] []
748 | otherwise -> avail me
749 FldParent p mb_lbl -> AvailTC p [] [mkFieldLabel me mb_lbl]
750
751 mkFieldLabel :: Name -> Maybe FastString -> FieldLabel
752 mkFieldLabel me mb_lbl =
753 case mb_lbl of
754 Nothing -> FieldLabel { flLabel = occNameFS (nameOccName me)
755 , flIsOverloaded = False
756 , flSelector = me }
757 Just lbl -> FieldLabel { flLabel = lbl
758 , flIsOverloaded = True
759 , flSelector = me }
760
761 emptyGlobalRdrEnv :: GlobalRdrEnv
762 emptyGlobalRdrEnv = emptyOccEnv
763
764 globalRdrEnvElts :: GlobalRdrEnv -> [GlobalRdrElt]
765 globalRdrEnvElts env = foldOccEnv (++) [] env
766
767 instance Outputable GlobalRdrElt where
768 ppr gre = hang (ppr (gre_name gre) <+> ppr (gre_par gre))
769 2 (pprNameProvenance gre)
770
771 pprGlobalRdrEnv :: Bool -> GlobalRdrEnv -> SDoc
772 pprGlobalRdrEnv locals_only env
773 = vcat [ text "GlobalRdrEnv" <+> ppWhen locals_only (ptext (sLit "(locals only)"))
774 <+> lbrace
775 , nest 2 (vcat [ pp (remove_locals gre_list) | gre_list <- occEnvElts env ]
776 <+> rbrace) ]
777 where
778 remove_locals gres | locals_only = filter isLocalGRE gres
779 | otherwise = gres
780 pp [] = empty
781 pp gres = hang (ppr occ
782 <+> parens (text "unique" <+> ppr (getUnique occ))
783 <> colon)
784 2 (vcat (map ppr gres))
785 where
786 occ = nameOccName (gre_name (head gres))
787
788 lookupGlobalRdrEnv :: GlobalRdrEnv -> OccName -> [GlobalRdrElt]
789 lookupGlobalRdrEnv env occ_name = case lookupOccEnv env occ_name of
790 Nothing -> []
791 Just gres -> gres
792
793 greOccName :: GlobalRdrElt -> OccName
794 greOccName (GRE{gre_par = FldParent{par_lbl = Just lbl}}) = mkVarOccFS lbl
795 greOccName gre = nameOccName (gre_name gre)
796
797 lookupGRE_RdrName :: RdrName -> GlobalRdrEnv -> [GlobalRdrElt]
798 lookupGRE_RdrName rdr_name env
799 = case lookupOccEnv env (rdrNameOcc rdr_name) of
800 Nothing -> []
801 Just gres -> pickGREs rdr_name gres
802
803 lookupGRE_Name :: GlobalRdrEnv -> Name -> Maybe GlobalRdrElt
804 -- ^ Look for precisely this 'Name' in the environment. This tests
805 -- whether it is in scope, ignoring anything else that might be in
806 -- scope with the same 'OccName'.
807 lookupGRE_Name env name
808 = lookupGRE_Name_OccName env name (nameOccName name)
809
810 lookupGRE_FieldLabel :: GlobalRdrEnv -> FieldLabel -> Maybe GlobalRdrElt
811 -- ^ Look for a particular record field selector in the environment, where the
812 -- selector name and field label may be different: the GlobalRdrEnv is keyed on
813 -- the label. See Note [Parents for record fields] for why this happens.
814 lookupGRE_FieldLabel env fl
815 = lookupGRE_Name_OccName env (flSelector fl) (mkVarOccFS (flLabel fl))
816
817 lookupGRE_Name_OccName :: GlobalRdrEnv -> Name -> OccName -> Maybe GlobalRdrElt
818 -- ^ Look for precisely this 'Name' in the environment, but with an 'OccName'
819 -- that might differ from that of the 'Name'. See 'lookupGRE_FieldLabel' and
820 -- Note [Parents for record fields].
821 lookupGRE_Name_OccName env name occ
822 = case [ gre | gre <- lookupGlobalRdrEnv env occ
823 , gre_name gre == name ] of
824 [] -> Nothing
825 [gre] -> Just gre
826 gres -> pprPanic "lookupGRE_Name_OccName"
827 (ppr name $$ ppr occ $$ ppr gres)
828 -- See INVARIANT 1 on GlobalRdrEnv
829
830
831 getGRE_NameQualifier_maybes :: GlobalRdrEnv -> Name -> [Maybe [ModuleName]]
832 -- Returns all the qualifiers by which 'x' is in scope
833 -- Nothing means "the unqualified version is in scope"
834 -- [] means the thing is not in scope at all
835 getGRE_NameQualifier_maybes env name
836 = case lookupGRE_Name env name of
837 Just gre -> [qualifier_maybe gre]
838 Nothing -> []
839 where
840 qualifier_maybe (GRE { gre_lcl = lcl, gre_imp = iss })
841 | lcl = Nothing
842 | otherwise = Just $ map (is_as . is_decl) iss
843
844 isLocalGRE :: GlobalRdrElt -> Bool
845 isLocalGRE (GRE {gre_lcl = lcl }) = lcl
846
847 isRecFldGRE :: GlobalRdrElt -> Bool
848 isRecFldGRE (GRE {gre_par = FldParent{}}) = True
849 isRecFldGRE _ = False
850
851 -- Returns the field label of this GRE, if it has one
852 greLabel :: GlobalRdrElt -> Maybe FieldLabelString
853 greLabel (GRE{gre_par = FldParent{par_lbl = Just lbl}}) = Just lbl
854 greLabel (GRE{gre_name = n, gre_par = FldParent{}}) = Just (occNameFS (nameOccName n))
855 greLabel _ = Nothing
856
857 unQualOK :: GlobalRdrElt -> Bool
858 -- ^ Test if an unqualified version of this thing would be in scope
859 unQualOK (GRE {gre_lcl = lcl, gre_imp = iss })
860 | lcl = True
861 | otherwise = any unQualSpecOK iss
862
863 {- Note [GRE filtering]
864 ~~~~~~~~~~~~~~~~~~~~~~~
865 (pickGREs rdr gres) takes a list of GREs which have the same OccName
866 as 'rdr', say "x". It does two things:
867
868 (a) filters the GREs to a subset that are in scope
869 * Qualified, as 'M.x' if want_qual is Qual M _
870 * Unqualified, as 'x' if want_unqual is Unqual _
871
872 (b) for that subset, filter the provenance field (gre_lcl and gre_imp)
873 to ones that brought it into scope qualified or unqualified resp.
874
875 Example:
876 module A ( f ) where
877 import qualified Foo( f )
878 import Baz( f )
879 f = undefined
880
881 Let's suppose that Foo.f and Baz.f are the same entity really, but the local
882 'f' is different, so there will be two GREs matching "f":
883 gre1: gre_lcl = True, gre_imp = []
884 gre2: gre_lcl = False, gre_imp = [ imported from Foo, imported from Bar ]
885
886 The use of "f" in the export list is ambiguous because it's in scope
887 from the local def and the import Baz(f); but *not* the import qualified Foo.
888 pickGREs returns two GRE
889 gre1: gre_lcl = True, gre_imp = []
890 gre2: gre_lcl = False, gre_imp = [ imported from Bar ]
891
892 Now the "ambiguous occurrence" message can correctly report how the
893 ambiguity arises.
894 -}
895
896 pickGREs :: RdrName -> [GlobalRdrElt] -> [GlobalRdrElt]
897 -- ^ Takes a list of GREs which have the right OccName 'x'
898 -- Pick those GREs that are in scope
899 -- * Qualified, as 'M.x' if want_qual is Qual M _
900 -- * Unqualified, as 'x' if want_unqual is Unqual _
901 --
902 -- Return each such GRE, with its ImportSpecs filtered, to reflect
903 -- how it is in scope qualified or unqualified respectively.
904 -- See Note [GRE filtering]
905 pickGREs (Unqual {}) gres = mapMaybe pickUnqualGRE gres
906 pickGREs (Qual mod _) gres = mapMaybe (pickQualGRE mod) gres
907 pickGREs _ _ = [] -- I don't think this actually happens
908
909 pickUnqualGRE :: GlobalRdrElt -> Maybe GlobalRdrElt
910 pickUnqualGRE gre@(GRE { gre_lcl = lcl, gre_imp = iss })
911 | not lcl, null iss' = Nothing
912 | otherwise = Just (gre { gre_imp = iss' })
913 where
914 iss' = filter unQualSpecOK iss
915
916 pickQualGRE :: ModuleName -> GlobalRdrElt -> Maybe GlobalRdrElt
917 pickQualGRE mod gre@(GRE { gre_name = n, gre_lcl = lcl, gre_imp = iss })
918 | not lcl', null iss' = Nothing
919 | otherwise = Just (gre { gre_lcl = lcl', gre_imp = iss' })
920 where
921 iss' = filter (qualSpecOK mod) iss
922 lcl' = lcl && name_is_from mod n
923
924 name_is_from :: ModuleName -> Name -> Bool
925 name_is_from mod name = case nameModule_maybe name of
926 Just n_mod -> moduleName n_mod == mod
927 Nothing -> False
928
929 pickGREsModExp :: ModuleName -> [GlobalRdrElt] -> [(GlobalRdrElt,GlobalRdrElt)]
930 -- ^ Pick GREs that are in scope *both* qualified *and* unqualified
931 -- Return each GRE that is, as a pair
932 -- (qual_gre, unqual_gre)
933 -- These two GREs are the original GRE with imports filtered to express how
934 -- it is in scope qualified an unqualified respectively
935 --
936 -- Used only for the 'module M' item in export list;
937 -- see RnNames.exports_from_avail
938 pickGREsModExp mod gres = mapMaybe (pickBothGRE mod) gres
939
940 pickBothGRE :: ModuleName -> GlobalRdrElt -> Maybe (GlobalRdrElt, GlobalRdrElt)
941 pickBothGRE mod gre@(GRE { gre_name = n })
942 | isBuiltInSyntax n = Nothing
943 | Just gre1 <- pickQualGRE mod gre
944 , Just gre2 <- pickUnqualGRE gre = Just (gre1, gre2)
945 | otherwise = Nothing
946 where
947 -- isBuiltInSyntax filter out names for built-in syntax They
948 -- just clutter up the environment (esp tuples), and the
949 -- parser will generate Exact RdrNames for them, so the
950 -- cluttered envt is no use. Really, it's only useful for
951 -- GHC.Base and GHC.Tuple.
952
953 -- Building GlobalRdrEnvs
954
955 plusGlobalRdrEnv :: GlobalRdrEnv -> GlobalRdrEnv -> GlobalRdrEnv
956 plusGlobalRdrEnv env1 env2 = plusOccEnv_C (foldr insertGRE) env1 env2
957
958 mkGlobalRdrEnv :: [GlobalRdrElt] -> GlobalRdrEnv
959 mkGlobalRdrEnv gres
960 = foldr add emptyGlobalRdrEnv gres
961 where
962 add gre env = extendOccEnv_Acc insertGRE singleton env
963 (greOccName gre)
964 gre
965
966 insertGRE :: GlobalRdrElt -> [GlobalRdrElt] -> [GlobalRdrElt]
967 insertGRE new_g [] = [new_g]
968 insertGRE new_g (old_g : old_gs)
969 | gre_name new_g == gre_name old_g
970 = new_g `plusGRE` old_g : old_gs
971 | otherwise
972 = old_g : insertGRE new_g old_gs
973
974 plusGRE :: GlobalRdrElt -> GlobalRdrElt -> GlobalRdrElt
975 -- Used when the gre_name fields match
976 plusGRE g1 g2
977 = GRE { gre_name = gre_name g1
978 , gre_lcl = gre_lcl g1 || gre_lcl g2
979 , gre_imp = gre_imp g1 ++ gre_imp g2
980 , gre_par = gre_par g1 `plusParent` gre_par g2 }
981
982 transformGREs :: (GlobalRdrElt -> GlobalRdrElt)
983 -> [OccName]
984 -> GlobalRdrEnv -> GlobalRdrEnv
985 -- ^ Apply a transformation function to the GREs for these OccNames
986 transformGREs trans_gre occs rdr_env
987 = foldr trans rdr_env occs
988 where
989 trans occ env
990 = case lookupOccEnv env occ of
991 Just gres -> extendOccEnv env occ (map trans_gre gres)
992 Nothing -> env
993
994 extendGlobalRdrEnv :: GlobalRdrEnv -> GlobalRdrElt -> GlobalRdrEnv
995 extendGlobalRdrEnv env gre
996 = extendOccEnv_Acc insertGRE singleton env
997 (greOccName gre) gre
998
999 shadowNames :: GlobalRdrEnv -> [Name] -> GlobalRdrEnv
1000 shadowNames = foldl shadowName
1001
1002 {- Note [GlobalRdrEnv shadowing]
1003 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1004 Before adding new names to the GlobalRdrEnv we nuke some existing entries;
1005 this is "shadowing". The actual work is done by RdrEnv.shadowName.
1006 Suppose
1007 env' = shadowName env M.f
1008
1009 Then:
1010 * Looking up (Unqual f) in env' should succeed, returning M.f,
1011 even if env contains existing unqualified bindings for f.
1012 They are shadowed
1013
1014 * Looking up (Qual M.f) in env' should succeed, returning M.f
1015
1016 * Looking up (Qual X.f) in env', where X /= M, should be the same as
1017 looking up (Qual X.f) in env.
1018 That is, shadowName does /not/ delete earlier qualified bindings
1019
1020 There are two reasons for shadowing:
1021
1022 * The GHCi REPL
1023
1024 - Ids bought into scope on the command line (eg let x = True) have
1025 External Names, like Ghci4.x. We want a new binding for 'x' (say)
1026 to override the existing binding for 'x'. Example:
1027
1028 ghci> :load M -- Brings `x` and `M.x` into scope
1029 ghci> x
1030 ghci> "Hello"
1031 ghci> M.x
1032 ghci> "hello"
1033 ghci> let x = True -- Shadows `x`
1034 ghci> x -- The locally bound `x`
1035 -- NOT an ambiguous reference
1036 ghci> True
1037 ghci> M.x -- M.x is still in scope!
1038 ghci> "Hello"
1039 So when we add `x = True` we must not delete the `M.x` from the
1040 `GlobalRdrEnv`; rather we just want to make it "qualified only";
1041 hence the `mk_fake-imp_spec` in `shadowName`. See also Note
1042 [Interactively-bound Ids in GHCi] in HscTypes
1043
1044 - Data types also have External Names, like Ghci4.T; but we still want
1045 'T' to mean the newly-declared 'T', not an old one.
1046
1047 * Nested Template Haskell declaration brackets
1048 See Note [Top-level Names in Template Haskell decl quotes] in RnNames
1049
1050 Consider a TH decl quote:
1051 module M where
1052 f x = h [d| f = ...f...M.f... |]
1053 We must shadow the outer unqualified binding of 'f', else we'll get
1054 a complaint when extending the GlobalRdrEnv, saying that there are
1055 two bindings for 'f'. There are several tricky points:
1056
1057 - This shadowing applies even if the binding for 'f' is in a
1058 where-clause, and hence is in the *local* RdrEnv not the *global*
1059 RdrEnv. This is done in lcl_env_TH in extendGlobalRdrEnvRn.
1060
1061 - The External Name M.f from the enclosing module must certainly
1062 still be available. So we don't nuke it entirely; we just make
1063 it seem like qualified import.
1064
1065 - We only shadow *External* names (which come from the main module),
1066 or from earlier GHCi commands. Do not shadow *Internal* names
1067 because in the bracket
1068 [d| class C a where f :: a
1069 f = 4 |]
1070 rnSrcDecls will first call extendGlobalRdrEnvRn with C[f] from the
1071 class decl, and *separately* extend the envt with the value binding.
1072 At that stage, the class op 'f' will have an Internal name.
1073 -}
1074
1075 shadowName :: GlobalRdrEnv -> Name -> GlobalRdrEnv
1076 -- Remove certain old GREs that share the same OccName as this new Name.
1077 -- See Note [GlobalRdrEnv shadowing] for details
1078 shadowName env name
1079 = alterOccEnv (fmap alter_fn) env (nameOccName name)
1080 where
1081 alter_fn :: [GlobalRdrElt] -> [GlobalRdrElt]
1082 alter_fn gres = mapMaybe (shadow_with name) gres
1083
1084 shadow_with :: Name -> GlobalRdrElt -> Maybe GlobalRdrElt
1085 shadow_with new_name
1086 old_gre@(GRE { gre_name = old_name, gre_lcl = lcl, gre_imp = iss })
1087 = case nameModule_maybe old_name of
1088 Nothing -> Just old_gre -- Old name is Internal; do not shadow
1089 Just old_mod
1090 | Just new_mod <- nameModule_maybe new_name
1091 , new_mod == old_mod -- Old name same as new name; shadow completely
1092 -> Nothing
1093
1094 | null iss' -- Nothing remains
1095 -> Nothing
1096
1097 | otherwise
1098 -> Just (old_gre { gre_lcl = False, gre_imp = iss' })
1099
1100 where
1101 iss' = lcl_imp ++ mapMaybe (shadow_is new_name) iss
1102 lcl_imp | lcl = [mk_fake_imp_spec old_name old_mod]
1103 | otherwise = []
1104
1105 mk_fake_imp_spec old_name old_mod -- Urgh!
1106 = ImpSpec id_spec ImpAll
1107 where
1108 old_mod_name = moduleName old_mod
1109 id_spec = ImpDeclSpec { is_mod = old_mod_name
1110 , is_as = old_mod_name
1111 , is_qual = True
1112 , is_dloc = nameSrcSpan old_name }
1113
1114 shadow_is :: Name -> ImportSpec -> Maybe ImportSpec
1115 shadow_is new_name is@(ImpSpec { is_decl = id_spec })
1116 | Just new_mod <- nameModule_maybe new_name
1117 , is_as id_spec == moduleName new_mod
1118 = Nothing -- Shadow both qualified and unqualified
1119 | otherwise -- Shadow unqualified only
1120 = Just (is { is_decl = id_spec { is_qual = True } })
1121
1122
1123 {-
1124 ************************************************************************
1125 * *
1126 ImportSpec
1127 * *
1128 ************************************************************************
1129 -}
1130
1131 -- | Import Specification
1132 --
1133 -- The 'ImportSpec' of something says how it came to be imported
1134 -- It's quite elaborate so that we can give accurate unused-name warnings.
1135 data ImportSpec = ImpSpec { is_decl :: ImpDeclSpec,
1136 is_item :: ImpItemSpec }
1137 deriving( Eq, Ord, Data )
1138
1139 -- | Import Declaration Specification
1140 --
1141 -- Describes a particular import declaration and is
1142 -- shared among all the 'Provenance's for that decl
1143 data ImpDeclSpec
1144 = ImpDeclSpec {
1145 is_mod :: ModuleName, -- ^ Module imported, e.g. @import Muggle@
1146 -- Note the @Muggle@ may well not be
1147 -- the defining module for this thing!
1148
1149 -- TODO: either should be Module, or there
1150 -- should be a Maybe UnitId here too.
1151 is_as :: ModuleName, -- ^ Import alias, e.g. from @as M@ (or @Muggle@ if there is no @as@ clause)
1152 is_qual :: Bool, -- ^ Was this import qualified?
1153 is_dloc :: SrcSpan -- ^ The location of the entire import declaration
1154 } deriving Data
1155
1156 -- | Import Item Specification
1157 --
1158 -- Describes import info a particular Name
1159 data ImpItemSpec
1160 = ImpAll -- ^ The import had no import list,
1161 -- or had a hiding list
1162
1163 | ImpSome {
1164 is_explicit :: Bool,
1165 is_iloc :: SrcSpan -- Location of the import item
1166 } -- ^ The import had an import list.
1167 -- The 'is_explicit' field is @True@ iff the thing was named
1168 -- /explicitly/ in the import specs rather
1169 -- than being imported as part of a "..." group. Consider:
1170 --
1171 -- > import C( T(..) )
1172 --
1173 -- Here the constructors of @T@ are not named explicitly;
1174 -- only @T@ is named explicitly.
1175 deriving Data
1176
1177 instance Eq ImpDeclSpec where
1178 p1 == p2 = case p1 `compare` p2 of EQ -> True; _ -> False
1179
1180 instance Ord ImpDeclSpec where
1181 compare is1 is2 = (is_mod is1 `compare` is_mod is2) `thenCmp`
1182 (is_dloc is1 `compare` is_dloc is2)
1183
1184 instance Eq ImpItemSpec where
1185 p1 == p2 = case p1 `compare` p2 of EQ -> True; _ -> False
1186
1187 instance Ord ImpItemSpec where
1188 compare is1 is2 =
1189 case (is1, is2) of
1190 (ImpAll, ImpAll) -> EQ
1191 (ImpAll, _) -> GT
1192 (_, ImpAll) -> LT
1193 (ImpSome _ l1, ImpSome _ l2) -> l1 `compare` l2
1194
1195
1196 bestImport :: [ImportSpec] -> ImportSpec
1197 -- Given a non-empty bunch of ImportSpecs, return the one that
1198 -- imported the item most specifically (e.g. by name), using
1199 -- textually-first as a tie breaker. This is used when reporting
1200 -- redundant imports
1201 bestImport iss
1202 = case sortBy best iss of
1203 (is:_) -> is
1204 [] -> pprPanic "bestImport" (ppr iss)
1205 where
1206 best :: ImportSpec -> ImportSpec -> Ordering
1207 -- Less means better
1208 best (ImpSpec { is_item = item1, is_decl = d1 })
1209 (ImpSpec { is_item = item2, is_decl = d2 })
1210 = best_item item1 item2 `thenCmp` (is_dloc d1 `compare` is_dloc d2)
1211
1212 best_item :: ImpItemSpec -> ImpItemSpec -> Ordering
1213 best_item ImpAll ImpAll = EQ
1214 best_item ImpAll (ImpSome {}) = GT
1215 best_item (ImpSome {}) ImpAll = LT
1216 best_item (ImpSome { is_explicit = e1 })
1217 (ImpSome { is_explicit = e2 }) = e2 `compare` e1
1218 -- False < True, so if e1 is explicit and e2 is not, we get LT
1219
1220 unQualSpecOK :: ImportSpec -> Bool
1221 -- ^ Is in scope unqualified?
1222 unQualSpecOK is = not (is_qual (is_decl is))
1223
1224 qualSpecOK :: ModuleName -> ImportSpec -> Bool
1225 -- ^ Is in scope qualified with the given module?
1226 qualSpecOK mod is = mod == is_as (is_decl is)
1227
1228 importSpecLoc :: ImportSpec -> SrcSpan
1229 importSpecLoc (ImpSpec decl ImpAll) = is_dloc decl
1230 importSpecLoc (ImpSpec _ item) = is_iloc item
1231
1232 importSpecModule :: ImportSpec -> ModuleName
1233 importSpecModule is = is_mod (is_decl is)
1234
1235 isExplicitItem :: ImpItemSpec -> Bool
1236 isExplicitItem ImpAll = False
1237 isExplicitItem (ImpSome {is_explicit = exp}) = exp
1238
1239 pprNameProvenance :: GlobalRdrElt -> SDoc
1240 -- ^ Print out one place where the name was define/imported
1241 -- (With -dppr-debug, print them all)
1242 pprNameProvenance (GRE { gre_name = name, gre_lcl = lcl, gre_imp = iss })
1243 = ifPprDebug (vcat pp_provs)
1244 (head pp_provs)
1245 where
1246 pp_provs = pp_lcl ++ map pp_is iss
1247 pp_lcl = if lcl then [text "defined at" <+> ppr (nameSrcLoc name)]
1248 else []
1249 pp_is is = sep [ppr is, ppr_defn_site is name]
1250
1251 -- If we know the exact definition point (which we may do with GHCi)
1252 -- then show that too. But not if it's just "imported from X".
1253 ppr_defn_site :: ImportSpec -> Name -> SDoc
1254 ppr_defn_site imp_spec name
1255 | same_module && not (isGoodSrcSpan loc)
1256 = empty -- Nothing interesting to say
1257 | otherwise
1258 = parens $ hang (text "and originally defined" <+> pp_mod)
1259 2 (pprLoc loc)
1260 where
1261 loc = nameSrcSpan name
1262 defining_mod = ASSERT2( isExternalName name, ppr name ) nameModule name
1263 same_module = importSpecModule imp_spec == moduleName defining_mod
1264 pp_mod | same_module = empty
1265 | otherwise = text "in" <+> quotes (ppr defining_mod)
1266
1267
1268 instance Outputable ImportSpec where
1269 ppr imp_spec
1270 = text "imported" <+> qual
1271 <+> text "from" <+> quotes (ppr (importSpecModule imp_spec))
1272 <+> pprLoc (importSpecLoc imp_spec)
1273 where
1274 qual | is_qual (is_decl imp_spec) = text "qualified"
1275 | otherwise = empty
1276
1277 pprLoc :: SrcSpan -> SDoc
1278 pprLoc (RealSrcSpan s) = text "at" <+> ppr s
1279 pprLoc (UnhelpfulSpan {}) = empty