Env.hs 67.9 KB
Newer Older
Austin Seipp's avatar
Austin Seipp committed
1 2 3
{-
(c) The GRASP/AQUA Project, Glasgow University, 1992-2006

4
GHC.Rename.Env contains functions which convert RdrNames into Names.
5

Austin Seipp's avatar
Austin Seipp committed
6
-}
7

Matthew Pickering's avatar
Matthew Pickering committed
8
{-# LANGUAGE CPP, MultiWayIf, NamedFieldPuns #-}
9

10
module GHC.Rename.Env (
Ian Lynagh's avatar
Ian Lynagh committed
11 12
        newTopSrcBinder,
        lookupLocatedTopBndrRn, lookupTopBndrRn,
13
        lookupLocatedOccRn, lookupOccRn, lookupOccRn_maybe,
14
        lookupLocalOccRn_maybe, lookupInfoOccRn,
15
        lookupLocalOccThLvl_maybe, lookupLocalOccRn,
16
        lookupTypeOccRn,
17
        lookupGlobalOccRn, lookupGlobalOccRn_maybe,
18
        lookupOccRn_overloaded, lookupGlobalOccRn_overloaded, lookupExactOcc,
19

Matthew Pickering's avatar
Matthew Pickering committed
20
        ChildLookupResult(..),
21 22
        lookupSubBndrOcc_helper,
        combineChildLookupResult, -- Called by lookupChildrenExport
Matthew Pickering's avatar
Matthew Pickering committed
23

Ian Lynagh's avatar
Ian Lynagh committed
24
        HsSigCtxt(..), lookupLocalTcNames, lookupSigOccRn,
25
        lookupSigCtxtOccRn,
26

27 28
        lookupInstDeclBndr, lookupRecFieldOcc, lookupFamInstName,
        lookupConstructorFields,
29 30 31 32

        lookupGreAvailRn,

        -- Rebindable Syntax
33 34
        lookupSyntaxName, lookupSyntaxName', lookupSyntaxNames,
        lookupIfThenElse,
35 36

        -- Constructing usage information
37
        addUsedGRE, addUsedGREs, addUsedDataCons,
Ian Lynagh's avatar
Ian Lynagh committed
38

39 40 41 42


        dataTcOccs, --TODO: Move this somewhere, into utils?

43
    ) where
44

45
#include "HsVersions.h"
46

47 48
import GhcPrelude

49 50
import GHC.Iface.Load   ( loadInterfaceForName, loadSrcInterface_maybe )
import GHC.Iface.Env
51
import GHC.Hs
52
import RdrName
53
import HscTypes
54
import TcEnv
55
import TcRnMonad
56
import RdrHsSyn         ( filterCTuple, setRdrNameSpace )
57
import TysWiredIn
58
import Name
59
import NameSet
Lemmih's avatar
Lemmih committed
60
import NameEnv
61
import Avail
62
import Module
cactus's avatar
cactus committed
63
import ConLike
64 65
import DataCon
import TyCon
66
import ErrUtils         ( MsgDoc )
67
import PrelNames        ( rOOT_MAIN )
Matthew Pickering's avatar
Matthew Pickering committed
68
import BasicTypes       ( pprWarningTxtForMsg, TopLevelFlag(..))
Ian Lynagh's avatar
Ian Lynagh committed
69
import SrcLoc
70
import Outputable
71
import UniqSet          ( uniqSetAny )
72
import Util
Lemmih's avatar
Lemmih committed
73
import Maybes
74
import DynFlags
75
import FastString
Ian Lynagh's avatar
Ian Lynagh committed
76
import Control.Monad
77
import ListSetOps       ( minusList )
78
import qualified GHC.LanguageExtensions as LangExt
79 80
import GHC.Rename.Unbound
import GHC.Rename.Utils
81
import qualified Data.Semigroup as Semi
82
import Data.Either      ( partitionEithers )
83
import Data.List        (find)
Ian Lynagh's avatar
Ian Lynagh committed
84

Austin Seipp's avatar
Austin Seipp committed
85 86 87
{-
*********************************************************
*                                                      *
Ian Lynagh's avatar
Ian Lynagh committed
88
                Source-code binders
Austin Seipp's avatar
Austin Seipp committed
89 90
*                                                      *
*********************************************************
91

92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
Note [Signature lazy interface loading]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

GHC's lazy interface loading can be a bit confusing, so this Note is an
empirical description of what happens in one interesting case. When
compiling a signature module against an its implementation, we do NOT
load interface files associated with its names until after the type
checking phase.  For example:

    module ASig where
        data T
        f :: T -> T

Suppose we compile this with -sig-of "A is ASig":

    module B where
        data T = T
        f T = T

    module A(module B) where
        import B

During type checking, we'll load A.hi because we need to know what the
RdrEnv for the module is, but we DO NOT load the interface for B.hi!
It's wholly unnecessary: our local definition 'data T' in ASig is all
the information we need to finish type checking.  This is contrast to
type checking of ordinary Haskell files, in which we would not have the
local definition "data T" and would need to consult B.hi immediately.
(Also, this situation never occurs for hs-boot files, since you're not
allowed to reexport from another module.)

After type checking, we then check that the types we provided are
consistent with the backing implementation (in checkHiBootOrHsigIface).
At this point, B.hi is loaded, because we need something to compare
against.

I discovered this behavior when trying to figure out why type class
instances for Data.Map weren't in the EPS when I was type checking a
test very much like ASig (sigof02dm): the associated interface hadn't
been loaded yet!  (The larger issue is a moot point, since an instance
declared in a signature can never be a duplicate.)

This behavior might change in the future.  Consider this
alternate module B:

    module B where
        {-# DEPRECATED T, f "Don't use" #-}
        data T = T
        f T = T

One might conceivably want to report deprecation warnings when compiling
ASig with -sig-of B, in which case we need to look at B.hi to find the
deprecation warnings during renaming.  At the moment, you don't get any
warning until you use the identifier further downstream.  This would
146
require adjusting addUsedGRE so that during signature compilation,
147 148
we do not report deprecation warnings for LocalDef.  See also
Note [Handling of deprecations]
Austin Seipp's avatar
Austin Seipp committed
149
-}
150

151 152
newTopSrcBinder :: Located RdrName -> RnM Name
newTopSrcBinder (L loc rdr_name)
153
  | Just name <- isExact_maybe rdr_name
Ian Lynagh's avatar
Ian Lynagh committed
154 155 156 157 158 159 160 161 162
  =     -- This is here to catch
        --   (a) Exact-name binders created by Template Haskell
        --   (b) The PrelBase defn of (say) [] and similar, for which
        --       the parser reads the special syntax and returns an Exact RdrName
        -- We are at a binding site for the name, so check first that it
        -- the current module is the correct one; otherwise GHC can get
        -- very confused indeed. This test rejects code like
        --      data T = (,) Int Int
        -- unless we are in GHC.Tup
163 164 165
    if isExternalName name then
      do { this_mod <- getModule
         ; unless (this_mod == nameModule name)
Ian Lynagh's avatar
Ian Lynagh committed
166
                  (addErrAt loc (badOrigBinding rdr_name))
167 168
         ; return name }
    else   -- See Note [Binders in Template Haskell] in Convert.hs
169 170
      do { this_mod <- getModule
         ; externaliseName this_mod name }
171

Simon Marlow's avatar
Simon Marlow committed
172
  | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
Ian Lynagh's avatar
Ian Lynagh committed
173
  = do  { this_mod <- getModule
174
        ; unless (rdr_mod == this_mod || rdr_mod == rOOT_MAIN)
Ian Lynagh's avatar
Ian Lynagh committed
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
                 (addErrAt loc (badOrigBinding rdr_name))
        -- When reading External Core we get Orig names as binders,
        -- but they should agree with the module gotten from the monad
        --
        -- We can get built-in syntax showing up here too, sadly.  If you type
        --      data T = (,,,)
        -- the constructor is parsed as a type, and then RdrHsSyn.tyConToDataCon
        -- uses setRdrNameSpace to make it into a data constructors.  At that point
        -- the nice Exact name for the TyCon gets swizzled to an Orig name.
        -- Hence the badOrigBinding error message.
        --
        -- Except for the ":Main.main = ..." definition inserted into
        -- the Main module; ugh!

        -- Because of this latter case, we call newGlobalBinder with a module from
        -- the RdrName, not from the environment.  In principle, it'd be fine to
        -- have an arbitrary mixture of external core definitions in a single module,
        -- (apart from module-initialisation issues, perhaps).
        ; newGlobalBinder rdr_mod rdr_occ loc }
194 195

  | otherwise
Matthew Pickering's avatar
Matthew Pickering committed
196
  = do  { when (isQual rdr_name)
Ian Lynagh's avatar
Ian Lynagh committed
197 198
                 (addErrAt loc (badQualBndrErr rdr_name))
                -- Binders should not be qualified; if they are, and with a different
199
                -- module name, we get a confusing "M.T is not in scope" error later
Ian Lynagh's avatar
Ian Lynagh committed
200 201 202 203

        ; stage <- getStage
        ; if isBrackStage stage then
                -- We are inside a TH bracket, so make an *Internal* name
204
                -- See Note [Top-level Names in Template Haskell decl quotes] in GHC.Rename.Names
Ian Lynagh's avatar
Ian Lynagh committed
205 206
             do { uniq <- newUnique
                ; return (mkInternalName uniq (rdrNameOcc rdr_name) loc) }
Edward Z. Yang's avatar
Edward Z. Yang committed
207
          else
208
             do { this_mod <- getModule
209
                ; traceRn "newTopSrcBinder" (ppr this_mod $$ ppr rdr_name $$ ppr loc)
Edward Z. Yang's avatar
Edward Z. Yang committed
210 211
                ; newGlobalBinder this_mod (rdrNameOcc rdr_name) loc }
        }
212

Austin Seipp's avatar
Austin Seipp committed
213 214 215
{-
*********************************************************
*                                                      *
Ian Lynagh's avatar
Ian Lynagh committed
216
        Source code occurrences
Austin Seipp's avatar
Austin Seipp committed
217 218
*                                                      *
*********************************************************
219

220
Looking up a name in the GHC.Rename.Env.
221

222 223
Note [Type and class operator definitions]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
224
We want to reject all of these unless we have -XTypeOperators (#3265)
225 226 227 228 229 230 231 232
   data a :*: b  = ...
   class a :*: b where ...
   data (:*:) a b  = ....
   class (:*:) a b where ...
The latter two mean that we are not just looking for a
*syntactically-infix* declaration, but one that uses an operator
OccName.  We use OccName.isSymOcc to detect that case, which isn't
terribly efficient, but there seems to be no better way.
Austin Seipp's avatar
Austin Seipp committed
233
-}
234

Matthew Pickering's avatar
Matthew Pickering committed
235 236
-- Can be made to not be exposed
-- Only used unwrapped in rnAnnProvenance
237 238
lookupTopBndrRn :: RdrName -> RnM Name
lookupTopBndrRn n = do nopt <- lookupTopBndrRn_maybe n
Ian Lynagh's avatar
Ian Lynagh committed
239
                       case nopt of
240
                         Just n' -> return n'
241
                         Nothing -> do traceRn "lookupTopBndrRn fail" (ppr n)
242
                                       unboundName WL_LocalTop n
243

244 245 246
lookupLocatedTopBndrRn :: Located RdrName -> RnM (Located Name)
lookupLocatedTopBndrRn = wrapLocM lookupTopBndrRn

247
lookupTopBndrRn_maybe :: RdrName -> RnM (Maybe Name)
248
-- Look up a top-level source-code binder.   We may be looking up an unqualified 'f',
249
-- and there may be several imported 'f's too, which must not confuse us.
250
-- For example, this is OK:
Ian Lynagh's avatar
Ian Lynagh committed
251 252 253
--      import Foo( f )
--      infix 9 f       -- The 'f' here does not need to be qualified
--      f x = x         -- Nor here, of course
254
-- So we have to filter out the non-local ones.
255
--
256 257
-- A separate function (importsFromLocalDecls) reports duplicate top level
-- decls, so here it's safe just to choose an arbitrary one.
258
--
259 260
-- There should never be a qualified name in a binding position in Haskell,
-- but there can be if we have read in an external-Core file.
Ian Lynagh's avatar
Ian Lynagh committed
261
-- The Haskell parser checks for the illegal qualified name in Haskell
262
-- source files, so we don't need to do so here.
263

Matthew Pickering's avatar
Matthew Pickering committed
264 265 266
lookupTopBndrRn_maybe rdr_name =
  lookupExactOrOrig rdr_name Just $
    do  {  -- Check for operators in type or class declarations
267 268 269
           -- See Note [Type and class operator definitions]
          let occ = rdrNameOcc rdr_name
        ; when (isTcOcc occ && isSymOcc occ)
270
               (do { op_ok <- xoptM LangExt.TypeOperators
Ian Lynagh's avatar
Ian Lynagh committed
271 272
                   ; unless op_ok (addErr (opDeclErr rdr_name)) })

273 274 275 276 277
        ; env <- getGlobalRdrEnv
        ; case filter isLocalGRE (lookupGRE_RdrName rdr_name env) of
            [gre] -> return (Just (gre_name gre))
            _     -> return Nothing  -- Ambiguous (can't happen) or unbound
    }
278

279
-----------------------------------------------
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
280 281
-- | Lookup an @Exact@ @RdrName@. See Note [Looking up Exact RdrNames].
-- This adds an error if the name cannot be found.
282 283
lookupExactOcc :: Name -> RnM Name
lookupExactOcc name
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
284 285 286 287 288 289 290 291 292 293 294
  = do { result <- lookupExactOcc_either name
       ; case result of
           Left err -> do { addErr err
                          ; return name }
           Right name' -> return name' }

-- | Lookup an @Exact@ @RdrName@. See Note [Looking up Exact RdrNames].
-- This never adds an error, but it may return one.
lookupExactOcc_either :: Name -> RnM (Either MsgDoc Name)
-- See Note [Looking up Exact RdrNames]
lookupExactOcc_either name
295 296
  | Just thing <- wiredInNameTyThing_maybe name
  , Just tycon <- case thing of
cactus's avatar
cactus committed
297 298 299
                    ATyCon tc                 -> Just tc
                    AConLike (RealDataCon dc) -> Just (dataConTyCon dc)
                    _                         -> Nothing
300 301
  , isTupleTyCon tycon
  = do { checkTupSize (tyConArity tycon)
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
302
       ; return (Right name) }
303

Ian Lynagh's avatar
Ian Lynagh committed
304
  | isExternalName name
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
305
  = return (Right name)
306

Ian Lynagh's avatar
Ian Lynagh committed
307
  | otherwise
308
  = do { env <- getGlobalRdrEnv
Ian Lynagh's avatar
Ian Lynagh committed
309
       ; let -- See Note [Splicing Exact names]
310 311 312 313 314 315
             main_occ =  nameOccName name
             demoted_occs = case demoteOccName main_occ of
                              Just occ -> [occ]
                              Nothing  -> []
             gres = [ gre | occ <- main_occ : demoted_occs
                          , gre <- lookupGlobalRdrEnv env occ
Ian Lynagh's avatar
Ian Lynagh committed
316
                          , gre_name gre == name ]
317
       ; case gres of
318 319
           [gre] -> return (Right (gre_name gre))

320 321
           []    -> -- See Note [Splicing Exact names]
                    do { lcl_env <- getLocalRdrEnv
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
322 323 324
                       ; if name `inLocalRdrEnvScope` lcl_env
                         then return (Right name)
                         else
325 326
                         do { th_topnames_var <- fmap tcg_th_topnames getGblEnv
                            ; th_topnames <- readTcRef th_topnames_var
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
327 328 329
                            ; if name `elemNameSet` th_topnames
                              then return (Right name)
                              else return (Left exact_nm_err)
330 331
                            }
                       }
332
           gres -> return (Left (sameNameErr gres))   -- Ugh!  See Note [Template Haskell ambiguity]
333
       }
334
  where
335 336 337 338
    exact_nm_err = hang (text "The exact Name" <+> quotes (ppr name) <+> ptext (sLit "is not in scope"))
                      2 (vcat [ text "Probable cause: you used a unique Template Haskell name (NameU), "
                              , text "perhaps via newName, but did not bind it"
                              , text "If that's it, then -ddump-splices might be useful" ])
339 340 341 342

sameNameErr :: [GlobalRdrElt] -> MsgDoc
sameNameErr [] = panic "addSameNameErr: empty list"
sameNameErr gres@(_ : _)
343
  = hang (text "Same exact name in multiple name-spaces:")
344 345 346 347 348 349
       2 (vcat (map pp_one sorted_names) $$ th_hint)
  where
    sorted_names = sortWith nameSrcLoc (map gre_name gres)
    pp_one name
      = hang (pprNameSpace (occNameSpace (getOccName name))
              <+> quotes (ppr name) <> comma)
350
           2 (text "declared at:" <+> ppr (nameSrcLoc name))
351

352 353 354
    th_hint = vcat [ text "Probable cause: you bound a unique Template Haskell name (NameU),"
                   , text "perhaps via newName, in different name-spaces."
                   , text "If that's it, then -ddump-splices might be useful" ]
355

356

Lemmih's avatar
Lemmih committed
357
-----------------------------------------------
358
lookupInstDeclBndr :: Name -> SDoc -> RdrName -> RnM Name
Ian Lynagh's avatar
Ian Lynagh committed
359
-- This is called on the method name on the left-hand side of an
360 361 362 363 364
-- instance declaration binding. eg.  instance Functor T where
--                                       fmap = ...
--                                       ^^^^ called on this
-- Regardless of how many unqualified fmaps are in scope, we want
-- the one that comes from the Functor class.
Lemmih's avatar
Lemmih committed
365
--
Ian Lynagh's avatar
Ian Lynagh committed
366
-- Furthermore, note that we take no account of whether the
Lemmih's avatar
Lemmih committed
367 368 369
-- name is only in scope qualified.  I.e. even if method op is
-- in scope as M.op, we still allow plain 'op' on the LHS of
-- an instance decl
370 371 372 373
--
-- The "what" parameter says "method" or "associated type",
-- depending on what we are looking up
lookupInstDeclBndr cls what rdr
374
  = do { when (isQual rdr)
Ian Lynagh's avatar
Ian Lynagh committed
375 376 377 378
              (addErr (badQualBndrErr rdr))
                -- In an instance decl you aren't allowed
                -- to use a qualified name for the method
                -- (Although it'd make perfect sense.)
379 380
       ; mb_name <- lookupSubBndrOcc
                          False -- False => we don't give deprecated
381 382 383
                                -- warnings when a deprecated class
                                -- method is defined. We only warn
                                -- when it's used
384 385 386 387
                          cls doc rdr
       ; case mb_name of
           Left err -> do { addErr err; return (mkUnboundNameRdr rdr) }
           Right nm -> return nm }
Lemmih's avatar
Lemmih committed
388
  where
389
    doc = what <+> text "of class" <+> quotes (ppr cls)
Lemmih's avatar
Lemmih committed
390

391
-----------------------------------------------
392 393
lookupFamInstName :: Maybe Name -> Located RdrName
                  -> RnM (Located Name)
Ian Lynagh's avatar
Ian Lynagh committed
394
-- Used for TyData and TySynonym family instances only,
395
-- See Note [Family instance binders]
396
lookupFamInstName (Just cls) tc_rdr  -- Associated type; c.f GHC.Rename.Binds.rnMethodBind
397
  = wrapLocM (lookupInstDeclBndr cls (text "associated type")) tc_rdr
398
lookupFamInstName Nothing tc_rdr     -- Family instance; tc_rdr is an *occurrence*
Ian Lynagh's avatar
Ian Lynagh committed
399
  = lookupLocatedOccRn tc_rdr
400

Lemmih's avatar
Lemmih committed
401
-----------------------------------------------
402
lookupConstructorFields :: Name -> RnM [FieldLabel]
Lemmih's avatar
Lemmih committed
403
-- Look up the fields of a given constructor
Ian Lynagh's avatar
Ian Lynagh committed
404 405 406 407 408
--   *  For constructors from this module, use the record field env,
--      which is itself gathered from the (as yet un-typechecked)
--      data type decls
--
--    * For constructors from imported modules, use the *type* environment
409
--      since imported modules are already compiled, the info is conveniently
Ian Lynagh's avatar
Ian Lynagh committed
410
--      right there
Lemmih's avatar
Lemmih committed
411 412

lookupConstructorFields con_name
Ian Lynagh's avatar
Ian Lynagh committed
413 414
  = do  { this_mod <- getModule
        ; if nameIsLocalOrFrom this_mod con_name then
415
          do { field_env <- getRecFieldEnv
416
             ; traceTc "lookupCF" (ppr con_name $$ ppr (lookupNameEnv field_env con_name) $$ ppr field_env)
Ian Lynagh's avatar
Ian Lynagh committed
417 418
             ; return (lookupNameEnv field_env con_name `orElse` []) }
          else
419
          do { con <- tcLookupConLike con_name
420
             ; traceTc "lookupCF 2" (ppr con)
421
             ; return (conLikeFieldLabels con) } }
Lemmih's avatar
Lemmih committed
422

Matthew Pickering's avatar
Matthew Pickering committed
423 424 425 426 427 428 429 430 431 432 433 434

-- In CPS style as `RnM r` is monadic
lookupExactOrOrig :: RdrName -> (Name -> r) -> RnM r -> RnM r
lookupExactOrOrig rdr_name res k
  | Just n <- isExact_maybe rdr_name   -- This happens in derived code
  = res <$> lookupExactOcc n
  | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
  = res <$> lookupOrig rdr_mod rdr_occ
  | otherwise = k



Lemmih's avatar
Lemmih committed
435
-----------------------------------------------
436 437 438 439
-- | Look up an occurrence of a field in record construction or pattern
-- matching (but not update).  When the -XDisambiguateRecordFields
-- flag is on, take account of the data constructor name to
-- disambiguate which field to use.
Ian Lynagh's avatar
Ian Lynagh committed
440
--
441 442 443 444
-- See Note [DisambiguateRecordFields].
lookupRecFieldOcc :: Maybe Name -- Nothing  => just look it up as usual
                                -- Just con => use data con to disambiguate
                  -> RdrName
445
                  -> RnM Name
446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
lookupRecFieldOcc mb_con rdr_name
  | Just con <- mb_con
  , isUnboundName con  -- Avoid error cascade
  = return (mkUnboundNameRdr rdr_name)
  | Just con <- mb_con
  = do { flds <- lookupConstructorFields con
       ; env <- getGlobalRdrEnv
       ; let lbl      = occNameFS (rdrNameOcc rdr_name)
             mb_field = do fl <- find ((== lbl) . flLabel) flds
                           -- We have the label, now check it is in
                           -- scope (with the correct qualifier if
                           -- there is one, hence calling pickGREs).
                           gre <- lookupGRE_FieldLabel env fl
                           guard (not (isQual rdr_name
                                         && null (pickGREs rdr_name [gre])))
                           return (fl, gre)
       ; case mb_field of
           Just (fl, gre) -> do { addUsedGRE True gre
                                ; return (flSelector fl) }
           Nothing        -> lookupGlobalOccRn rdr_name }
             -- See Note [Fall back on lookupGlobalOccRn in lookupRecFieldOcc]
467
  | otherwise
Matthew Pickering's avatar
Matthew Pickering committed
468 469
  -- This use of Global is right as we are looking up a selector which
  -- can only be defined at the top level.
470 471
  = lookupGlobalOccRn rdr_name

472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 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
{- Note [DisambiguateRecordFields]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When we are looking up record fields in record construction or pattern
matching, we can take advantage of the data constructor name to
resolve fields that would otherwise be ambiguous (provided the
-XDisambiguateRecordFields flag is on).

For example, consider:

   data S = MkS { x :: Int }
   data T = MkT { x :: Int }

   e = MkS { x = 3 }

When we are renaming the occurrence of `x` in `e`, instead of looking
`x` up directly (and finding both fields), lookupRecFieldOcc will
search the fields of `MkS` to find the only possible `x` the user can
mean.

Of course, we still have to check the field is in scope, using
lookupGRE_FieldLabel.  The handling of qualified imports is slightly
subtle: the occurrence may be unqualified even if the field is
imported only qualified (but if the occurrence is qualified, the
qualifier must be correct). For example:

   module A where
     data S = MkS { x :: Int }
     data T = MkT { x :: Int }

   module B where
     import qualified A (S(..))
     import A (T(MkT))

     e1 = MkT   { x = 3 }   -- x not in scope, so fail
     e2 = A.MkS { B.x = 3 } -- module qualifier is wrong, so fail
     e3 = A.MkS { x = 3 }   -- x in scope (lack of module qualifier permitted)

In case `e1`, lookupGRE_FieldLabel will return Nothing.  In case `e2`,
lookupGRE_FieldLabel will return the GRE for `A.x`, but then the guard
will fail because the field RdrName `B.x` is qualified and pickGREs
rejects the GRE.  In case `e3`, lookupGRE_FieldLabel will return the
GRE for `A.x` and the guard will succeed because the field RdrName `x`
is unqualified.


Note [Fall back on lookupGlobalOccRn in lookupRecFieldOcc]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Whenever we fail to find the field or it is not in scope, mb_field
will be False, and we fall back on looking it up normally using
lookupGlobalOccRn.  We don't report an error immediately because the
522
actual problem might be located elsewhere.  For example (#9975):
523 524 525 526 527 528 529 530 531 532 533 534

   data Test = Test { x :: Int }
   pattern Test wat = Test { x = wat }

Here there are multiple declarations of Test (as a data constructor
and as a pattern synonym), which will be reported as an error.  We
shouldn't also report an error about the occurrence of `x` in the
pattern synonym RHS.  However, if the pattern synonym gets added to
the environment first, we will try and fail to find `x` amongst the
(nonexistent) fields of the pattern synonym.

Alternatively, the scope check can fail due to Template Haskell.
535
Consider (#12130):
536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551

   module Foo where
     import M
     b = $(funny)

   module M(funny) where
     data T = MkT { x :: Int }
     funny :: Q Exp
     funny = [| MkT { x = 3 } |]

When we splice, `MkT` is not lexically in scope, so
lookupGRE_FieldLabel will fail.  But there is no need for
disambiguation anyway, because `x` is an original name, and
lookupGlobalOccRn will find it.
-}

Matthew Pickering's avatar
Matthew Pickering committed
552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640


-- | Used in export lists to lookup the children.
lookupSubBndrOcc_helper :: Bool -> Bool -> Name -> RdrName
                        -> RnM ChildLookupResult
lookupSubBndrOcc_helper must_have_parent warn_if_deprec parent rdr_name
  | isUnboundName parent
    -- Avoid an error cascade
  = return (FoundName NoParent (mkUnboundNameRdr rdr_name))

  | otherwise = do
  gre_env <- getGlobalRdrEnv

  let original_gres = lookupGlobalRdrEnv gre_env (rdrNameOcc rdr_name)
  -- Disambiguate the lookup based on the parent information.
  -- The remaining GREs are things that we *could* export here, note that
  -- this includes things which have `NoParent`. Those are sorted in
  -- `checkPatSynParent`.
  traceRn "parent" (ppr parent)
  traceRn "lookupExportChild original_gres:" (ppr original_gres)
  traceRn "lookupExportChild picked_gres:" (ppr $ picked_gres original_gres)
  case picked_gres original_gres of
    NoOccurrence ->
      noMatchingParentErr original_gres
    UniqueOccurrence g ->
      if must_have_parent then noMatchingParentErr original_gres
                          else checkFld g
    DisambiguatedOccurrence g ->
      checkFld g
    AmbiguousOccurrence gres ->
      mkNameClashErr gres
    where
        -- Convert into FieldLabel if necessary
        checkFld :: GlobalRdrElt -> RnM ChildLookupResult
        checkFld g@GRE{gre_name, gre_par} = do
          addUsedGRE warn_if_deprec g
          return $ case gre_par of
            FldParent _ mfs ->
              FoundFL  (fldParentToFieldLabel gre_name mfs)
            _ -> FoundName gre_par gre_name

        fldParentToFieldLabel :: Name -> Maybe FastString -> FieldLabel
        fldParentToFieldLabel name mfs =
          case mfs of
            Nothing ->
              let fs = occNameFS (nameOccName name)
              in FieldLabel fs False name
            Just fs -> FieldLabel fs True name

        -- Called when we find no matching GREs after disambiguation but
        -- there are three situations where this happens.
        -- 1. There were none to begin with.
        -- 2. None of the matching ones were the parent but
        --  a. They were from an overloaded record field so we can report
        --     a better error
        --  b. The original lookup was actually ambiguous.
        --     For example, the case where overloading is off and two
        --     record fields are in scope from different record
        --     constructors, neither of which is the parent.
        noMatchingParentErr :: [GlobalRdrElt] -> RnM ChildLookupResult
        noMatchingParentErr original_gres = do
          overload_ok <- xoptM LangExt.DuplicateRecordFields
          case original_gres of
            [] ->  return NameNotFound
            [g] -> return $ IncorrectParent parent
                              (gre_name g) (ppr $ gre_name g)
                              [p | Just p <- [getParent g]]
            gss@(g:_:_) ->
              if all isRecFldGRE gss && overload_ok
                then return $
                      IncorrectParent parent
                        (gre_name g)
                        (ppr $ expectJust "noMatchingParentErr" (greLabel g))
                        [p | x <- gss, Just p <- [getParent x]]
                else mkNameClashErr gss

        mkNameClashErr :: [GlobalRdrElt] -> RnM ChildLookupResult
        mkNameClashErr gres = do
          addNameClashErrRn rdr_name gres
          return (FoundName (gre_par (head gres)) (gre_name (head gres)))

        getParent :: GlobalRdrElt -> Maybe Name
        getParent (GRE { gre_par = p } ) =
          case p of
            ParentIs cur_parent -> Just cur_parent
            FldParent { par_is = cur_parent } -> Just cur_parent
            NoParent -> Nothing

        picked_gres :: [GlobalRdrElt] -> DisambigInfo
David Eichmann's avatar
David Eichmann committed
641 642
        -- For Unqual, find GREs that are in scope qualified or unqualified
        -- For Qual,   find GREs that are in scope with that qualification
Matthew Pickering's avatar
Matthew Pickering committed
643 644
        picked_gres gres
          | isUnqual rdr_name
David Eichmann's avatar
David Eichmann committed
645
          = mconcat (map right_parent gres)
Matthew Pickering's avatar
Matthew Pickering committed
646
          | otherwise
David Eichmann's avatar
David Eichmann committed
647
          = mconcat (map right_parent (pickGREs rdr_name gres))
Matthew Pickering's avatar
Matthew Pickering committed
648 649 650

        right_parent :: GlobalRdrElt -> DisambigInfo
        right_parent p
David Eichmann's avatar
David Eichmann committed
651 652 653 654 655
          = case getParent p of
               Just cur_parent
                  | parent == cur_parent -> DisambiguatedOccurrence p
                  | otherwise            -> NoOccurrence
               Nothing                   -> UniqueOccurrence p
Matthew Pickering's avatar
Matthew Pickering committed
656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677


-- This domain specific datatype is used to record why we decided it was
-- possible that a GRE could be exported with a parent.
data DisambigInfo
       = NoOccurrence
          -- The GRE could never be exported. It has the wrong parent.
       | UniqueOccurrence GlobalRdrElt
          -- The GRE has no parent. It could be a pattern synonym.
       | DisambiguatedOccurrence GlobalRdrElt
          -- The parent of the GRE is the correct parent
       | AmbiguousOccurrence [GlobalRdrElt]
          -- For example, two normal identifiers with the same name are in
          -- scope. They will both be resolved to "UniqueOccurrence" and the
          -- monoid will combine them to this failing case.

instance Outputable DisambigInfo where
  ppr NoOccurrence = text "NoOccurence"
  ppr (UniqueOccurrence gre) = text "UniqueOccurrence:" <+> ppr gre
  ppr (DisambiguatedOccurrence gre) = text "DiambiguatedOccurrence:" <+> ppr gre
  ppr (AmbiguousOccurrence gres)    = text "Ambiguous:" <+> ppr gres

678
instance Semi.Semigroup DisambigInfo where
Matthew Pickering's avatar
Matthew Pickering committed
679 680
  -- This is the key line: We prefer disambiguated occurrences to other
  -- names.
681 682
  _ <> DisambiguatedOccurrence g' = DisambiguatedOccurrence g'
  DisambiguatedOccurrence g' <> _ = DisambiguatedOccurrence g'
Matthew Pickering's avatar
Matthew Pickering committed
683

684 685 686
  NoOccurrence <> m = m
  m <> NoOccurrence = m
  UniqueOccurrence g <> UniqueOccurrence g'
Matthew Pickering's avatar
Matthew Pickering committed
687
    = AmbiguousOccurrence [g, g']
688
  UniqueOccurrence g <> AmbiguousOccurrence gs
Matthew Pickering's avatar
Matthew Pickering committed
689
    = AmbiguousOccurrence (g:gs)
690
  AmbiguousOccurrence gs <> UniqueOccurrence g'
Matthew Pickering's avatar
Matthew Pickering committed
691
    = AmbiguousOccurrence (g':gs)
692
  AmbiguousOccurrence gs <> AmbiguousOccurrence gs'
Matthew Pickering's avatar
Matthew Pickering committed
693
    = AmbiguousOccurrence (gs ++ gs')
694 695 696 697 698

instance Monoid DisambigInfo where
  mempty = NoOccurrence
  mappend = (Semi.<>)

Matthew Pickering's avatar
Matthew Pickering committed
699 700 701 702 703 704 705 706 707
-- Lookup SubBndrOcc can never be ambiguous
--
-- Records the result of looking up a child.
data ChildLookupResult
      = NameNotFound                --  We couldn't find a suitable name
      | IncorrectParent Name        -- Parent
                        Name        -- Name of thing we were looking for
                        SDoc        -- How to print the name
                        [Name]      -- List of possible parents
708 709
      | FoundName Parent Name       --  We resolved to a normal name
      | FoundFL FieldLabel          --  We resolved to a FL
Matthew Pickering's avatar
Matthew Pickering committed
710 711 712 713 714 715 716 717 718 719 720 721

-- | Specialised version of msum for RnM ChildLookupResult
combineChildLookupResult :: [RnM ChildLookupResult] -> RnM ChildLookupResult
combineChildLookupResult [] = return NameNotFound
combineChildLookupResult (x:xs) = do
  res <- x
  case res of
    NameNotFound -> combineChildLookupResult xs
    _ -> return res

instance Outputable ChildLookupResult where
  ppr NameNotFound = text "NameNotFound"
722
  ppr (FoundName p n) = text "Found:" <+> ppr p <+> ppr n
Matthew Pickering's avatar
Matthew Pickering committed
723 724 725 726
  ppr (FoundFL fls) = text "FoundFL:" <+> ppr fls
  ppr (IncorrectParent p n td ns) = text "IncorrectParent"
                                  <+> hsep [ppr p, ppr n, td, ppr ns]

727
lookupSubBndrOcc :: Bool
728 729 730 731 732 733
                 -> Name     -- Parent
                 -> SDoc
                 -> RdrName
                 -> RnM (Either MsgDoc Name)
-- Find all the things the rdr-name maps to
-- and pick the one with the right parent namep
Matthew Pickering's avatar
Matthew Pickering committed
734 735 736 737 738 739 740 741 742
lookupSubBndrOcc warn_if_deprec the_parent doc rdr_name = do
  res <-
    lookupExactOrOrig rdr_name (FoundName NoParent) $
      -- This happens for built-in classes, see mod052 for example
      lookupSubBndrOcc_helper True warn_if_deprec the_parent rdr_name
  case res of
    NameNotFound -> return (Left (unknownSubordinateErr doc rdr_name))
    FoundName _p n -> return (Right n)
    FoundFL fl  ->  return (Right (flSelector fl))
743 744 745 746
    IncorrectParent {}
         -- See [Mismatched class methods and associated type families]
         -- in TcInstDecls.
      -> return $ Left (unknownSubordinateErr doc rdr_name)
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
747

Austin Seipp's avatar
Austin Seipp committed
748
{-
749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775
Note [Family instance binders]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
  data family F a
  data instance F T = X1 | X2

The 'data instance' decl has an *occurrence* of F (and T), and *binds*
X1 and X2.  (This is unlike a normal data type declaration which would
bind F too.)  So we want an AvailTC F [X1,X2].

Now consider a similar pair:
  class C a where
    data G a
  instance C S where
    data G S = Y1 | Y2

The 'data G S' *binds* Y1 and Y2, and has an *occurrence* of G.

But there is a small complication: in an instance decl, we don't use
qualified names on the LHS; instead we use the class to disambiguate.
Thus:
  module M where
    import Blib( G )
    class C a where
      data G a
    instance C S where
      data G S = Y1 | Y2
Gabor Greif's avatar
Gabor Greif committed
776
Even though there are two G's in scope (M.G and Blib.G), the occurrence
Gabor Greif's avatar
typos  
Gabor Greif committed
777
of 'G' in the 'instance C S' decl is unambiguous, because C has only
778 779 780 781 782
one associated type called G. This is exactly what happens for methods,
and it is only consistent to do the same thing for types. That's the
role of the function lookupTcdName; the (Maybe Name) give the class of
the encloseing instance decl, if any.

783 784 785 786 787 788 789 790 791 792
Note [Looking up Exact RdrNames]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Exact RdrNames are generated by Template Haskell.  See Note [Binders
in Template Haskell] in Convert.

For data types and classes have Exact system Names in the binding
positions for constructors, TyCons etc.  For example
    [d| data T = MkT Int |]
when we splice in and Convert to HsSyn RdrName, we'll get
    data (Exact (system Name "T")) = (Exact (system Name "MkT")) ...
793
These System names are generated by Convert.thRdrName
794 795 796 797

But, constructors and the like need External Names, not System Names!
So we do the following

798
 * In GHC.Rename.Env.newTopSrcBinder we spot Exact RdrNames that wrap a
799 800 801 802
   non-External Name, and make an External name for it. This is
   the name that goes in the GlobalRdrEnv

 * When looking up an occurrence of an Exact name, done in
803
   GHC.Rename.Env.lookupExactOcc, we find the Name with the right unique in the
804
   GlobalRdrEnv, and use the one from the envt -- it will be an
805 806 807 808 809
   External Name in the case of the data type/constructor above.

 * Exact names are also use for purely local binders generated
   by TH, such as    \x_33. x_33
   Both binder and occurrence are Exact RdrNames.  The occurrence
810
   gets looked up in the LocalRdrEnv by GHC.Rename.Env.lookupOccRn, and
811 812 813 814 815
   misses, because lookupLocalRdrEnv always returns Nothing for
   an Exact Name.  Now we fall through to lookupExactOcc, which
   will find the Name is not in the GlobalRdrEnv, so we just use
   the Exact supplied Name.

816 817 818
Note [Splicing Exact names]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider the splice $(do { x <- newName "x"; return (VarE x) })
Ian Lynagh's avatar
Ian Lynagh committed
819
This will generate a (HsExpr RdrName) term that mentions the
820 821 822 823 824
Exact RdrName "x_56" (or whatever), but does not bind it.  So
when looking such Exact names we want to check that it's in scope,
otherwise the type checker will get confused.  To do this we need to
keep track of all the Names in scope, and the LocalRdrEnv does just that;
we consult it with RdrName.inLocalRdrEnvScope.
825

826
There is another wrinkle.  With TH and -XDataKinds, consider
Ian Lynagh's avatar
Ian Lynagh committed
827
   $( [d| data Nat = Zero
828 829 830 831
          data T = MkT (Proxy 'Zero)  |] )
After splicing, but before renaming we get this:
   data Nat_77{tc} = Zero_78{d}
   data T_79{tc} = MkT_80{d} (Proxy 'Zero_78{tc})  |] )
832
The occurrence of 'Zero in the data type for T has the right unique,
833
but it has a TcClsName name-space in its OccName.  (This is set by
Ian Lynagh's avatar
Ian Lynagh committed
834
the ctxt_ns argument of Convert.thRdrName.)  When we check that is
835 836 837 838
in scope in the GlobalRdrEnv, we need to look up the DataName namespace
too.  (An alternative would be to make the GlobalRdrEnv also have
a Name -> GRE mapping.)

839 840 841 842 843 844 845 846 847
Note [Template Haskell ambiguity]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The GlobalRdrEnv invariant says that if
  occ -> [gre1, ..., gren]
then the gres have distinct Names (INVARIANT 1 of GlobalRdrEnv).
This is guaranteed by extendGlobalRdrEnvRn (the dups check in add_gre).

So how can we get multiple gres in lookupExactOcc_maybe?  Because in
TH we might use the same TH NameU in two different name spaces.
848
eg (#7241):
849 850
   $(newName "Foo" >>= \o -> return [DataD [] o [] [RecC o []] [''Show]])
Here we generate a type constructor and data constructor with the same
Gabor Greif's avatar
Gabor Greif committed
851
unique, but different name spaces.
852 853 854 855 856 857

It'd be nicer to rule this out in extendGlobalRdrEnvRn, but that would
mean looking up the OccName in every name-space, just in case, and that
seems a bit brutal.  So it's just done here on lookup.  But we might
need to revisit that choice.

simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
858 859 860
Note [Usage for sub-bndrs]
~~~~~~~~~~~~~~~~~~~~~~~~~~
If you have this
Ian Lynagh's avatar
Ian Lynagh committed
861
   import qualified M( C( f ) )
862
   instance M.C T where
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
863 864 865 866 867
     f x = x
then is the qualified import M.f used?  Obviously yes.
But the RdrName used in the instance decl is unqualified.  In effect,
we fill in the qualification by looking for f's whose class is M.C
But when adding to the UsedRdrNames we must make that qualification
868 869 870
explicit (saying "used  M.f"), otherwise we get "Redundant import of M.f".

So we make up a suitable (fake) RdrName.  But be careful
Gabor Greif's avatar
Gabor Greif committed
871
   import qualified M
872 873 874 875 876
   import M( C(f) )
   instance C T where
     f x = x
Here we want to record a use of 'f', not of 'M.f', otherwise
we'll miss the fact that the qualified import is redundant.
877

878
--------------------------------------------------
Ian Lynagh's avatar
Ian Lynagh committed
879
--              Occurrences
880
--------------------------------------------------
Austin Seipp's avatar
Austin Seipp committed
881
-}
882

883

884 885 886
lookupLocatedOccRn :: Located RdrName -> RnM (Located Name)
lookupLocatedOccRn = wrapLocM lookupOccRn

887 888
lookupLocalOccRn_maybe :: RdrName -> RnM (Maybe Name)
-- Just look in the local environment
Ian Lynagh's avatar
Ian Lynagh committed
889
lookupLocalOccRn_maybe rdr_name
890 891 892
  = do { local_env <- getLocalRdrEnv
       ; return (lookupLocalRdrEnv local_env rdr_name) }

893
lookupLocalOccThLvl_maybe :: Name -> RnM (Maybe (TopLevelFlag, ThLevel))
gmainland's avatar
gmainland committed
894
-- Just look in the local environment
895 896 897
lookupLocalOccThLvl_maybe name
  = do { lcl_env <- getLclEnv
       ; return (lookupNameEnv (tcl_th_bndrs lcl_env) name) }
gmainland's avatar
gmainland committed
898

dreixel's avatar
dreixel committed
899 900
-- lookupOccRn looks up an occurrence of a RdrName
lookupOccRn :: RdrName -> RnM Name
901
lookupOccRn rdr_name
902 903
  = do { mb_name <- lookupOccRn_maybe rdr_name
       ; case mb_name of
904
           Just name -> return name
905
           Nothing   -> reportUnboundName rdr_name }
dreixel's avatar
dreixel committed
906

907
-- Only used in one place, to rename pattern synonym binders.
908
-- See Note [Renaming pattern synonym variables] in GHC.Rename.Binds
909 910 911 912 913 914 915
lookupLocalOccRn :: RdrName -> RnM Name
lookupLocalOccRn rdr_name
  = do { mb_name <- lookupLocalOccRn_maybe rdr_name
       ; case mb_name of
           Just name -> return name
           Nothing   -> unboundName WL_LocalOnly rdr_name }

dreixel's avatar
dreixel committed
916
-- lookupPromotedOccRn looks up an optionally promoted RdrName.
917
lookupTypeOccRn :: RdrName -> RnM Name
Ian Lynagh's avatar
Ian Lynagh committed
918 919
-- see Note [Demotion]
lookupTypeOccRn rdr_name
920 921 922
  | isVarOcc (rdrNameOcc rdr_name)  -- See Note [Promoted variables in types]
  = badVarInType rdr_name
  | otherwise
Ian Lynagh's avatar
Ian Lynagh committed
923
  = do { mb_name <- lookupOccRn_maybe rdr_name
924 925 926
       ; case mb_name of
             Just name -> return name
             Nothing   -> lookup_demoted rdr_name }
927

928 929
lookup_demoted :: RdrName -> RnM Name
lookup_demoted rdr_name
930 931
  | Just demoted_rdr <- demoteRdrName rdr_name
    -- Maybe it's the name of a *data* constructor
932
  = do { data_kinds <- xoptM LangExt.DataKinds
933
       ; star_is_type <- xoptM LangExt.StarIsType
934
       ; let star_info = starInfo star_is_type rdr_name
935 936 937 938 939 940 941 942 943 944
       ; if data_kinds
            then do { mb_demoted_name <- lookupOccRn_maybe demoted_rdr
                    ; case mb_demoted_name of
                        Nothing -> unboundNameX WL_Any rdr_name star_info
                        Just demoted_name ->
                          do { whenWOptM Opt_WarnUntickedPromotedConstructors $
                               addWarn
                                 (Reason Opt_WarnUntickedPromotedConstructors)
                                 (untickedPromConstrWarn demoted_name)
                             ; return demoted_name } }
945 946 947 948 949 950 951
            else do { -- We need to check if a data constructor of this name is
                      -- in scope to give good error messages. However, we do
                      -- not want to give an additional error if the data
                      -- constructor happens to be out of scope! See #13947.
                      mb_demoted_name <- discardErrs $
                                         lookupOccRn_maybe demoted_rdr
                    ; let suggestion | isJust mb_demoted_name = suggest_dk
952
                                     | otherwise = star_info
953
                    ; unboundNameX WL_Any rdr_name suggestion } }
Ian Lynagh's avatar
Ian Lynagh committed
954

955
  | otherwise
956
  = reportUnboundName rdr_name
957

Ian Lynagh's avatar
Ian Lynagh committed
958
  where
959
    suggest_dk = text "A data constructor of that name is in scope; did you mean DataKinds?"
carlostome's avatar
carlostome committed
960 961 962 963 964 965 966
    untickedPromConstrWarn name =
      text "Unticked promoted constructor" <> colon <+> quotes (ppr name) <> dot
      $$
      hsep [ text "Use"
           , quotes (char '\'' <> ppr name)
           , text "instead of"
           , quotes (ppr name) <> dot ]
967

968 969 970 971 972 973 974 975
badVarInType :: RdrName -> RnM Name
badVarInType rdr_name
  = do { addErr (text "Illegal promoted term variable in a type:"
                 <+> ppr rdr_name)
       ; return (mkUnboundNameRdr rdr_name) }

{- Note [Promoted variables in types]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
976
Consider this (#12686):
977 978 979 980 981 982 983 984 985 986
   x = True
   data Bad = Bad 'x

The parser treats the quote in 'x as saying "use the term
namespace", so we'll get (Bad x{v}), with 'x' in the
VarName namespace.  If we don't test for this, the renamer
will happily rename it to the x bound at top level, and then
the typecheck falls over because it doesn't have 'x' in scope
when kind-checking.

987 988 989 990 991 992 993 994
Note [Demotion]
~~~~~~~~~~~~~~~
When the user writes:
  data Nat = Zero | Succ Nat
  foo :: f Zero -> Int

'Zero' in the type signature of 'foo' is parsed as:
  HsTyVar ("Zero", TcClsName)
dreixel's avatar
dreixel committed
995

Gabor Greif's avatar
Gabor Greif committed
996
When the renamer hits this occurrence of 'Zero' it's going to realise
997 998 999 1000 1001 1002
that it's not in scope. But because it is renaming a type, it knows
that 'Zero' might be a promoted data constructor, so it will demote
its namespace to DataName and do a second lookup.

The final result (after the renamer) will be:
  HsTyVar ("Zero", DataName)
Austin Seipp's avatar
Austin Seipp committed
1003
-}
1004

Matthew Pickering's avatar
Matthew Pickering committed
1005 1006 1007 1008 1009 1010
lookupOccRnX_maybe :: (RdrName -> RnM (Maybe r)) -> (Name -> r) -> RdrName
                   -> RnM (Maybe r)
lookupOccRnX_maybe globalLookup wrapper rdr_name
  = runMaybeT . msum . map MaybeT $
      [ fmap wrapper <$> lookupLocalOccRn_maybe rdr_name
      , globalLookup rdr_name ]
1011

1012
lookupOccRn_maybe :: RdrName -> RnM (Maybe Name)
Matthew Pickering's avatar
Matthew Pickering committed
1013 1014
lookupOccRn_maybe = lookupOccRnX_maybe lookupGlobalOccRn_maybe id

1015 1016
lookupOccRn_overloaded :: Bool -> RdrName
                       -> RnM (Maybe (Either Name [Name]))
Matthew Pickering's avatar
Matthew Pickering committed
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
lookupOccRn_overloaded overload_ok
  = lookupOccRnX_maybe global_lookup Left
      where
        global_lookup :: RdrName -> RnM (Maybe (Either Name [Name]))
        global_lookup n =
          runMaybeT . msum . map MaybeT $
            [ lookupGlobalOccRn_overloaded overload_ok n
            , fmap Left . listToMaybe <$> lookupQualifiedNameGHCi n ]


1027 1028 1029 1030 1031 1032 1033

lookupGlobalOccRn_maybe :: RdrName -> RnM (Maybe Name)
-- Looks up a RdrName occurrence in the top-level
--   environment, including using lookupQualifiedNameGHCi
--   for the GHCi case
-- No filter function; does not report an error on failure
-- Uses addUsedRdrName to record use and deprecations
Matthew Pickering's avatar
Matthew Pickering committed
1034 1035 1036 1037 1038
lookupGlobalOccRn_maybe rdr_name =
  lookupExactOrOrig rdr_name Just $
    runMaybeT . msum . map MaybeT $
      [ fmap gre_name <$> lookupGreRn_maybe rdr_name
      , listToMaybe <$> lookupQualifiedNameGHCi rdr_name ]
1039 1040
                      -- This test is not expensive,
                      -- and only happens for failed lookups
1041 1042

lookupGlobalOccRn :: RdrName -> RnM Name
Ian Lynagh's avatar
Ian Lynagh committed
1043
-- lookupGlobalOccRn is like lookupOccRn, except that it looks in the global
1044
-- environment.  Adds an error message if the RdrName is not in scope.
Matthew Pickering's avatar
Matthew Pickering committed
1045 1046
-- You usually want to use "lookupOccRn" which also looks in the local
-- environment.
1047 1048 1049 1050
lookupGlobalOccRn rdr_name
  = do { mb_name <- lookupGlobalOccRn_maybe rdr_name
       ; case mb_name of
           Just n  -> return n
1051
           Nothing -> do { traceRn "lookupGlobalOccRn" (ppr rdr_name)
1052
                         ; unboundName WL_Global rdr_name } }
1053

1054 1055 1056 1057
lookupInfoOccRn :: RdrName -> RnM [Name]
-- lookupInfoOccRn is intended for use in GHCi's ":info" command
-- It finds all the GREs that RdrName could mean, not complaining
-- about ambiguity, but rather returning them all
1058
-- C.f. #9881
Matthew Pickering's avatar
Matthew Pickering committed
1059 1060 1061
lookupInfoOccRn rdr_name =
  lookupExactOrOrig rdr_name (:[]) $
    do { rdr_env <- getGlobalRdrEnv
1062 1063 1064 1065
       ; let ns = map gre_name (lookupGRE_RdrName rdr_name rdr_env)
       ; qual_ns <- lookupQualifiedNameGHCi rdr_name
       ; return (ns ++ (qual_ns `minusList` ns)) }

1066 1067 1068 1069 1070 1071 1072 1073 1074 1075
-- | Like 'lookupOccRn_maybe', but with a more informative result if
-- the 'RdrName' happens to be a record selector:
--
--   * Nothing         -> name not in scope (no error reported)
--   * Just (Left x)   -> name uniquely refers to x,
--                        or there is a name clash (reported)
--   * Just (Right xs) -> name refers to one or more record selectors;
--                        if overload_ok was False, this list will be
--                        a singleton.

Matthew Pickering's avatar
Matthew Pickering committed
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
lookupGlobalOccRn_overloaded :: Bool -> RdrName
                             -> RnM (Maybe (Either Name [Name]))
lookupGlobalOccRn_overloaded overload_ok rdr_name =
  lookupExactOrOrig rdr_name (Just . Left) $
     do  { res <- lookupGreRn_helper rdr_name
         ; case res of
                GreNotFound  -> return Nothing
                OneNameMatch gre -> do
                  let wrapper = if isRecFldGRE gre then Right . (:[]) else Left
                  return $ Just (wrapper (gre_name gre))
                MultipleNames gres  | all isRecFldGRE gres && overload_ok ->
                  -- Don't record usage for ambiguous selectors
                  -- until we know which is meant
                  return $ Just (Right (map gre_name gres))
                MultipleNames gres  -> do
                  addNameClashErrRn rdr_name gres
                  return (Just (Left (gre_name (head gres)))) }
1093 1094


1095
--------------------------------------------------
Ian Lynagh's avatar
Ian Lynagh committed
1096
--      Lookup in the Global RdrEnv of the module
1097 1098
--------------------------------------------------

Matthew Pickering's avatar
Matthew Pickering committed
1099
data GreLookupResult = GreNotFound
Matthew Pickering's avatar
Matthew Pickering committed
1100 1101 1102
                     | OneNameMatch GlobalRdrElt
                     | MultipleNames [GlobalRdrElt]

1103
lookupGreRn_maybe :: RdrName -> RnM (Maybe GlobalRdrElt)
1104 1105 1106 1107
-- Look up the RdrName in the GlobalRdrEnv
--   Exactly one binding: records it as "used", return (Just gre)
--   No bindings:         return Nothing
--   Many bindings:       report "ambiguous", return an arbitrary (Just gre)
1108
-- Uses addUsedRdrName to record use and deprecations
Ian Lynagh's avatar
Ian Lynagh committed
1109
lookupGreRn_maybe rdr_name
Matthew Pickering's avatar
Matthew Pickering committed
1110 1111 1112 1113 1114
  = do
      res <- lookupGreRn_helper rdr_name
      case res of
        OneNameMatch gre ->  return $ Just gre
        MultipleNames gres -> do
Matthew Pickering's avatar
Matthew Pickering committed
1115
          traceRn "lookupGreRn_maybe:NameClash" (ppr gres)
Matthew Pickering's avatar
Matthew Pickering committed
1116 1117
          addNameClashErrRn rdr_name gres
          return $ Just (head gres)
Matthew Pickering's avatar
Matthew Pickering committed
1118
        GreNotFound -> return Nothing
1119

Matthew Pickering's avatar
Matthew Pickering committed
1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139
{-

Note [ Unbound vs Ambiguous Names ]

lookupGreRn_maybe deals with failures in two different ways. If a name
is unbound then we return a `Nothing` but if the name is ambiguous
then we raise an error and return a dummy name.

The reason for this is that when we call `lookupGreRn_maybe` we are
speculatively looking for whatever we are looking up. If we don't find it,
then we might have been looking for the wrong thing and can keep trying.
On the other hand, if we find a clash then there is no way to recover as
we found the thing we were looking for but can no longer resolve which
the correct one is.

One example of this is in `lookupTypeOccRn` which first looks in the type
constructor namespace before looking in the data constructor namespace to
deal with `DataKinds`.

There is however, as always, one exception to this scheme. If we find
1140
an ambiguous occurrence of a record selector and DuplicateRecordFields
Matthew Pickering's avatar
Matthew Pickering committed
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
is enabled then we defer the selection until the typechecker.

-}




-- Internal Function
lookupGreRn_helper :: RdrName -> RnM GreLookupResult
lookupGreRn_helper rdr_name
1151 1152
  = do  { env <- getGlobalRdrEnv
        ; case lookupGRE_RdrName rdr_name env of
Matthew Pickering's avatar
Matthew Pickering committed
1153
            []    -> return GreNotFound
1154
            [gre] -> do { addUsedGRE True gre
Matthew Pickering's avatar
Matthew Pickering committed
1155 1156
                        ; return (OneNameMatch gre) }
            gres  -> return (MultipleNames gres) }
1157 1158 1159 1160

lookupGreAvailRn :: RdrName -> RnM (Name, AvailInfo)
-- Used in export lists
-- If not found or ambiguous, add error message, and fake with UnboundName
1161
-- Uses addUsedRdrName to record use and deprecations
1162
lookupGreAvailRn rdr_name
Matthew Pickering's avatar
Matthew Pickering committed
1163 1164 1165
  = do
      mb_gre <- lookupGreRn_helper rdr_name
      case mb_gre of
Matthew Pickering's avatar
Matthew Pickering committed
1166
        GreNotFound ->
Matthew Pickering's avatar
Matthew Pickering committed
1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177
          do
            traceRn "lookupGreAvailRn" (ppr rdr_name)
            name <- unboundName WL_Global rdr_name
            return (name, avail name)
        MultipleNames gres ->
          do
            addNameClashErrRn rdr_name gres
            let unbound_name = mkUnboundNameRdr rdr_name
            return (unbound_name, avail unbound_name)
                        -- Returning an unbound name here prevents an error
                        -- cascade
Matthew Pickering's avatar
Matthew Pickering committed
1178 1179
        OneNameMatch gre ->
          return (gre_name gre, availFromGRE gre)
Matthew Pickering's avatar
Matthew Pickering committed
1180

1181

Austin Seipp's avatar
Austin Seipp committed
1182 1183 1184
{-
*********************************************************
*                                                      *
Ian Lynagh's avatar
Ian Lynagh committed
1185
                Deprecations
Austin Seipp's avatar
Austin Seipp committed
1186 1187
*                                                      *
*********************************************************
1188

1189 1190 1191
Note [Handling of deprecations]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* We report deprecations at each *occurrence* of the deprecated thing
1192
  (see #5867)
1193

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1194
* We do not report deprecations for locally-defined names. For a
1195 1196 1197 1198 1199
  start, we may be exporting a deprecated thing. Also we may use a
  deprecated thing in the defn of another deprecated things.  We may
  even use a deprecated thing in the defn of a non-deprecated thing,
  when changing a module's interface.

1200
* addUsedGREs: we do not report deprecations for sub-binders:
1201 1202 1203
     - the ".." completion for records
     - the ".." in an export item 'T(..)'
     - the things exported by a module export 'module M'
Austin Seipp's avatar
Austin Seipp committed
1204
-}
1205

1206
addUsedDataCons :: GlobalRdrEnv -> TyCon -> RnM ()
1207
-- Remember use of in-scope data constructors (#7969)
1208 1209 1210
addUsedDataCons rdr_env tycon
  = addUsedGREs [ gre
                | dc <- tyConDataCons tycon
1211
                , Just gre <- [lookupGRE_Name rdr_env (dataConName dc)] ]
1212 1213 1214 1215 1216 1217 1218 1219

addUsedGRE :: Bool -> GlobalRdrElt -> RnM ()
-- Called for both local and imported things
-- Add usage *and* warn if deprecated
addUsedGRE warn_if_deprec gre
  = do { when warn_if_deprec (warnIfDeprecated gre)
       ; unless (isLocalGRE gre) $
         do { env <- getGblEnv
1220
            ; traceRn "addUsedGRE" (ppr gre)
1221 1222 1223 1224 1225
            ; updMutVar (tcg_used_gres env) (gre :) } }

addUsedGREs :: [GlobalRdrElt] -> RnM ()
-- Record uses of any *imported* GREs
-- Used for recording used sub-bndrs
1226
-- NB: no call to warnIfDeprecated; see Note [Handling of deprecations]
1227 1228 1229
addUsedGREs gres
  | null imp_gres = return ()
  | otherwise     = do { env <- getGblEnv
1230
                       ; traceRn "addUsedGREs" (ppr imp_gres)
1231 1232 1233
                       ; updMutVar (tcg_used_gres env) (imp_gres ++) }
  where
    imp_gres = filterOut isLocalGRE gres
1234

1235
warnIfDeprecated :: GlobalRdrElt -> RnM ()
1236 1237
warnIfDeprecated gre@(GRE { gre_name = name, gre_imp = iss })
  | (imp_spec : _) <- iss
1238
  = do { dflags <- getDynFlags
1239 1240 1241 1242
       ; this_mod <- getModule
       ; when (wopt Opt_WarnWarningsDeprecations dflags &&
               not (nameIsLocalOrFrom this_mod name)) $
                   -- See Note [Handling of deprecations]
1243 1244
         do { iface <- loadInterfaceForName doc name
            ; case lookupImpDeprec iface gre of
1245 1246
                Just txt -> addWarn (Reason Opt_WarnWarningsDeprecations)
                                   (mk_msg imp_spec txt)
1247
                Nothing  -> return () } }