Embrace -XTypeInType, add -XStarIsType
[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 greUsedRdrName, 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(..),
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, foldl', nub )
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 greUsedRdrName :: GlobalRdrElt -> RdrName
661 -- For imported things, return a RdrName to add to the used-RdrName
662 -- set, which is used to generate unused-import-decl warnings.
663 -- Return a Qual RdrName if poss, so that identifies the most
664 -- specific ImportSpec. See Trac #10890 for some good examples.
665 greUsedRdrName gre@GRE{ gre_name = name, gre_lcl = lcl, gre_imp = iss }
666 | lcl, Just mod <- nameModule_maybe name = Qual (moduleName mod) occ
667 | not (null iss), is <- bestImport iss = Qual (is_as (is_decl is)) occ
668 | otherwise = pprTrace "greUsedRdrName" (ppr gre) (Unqual occ)
669 where
670 occ = greOccName gre
671
672 greRdrNames :: GlobalRdrElt -> [RdrName]
673 greRdrNames gre@GRE{ gre_lcl = lcl, gre_imp = iss }
674 = (if lcl then [unqual] else []) ++ concatMap do_spec (map is_decl iss)
675 where
676 occ = greOccName gre
677 unqual = Unqual occ
678 do_spec decl_spec
679 | is_qual decl_spec = [qual]
680 | otherwise = [unqual,qual]
681 where qual = Qual (is_as decl_spec) occ
682
683 -- the SrcSpan that pprNameProvenance prints out depends on whether
684 -- the Name is defined locally or not: for a local definition the
685 -- definition site is used, otherwise the location of the import
686 -- declaration. We want to sort the export locations in
687 -- exportClashErr by this SrcSpan, we need to extract it:
688 greSrcSpan :: GlobalRdrElt -> SrcSpan
689 greSrcSpan gre@(GRE { gre_name = name, gre_lcl = lcl, gre_imp = iss } )
690 | lcl = nameSrcSpan name
691 | (is:_) <- iss = is_dloc (is_decl is)
692 | otherwise = pprPanic "greSrcSpan" (ppr gre)
693
694 mkParent :: Name -> AvailInfo -> Parent
695 mkParent _ (Avail _) = NoParent
696 mkParent n (AvailTC m _ _) | n == m = NoParent
697 | otherwise = ParentIs m
698
699 greParentName :: GlobalRdrElt -> Maybe Name
700 greParentName gre = case gre_par gre of
701 NoParent -> Nothing
702 ParentIs n -> Just n
703 FldParent n _ -> Just n
704
705 -- | Takes a list of distinct GREs and folds them
706 -- into AvailInfos. This is more efficient than mapping each individual
707 -- GRE to an AvailInfo and the folding using `plusAvail` but needs the
708 -- uniqueness assumption.
709 gresToAvailInfo :: [GlobalRdrElt] -> [AvailInfo]
710 gresToAvailInfo gres
711 = ASSERT( nub gres == gres ) nameEnvElts avail_env
712 where
713 avail_env :: NameEnv AvailInfo -- keyed by the parent
714 avail_env = foldl' add emptyNameEnv gres
715
716 add :: NameEnv AvailInfo -> GlobalRdrElt -> NameEnv AvailInfo
717 add env gre = extendNameEnv_Acc comb availFromGRE env
718 (fromMaybe (gre_name gre)
719 (greParentName gre)) gre
720
721 where
722 -- We want to insert the child `k` into a list of children but
723 -- need to maintain the invariant that the parent is first.
724 --
725 -- We also use the invariant that `k` is not already in `ns`.
726 insertChildIntoChildren :: Name -> [Name] -> Name -> [Name]
727 insertChildIntoChildren _ [] k = [k]
728 insertChildIntoChildren p (n:ns) k
729 | p == k = k:n:ns
730 | otherwise = n:k:ns
731
732 comb :: GlobalRdrElt -> AvailInfo -> AvailInfo
733 comb _ (Avail n) = Avail n -- Duplicated name
734 comb gre (AvailTC m ns fls) =
735 let n = gre_name gre
736 in case gre_par gre of
737 NoParent -> AvailTC m (n:ns) fls -- Not sure this ever happens
738 ParentIs {} -> AvailTC m (insertChildIntoChildren m ns n) fls
739 FldParent _ mb_lbl -> AvailTC m ns (mkFieldLabel n mb_lbl : fls)
740
741 availFromGRE :: GlobalRdrElt -> AvailInfo
742 availFromGRE (GRE { gre_name = me, gre_par = parent })
743 = case parent of
744 ParentIs p -> AvailTC p [me] []
745 NoParent | isTyConName me -> AvailTC me [me] []
746 | otherwise -> avail me
747 FldParent p mb_lbl -> AvailTC p [] [mkFieldLabel me mb_lbl]
748
749 mkFieldLabel :: Name -> Maybe FastString -> FieldLabel
750 mkFieldLabel me mb_lbl =
751 case mb_lbl of
752 Nothing -> FieldLabel { flLabel = occNameFS (nameOccName me)
753 , flIsOverloaded = False
754 , flSelector = me }
755 Just lbl -> FieldLabel { flLabel = lbl
756 , flIsOverloaded = True
757 , flSelector = me }
758
759 emptyGlobalRdrEnv :: GlobalRdrEnv
760 emptyGlobalRdrEnv = emptyOccEnv
761
762 globalRdrEnvElts :: GlobalRdrEnv -> [GlobalRdrElt]
763 globalRdrEnvElts env = foldOccEnv (++) [] env
764
765 instance Outputable GlobalRdrElt where
766 ppr gre = hang (ppr (gre_name gre) <+> ppr (gre_par gre))
767 2 (pprNameProvenance gre)
768
769 pprGlobalRdrEnv :: Bool -> GlobalRdrEnv -> SDoc
770 pprGlobalRdrEnv locals_only env
771 = vcat [ text "GlobalRdrEnv" <+> ppWhen locals_only (ptext (sLit "(locals only)"))
772 <+> lbrace
773 , nest 2 (vcat [ pp (remove_locals gre_list) | gre_list <- occEnvElts env ]
774 <+> rbrace) ]
775 where
776 remove_locals gres | locals_only = filter isLocalGRE gres
777 | otherwise = gres
778 pp [] = empty
779 pp gres = hang (ppr occ
780 <+> parens (text "unique" <+> ppr (getUnique occ))
781 <> colon)
782 2 (vcat (map ppr gres))
783 where
784 occ = nameOccName (gre_name (head gres))
785
786 lookupGlobalRdrEnv :: GlobalRdrEnv -> OccName -> [GlobalRdrElt]
787 lookupGlobalRdrEnv env occ_name = case lookupOccEnv env occ_name of
788 Nothing -> []
789 Just gres -> gres
790
791 greOccName :: GlobalRdrElt -> OccName
792 greOccName (GRE{gre_par = FldParent{par_lbl = Just lbl}}) = mkVarOccFS lbl
793 greOccName gre = nameOccName (gre_name gre)
794
795 lookupGRE_RdrName :: RdrName -> GlobalRdrEnv -> [GlobalRdrElt]
796 lookupGRE_RdrName rdr_name env
797 = case lookupOccEnv env (rdrNameOcc rdr_name) of
798 Nothing -> []
799 Just gres -> pickGREs rdr_name gres
800
801 lookupGRE_Name :: GlobalRdrEnv -> Name -> Maybe GlobalRdrElt
802 -- ^ Look for precisely this 'Name' in the environment. This tests
803 -- whether it is in scope, ignoring anything else that might be in
804 -- scope with the same 'OccName'.
805 lookupGRE_Name env name
806 = lookupGRE_Name_OccName env name (nameOccName name)
807
808 lookupGRE_FieldLabel :: GlobalRdrEnv -> FieldLabel -> Maybe GlobalRdrElt
809 -- ^ Look for a particular record field selector in the environment, where the
810 -- selector name and field label may be different: the GlobalRdrEnv is keyed on
811 -- the label. See Note [Parents for record fields] for why this happens.
812 lookupGRE_FieldLabel env fl
813 = lookupGRE_Name_OccName env (flSelector fl) (mkVarOccFS (flLabel fl))
814
815 lookupGRE_Name_OccName :: GlobalRdrEnv -> Name -> OccName -> Maybe GlobalRdrElt
816 -- ^ Look for precisely this 'Name' in the environment, but with an 'OccName'
817 -- that might differ from that of the 'Name'. See 'lookupGRE_FieldLabel' and
818 -- Note [Parents for record fields].
819 lookupGRE_Name_OccName env name occ
820 = case [ gre | gre <- lookupGlobalRdrEnv env occ
821 , gre_name gre == name ] of
822 [] -> Nothing
823 [gre] -> Just gre
824 gres -> pprPanic "lookupGRE_Name_OccName"
825 (ppr name $$ ppr occ $$ ppr gres)
826 -- See INVARIANT 1 on GlobalRdrEnv
827
828
829 getGRE_NameQualifier_maybes :: GlobalRdrEnv -> Name -> [Maybe [ModuleName]]
830 -- Returns all the qualifiers by which 'x' is in scope
831 -- Nothing means "the unqualified version is in scope"
832 -- [] means the thing is not in scope at all
833 getGRE_NameQualifier_maybes env name
834 = case lookupGRE_Name env name of
835 Just gre -> [qualifier_maybe gre]
836 Nothing -> []
837 where
838 qualifier_maybe (GRE { gre_lcl = lcl, gre_imp = iss })
839 | lcl = Nothing
840 | otherwise = Just $ map (is_as . is_decl) iss
841
842 isLocalGRE :: GlobalRdrElt -> Bool
843 isLocalGRE (GRE {gre_lcl = lcl }) = lcl
844
845 isRecFldGRE :: GlobalRdrElt -> Bool
846 isRecFldGRE (GRE {gre_par = FldParent{}}) = True
847 isRecFldGRE _ = False
848
849 -- Returns the field label of this GRE, if it has one
850 greLabel :: GlobalRdrElt -> Maybe FieldLabelString
851 greLabel (GRE{gre_par = FldParent{par_lbl = Just lbl}}) = Just lbl
852 greLabel (GRE{gre_name = n, gre_par = FldParent{}}) = Just (occNameFS (nameOccName n))
853 greLabel _ = Nothing
854
855 unQualOK :: GlobalRdrElt -> Bool
856 -- ^ Test if an unqualified version of this thing would be in scope
857 unQualOK (GRE {gre_lcl = lcl, gre_imp = iss })
858 | lcl = True
859 | otherwise = any unQualSpecOK iss
860
861 {- Note [GRE filtering]
862 ~~~~~~~~~~~~~~~~~~~~~~~
863 (pickGREs rdr gres) takes a list of GREs which have the same OccName
864 as 'rdr', say "x". It does two things:
865
866 (a) filters the GREs to a subset that are in scope
867 * Qualified, as 'M.x' if want_qual is Qual M _
868 * Unqualified, as 'x' if want_unqual is Unqual _
869
870 (b) for that subset, filter the provenance field (gre_lcl and gre_imp)
871 to ones that brought it into scope qualified or unqualified resp.
872
873 Example:
874 module A ( f ) where
875 import qualified Foo( f )
876 import Baz( f )
877 f = undefined
878
879 Let's suppose that Foo.f and Baz.f are the same entity really, but the local
880 'f' is different, so there will be two GREs matching "f":
881 gre1: gre_lcl = True, gre_imp = []
882 gre2: gre_lcl = False, gre_imp = [ imported from Foo, imported from Bar ]
883
884 The use of "f" in the export list is ambiguous because it's in scope
885 from the local def and the import Baz(f); but *not* the import qualified Foo.
886 pickGREs returns two GRE
887 gre1: gre_lcl = True, gre_imp = []
888 gre2: gre_lcl = False, gre_imp = [ imported from Bar ]
889
890 Now the "ambiguous occurrence" message can correctly report how the
891 ambiguity arises.
892 -}
893
894 pickGREs :: RdrName -> [GlobalRdrElt] -> [GlobalRdrElt]
895 -- ^ Takes a list of GREs which have the right OccName 'x'
896 -- Pick those GREs that are in scope
897 -- * Qualified, as 'M.x' if want_qual is Qual M _
898 -- * Unqualified, as 'x' if want_unqual is Unqual _
899 --
900 -- Return each such GRE, with its ImportSpecs filtered, to reflect
901 -- how it is in scope qualified or unqualified respectively.
902 -- See Note [GRE filtering]
903 pickGREs (Unqual {}) gres = mapMaybe pickUnqualGRE gres
904 pickGREs (Qual mod _) gres = mapMaybe (pickQualGRE mod) gres
905 pickGREs _ _ = [] -- I don't think this actually happens
906
907 pickUnqualGRE :: GlobalRdrElt -> Maybe GlobalRdrElt
908 pickUnqualGRE gre@(GRE { gre_lcl = lcl, gre_imp = iss })
909 | not lcl, null iss' = Nothing
910 | otherwise = Just (gre { gre_imp = iss' })
911 where
912 iss' = filter unQualSpecOK iss
913
914 pickQualGRE :: ModuleName -> GlobalRdrElt -> Maybe GlobalRdrElt
915 pickQualGRE mod gre@(GRE { gre_name = n, gre_lcl = lcl, gre_imp = iss })
916 | not lcl', null iss' = Nothing
917 | otherwise = Just (gre { gre_lcl = lcl', gre_imp = iss' })
918 where
919 iss' = filter (qualSpecOK mod) iss
920 lcl' = lcl && name_is_from mod n
921
922 name_is_from :: ModuleName -> Name -> Bool
923 name_is_from mod name = case nameModule_maybe name of
924 Just n_mod -> moduleName n_mod == mod
925 Nothing -> False
926
927 pickGREsModExp :: ModuleName -> [GlobalRdrElt] -> [(GlobalRdrElt,GlobalRdrElt)]
928 -- ^ Pick GREs that are in scope *both* qualified *and* unqualified
929 -- Return each GRE that is, as a pair
930 -- (qual_gre, unqual_gre)
931 -- These two GREs are the original GRE with imports filtered to express how
932 -- it is in scope qualified an unqualified respectively
933 --
934 -- Used only for the 'module M' item in export list;
935 -- see RnNames.exports_from_avail
936 pickGREsModExp mod gres = mapMaybe (pickBothGRE mod) gres
937
938 pickBothGRE :: ModuleName -> GlobalRdrElt -> Maybe (GlobalRdrElt, GlobalRdrElt)
939 pickBothGRE mod gre@(GRE { gre_name = n })
940 | isBuiltInSyntax n = Nothing
941 | Just gre1 <- pickQualGRE mod gre
942 , Just gre2 <- pickUnqualGRE gre = Just (gre1, gre2)
943 | otherwise = Nothing
944 where
945 -- isBuiltInSyntax filter out names for built-in syntax They
946 -- just clutter up the environment (esp tuples), and the
947 -- parser will generate Exact RdrNames for them, so the
948 -- cluttered envt is no use. Really, it's only useful for
949 -- GHC.Base and GHC.Tuple.
950
951 -- Building GlobalRdrEnvs
952
953 plusGlobalRdrEnv :: GlobalRdrEnv -> GlobalRdrEnv -> GlobalRdrEnv
954 plusGlobalRdrEnv env1 env2 = plusOccEnv_C (foldr insertGRE) env1 env2
955
956 mkGlobalRdrEnv :: [GlobalRdrElt] -> GlobalRdrEnv
957 mkGlobalRdrEnv gres
958 = foldr add emptyGlobalRdrEnv gres
959 where
960 add gre env = extendOccEnv_Acc insertGRE singleton env
961 (greOccName gre)
962 gre
963
964 insertGRE :: GlobalRdrElt -> [GlobalRdrElt] -> [GlobalRdrElt]
965 insertGRE new_g [] = [new_g]
966 insertGRE new_g (old_g : old_gs)
967 | gre_name new_g == gre_name old_g
968 = new_g `plusGRE` old_g : old_gs
969 | otherwise
970 = old_g : insertGRE new_g old_gs
971
972 plusGRE :: GlobalRdrElt -> GlobalRdrElt -> GlobalRdrElt
973 -- Used when the gre_name fields match
974 plusGRE g1 g2
975 = GRE { gre_name = gre_name g1
976 , gre_lcl = gre_lcl g1 || gre_lcl g2
977 , gre_imp = gre_imp g1 ++ gre_imp g2
978 , gre_par = gre_par g1 `plusParent` gre_par g2 }
979
980 transformGREs :: (GlobalRdrElt -> GlobalRdrElt)
981 -> [OccName]
982 -> GlobalRdrEnv -> GlobalRdrEnv
983 -- ^ Apply a transformation function to the GREs for these OccNames
984 transformGREs trans_gre occs rdr_env
985 = foldr trans rdr_env occs
986 where
987 trans occ env
988 = case lookupOccEnv env occ of
989 Just gres -> extendOccEnv env occ (map trans_gre gres)
990 Nothing -> env
991
992 extendGlobalRdrEnv :: GlobalRdrEnv -> GlobalRdrElt -> GlobalRdrEnv
993 extendGlobalRdrEnv env gre
994 = extendOccEnv_Acc insertGRE singleton env
995 (greOccName gre) gre
996
997 shadowNames :: GlobalRdrEnv -> [Name] -> GlobalRdrEnv
998 shadowNames = foldl shadowName
999
1000 {- Note [GlobalRdrEnv shadowing]
1001 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1002 Before adding new names to the GlobalRdrEnv we nuke some existing entries;
1003 this is "shadowing". The actual work is done by RdrEnv.shadowName.
1004 Suppose
1005 env' = shadowName env M.f
1006
1007 Then:
1008 * Looking up (Unqual f) in env' should succeed, returning M.f,
1009 even if env contains existing unqualified bindings for f.
1010 They are shadowed
1011
1012 * Looking up (Qual M.f) in env' should succeed, returning M.f
1013
1014 * Looking up (Qual X.f) in env', where X /= M, should be the same as
1015 looking up (Qual X.f) in env.
1016 That is, shadowName does /not/ delete earlier qualified bindings
1017
1018 There are two reasons for shadowing:
1019
1020 * The GHCi REPL
1021
1022 - Ids bought into scope on the command line (eg let x = True) have
1023 External Names, like Ghci4.x. We want a new binding for 'x' (say)
1024 to override the existing binding for 'x'. Example:
1025
1026 ghci> :load M -- Brings `x` and `M.x` into scope
1027 ghci> x
1028 ghci> "Hello"
1029 ghci> M.x
1030 ghci> "hello"
1031 ghci> let x = True -- Shadows `x`
1032 ghci> x -- The locally bound `x`
1033 -- NOT an ambiguous reference
1034 ghci> True
1035 ghci> M.x -- M.x is still in scope!
1036 ghci> "Hello"
1037 So when we add `x = True` we must not delete the `M.x` from the
1038 `GlobalRdrEnv`; rather we just want to make it "qualified only";
1039 hence the `mk_fake-imp_spec` in `shadowName`. See also Note
1040 [Interactively-bound Ids in GHCi] in HscTypes
1041
1042 - Data types also have External Names, like Ghci4.T; but we still want
1043 'T' to mean the newly-declared 'T', not an old one.
1044
1045 * Nested Template Haskell declaration brackets
1046 See Note [Top-level Names in Template Haskell decl quotes] in RnNames
1047
1048 Consider a TH decl quote:
1049 module M where
1050 f x = h [d| f = ...f...M.f... |]
1051 We must shadow the outer unqualified binding of 'f', else we'll get
1052 a complaint when extending the GlobalRdrEnv, saying that there are
1053 two bindings for 'f'. There are several tricky points:
1054
1055 - This shadowing applies even if the binding for 'f' is in a
1056 where-clause, and hence is in the *local* RdrEnv not the *global*
1057 RdrEnv. This is done in lcl_env_TH in extendGlobalRdrEnvRn.
1058
1059 - The External Name M.f from the enclosing module must certainly
1060 still be available. So we don't nuke it entirely; we just make
1061 it seem like qualified import.
1062
1063 - We only shadow *External* names (which come from the main module),
1064 or from earlier GHCi commands. Do not shadow *Internal* names
1065 because in the bracket
1066 [d| class C a where f :: a
1067 f = 4 |]
1068 rnSrcDecls will first call extendGlobalRdrEnvRn with C[f] from the
1069 class decl, and *separately* extend the envt with the value binding.
1070 At that stage, the class op 'f' will have an Internal name.
1071 -}
1072
1073 shadowName :: GlobalRdrEnv -> Name -> GlobalRdrEnv
1074 -- Remove certain old GREs that share the same OccName as this new Name.
1075 -- See Note [GlobalRdrEnv shadowing] for details
1076 shadowName env name
1077 = alterOccEnv (fmap alter_fn) env (nameOccName name)
1078 where
1079 alter_fn :: [GlobalRdrElt] -> [GlobalRdrElt]
1080 alter_fn gres = mapMaybe (shadow_with name) gres
1081
1082 shadow_with :: Name -> GlobalRdrElt -> Maybe GlobalRdrElt
1083 shadow_with new_name
1084 old_gre@(GRE { gre_name = old_name, gre_lcl = lcl, gre_imp = iss })
1085 = case nameModule_maybe old_name of
1086 Nothing -> Just old_gre -- Old name is Internal; do not shadow
1087 Just old_mod
1088 | Just new_mod <- nameModule_maybe new_name
1089 , new_mod == old_mod -- Old name same as new name; shadow completely
1090 -> Nothing
1091
1092 | null iss' -- Nothing remains
1093 -> Nothing
1094
1095 | otherwise
1096 -> Just (old_gre { gre_lcl = False, gre_imp = iss' })
1097
1098 where
1099 iss' = lcl_imp ++ mapMaybe (shadow_is new_name) iss
1100 lcl_imp | lcl = [mk_fake_imp_spec old_name old_mod]
1101 | otherwise = []
1102
1103 mk_fake_imp_spec old_name old_mod -- Urgh!
1104 = ImpSpec id_spec ImpAll
1105 where
1106 old_mod_name = moduleName old_mod
1107 id_spec = ImpDeclSpec { is_mod = old_mod_name
1108 , is_as = old_mod_name
1109 , is_qual = True
1110 , is_dloc = nameSrcSpan old_name }
1111
1112 shadow_is :: Name -> ImportSpec -> Maybe ImportSpec
1113 shadow_is new_name is@(ImpSpec { is_decl = id_spec })
1114 | Just new_mod <- nameModule_maybe new_name
1115 , is_as id_spec == moduleName new_mod
1116 = Nothing -- Shadow both qualified and unqualified
1117 | otherwise -- Shadow unqualified only
1118 = Just (is { is_decl = id_spec { is_qual = True } })
1119
1120
1121 {-
1122 ************************************************************************
1123 * *
1124 ImportSpec
1125 * *
1126 ************************************************************************
1127 -}
1128
1129 -- | Import Specification
1130 --
1131 -- The 'ImportSpec' of something says how it came to be imported
1132 -- It's quite elaborate so that we can give accurate unused-name warnings.
1133 data ImportSpec = ImpSpec { is_decl :: ImpDeclSpec,
1134 is_item :: ImpItemSpec }
1135 deriving( Eq, Ord, Data )
1136
1137 -- | Import Declaration Specification
1138 --
1139 -- Describes a particular import declaration and is
1140 -- shared among all the 'Provenance's for that decl
1141 data ImpDeclSpec
1142 = ImpDeclSpec {
1143 is_mod :: ModuleName, -- ^ Module imported, e.g. @import Muggle@
1144 -- Note the @Muggle@ may well not be
1145 -- the defining module for this thing!
1146
1147 -- TODO: either should be Module, or there
1148 -- should be a Maybe UnitId here too.
1149 is_as :: ModuleName, -- ^ Import alias, e.g. from @as M@ (or @Muggle@ if there is no @as@ clause)
1150 is_qual :: Bool, -- ^ Was this import qualified?
1151 is_dloc :: SrcSpan -- ^ The location of the entire import declaration
1152 } deriving Data
1153
1154 -- | Import Item Specification
1155 --
1156 -- Describes import info a particular Name
1157 data ImpItemSpec
1158 = ImpAll -- ^ The import had no import list,
1159 -- or had a hiding list
1160
1161 | ImpSome {
1162 is_explicit :: Bool,
1163 is_iloc :: SrcSpan -- Location of the import item
1164 } -- ^ The import had an import list.
1165 -- The 'is_explicit' field is @True@ iff the thing was named
1166 -- /explicitly/ in the import specs rather
1167 -- than being imported as part of a "..." group. Consider:
1168 --
1169 -- > import C( T(..) )
1170 --
1171 -- Here the constructors of @T@ are not named explicitly;
1172 -- only @T@ is named explicitly.
1173 deriving Data
1174
1175 instance Eq ImpDeclSpec where
1176 p1 == p2 = case p1 `compare` p2 of EQ -> True; _ -> False
1177
1178 instance Ord ImpDeclSpec where
1179 compare is1 is2 = (is_mod is1 `compare` is_mod is2) `thenCmp`
1180 (is_dloc is1 `compare` is_dloc is2)
1181
1182 instance Eq ImpItemSpec where
1183 p1 == p2 = case p1 `compare` p2 of EQ -> True; _ -> False
1184
1185 instance Ord ImpItemSpec where
1186 compare is1 is2 =
1187 case (is1, is2) of
1188 (ImpAll, ImpAll) -> EQ
1189 (ImpAll, _) -> GT
1190 (_, ImpAll) -> LT
1191 (ImpSome _ l1, ImpSome _ l2) -> l1 `compare` l2
1192
1193
1194 bestImport :: [ImportSpec] -> ImportSpec
1195 -- Given a non-empty bunch of ImportSpecs, return the one that
1196 -- imported the item most specifically (e.g. by name), using
1197 -- textually-first as a tie breaker. This is used when reporting
1198 -- redundant imports
1199 bestImport iss
1200 = case sortBy best iss of
1201 (is:_) -> is
1202 [] -> pprPanic "bestImport" (ppr iss)
1203 where
1204 best :: ImportSpec -> ImportSpec -> Ordering
1205 -- Less means better
1206 best (ImpSpec { is_item = item1, is_decl = d1 })
1207 (ImpSpec { is_item = item2, is_decl = d2 })
1208 = best_item item1 item2 `thenCmp` (is_dloc d1 `compare` is_dloc d2)
1209
1210 best_item :: ImpItemSpec -> ImpItemSpec -> Ordering
1211 best_item ImpAll ImpAll = EQ
1212 best_item ImpAll (ImpSome {}) = GT
1213 best_item (ImpSome {}) ImpAll = LT
1214 best_item (ImpSome { is_explicit = e1 })
1215 (ImpSome { is_explicit = e2 }) = e2 `compare` e1
1216 -- False < True, so if e1 is explicit and e2 is not, we get LT
1217
1218 unQualSpecOK :: ImportSpec -> Bool
1219 -- ^ Is in scope unqualified?
1220 unQualSpecOK is = not (is_qual (is_decl is))
1221
1222 qualSpecOK :: ModuleName -> ImportSpec -> Bool
1223 -- ^ Is in scope qualified with the given module?
1224 qualSpecOK mod is = mod == is_as (is_decl is)
1225
1226 importSpecLoc :: ImportSpec -> SrcSpan
1227 importSpecLoc (ImpSpec decl ImpAll) = is_dloc decl
1228 importSpecLoc (ImpSpec _ item) = is_iloc item
1229
1230 importSpecModule :: ImportSpec -> ModuleName
1231 importSpecModule is = is_mod (is_decl is)
1232
1233 isExplicitItem :: ImpItemSpec -> Bool
1234 isExplicitItem ImpAll = False
1235 isExplicitItem (ImpSome {is_explicit = exp}) = exp
1236
1237 pprNameProvenance :: GlobalRdrElt -> SDoc
1238 -- ^ Print out one place where the name was define/imported
1239 -- (With -dppr-debug, print them all)
1240 pprNameProvenance (GRE { gre_name = name, gre_lcl = lcl, gre_imp = iss })
1241 = ifPprDebug (vcat pp_provs)
1242 (head pp_provs)
1243 where
1244 pp_provs = pp_lcl ++ map pp_is iss
1245 pp_lcl = if lcl then [text "defined at" <+> ppr (nameSrcLoc name)]
1246 else []
1247 pp_is is = sep [ppr is, ppr_defn_site is name]
1248
1249 -- If we know the exact definition point (which we may do with GHCi)
1250 -- then show that too. But not if it's just "imported from X".
1251 ppr_defn_site :: ImportSpec -> Name -> SDoc
1252 ppr_defn_site imp_spec name
1253 | same_module && not (isGoodSrcSpan loc)
1254 = empty -- Nothing interesting to say
1255 | otherwise
1256 = parens $ hang (text "and originally defined" <+> pp_mod)
1257 2 (pprLoc loc)
1258 where
1259 loc = nameSrcSpan name
1260 defining_mod = ASSERT2( isExternalName name, ppr name ) nameModule name
1261 same_module = importSpecModule imp_spec == moduleName defining_mod
1262 pp_mod | same_module = empty
1263 | otherwise = text "in" <+> quotes (ppr defining_mod)
1264
1265
1266 instance Outputable ImportSpec where
1267 ppr imp_spec
1268 = text "imported" <+> qual
1269 <+> text "from" <+> quotes (ppr (importSpecModule imp_spec))
1270 <+> pprLoc (importSpecLoc imp_spec)
1271 where
1272 qual | is_qual (is_decl imp_spec) = text "qualified"
1273 | otherwise = empty
1274
1275 pprLoc :: SrcSpan -> SDoc
1276 pprLoc (RealSrcSpan s) = text "at" <+> ppr s
1277 pprLoc (UnhelpfulSpan {}) = empty
1278
1279 -- | Display info about the treatment of '*' under NoStarIsType.
1280 --
1281 -- With StarIsType, three properties of '*' hold:
1282 --
1283 -- (a) it is not an infix operator
1284 -- (b) it is always in scope
1285 -- (c) it is a synonym for Data.Kind.Type
1286 --
1287 -- However, the user might not know that he's working on a module with
1288 -- NoStarIsType and write code that still assumes (a), (b), and (c), which
1289 -- actually do not hold in that module.
1290 --
1291 -- Violation of (a) shows up in the parser. For instance, in the following
1292 -- examples, we have '*' not applied to enough arguments:
1293 --
1294 -- data A :: *
1295 -- data F :: * -> *
1296 --
1297 -- Violation of (b) or (c) show up in the renamer and the typechecker
1298 -- respectively. For instance:
1299 --
1300 -- type K = Either * Bool
1301 --
1302 -- This will parse differently depending on whether StarIsType is enabled,
1303 -- but it will parse nonetheless. With NoStarIsType it is parsed as a type
1304 -- operator, thus we have ((*) Either Bool). Now there are two cases to
1305 -- consider:
1306 --
1307 -- 1. There is no definition of (*) in scope. In this case the renamer will
1308 -- fail to look it up. This is a violation of assumption (b).
1309 --
1310 -- 2. There is a definition of the (*) type operator in scope (for example
1311 -- coming from GHC.TypeNats). In this case the user will get a kind
1312 -- mismatch error. This is a violation of assumption (c).
1313 --
1314 -- Since NoStarIsType is implied by a fairly common extension TypeOperators,
1315 -- the user might be working on a module with NoStarIsType unbeknownst to him.
1316 -- Even if the user switched off StarIsType manually, he might have forgotten
1317 -- about it and use '*' as 'Data.Kind.Type' out of habit.
1318 --
1319 -- Thus it is very important to give a hint whenever an assumption about '*' is
1320 -- violated. Unfortunately, it is somewhat difficult to deal with (c), so we
1321 -- limit ourselves to (a) and (b).
1322 --
1323 -- 'starInfo' generates an appropriate hint to the user depending on the
1324 -- extensions enabled in the module and the name that triggered the error.
1325 -- That is, if we have NoStarIsType and the error is related to '*' or its
1326 -- Unicode variant, the resulting SDoc will contain a helpful suggestion.
1327 -- Otherwise it is empty.
1328 --
1329 starInfo :: (Bool, Bool) -> RdrName -> SDoc
1330 starInfo (type_operators, star_is_type) rdr_name =
1331 -- One might ask: if can use sdocWithDynFlags here, why bother to take
1332 -- (type_operators, star_is_type) as input? Why not refactor?
1333 --
1334 -- The reason is that sdocWithDynFlags would provide DynFlags that are active
1335 -- in the module that tries to load the problematic definition, not
1336 -- in the module that is being loaded.
1337 --
1338 -- So if we have 'data T :: *' in a module with NoStarIsType, then the hint
1339 -- must be displayed even if we load this definition from a module (or GHCi)
1340 -- with StarIsType enabled!
1341 --
1342 if isUnqualStar && not star_is_type
1343 then text "With NoStarIsType" <>
1344 (if type_operators
1345 then text " (implied by TypeOperators), "
1346 else text ", ") <>
1347 quotes (ppr rdr_name) <>
1348 text " is treated as a regular type operator. "
1349 $$
1350 text "Did you mean to use " <> quotes (text "Type") <>
1351 text " from Data.Kind instead?"
1352 else empty
1353 where
1354 -- Does rdr_name look like the user might have meant the '*' kind by it?
1355 -- We focus on unqualified stars specifically, because qualified stars are
1356 -- treated as type operators even under StarIsType.
1357 isUnqualStar
1358 | Unqual occName <- rdr_name
1359 = let fs = occNameFS occName
1360 in fs == fsLit "*" || fs == fsLit "★"
1361 | otherwise = False