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