RdrName.hs 40.1 KB
Newer Older
Austin Seipp's avatar
Austin Seipp committed
1 2 3 4
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
-}
5

6
{-# LANGUAGE CPP, DeriveDataTypeable #-}
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23

-- |
-- #name_types#
-- GHC uses several kinds of name internally:
--
-- * 'OccName.OccName': see "OccName#name_types"
--
-- * 'RdrName.RdrName' is the type of names that come directly from the parser. They
--   have not yet had their scoping and binding resolved by the renamer and can be
--   thought of to a first approximation as an 'OccName.OccName' with an optional module
--   qualifier
--
-- * 'Name.Name': see "Name#name_types"
--
-- * 'Id.Id': see "Id#name_types"
--
-- * 'Var.Var': see "Var#name_types"
Ian Lynagh's avatar
Ian Lynagh committed
24

25
module RdrName (
26
        -- * The main type
27
        RdrName(..),    -- Constructors exported only to BinIface
28

29 30 31 32
        -- ** Construction
        mkRdrUnqual, mkRdrQual,
        mkUnqual, mkVarUnqual, mkQual, mkOrig,
        nameRdrName, getRdrName,
33

34
        -- ** Destruction
35
        rdrNameOcc, rdrNameSpace, demoteRdrName,
36 37
        isRdrDataCon, isRdrTyVar, isRdrTc, isQual, isQual_maybe, isUnqual,
        isOrig, isOrig_maybe, isExact, isExact_maybe, isSrcRdrName,
38

39 40
        -- * Local mapping of 'RdrName' to 'Name.Name'
        LocalRdrEnv, emptyLocalRdrEnv, extendLocalRdrEnv, extendLocalRdrEnvList,
41
        lookupLocalRdrEnv, lookupLocalRdrOcc,
gmainland's avatar
gmainland committed
42
        elemLocalRdrEnv, inLocalRdrEnvScope,
43
        localRdrEnvElts, delLocalRdrEnvList,
44

45 46
        -- * Global mapping of 'RdrName' to 'GlobalRdrElt's
        GlobalRdrEnv, emptyGlobalRdrEnv, mkGlobalRdrEnv, plusGlobalRdrEnv,
Adam Gundry's avatar
Adam Gundry committed
47
        lookupGlobalRdrEnv, extendGlobalRdrEnv, greOccName, shadowNames,
48
        pprGlobalRdrEnv, globalRdrEnvElts,
Adam Gundry's avatar
Adam Gundry committed
49
        lookupGRE_RdrName, lookupGRE_Name, lookupGRE_Field_Name, getGRE_NameQualifier_maybes,
50
        transformGREs, pickGREs,
51

52
        -- * GlobalRdrElts
53
        gresFromAvails, gresFromAvail, localGREsFromAvail, availFromGRE,
54
        greUsedRdrName, greRdrNames, greSrcSpan, greQualModName,
55

56
        -- ** Global 'RdrName' mapping elements: 'GlobalRdrElt', 'Provenance', 'ImportSpec'
Adam Gundry's avatar
Adam Gundry committed
57 58
        GlobalRdrElt(..), isLocalGRE, isRecFldGRE, greLabel,
        unQualOK, qualSpecOK, unQualSpecOK,
59
        pprNameProvenance,
60 61
        Parent(..),
        ImportSpec(..), ImpDeclSpec(..), ImpItemSpec(..),
62
        importSpecLoc, importSpecModule, isExplicitItem, bestImport
63
  ) where
64 65 66

#include "HsVersions.h"

Simon Marlow's avatar
Simon Marlow committed
67 68
import Module
import Name
69
import Avail
70
import NameSet
Simon Marlow's avatar
Simon Marlow committed
71 72 73
import Maybes
import SrcLoc
import FastString
Adam Gundry's avatar
Adam Gundry committed
74
import FieldLabel
75
import Outputable
76
import Unique
Simon Marlow's avatar
Simon Marlow committed
77
import Util
78
import StaticFlags( opt_PprStyle_Debug )
79 80

import Data.Data
81
import Data.List( sortBy )
82

Austin Seipp's avatar
Austin Seipp committed
83 84 85
{-
************************************************************************
*                                                                      *
86
\subsection{The main data type}
Austin Seipp's avatar
Austin Seipp committed
87 88 89
*                                                                      *
************************************************************************
-}
90

91 92
-- | Do not use the data constructors of RdrName directly: prefer the family
-- of functions that creates them, such as 'mkRdrUnqual'
Alan Zimmerman's avatar
Alan Zimmerman committed
93 94 95 96 97 98 99 100 101 102 103 104 105 106
--
-- - Note: A Located RdrName will only have API Annotations if it is a
--         compound one,
--   e.g.
--
-- > `bar`
-- > ( ~ )
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnType',
--           'ApiAnnotation.AnnOpen'  @'('@ or @'['@ or @'[:'@,
--           'ApiAnnotation.AnnClose' @')'@ or @']'@ or @':]'@,,
--           'ApiAnnotation.AnnBackquote' @'`'@,
--           'ApiAnnotation.AnnVal','ApiAnnotation.AnnTildehsh',
--           'ApiAnnotation.AnnTilde',
107 108

-- For details on above see note [Api annotations] in ApiAnnotation
109
data RdrName
110
  = Unqual OccName
111 112
        -- ^ Used for ordinary, unqualified occurrences, e.g. @x@, @y@ or @Foo@.
        -- Create such a 'RdrName' with 'mkRdrUnqual'
113

Simon Marlow's avatar
Simon Marlow committed
114
  | Qual ModuleName OccName
115 116 117 118 119 120
        -- ^ A qualified name written by the user in
        -- /source/ code.  The module isn't necessarily
        -- the module where the thing is defined;
        -- just the one from which it is imported.
        -- Examples are @Bar.x@, @Bar.y@ or @Bar.Foo@.
        -- Create such a 'RdrName' with 'mkRdrQual'
121

122
  | Orig Module OccName
123 124 125 126 127 128
        -- ^ An original name; the module is the /defining/ module.
        -- This is used when GHC generates code that will be fed
        -- into the renamer (e.g. from deriving clauses), but where
        -- we want to say \"Use Prelude.map dammit\". One of these
        -- can be created with 'mkOrig'

129
  | Exact Name
130 131 132 133 134 135 136 137
        -- ^ We know exactly the 'Name'. This is used:
        --
        --  (1) When the parser parses built-in syntax like @[]@
        --      and @(,)@, but wants a 'RdrName' from it
        --
        --  (2) By Template Haskell, when TH has generated a unique name
        --
        -- Such a 'RdrName' can be created by using 'getRdrName' on a 'Name'
138
  deriving (Data, Typeable)
139

Austin Seipp's avatar
Austin Seipp committed
140 141 142
{-
************************************************************************
*                                                                      *
143
\subsection{Simple functions}
Austin Seipp's avatar
Austin Seipp committed
144 145 146
*                                                                      *
************************************************************************
-}
147 148 149 150

instance HasOccName RdrName where
  occName = rdrNameOcc

151
rdrNameOcc :: RdrName -> OccName
152 153 154 155 156
rdrNameOcc (Qual _ occ) = occ
rdrNameOcc (Unqual occ) = occ
rdrNameOcc (Orig _ occ) = occ
rdrNameOcc (Exact name) = nameOccName name

157 158 159
rdrNameSpace :: RdrName -> NameSpace
rdrNameSpace = occNameSpace . rdrNameOcc

dreixel's avatar
dreixel committed
160 161 162 163 164 165 166
-- demoteRdrName lowers the NameSpace of RdrName.
-- see Note [Demotion] in OccName
demoteRdrName :: RdrName -> Maybe RdrName
demoteRdrName (Unqual occ) = fmap Unqual (demoteOccName occ)
demoteRdrName (Qual m occ) = fmap (Qual m) (demoteOccName occ)
demoteRdrName (Orig _ _) = panic "demoteRdrName"
demoteRdrName (Exact _) = panic "demoteRdrName"
167

168
        -- These two are the basic constructors
169
mkRdrUnqual :: OccName -> RdrName
170
mkRdrUnqual occ = Unqual occ
171

Simon Marlow's avatar
Simon Marlow committed
172
mkRdrQual :: ModuleName -> OccName -> RdrName
173
mkRdrQual mod occ = Qual mod occ
174

175
mkOrig :: Module -> OccName -> RdrName
176
mkOrig mod occ = Orig mod occ
177

178
---------------
179 180
        -- These two are used when parsing source files
        -- They do encode the module and occurrence names
181 182
mkUnqual :: NameSpace -> FastString -> RdrName
mkUnqual sp n = Unqual (mkOccNameFS sp n)
183

184 185
mkVarUnqual :: FastString -> RdrName
mkVarUnqual n = Unqual (mkVarOccFS n)
186

187 188
-- | Make a qualified 'RdrName' in the given namespace and where the 'ModuleName' and
-- the 'OccName' are taken from the first and second elements of the tuple respectively
189
mkQual :: NameSpace -> (FastString, FastString) -> RdrName
Simon Marlow's avatar
Simon Marlow committed
190
mkQual sp (m, n) = Qual (mkModuleNameFS m) (mkOccNameFS sp n)
191 192

getRdrName :: NamedThing thing => thing -> RdrName
193
getRdrName name = nameRdrName (getName name)
194

195 196
nameRdrName :: Name -> RdrName
nameRdrName name = Exact name
197 198 199
-- Keep the Name even for Internal names, so that the
-- unique is still there for debug printing, particularly
-- of Types (which are converted to IfaceTypes before printing)
200

201
nukeExact :: Name -> RdrName
202
nukeExact n
203
  | isExternalName n = Orig (nameModule n) (nameOccName n)
204
  | otherwise        = Unqual (nameOccName n)
205

twanvl's avatar
twanvl committed
206 207 208 209
isRdrDataCon :: RdrName -> Bool
isRdrTyVar   :: RdrName -> Bool
isRdrTc      :: RdrName -> Bool

210 211 212
isRdrDataCon rn = isDataOcc (rdrNameOcc rn)
isRdrTyVar   rn = isTvOcc   (rdrNameOcc rn)
isRdrTc      rn = isTcOcc   (rdrNameOcc rn)
213

twanvl's avatar
twanvl committed
214
isSrcRdrName :: RdrName -> Bool
215 216
isSrcRdrName (Unqual _) = True
isSrcRdrName (Qual _ _) = True
217
isSrcRdrName _          = False
218

twanvl's avatar
twanvl committed
219
isUnqual :: RdrName -> Bool
220
isUnqual (Unqual _) = True
twanvl's avatar
twanvl committed
221
isUnqual _          = False
222

twanvl's avatar
twanvl committed
223
isQual :: RdrName -> Bool
224
isQual (Qual _ _) = True
225
isQual _          = False
226

twanvl's avatar
twanvl committed
227
isQual_maybe :: RdrName -> Maybe (ModuleName, OccName)
Simon Marlow's avatar
Simon Marlow committed
228
isQual_maybe (Qual m n) = Just (m,n)
229
isQual_maybe _          = Nothing
Simon Marlow's avatar
Simon Marlow committed
230

twanvl's avatar
twanvl committed
231
isOrig :: RdrName -> Bool
232
isOrig (Orig _ _) = True
233
isOrig _          = False
234

twanvl's avatar
twanvl committed
235
isOrig_maybe :: RdrName -> Maybe (Module, OccName)
236
isOrig_maybe (Orig m n) = Just (m,n)
237
isOrig_maybe _          = Nothing
238

twanvl's avatar
twanvl committed
239
isExact :: RdrName -> Bool
240
isExact (Exact _) = True
twanvl's avatar
twanvl committed
241
isExact _         = False
242

twanvl's avatar
twanvl committed
243
isExact_maybe :: RdrName -> Maybe Name
244
isExact_maybe (Exact n) = Just n
twanvl's avatar
twanvl committed
245
isExact_maybe _         = Nothing
246

Austin Seipp's avatar
Austin Seipp committed
247 248 249
{-
************************************************************************
*                                                                      *
250
\subsection{Instances}
Austin Seipp's avatar
Austin Seipp committed
251 252 253
*                                                                      *
************************************************************************
-}
254 255

instance Outputable RdrName where
256
    ppr (Exact name)   = ppr name
257 258
    ppr (Unqual occ)   = ppr occ
    ppr (Qual mod occ) = ppr mod <> dot <> ppr occ
259
    ppr (Orig mod occ) = getPprStyle (\sty -> pprModulePrefix sty mod occ <> ppr occ)
260

261
instance OutputableBndr RdrName where
262 263 264
    pprBndr _ n
        | isTvOcc (rdrNameOcc n) = char '@' <+> ppr n
        | otherwise              = ppr n
265

266
    pprInfixOcc  rdr = pprInfixVar  (isSymOcc (rdrNameOcc rdr)) (ppr rdr)
267
    pprPrefixOcc rdr
268 269 270 271
      | Just name <- isExact_maybe rdr = pprPrefixName name
             -- pprPrefixName has some special cases, so
             -- we delegate to them rather than reproduce them
      | otherwise = pprPrefixVar (isSymOcc (rdrNameOcc rdr)) (ppr rdr)
272

273
instance Eq RdrName where
274 275 276
    (Exact n1)    == (Exact n2)    = n1==n2
        -- Convert exact to orig
    (Exact n1)    == r2@(Orig _ _) = nukeExact n1 == r2
277 278 279 280 281
    r1@(Orig _ _) == (Exact n2)    = r1 == nukeExact n2

    (Orig m1 o1)  == (Orig m2 o2)  = m1==m2 && o1==o2
    (Qual m1 o1)  == (Qual m2 o2)  = m1==m2 && o1==o2
    (Unqual o1)   == (Unqual o2)   = o1==o2
twanvl's avatar
twanvl committed
282
    _             == _             = False
283 284 285

instance Ord RdrName where
    a <= b = case (a `compare` b) of { LT -> True;  EQ -> True;  GT -> False }
286
    a <  b = case (a `compare` b) of { LT -> True;  EQ -> False; GT -> False }
287
    a >= b = case (a `compare` b) of { LT -> False; EQ -> True;  GT -> True  }
288 289 290 291 292 293 294 295 296 297
    a >  b = case (a `compare` b) of { LT -> False; EQ -> False; GT -> True  }

        -- Exact < Unqual < Qual < Orig
        -- [Note: Apr 2004] We used to use nukeExact to convert Exact to Orig
        --      before comparing so that Prelude.map == the exact Prelude.map, but
        --      that meant that we reported duplicates when renaming bindings
        --      generated by Template Haskell; e.g
        --      do { n1 <- newName "foo"; n2 <- newName "foo";
        --           <decl involving n1,n2> }
        --      I think we can do without this conversion
298
    compare (Exact n1) (Exact n2) = n1 `compare` n2
twanvl's avatar
twanvl committed
299
    compare (Exact _)  _          = LT
300 301

    compare (Unqual _)   (Exact _)    = GT
302
    compare (Unqual o1)  (Unqual  o2) = o1 `compare` o2
303
    compare (Unqual _)   _            = LT
304 305 306

    compare (Qual _ _)   (Exact _)    = GT
    compare (Qual _ _)   (Unqual _)   = GT
307
    compare (Qual m1 o1) (Qual m2 o2) = (o1 `compare` o2) `thenCmp` (m1 `compare` m2)
308
    compare (Qual _ _)   (Orig _ _)   = LT
309

310 311
    compare (Orig m1 o1) (Orig m2 o2) = (o1 `compare` o2) `thenCmp` (m1 `compare` m2)
    compare (Orig _ _)   _            = GT
312

Austin Seipp's avatar
Austin Seipp committed
313 314 315
{-
************************************************************************
*                                                                      *
316
                        LocalRdrEnv
Austin Seipp's avatar
Austin Seipp committed
317 318 319
*                                                                      *
************************************************************************
-}
320

321 322
-- | This environment is used to store local bindings (@let@, @where@, lambda, @case@).
-- It is keyed by OccName, because we never use it for qualified names
323 324
-- We keep the current mapping, *and* the set of all Names in scope
-- Reason: see Note [Splicing Exact Names] in RnEnv
325 326 327 328 329 330 331
data LocalRdrEnv = LRE { lre_env      :: OccEnv Name
                       , lre_in_scope :: NameSet }

instance Outputable LocalRdrEnv where
  ppr (LRE {lre_env = env, lre_in_scope = ns})
    = hang (ptext (sLit "LocalRdrEnv {"))
         2 (vcat [ ptext (sLit "env =") <+> pprOccEnv ppr_elt env
332
                 , ptext (sLit "in_scope =") <+> braces (pprWithCommas ppr (nameSetElems ns))
333 334 335 336
                 ] <+> char '}')
    where
      ppr_elt name = parens (ppr (getUnique (nameOccName name))) <+> ppr name
                     -- So we can see if the keys line up correctly
337

twanvl's avatar
twanvl committed
338
emptyLocalRdrEnv :: LocalRdrEnv
339
emptyLocalRdrEnv = LRE { lre_env = emptyOccEnv, lre_in_scope = emptyNameSet }
gmainland's avatar
gmainland committed
340

341 342
extendLocalRdrEnv :: LocalRdrEnv -> Name -> LocalRdrEnv
-- The Name should be a non-top-level thing
343
extendLocalRdrEnv (LRE { lre_env = env, lre_in_scope = ns }) name
344
  = WARN( isExternalName name, ppr name )
345
    LRE { lre_env      = extendOccEnv env (nameOccName name) name
346
        , lre_in_scope = extendNameSet ns name }
gmainland's avatar
gmainland committed
347

348
extendLocalRdrEnvList :: LocalRdrEnv -> [Name] -> LocalRdrEnv
349
extendLocalRdrEnvList (LRE { lre_env = env, lre_in_scope = ns }) names
350
  = WARN( any isExternalName names, ppr names )
351
    LRE { lre_env = extendOccEnvList env [(nameOccName n, n) | n <- names]
352
        , lre_in_scope = extendNameSetList ns names }
353 354

lookupLocalRdrEnv :: LocalRdrEnv -> RdrName -> Maybe Name
355 356
lookupLocalRdrEnv (LRE { lre_env = env }) (Unqual occ) = lookupOccEnv env occ
lookupLocalRdrEnv _                       _            = Nothing
357

358
lookupLocalRdrOcc :: LocalRdrEnv -> OccName -> Maybe Name
359
lookupLocalRdrOcc (LRE { lre_env = env }) occ = lookupOccEnv env occ
360

361
elemLocalRdrEnv :: RdrName -> LocalRdrEnv -> Bool
362 363 364 365 366 367
elemLocalRdrEnv rdr_name (LRE { lre_env = env, lre_in_scope = ns })
  = case rdr_name of
      Unqual occ -> occ  `elemOccEnv` env
      Exact name -> name `elemNameSet` ns  -- See Note [Local bindings with Exact Names]
      Qual {} -> False
      Orig {} -> False
368 369

localRdrEnvElts :: LocalRdrEnv -> [Name]
370
localRdrEnvElts (LRE { lre_env = env }) = occEnvElts env
371 372 373

inLocalRdrEnvScope :: Name -> LocalRdrEnv -> Bool
-- This is the point of the NameSet
374
inLocalRdrEnvScope name (LRE { lre_in_scope = ns }) = name `elemNameSet` ns
375 376

delLocalRdrEnvList :: LocalRdrEnv -> [OccName] -> LocalRdrEnv
Austin Seipp's avatar
Austin Seipp committed
377
delLocalRdrEnvList (LRE { lre_env = env, lre_in_scope = ns }) occs
378 379
  = LRE { lre_env = delListFromOccEnv env occs
        , lre_in_scope = ns }
380

Austin Seipp's avatar
Austin Seipp committed
381
{-
382 383 384 385 386 387 388 389
Note [Local bindings with Exact Names]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
With Template Haskell we can make local bindings that have Exact Names.
Computing shadowing etc may use elemLocalRdrEnv (at least it certainly
does so in RnTpes.bindHsTyVars), so for an Exact Name we must consult
the in-scope-name-set.


Austin Seipp's avatar
Austin Seipp committed
390 391
************************************************************************
*                                                                      *
392
                        GlobalRdrEnv
Austin Seipp's avatar
Austin Seipp committed
393 394 395
*                                                                      *
************************************************************************
-}
396 397

type GlobalRdrEnv = OccEnv [GlobalRdrElt]
398 399 400 401 402 403 404 405 406
-- ^ Keyed by 'OccName'; when looking up a qualified name
-- we look up the 'OccName' part, and then check the 'Provenance'
-- to see if the appropriate qualification is valid.  This
-- saves routinely doubling the size of the env by adding both
-- qualified and unqualified names to the domain.
--
-- The list in the codomain is required because there may be name clashes
-- These only get reported on lookup, not on construction
--
407 408
-- INVARIANT 1: All the members of the list have distinct
--              'gre_name' fields; that is, no duplicate Names
409
--
410 411 412 413 414
-- INVARIANT 2: Imported provenance => Name is an ExternalName
--              However LocalDefs can have an InternalName.  This
--              happens only when type-checking a [d| ... |] Template
--              Haskell quotation; see this note in RnNames
--              Note [Top-level Names in Template Haskell decl quotes]
415

416
-- | An element of the 'GlobalRdrEnv'
417
data GlobalRdrElt
418 419 420 421 422 423
  = GRE { gre_name :: Name
        , gre_par  :: Parent
        , gre_lcl :: Bool          -- ^ True <=> the thing was defined locally
        , gre_imp :: [ImportSpec]  -- ^ In scope through these imports
    }    -- INVARIANT: either gre_lcl = True or gre_imp is non-empty
         -- See Note [GlobalRdrElt provenance]
424

425
-- | The children of a Name are the things that are abbreviated by the ".."
426
--   notation in export lists.  See Note [Parents]
Adam Gundry's avatar
Adam Gundry committed
427 428 429 430 431
data Parent = NoParent
            | ParentIs  { par_is :: Name }
            | FldParent { par_is :: Name, par_lbl :: Maybe FieldLabelString }
              -- ^ See Note [Parents for record fields]
            deriving (Eq)
432

433
instance Outputable Parent where
Adam Gundry's avatar
Adam Gundry committed
434 435 436 437
   ppr NoParent        = empty
   ppr (ParentIs n)    = ptext (sLit "parent:") <> ppr n
   ppr (FldParent n f) = ptext (sLit "fldparent:")
                             <> ppr n <> colon <> ppr f
438 439 440

plusParent :: Parent -> Parent -> Parent
-- See Note [Combining parents]
Adam Gundry's avatar
Adam Gundry committed
441 442 443 444 445
plusParent p1@(ParentIs _)    p2 = hasParent p1 p2
plusParent p1@(FldParent _ _) p2 = hasParent p1 p2
plusParent p1 p2@(ParentIs _)    = hasParent p2 p1
plusParent p1 p2@(FldParent _ _) = hasParent p2 p1
plusParent NoParent NoParent     = NoParent
446

Adam Gundry's avatar
Adam Gundry committed
447
hasParent :: Parent -> Parent -> Parent
448
#ifdef DEBUG
Adam Gundry's avatar
Adam Gundry committed
449 450 451
hasParent p NoParent = p
hasParent p p'
  | p /= p' = pprPanic "hasParent" (ppr p <+> ppr p')  -- Parents should agree
452
#endif
Adam Gundry's avatar
Adam Gundry committed
453 454
hasParent p _  = p

455

456 457 458 459 460 461 462 463
{- Note [GlobalRdrElt provenance]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The gre_lcl and gre_imp fields of a GlobalRdrElt describe its "provenance",
i.e. how the Name came to be in scope.  It can be in scope two ways:
  - gre_lcl = True: it is bound in this module
  - gre_imp: a list of all the imports that brought it into scope

It's an INVARIANT that you have one or the other; that is, either
Sergei Trofimovich's avatar
Sergei Trofimovich committed
464
gre_lcl is True, or gre_imp is non-empty.
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481

It is just possible to have *both* if there is a module loop: a Name
is defined locally in A, and also brought into scope by importing a
module that SOURCE-imported A.  Exapmle (Trac #7672):

 A.hs-boot   module A where
               data T

 B.hs        module B(Decl.T) where
               import {-# SOURCE #-} qualified A as Decl

 A.hs        module A where
               import qualified B
               data T = Z | S B.T

In A.hs, 'T' is locally bound, *and* imported as B.T.

482
Note [Parents]
483
~~~~~~~~~~~~~~~~~
484
  Parent           Children
485 486
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  data T           Data constructors
487
                   Record-field ids
488 489 490 491

  data family T    Data constructors and record-field ids
                   of all visible data instances of T

492 493
  class C          Class operations
                   Associated type constructors
494

Adam Gundry's avatar
Adam Gundry committed
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522

Note [Parents for record fields]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

For record fields, in addition to the Name of the type constructor
(stored in par_is), we use FldParent to store the field label.  This
extra information is used for identifying overloaded record fields
during renaming.

In a definition arising from a normal module (without
-XDuplicateRecordFields), par_lbl will be Nothing, meaning that the
field's label is the same as the OccName of the selector's Name.  The
GlobalRdrEnv will contain an entry like this:

    "x" |->  GRE x (FldParent T Nothing) LocalDef

When -XDuplicateRecordFields is enabled for the module that contains
T, the selector's Name will be mangled (see comments in FieldLabel).
Thus we store the actual field label in par_lbl, and the GlobalRdrEnv
entry looks like this:

    "x" |->  GRE $sel:x:MkT (FldParent T (Just "x")) LocalDef

Note that the OccName used when adding a GRE to the environment
(greOccName) now depends on the parent field: for FldParent it is the
field label, if present, rather than the selector name.


523 524 525 526 527 528 529 530 531 532 533 534 535
Note [Combining parents]
~~~~~~~~~~~~~~~~~~~~~~~~
With an associated type we might have
   module M where
     class C a where
       data T a
       op :: T a -> a
     instance C Int where
       data T Int = TInt
     instance C Bool where
       data T Bool = TBool

Then:   C is the parent of T
536
        T is the parent of TInt and TBool
537 538 539 540 541 542 543
So: in an export list
    C(..) is short for C( op, T )
    T(..) is short for T( TInt, TBool )

Module M exports everything, so its exports will be
   AvailTC C [C,T,op]
   AvailTC T [T,TInt,TBool]
544
On import we convert to GlobalRdrElt and then combine
545
those.  For T that will mean we have
546 547 548
  one GRE with Parent C
  one GRE with NoParent
That's why plusParent picks the "best" case.
Austin Seipp's avatar
Austin Seipp committed
549
-}
550

551
-- | make a 'GlobalRdrEnv' where all the elements point to the same
552 553 554 555
-- Provenance (useful for "hiding" imports, or imports with no details).
gresFromAvails :: Maybe ImportSpec -> [AvailInfo] -> [GlobalRdrElt]
-- prov = Nothing   => locally bound
--        Just spec => imported as described by spec
556 557 558
gresFromAvails prov avails
  = concatMap (gresFromAvail (const prov)) avails

559 560
localGREsFromAvail :: AvailInfo -> [GlobalRdrElt]
-- Turn an Avail into a list of LocalDef GlobalRdrElts
561 562 563 564
localGREsFromAvail = gresFromAvail (const Nothing)

gresFromAvail :: (Name -> Maybe ImportSpec) -> AvailInfo -> [GlobalRdrElt]
gresFromAvail prov_fn avail
Adam Gundry's avatar
Adam Gundry committed
565
  = map mk_gre (availNonFldNames avail) ++ map mk_fld_gre (availFlds avail)
566 567 568 569 570 571 572 573 574
  where
    mk_gre n
      = case prov_fn n of  -- Nothing => bound locally
                           -- Just is => imported from 'is'
          Nothing -> GRE { gre_name = n, gre_par = mkParent n avail
                         , gre_lcl = True, gre_imp = [] }
          Just is -> GRE { gre_name = n, gre_par = mkParent n avail
                         , gre_lcl = False, gre_imp = [is] }

Adam Gundry's avatar
Adam Gundry committed
575 576 577 578 579 580 581 582 583 584 585 586
    mk_fld_gre (FieldLabel lbl is_overloaded n)
      = case prov_fn n of  -- Nothing => bound locally
                           -- Just is => imported from 'is'
          Nothing -> GRE { gre_name = n, gre_par = FldParent (availName avail) mb_lbl
                         , gre_lcl = True, gre_imp = [] }
          Just is -> GRE { gre_name = n, gre_par = FldParent (availName avail) mb_lbl
                         , gre_lcl = False, gre_imp = [is] }
      where
        mb_lbl | is_overloaded = Just lbl
               | otherwise     = Nothing


587 588 589 590 591 592 593 594 595 596
greQualModName :: GlobalRdrElt -> ModuleName
-- Get a suitable module qualifier for the GRE
-- (used in mkPrintUnqualified)
-- Prerecondition: the gre_name is always External
greQualModName gre@(GRE { gre_name = name, gre_lcl = lcl, gre_imp = iss })
 | lcl, Just mod <- nameModule_maybe name = moduleName mod
 | (is:_) <- iss                          = is_as (is_decl is)
 | otherwise                              = pprPanic "greQualModName" (ppr gre)

greUsedRdrName :: GlobalRdrElt -> RdrName
597 598 599 600
-- For imported things, return a RdrName to add to the used-RdrName
-- set, which is used to generate unused-import-decl warnings.
-- Return a Qual RdrName if poss, so that identifies the most
-- specific ImportSpec.  See Trac #10890 for some good examples.
Adam Gundry's avatar
Adam Gundry committed
601
greUsedRdrName gre@GRE{ gre_name = name, gre_lcl = lcl, gre_imp = iss }
602 603 604
  | lcl, Just mod <- nameModule_maybe name = Qual (moduleName mod)     occ
  | not (null iss), is <- bestImport iss   = Qual (is_as (is_decl is)) occ
  | otherwise                              = pprTrace "greUsedRdrName" (ppr gre) (Unqual occ)
605
  where
Adam Gundry's avatar
Adam Gundry committed
606
    occ = greOccName gre
607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628

greRdrNames :: GlobalRdrElt -> [RdrName]
greRdrNames GRE{ gre_name = name, gre_lcl = lcl, gre_imp = iss }
  = (if lcl then [unqual] else []) ++ concatMap do_spec (map is_decl iss)
  where
    occ    = nameOccName name
    unqual = Unqual occ
    do_spec decl_spec
        | is_qual decl_spec = [qual]
        | otherwise         = [unqual,qual]
        where qual = Qual (is_as decl_spec) occ

-- the SrcSpan that pprNameProvenance prints out depends on whether
-- the Name is defined locally or not: for a local definition the
-- definition site is used, otherwise the location of the import
-- declaration.  We want to sort the export locations in
-- exportClashErr by this SrcSpan, we need to extract it:
greSrcSpan :: GlobalRdrElt -> SrcSpan
greSrcSpan gre@(GRE { gre_name = name, gre_lcl = lcl, gre_imp = iss } )
  | lcl           = nameSrcSpan name
  | (is:_) <- iss = is_dloc (is_decl is)
  | otherwise     = pprPanic "greSrcSpan" (ppr gre)
629

630
mkParent :: Name -> AvailInfo -> Parent
Adam Gundry's avatar
Adam Gundry committed
631 632 633
mkParent _ (Avail _)                   = NoParent
mkParent n (AvailTC m _ _) | n == m    = NoParent
                           | otherwise = ParentIs m
634

635 636 637
availFromGRE :: GlobalRdrElt -> AvailInfo
availFromGRE gre
  = case gre_par gre of
Adam Gundry's avatar
Adam Gundry committed
638 639
      ParentIs p                  -> AvailTC p [me] []
      NoParent   | isTyConName me -> AvailTC me [me] []
640
                 | otherwise      -> Avail   me
Adam Gundry's avatar
Adam Gundry committed
641 642
      FldParent p Nothing         -> AvailTC p [] [FieldLabel (occNameFS $ nameOccName me) False me]
      FldParent p (Just lbl)      -> AvailTC p [] [FieldLabel lbl True me]
643 644 645
  where
    me = gre_name gre

twanvl's avatar
twanvl committed
646
emptyGlobalRdrEnv :: GlobalRdrEnv
647 648 649 650 651 652
emptyGlobalRdrEnv = emptyOccEnv

globalRdrEnvElts :: GlobalRdrEnv -> [GlobalRdrElt]
globalRdrEnvElts env = foldOccEnv (++) [] env

instance Outputable GlobalRdrElt where
653 654
  ppr gre = hang (ppr (gre_name gre) <+> ppr (gre_par gre))
               2 (pprNameProvenance gre)
655

656 657
pprGlobalRdrEnv :: Bool -> GlobalRdrEnv -> SDoc
pprGlobalRdrEnv locals_only env
Austin Seipp's avatar
Austin Seipp committed
658
  = vcat [ ptext (sLit "GlobalRdrEnv") <+> ppWhen locals_only (ptext (sLit "(locals only)"))
659
             <+> lbrace
Austin Seipp's avatar
Austin Seipp committed
660
         , nest 2 (vcat [ pp (remove_locals gre_list) | gre_list <- occEnvElts env ]
661
             <+> rbrace) ]
662
  where
663 664 665 666 667 668 669 670 671
    remove_locals gres | locals_only = filter isLocalGRE gres
                       | otherwise   = gres
    pp []   = empty
    pp gres = hang (ppr occ
                     <+> parens (ptext (sLit "unique") <+> ppr (getUnique occ))
                     <> colon)
                 2 (vcat (map ppr gres))
      where
        occ = nameOccName (gre_name (head gres))
672 673

lookupGlobalRdrEnv :: GlobalRdrEnv -> OccName -> [GlobalRdrElt]
674
lookupGlobalRdrEnv env occ_name = case lookupOccEnv env occ_name of
675 676
                                  Nothing   -> []
                                  Just gres -> gres
Adam Gundry's avatar
Adam Gundry committed
677 678 679 680 681

greOccName :: GlobalRdrElt -> OccName
greOccName (GRE{gre_par = FldParent{par_lbl = Just lbl}}) = mkVarOccFS lbl
greOccName gre                                            = nameOccName (gre_name gre)

682 683
lookupGRE_RdrName :: RdrName -> GlobalRdrEnv -> [GlobalRdrElt]
lookupGRE_RdrName rdr_name env
684
  = case lookupOccEnv env (rdrNameOcc rdr_name) of
685 686
    Nothing   -> []
    Just gres -> pickGREs rdr_name gres
687 688 689 690

lookupGRE_Name :: GlobalRdrEnv -> Name -> [GlobalRdrElt]
lookupGRE_Name env name
  = [ gre | gre <- lookupGlobalRdrEnv env (nameOccName name),
691
            gre_name gre == name ]
692

Adam Gundry's avatar
Adam Gundry committed
693 694 695 696 697 698 699 700
lookupGRE_Field_Name :: GlobalRdrEnv -> Name -> FastString -> [GlobalRdrElt]
-- Used when looking up record fields, where the selector name and
-- field label are different: the GlobalRdrEnv is keyed on the label
lookupGRE_Field_Name env sel_name lbl
  = [ gre | gre <- lookupGlobalRdrEnv env (mkVarOccFS lbl),
            gre_name gre == sel_name ]


701
getGRE_NameQualifier_maybes :: GlobalRdrEnv -> Name -> [Maybe [ModuleName]]
702 703
-- Returns all the qualifiers by which 'x' is in scope
-- Nothing means "the unqualified version is in scope"
704
-- [] means the thing is not in scope at all
705
getGRE_NameQualifier_maybes env
706
  = map (qualifier_maybe) . lookupGRE_Name env
707
  where
708 709 710
    qualifier_maybe (GRE { gre_lcl = lcl, gre_imp = iss })
      | lcl       = Nothing
      | otherwise = Just $ map (is_as . is_decl) iss
711

712
isLocalGRE :: GlobalRdrElt -> Bool
713
isLocalGRE (GRE {gre_lcl = lcl }) = lcl
714

Adam Gundry's avatar
Adam Gundry committed
715 716 717 718 719 720 721 722 723 724
isRecFldGRE :: GlobalRdrElt -> Bool
isRecFldGRE (GRE {gre_par = FldParent{}}) = True
isRecFldGRE _                             = False

-- Returns the field label of this GRE, if it has one
greLabel :: GlobalRdrElt -> Maybe FieldLabelString
greLabel (GRE{gre_par = FldParent{par_lbl = Just lbl}}) = Just lbl
greLabel (GRE{gre_name = n, gre_par = FldParent{}})     = Just (occNameFS (nameOccName n))
greLabel _                                              = Nothing

725 726
unQualOK :: GlobalRdrElt -> Bool
-- ^ Test if an unqualifed version of this thing would be in scope
727 728 729
unQualOK (GRE {gre_lcl = lcl, gre_imp = iss })
  | lcl = True
  | otherwise = any unQualSpecOK iss
730

731
pickGREs :: RdrName -> [GlobalRdrElt] -> [GlobalRdrElt]
732
-- ^ Take a list of GREs which have the right OccName
733 734
-- Pick those GREs that are suitable for this RdrName
-- And for those, keep only only the Provenances that are suitable
Simon Peyton Jones's avatar
Simon Peyton Jones committed
735
-- Only used for Qual and Unqual, not Orig or Exact
736
--
737 738 739
-- Consider:
--
-- @
740 741 742 743
--       module A ( f ) where
--       import qualified Foo( f )
--       import Baz( f )
--       f = undefined
744 745 746 747 748
-- @
--
-- Let's suppose that @Foo.f@ and @Baz.f@ are the same entity really.
-- The export of @f@ is ambiguous because it's in scope from the local def
-- and the import.  The lookup of @Unqual f@ should return a GRE for
749
-- the locally-defined @f@, and a GRE for the imported @f@, with a /single/
750 751
-- provenance, namely the one for @Baz(f)@, so that the "ambiguous occurrence"
-- message mentions the correct candidates
752
pickGREs rdr_name gres
Simon Peyton Jones's avatar
Simon Peyton Jones committed
753
  = ASSERT2( isSrcRdrName rdr_name, ppr rdr_name )
754
    mapMaybe pick gres
755
  where
Simon Marlow's avatar
Simon Marlow committed
756 757
    rdr_is_unqual = isUnqual rdr_name
    rdr_is_qual   = isQual_maybe rdr_name
758 759

    pick :: GlobalRdrElt -> Maybe GlobalRdrElt
760 761 762 763 764 765 766
    pick gre@(GRE { gre_name = n, gre_lcl = lcl, gre_imp = iss })
        | not lcl' && null iss'
        = Nothing

        | otherwise
        = Just (gre { gre_lcl = lcl', gre_imp = iss' })

767
        where
768 769 770 771 772 773 774 775 776 777 778 779 780 781
          lcl' | not lcl       = False
               | rdr_is_unqual = True
               | Just (mod,_) <- rdr_is_qual        -- Qualified name
               , Just n_mod <- nameModule_maybe n   -- Binder is External
               = mod == moduleName n_mod
               | otherwise
               = False

          iss' | rdr_is_unqual
               = filter (not . is_qual    . is_decl) iss
               | Just (mod,_) <- rdr_is_qual
               = filter ((== mod) . is_as . is_decl) iss
               | otherwise
               = []
782

Austin Seipp's avatar
Austin Seipp committed
783
-- Building GlobalRdrEnvs
784

785 786 787 788 789 790 791
plusGlobalRdrEnv :: GlobalRdrEnv -> GlobalRdrEnv -> GlobalRdrEnv
plusGlobalRdrEnv env1 env2 = plusOccEnv_C (foldr insertGRE) env1 env2

mkGlobalRdrEnv :: [GlobalRdrElt] -> GlobalRdrEnv
mkGlobalRdrEnv gres
  = foldr add emptyGlobalRdrEnv gres
  where
792
    add gre env = extendOccEnv_Acc insertGRE singleton env
Adam Gundry's avatar
Adam Gundry committed
793
                                   (greOccName gre)
794
                                   gre
795 796 797 798

insertGRE :: GlobalRdrElt -> [GlobalRdrElt] -> [GlobalRdrElt]
insertGRE new_g [] = [new_g]
insertGRE new_g (old_g : old_gs)
799 800 801 802
        | gre_name new_g == gre_name old_g
        = new_g `plusGRE` old_g : old_gs
        | otherwise
        = old_g : insertGRE new_g old_gs
803 804 805 806

plusGRE :: GlobalRdrElt -> GlobalRdrElt -> GlobalRdrElt
-- Used when the gre_name fields match
plusGRE g1 g2
807 808 809 810
  = GRE { gre_name = gre_name g1
        , gre_lcl  = gre_lcl g1 || gre_lcl g2
        , gre_imp  = gre_imp g1 ++ gre_imp g2
        , gre_par  = gre_par  g1 `plusParent` gre_par  g2 }
811

812
transformGREs :: (GlobalRdrElt -> GlobalRdrElt)
813
              -> [OccName]
814 815 816 817
              -> GlobalRdrEnv -> GlobalRdrEnv
-- ^ Apply a transformation function to the GREs for these OccNames
transformGREs trans_gre occs rdr_env
  = foldr trans rdr_env occs
818
  where
819 820
    trans occ env
      = case lookupOccEnv env occ of
821 822
           Just gres -> extendOccEnv env occ (map trans_gre gres)
           Nothing   -> env
823

824 825 826
extendGlobalRdrEnv :: GlobalRdrEnv -> GlobalRdrElt -> GlobalRdrEnv
extendGlobalRdrEnv env gre
  = extendOccEnv_Acc insertGRE singleton env
Adam Gundry's avatar
Adam Gundry committed
827
                     (greOccName gre) gre
828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874

shadowNames :: GlobalRdrEnv -> [Name] -> GlobalRdrEnv
shadowNames = foldl shadowName

{- Note [GlobalRdrEnv shadowing]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Before adding new names to the GlobalRdrEnv we nuke some existing entries;
this is "shadowing".  The actual work is done by RdrEnv.shadowNames.
There are two reasons for shadowing:

* The GHCi REPL

  - Ids bought into scope on the command line (eg let x = True) have
    External Names, like Ghci4.x.  We want a new binding for 'x' (say)
    to override the existing binding for 'x'.
    See Note [Interactively-bound Ids in GHCi] in HscTypes

  - Data types also have Extenal Names, like Ghci4.T; but we still want
    'T' to mean the newly-declared 'T', not an old one.

* Nested Template Haskell declaration brackets
  See Note [Top-level Names in Template Haskell decl quotes] in RnNames

  Consider a TH decl quote:
      module M where
        f x = h [d| f = 3 |]
  We must shadow the outer declaration of 'f', else we'll get a
  complaint when extending the GlobalRdrEnv, saying that there are two
  bindings for 'f'.  There are several tricky points:

    - This shadowing applies even if the binding for 'f' is in a
      where-clause, and hence is in the *local* RdrEnv not the *global*
      RdrEnv.  This is done in lcl_env_TH in extendGlobalRdrEnvRn.

    - The External Name M.f from the enclosing module must certainly
      still be available.  So we don't nuke it entirely; we just make
      it seem like qualified import.

    - We only shadow *External* names (which come from the main module),
      or from earlier GHCi commands. Do not shadow *Internal* names
      because in the bracket
          [d| class C a where f :: a
              f = 4 |]
      rnSrcDecls will first call extendGlobalRdrEnvRn with C[f] from the
      class decl, and *separately* extend the envt with the value binding.
      At that stage, the class op 'f' will have an Internal name.
-}
875

876
shadowName :: GlobalRdrEnv -> Name -> GlobalRdrEnv
877
-- Remove certain old GREs that share the same OccName as this new Name.
878 879
-- See Note [GlobalRdrEnv shadowing] for details
shadowName env name
880 881 882
  = alterOccEnv (fmap alter_fn) env (nameOccName name)
  where
    alter_fn :: [GlobalRdrElt] -> [GlobalRdrElt]
Icelandjack's avatar
Icelandjack committed
883
    alter_fn gres = mapMaybe (shadow_with name) gres
884 885

    shadow_with :: Name -> GlobalRdrElt -> Maybe GlobalRdrElt
886 887
    shadow_with new_name
       old_gre@(GRE { gre_name = old_name, gre_lcl = lcl, gre_imp = iss })
888
       = case nameModule_maybe old_name of
889
           Nothing -> Just old_gre   -- Old name is Internal; do not shadow
890 891
           Just old_mod
              | Just new_mod <- nameModule_maybe new_name
892
              , new_mod == old_mod   -- Old name same as new name; shadow completely
893
              -> Nothing
894 895 896 897

              | null iss'            -- Nothing remains
              -> Nothing

898
              | otherwise
899
              -> Just (old_gre { gre_lcl = False, gre_imp = iss' })
900

901 902 903 904
              where
                iss' = lcl_imp ++ mapMaybe (shadow_is new_name) iss
                lcl_imp | lcl       = [mk_fake_imp_spec old_name old_mod]
                        | otherwise = []
905

906 907 908 909 910 911 912 913 914
    mk_fake_imp_spec old_name old_mod    -- Urgh!
      = ImpSpec id_spec ImpAll
      where
        old_mod_name = moduleName old_mod
        id_spec      = ImpDeclSpec { is_mod = old_mod_name
                                   , is_as = old_mod_name
                                   , is_qual = True
                                   , is_dloc = nameSrcSpan old_name }

915 916 917 918 919 920 921
    shadow_is :: Name -> ImportSpec -> Maybe ImportSpec
    shadow_is new_name is@(ImpSpec { is_decl = id_spec })
       | Just new_mod <- nameModule_maybe new_name
       , is_as id_spec == moduleName new_mod
       = Nothing   -- Shadow both qualified and unqualified
       | otherwise -- Shadow unqualified only
       = Just (is { is_decl = id_spec { is_qual = True } })
922

923

Austin Seipp's avatar
Austin Seipp committed
924 925 926
{-
************************************************************************
*                                                                      *
927
                        ImportSpec
Austin Seipp's avatar
Austin Seipp committed
928 929 930
*                                                                      *
************************************************************************
-}
931

932
-- | The 'ImportSpec' of something says how it came to be imported
933
-- It's quite elaborate so that we can give accurate unused-name warnings.
934
data ImportSpec = ImpSpec { is_decl :: ImpDeclSpec,
935 936
                            is_item :: ImpItemSpec }
                deriving( Eq, Ord )
937

938 939 940
-- | Describes a particular import declaration and is
-- shared among all the 'Provenance's for that decl
data ImpDeclSpec
941
  = ImpDeclSpec {
942 943 944
        is_mod      :: ModuleName, -- ^ Module imported, e.g. @import Muggle@
                                   -- Note the @Muggle@ may well not be
                                   -- the defining module for this thing!
945 946

                                   -- TODO: either should be Module, or there
947
                                   -- should be a Maybe UnitId here too.
948 949 950
        is_as       :: ModuleName, -- ^ Import alias, e.g. from @as M@ (or @Muggle@ if there is no @as@ clause)
        is_qual     :: Bool,       -- ^ Was this import qualified?
        is_dloc     :: SrcSpan     -- ^ The location of the entire import declaration
951 952
    }

953 954
-- | Describes import info a particular Name
data ImpItemSpec
955 956
  = ImpAll              -- ^ The import had no import list,
                        -- or had a hiding list
957

9