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