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