never executed always true always false
    1 
    2 {-# LANGUAGE NamedFieldPuns #-}
    3 {-# LANGUAGE TypeApplications #-}
    4 
    5 {-
    6 (c) The GRASP/AQUA Project, Glasgow University, 1992-2006
    7 
    8 GHC.Rename.Env contains functions which convert RdrNames into Names.
    9 
   10 -}
   11 
   12 module GHC.Rename.Env (
   13         newTopSrcBinder,
   14 
   15         lookupLocatedTopBndrRn, lookupLocatedTopBndrRnN, lookupTopBndrRn,
   16         lookupLocatedTopConstructorRn, lookupLocatedTopConstructorRnN,
   17 
   18         lookupLocatedOccRn, lookupLocatedOccRnConstr, lookupLocatedOccRnRecField,
   19         lookupLocatedOccRnNone,
   20         lookupOccRn, lookupOccRn_maybe,
   21         lookupLocalOccRn_maybe, lookupInfoOccRn,
   22         lookupLocalOccThLvl_maybe, lookupLocalOccRn,
   23         lookupTypeOccRn,
   24         lookupGlobalOccRn, lookupGlobalOccRn_maybe,
   25 
   26         AmbiguousResult(..),
   27         lookupExprOccRn,
   28         lookupRecFieldOcc,
   29         lookupRecFieldOcc_update,
   30 
   31         ChildLookupResult(..),
   32         lookupSubBndrOcc_helper,
   33         combineChildLookupResult, -- Called by lookupChildrenExport
   34 
   35         HsSigCtxt(..), lookupLocalTcNames, lookupSigOccRn, lookupSigOccRnN,
   36         lookupSigCtxtOccRn, lookupSigCtxtOccRnN,
   37 
   38         lookupInstDeclBndr, lookupFamInstName,
   39         lookupConstructorFields,
   40 
   41         lookupGreAvailRn,
   42 
   43         -- Rebindable Syntax
   44         lookupSyntax, lookupSyntaxExpr, lookupSyntaxNames,
   45         lookupSyntaxName,
   46         lookupIfThenElse,
   47 
   48         -- QualifiedDo
   49         lookupQualifiedDoExpr, lookupQualifiedDo,
   50         lookupQualifiedDoName, lookupNameWithQualifier,
   51 
   52         -- Constructing usage information
   53         addUsedGRE, addUsedGREs, addUsedDataCons,
   54 
   55 
   56 
   57         dataTcOccs, --TODO: Move this somewhere, into utils?
   58 
   59     ) where
   60 
   61 import GHC.Prelude
   62 
   63 import GHC.Iface.Load   ( loadInterfaceForName, loadSrcInterface_maybe )
   64 import GHC.Iface.Env
   65 import GHC.Hs
   66 import GHC.Types.Name.Reader
   67 import GHC.Tc.Errors.Types
   68 import GHC.Tc.Utils.Env
   69 import GHC.Tc.Utils.Monad
   70 import GHC.Parser.PostProcess ( setRdrNameSpace )
   71 import GHC.Builtin.Types
   72 import GHC.Types.Name
   73 import GHC.Types.Name.Set
   74 import GHC.Types.Name.Env
   75 import GHC.Types.Avail
   76 import GHC.Types.Error
   77 import GHC.Unit.Module
   78 import GHC.Unit.Module.ModIface
   79 import GHC.Unit.Module.Warnings  ( WarningTxt, pprWarningTxtForMsg )
   80 import GHC.Core.ConLike
   81 import GHC.Core.DataCon
   82 import GHC.Core.TyCon
   83 import GHC.Builtin.Names( rOOT_MAIN )
   84 import GHC.Types.Basic  ( TopLevelFlag(..), TupleSort(..) )
   85 import GHC.Types.SrcLoc as SrcLoc
   86 import GHC.Utils.Outputable as Outputable
   87 import GHC.Types.Unique.Set ( uniqSetAny )
   88 import GHC.Utils.Misc
   89 import GHC.Utils.Panic
   90 import GHC.Data.Maybe
   91 import GHC.Driver.Session
   92 import GHC.Data.FastString
   93 import Control.Monad
   94 import GHC.Data.List.SetOps ( minusList )
   95 import qualified GHC.LanguageExtensions as LangExt
   96 import GHC.Rename.Unbound
   97 import GHC.Rename.Utils
   98 import qualified Data.Semigroup as Semi
   99 import Data.Either      ( partitionEithers )
  100 import Data.List        ( find, sortBy )
  101 import qualified Data.List.NonEmpty as NE
  102 import Control.Arrow    ( first )
  103 import Data.Function
  104 import GHC.Types.FieldLabel
  105 import GHC.Data.Bag
  106 import GHC.Types.PkgQual
  107 
  108 {-
  109 *********************************************************
  110 *                                                      *
  111                 Source-code binders
  112 *                                                      *
  113 *********************************************************
  114 
  115 Note [Signature lazy interface loading]
  116 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  117 
  118 GHC's lazy interface loading can be a bit confusing, so this Note is an
  119 empirical description of what happens in one interesting case. When
  120 compiling a signature module against an its implementation, we do NOT
  121 load interface files associated with its names until after the type
  122 checking phase.  For example:
  123 
  124     module ASig where
  125         data T
  126         f :: T -> T
  127 
  128 Suppose we compile this with -sig-of "A is ASig":
  129 
  130     module B where
  131         data T = T
  132         f T = T
  133 
  134     module A(module B) where
  135         import B
  136 
  137 During type checking, we'll load A.hi because we need to know what the
  138 RdrEnv for the module is, but we DO NOT load the interface for B.hi!
  139 It's wholly unnecessary: our local definition 'data T' in ASig is all
  140 the information we need to finish type checking.  This is contrast to
  141 type checking of ordinary Haskell files, in which we would not have the
  142 local definition "data T" and would need to consult B.hi immediately.
  143 (Also, this situation never occurs for hs-boot files, since you're not
  144 allowed to reexport from another module.)
  145 
  146 After type checking, we then check that the types we provided are
  147 consistent with the backing implementation (in checkHiBootOrHsigIface).
  148 At this point, B.hi is loaded, because we need something to compare
  149 against.
  150 
  151 I discovered this behavior when trying to figure out why type class
  152 instances for Data.Map weren't in the EPS when I was type checking a
  153 test very much like ASig (sigof02dm): the associated interface hadn't
  154 been loaded yet!  (The larger issue is a moot point, since an instance
  155 declared in a signature can never be a duplicate.)
  156 
  157 This behavior might change in the future.  Consider this
  158 alternate module B:
  159 
  160     module B where
  161         {-# DEPRECATED T, f "Don't use" #-}
  162         data T = T
  163         f T = T
  164 
  165 One might conceivably want to report deprecation warnings when compiling
  166 ASig with -sig-of B, in which case we need to look at B.hi to find the
  167 deprecation warnings during renaming.  At the moment, you don't get any
  168 warning until you use the identifier further downstream.  This would
  169 require adjusting addUsedGRE so that during signature compilation,
  170 we do not report deprecation warnings for LocalDef.  See also
  171 Note [Handling of deprecations]
  172 -}
  173 
  174 newTopSrcBinder :: LocatedN RdrName -> RnM Name
  175 newTopSrcBinder (L loc rdr_name)
  176   | Just name <- isExact_maybe rdr_name
  177   =     -- This is here to catch
  178         --   (a) Exact-name binders created by Template Haskell
  179         --   (b) The PrelBase defn of (say) [] and similar, for which
  180         --       the parser reads the special syntax and returns an Exact RdrName
  181         -- We are at a binding site for the name, so check first that it
  182         -- the current module is the correct one; otherwise GHC can get
  183         -- very confused indeed. This test rejects code like
  184         --      data T = (,) Int Int
  185         -- unless we are in GHC.Tup
  186     if isExternalName name then
  187       do { this_mod <- getModule
  188          ; unless (this_mod == nameModule name)
  189                   (addErrAt (locA loc) (badOrigBinding rdr_name))
  190          ; return name }
  191     else   -- See Note [Binders in Template Haskell] in "GHC.ThToHs"
  192       do { this_mod <- getModule
  193          ; externaliseName this_mod name }
  194 
  195   | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
  196   = do  { this_mod <- getModule
  197         ; unless (rdr_mod == this_mod || rdr_mod == rOOT_MAIN)
  198                  (addErrAt (locA loc) (badOrigBinding rdr_name))
  199         -- When reading External Core we get Orig names as binders,
  200         -- but they should agree with the module gotten from the monad
  201         --
  202         -- We can get built-in syntax showing up here too, sadly.  If you type
  203         --      data T = (,,,)
  204         -- the constructor is parsed as a type, and then GHC.Parser.PostProcess.tyConToDataCon
  205         -- uses setRdrNameSpace to make it into a data constructors.  At that point
  206         -- the nice Exact name for the TyCon gets swizzled to an Orig name.
  207         -- Hence the badOrigBinding error message.
  208         --
  209         -- Except for the ":Main.main = ..." definition inserted into
  210         -- the Main module; ugh!
  211 
  212         -- Because of this latter case, we call newGlobalBinder with a module from
  213         -- the RdrName, not from the environment.  In principle, it'd be fine to
  214         -- have an arbitrary mixture of external core definitions in a single module,
  215         -- (apart from module-initialisation issues, perhaps).
  216         ; newGlobalBinder rdr_mod rdr_occ (locA loc) }
  217 
  218   | otherwise
  219   = do  { when (isQual rdr_name)
  220                  (addErrAt (locA loc) (badQualBndrErr rdr_name))
  221                 -- Binders should not be qualified; if they are, and with a different
  222                 -- module name, we get a confusing "M.T is not in scope" error later
  223 
  224         ; stage <- getStage
  225         ; if isBrackStage stage then
  226                 -- We are inside a TH bracket, so make an *Internal* name
  227                 -- See Note [Top-level Names in Template Haskell decl quotes] in GHC.Rename.Names
  228              do { uniq <- newUnique
  229                 ; return (mkInternalName uniq (rdrNameOcc rdr_name) (locA loc)) }
  230           else
  231              do { this_mod <- getModule
  232                 ; traceRn "newTopSrcBinder" (ppr this_mod $$ ppr rdr_name $$ ppr (locA loc))
  233                 ; newGlobalBinder this_mod (rdrNameOcc rdr_name) (locA loc) }
  234         }
  235 
  236 {-
  237 *********************************************************
  238 *                                                      *
  239         Source code occurrences
  240 *                                                      *
  241 *********************************************************
  242 
  243 Looking up a name in the GHC.Rename.Env.
  244 
  245 Note [Type and class operator definitions]
  246 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  247 We want to reject all of these unless we have -XTypeOperators (#3265)
  248    data a :*: b  = ...
  249    class a :*: b where ...
  250    data (:*:) a b  = ....
  251    class (:*:) a b where ...
  252 The latter two mean that we are not just looking for a
  253 *syntactically-infix* declaration, but one that uses an operator
  254 OccName.  We use OccName.isSymOcc to detect that case, which isn't
  255 terribly efficient, but there seems to be no better way.
  256 -}
  257 
  258 -- Can be made to not be exposed
  259 -- Only used unwrapped in rnAnnProvenance
  260 lookupTopBndrRn :: WhatLooking -> RdrName -> RnM Name
  261 -- Look up a top-level source-code binder.   We may be looking up an unqualified 'f',
  262 -- and there may be several imported 'f's too, which must not confuse us.
  263 -- For example, this is OK:
  264 --      import Foo( f )
  265 --      infix 9 f       -- The 'f' here does not need to be qualified
  266 --      f x = x         -- Nor here, of course
  267 -- So we have to filter out the non-local ones.
  268 --
  269 -- A separate function (importsFromLocalDecls) reports duplicate top level
  270 -- decls, so here it's safe just to choose an arbitrary one.
  271 lookupTopBndrRn which_suggest rdr_name =
  272   lookupExactOrOrig rdr_name id $
  273     do  {  -- Check for operators in type or class declarations
  274            -- See Note [Type and class operator definitions]
  275           let occ = rdrNameOcc rdr_name
  276         ; when (isTcOcc occ && isSymOcc occ)
  277                (do { op_ok <- xoptM LangExt.TypeOperators
  278                    ; unless op_ok (addErr (opDeclErr rdr_name)) })
  279 
  280         ; env <- getGlobalRdrEnv
  281         ; case filter isLocalGRE (lookupGRE_RdrName rdr_name env) of
  282             [gre] -> return (greMangledName gre)
  283             _     -> do -- Ambiguous (can't happen) or unbound
  284                         traceRn "lookupTopBndrRN fail" (ppr rdr_name)
  285                         unboundName (LF which_suggest WL_LocalTop) rdr_name
  286     }
  287 
  288 lookupLocatedTopConstructorRn :: Located RdrName -> RnM (Located Name)
  289 lookupLocatedTopConstructorRn = wrapLocM (lookupTopBndrRn WL_Constructor)
  290 
  291 lookupLocatedTopConstructorRnN :: LocatedN RdrName -> RnM (LocatedN Name)
  292 lookupLocatedTopConstructorRnN = wrapLocMA (lookupTopBndrRn WL_Constructor)
  293 
  294 lookupLocatedTopBndrRn :: Located RdrName -> RnM (Located Name)
  295 lookupLocatedTopBndrRn = wrapLocM (lookupTopBndrRn WL_Anything)
  296 
  297 lookupLocatedTopBndrRnN :: LocatedN RdrName -> RnM (LocatedN Name)
  298 lookupLocatedTopBndrRnN = wrapLocMA (lookupTopBndrRn WL_Anything)
  299 
  300 -- | Lookup an @Exact@ @RdrName@. See Note [Looking up Exact RdrNames].
  301 -- This never adds an error, but it may return one, see
  302 -- Note [Errors in lookup functions]
  303 lookupExactOcc_either :: Name -> RnM (Either SDoc Name)
  304 lookupExactOcc_either name
  305   | Just thing <- wiredInNameTyThing_maybe name
  306   , Just tycon <- case thing of
  307                     ATyCon tc                 -> Just tc
  308                     AConLike (RealDataCon dc) -> Just (dataConTyCon dc)
  309                     _                         -> Nothing
  310   , Just tupleSort <- tyConTuple_maybe tycon
  311   = do { let tupArity = case tupleSort of
  312                -- Unboxed tuples have twice as many arguments because of the
  313                -- 'RuntimeRep's (#17837)
  314                UnboxedTuple -> tyConArity tycon `div` 2
  315                _ -> tyConArity tycon
  316        ; checkTupSize tupArity
  317        ; return (Right name) }
  318 
  319   | isExternalName name
  320   = return (Right name)
  321 
  322   | otherwise
  323   = do { env <- getGlobalRdrEnv
  324        ; let -- See Note [Splicing Exact names]
  325              main_occ =  nameOccName name
  326              demoted_occs = case demoteOccName main_occ of
  327                               Just occ -> [occ]
  328                               Nothing  -> []
  329              gres = [ gre | occ <- main_occ : demoted_occs
  330                           , gre <- lookupGlobalRdrEnv env occ
  331                           , greMangledName gre == name ]
  332        ; case gres of
  333            [gre] -> return (Right (greMangledName gre))
  334 
  335            []    -> -- See Note [Splicing Exact names]
  336                     do { lcl_env <- getLocalRdrEnv
  337                        ; if name `inLocalRdrEnvScope` lcl_env
  338                          then return (Right name)
  339                          else
  340                          do { th_topnames_var <- fmap tcg_th_topnames getGblEnv
  341                             ; th_topnames <- readTcRef th_topnames_var
  342                             ; if name `elemNameSet` th_topnames
  343                               then return (Right name)
  344                               else return (Left (exactNameErr name))
  345                             }
  346                        }
  347            gres -> return (Left (sameNameErr gres))   -- Ugh!  See Note [Template Haskell ambiguity]
  348        }
  349 
  350 sameNameErr :: [GlobalRdrElt] -> SDoc
  351 sameNameErr [] = panic "addSameNameErr: empty list"
  352 sameNameErr gres@(_ : _)
  353   = hang (text "Same exact name in multiple name-spaces:")
  354        2 (vcat (map pp_one sorted_names) $$ th_hint)
  355   where
  356     sorted_names = sortBy (SrcLoc.leftmost_smallest `on` nameSrcSpan) (map greMangledName gres)
  357     pp_one name
  358       = hang (pprNameSpace (occNameSpace (getOccName name))
  359               <+> quotes (ppr name) <> comma)
  360            2 (text "declared at:" <+> ppr (nameSrcLoc name))
  361 
  362     th_hint = vcat [ text "Probable cause: you bound a unique Template Haskell name (NameU),"
  363                    , text "perhaps via newName, in different name-spaces."
  364                    , text "If that's it, then -ddump-splices might be useful" ]
  365 
  366 
  367 -----------------------------------------------
  368 lookupInstDeclBndr :: Name -> SDoc -> RdrName -> RnM Name
  369 -- This is called on the method name on the left-hand side of an
  370 -- instance declaration binding. eg.  instance Functor T where
  371 --                                       fmap = ...
  372 --                                       ^^^^ called on this
  373 -- Regardless of how many unqualified fmaps are in scope, we want
  374 -- the one that comes from the Functor class.
  375 --
  376 -- Furthermore, note that we take no account of whether the
  377 -- name is only in scope qualified.  I.e. even if method op is
  378 -- in scope as M.op, we still allow plain 'op' on the LHS of
  379 -- an instance decl
  380 --
  381 -- The "what" parameter says "method" or "associated type",
  382 -- depending on what we are looking up
  383 lookupInstDeclBndr cls what rdr
  384   = do { when (isQual rdr)
  385               (addErr (badQualBndrErr rdr))
  386                 -- In an instance decl you aren't allowed
  387                 -- to use a qualified name for the method
  388                 -- (Although it'd make perfect sense.)
  389        ; mb_name <- lookupSubBndrOcc
  390                           False -- False => we don't give deprecated
  391                                 -- warnings when a deprecated class
  392                                 -- method is defined. We only warn
  393                                 -- when it's used
  394                           cls doc rdr
  395        ; case mb_name of
  396            Left err -> do { addErr (TcRnUnknownMessage $ mkPlainError noHints err)
  397                           ; return (mkUnboundNameRdr rdr) }
  398            Right nm -> return nm }
  399   where
  400     doc = what <+> text "of class" <+> quotes (ppr cls)
  401 
  402 -----------------------------------------------
  403 lookupFamInstName :: Maybe Name -> LocatedN RdrName
  404                   -> RnM (LocatedN Name)
  405 -- Used for TyData and TySynonym family instances only,
  406 -- See Note [Family instance binders]
  407 lookupFamInstName (Just cls) tc_rdr  -- Associated type; c.f GHC.Rename.Bind.rnMethodBind
  408   = wrapLocMA (lookupInstDeclBndr cls (text "associated type")) tc_rdr
  409 lookupFamInstName Nothing tc_rdr     -- Family instance; tc_rdr is an *occurrence*
  410   = lookupLocatedOccRnConstr tc_rdr
  411 
  412 -----------------------------------------------
  413 lookupConstructorFields :: Name -> RnM [FieldLabel]
  414 -- Look up the fields of a given constructor
  415 --   *  For constructors from this module, use the record field env,
  416 --      which is itself gathered from the (as yet un-typechecked)
  417 --      data type decls
  418 --
  419 --    * For constructors from imported modules, use the *type* environment
  420 --      since imported modules are already compiled, the info is conveniently
  421 --      right there
  422 
  423 lookupConstructorFields con_name
  424   = do  { this_mod <- getModule
  425         ; if nameIsLocalOrFrom this_mod con_name then
  426           do { field_env <- getRecFieldEnv
  427              ; traceTc "lookupCF" (ppr con_name $$ ppr (lookupNameEnv field_env con_name) $$ ppr field_env)
  428              ; return (lookupNameEnv field_env con_name `orElse` []) }
  429           else
  430           do { con <- tcLookupConLike con_name
  431              ; traceTc "lookupCF 2" (ppr con)
  432              ; return (conLikeFieldLabels con) } }
  433 
  434 
  435 -- In CPS style as `RnM r` is monadic
  436 -- Reports an error if the name is an Exact or Orig and it can't find the name
  437 -- Otherwise if it is not an Exact or Orig, returns k
  438 lookupExactOrOrig :: RdrName -> (Name -> r) -> RnM r -> RnM r
  439 lookupExactOrOrig rdr_name res k
  440   = do { men <- lookupExactOrOrig_base rdr_name
  441        ; case men of
  442           FoundExactOrOrig n -> return (res n)
  443           ExactOrOrigError e ->
  444             do { addErr (TcRnUnknownMessage $ mkPlainError noHints e)
  445                ; return (res (mkUnboundNameRdr rdr_name)) }
  446           NotExactOrOrig     -> k }
  447 
  448 -- Variant of 'lookupExactOrOrig' that does not report an error
  449 -- See Note [Errors in lookup functions]
  450 -- Calls k if the name is neither an Exact nor Orig
  451 lookupExactOrOrig_maybe :: RdrName -> (Maybe Name -> r) -> RnM r -> RnM r
  452 lookupExactOrOrig_maybe rdr_name res k
  453   = do { men <- lookupExactOrOrig_base rdr_name
  454        ; case men of
  455            FoundExactOrOrig n -> return (res (Just n))
  456            ExactOrOrigError _ -> return (res Nothing)
  457            NotExactOrOrig     -> k }
  458 
  459 data ExactOrOrigResult = FoundExactOrOrig Name -- ^ Found an Exact Or Orig Name
  460                        | ExactOrOrigError SDoc -- ^ The RdrName was an Exact
  461                                                  -- or Orig, but there was an
  462                                                  -- error looking up the Name
  463                        | NotExactOrOrig -- ^ The RdrName is neither an Exact nor
  464                                         -- Orig
  465 
  466 -- Does the actual looking up an Exact or Orig name, see 'ExactOrOrigResult'
  467 lookupExactOrOrig_base :: RdrName -> RnM ExactOrOrigResult
  468 lookupExactOrOrig_base rdr_name
  469   | Just n <- isExact_maybe rdr_name   -- This happens in derived code
  470   = cvtEither <$> lookupExactOcc_either n
  471   | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
  472   = FoundExactOrOrig <$> lookupOrig rdr_mod rdr_occ
  473   | otherwise = return NotExactOrOrig
  474   where
  475     cvtEither (Left e)  = ExactOrOrigError e
  476     cvtEither (Right n) = FoundExactOrOrig n
  477 
  478 
  479 {- Note [Errors in lookup functions]
  480 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  481 Many of these lookup functions will attach an error if it can't find the Name it
  482 is trying to lookup. However there are also _maybe and _either variants for many
  483 of these functions.
  484 
  485 These variants should *not* attach any errors, as there are
  486 places where we want to attempt looking up a name, but it's not the end of the
  487 world if we don't find it.
  488 
  489 For example, see lookupThName_maybe: It calls lookupOccRn_maybe multiple
  490 times for varying names in different namespaces. lookupOccRn_maybe should
  491 therefore never attach an error, instead just return a Nothing.
  492 
  493 For these _maybe/_either variant functions then, avoid calling further lookup
  494 functions that can attach errors and instead call their _maybe/_either
  495 counterparts.
  496 -}
  497 
  498 -----------------------------------------------
  499 -- | Look up an occurrence of a field in record construction or pattern
  500 -- matching (but not update).  When the -XDisambiguateRecordFields
  501 -- flag is on, take account of the data constructor name to
  502 -- disambiguate which field to use.
  503 --
  504 -- See Note [DisambiguateRecordFields] and Note [NoFieldSelectors].
  505 lookupRecFieldOcc :: Maybe Name -- Nothing  => just look it up as usual
  506                                 -- Just con => use data con to disambiguate
  507                   -> RdrName
  508                   -> RnM Name
  509 lookupRecFieldOcc mb_con rdr_name
  510   | Just con <- mb_con
  511   , isUnboundName con  -- Avoid error cascade
  512   = return (mkUnboundNameRdr rdr_name)
  513   | Just con <- mb_con
  514   = do { flds <- lookupConstructorFields con
  515        ; env <- getGlobalRdrEnv
  516        ; let lbl      = occNameFS (rdrNameOcc rdr_name)
  517              mb_field = do fl <- find ((== lbl) . flLabel) flds
  518                            -- We have the label, now check it is in scope.  If
  519                            -- there is a qualifier, use pickGREs to check that
  520                            -- the qualifier is correct, and return the filtered
  521                            -- GRE so we get import usage right (see #17853).
  522                            gre <- lookupGRE_FieldLabel env fl
  523                            if isQual rdr_name
  524                              then do gre' <- listToMaybe (pickGREs rdr_name [gre])
  525                                      return (fl, gre')
  526                               else return (fl, gre)
  527        ; case mb_field of
  528            Just (fl, gre) -> do { addUsedGRE True gre
  529                                 ; return (flSelector fl) }
  530            Nothing        -> lookupGlobalOccRn' WantBoth rdr_name }
  531              -- See Note [Fall back on lookupGlobalOccRn in lookupRecFieldOcc]
  532   | otherwise
  533   -- This use of Global is right as we are looking up a selector which
  534   -- can only be defined at the top level.
  535   = lookupGlobalOccRn' WantBoth rdr_name
  536 
  537 -- | Look up an occurrence of a field in a record update, returning the selector
  538 -- name.
  539 --
  540 -- Unlike construction and pattern matching with @-XDisambiguateRecordFields@
  541 -- (see 'lookupRecFieldOcc'), there is no data constructor to help disambiguate,
  542 -- so this may be ambiguous if the field is in scope multiple times.  However we
  543 -- ignore non-fields in scope with the same name if @-XDisambiguateRecordFields@
  544 -- is on (see Note [DisambiguateRecordFields for updates]).
  545 --
  546 -- Here a field is in scope even if @NoFieldSelectors@ was enabled at its
  547 -- definition site (see Note [NoFieldSelectors]).
  548 lookupRecFieldOcc_update
  549   :: DuplicateRecordFields
  550   -> RdrName
  551   -> RnM AmbiguousResult
  552 lookupRecFieldOcc_update dup_fields_ok rdr_name = do
  553     disambig_ok <- xoptM LangExt.DisambiguateRecordFields
  554     let want | disambig_ok = WantField
  555              | otherwise   = WantBoth
  556     mr <- lookupGlobalOccRn_overloaded dup_fields_ok want rdr_name
  557     case mr of
  558         Just r  -> return r
  559         Nothing  -- Try again if we previously looked only for fields, see
  560                  -- Note [DisambiguateRecordFields for updates]
  561           | disambig_ok -> do mr' <- lookupGlobalOccRn_overloaded dup_fields_ok WantBoth rdr_name
  562                               case mr' of
  563                                   Just r -> return r
  564                                   Nothing -> unbound
  565           | otherwise   -> unbound
  566   where
  567     unbound = UnambiguousGre . NormalGreName
  568           <$> unboundName (LF WL_RecField WL_Global) rdr_name
  569 
  570 
  571 {- Note [DisambiguateRecordFields]
  572 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  573 When we are looking up record fields in record construction or pattern
  574 matching, we can take advantage of the data constructor name to
  575 resolve fields that would otherwise be ambiguous (provided the
  576 -XDisambiguateRecordFields flag is on).
  577 
  578 For example, consider:
  579 
  580    data S = MkS { x :: Int }
  581    data T = MkT { x :: Int }
  582 
  583    e = MkS { x = 3 }
  584 
  585 When we are renaming the occurrence of `x` in `e`, instead of looking
  586 `x` up directly (and finding both fields), lookupRecFieldOcc will
  587 search the fields of `MkS` to find the only possible `x` the user can
  588 mean.
  589 
  590 Of course, we still have to check the field is in scope, using
  591 lookupGRE_FieldLabel.  The handling of qualified imports is slightly
  592 subtle: the occurrence may be unqualified even if the field is
  593 imported only qualified (but if the occurrence is qualified, the
  594 qualifier must be correct). For example:
  595 
  596    module A where
  597      data S = MkS { x :: Int }
  598      data T = MkT { x :: Int }
  599 
  600    module B where
  601      import qualified A (S(..))
  602      import A (T(MkT))
  603 
  604      e1 = MkT   { x = 3 }   -- x not in scope, so fail
  605      e2 = A.MkS { B.x = 3 } -- module qualifier is wrong, so fail
  606      e3 = A.MkS { x = 3 }   -- x in scope (lack of module qualifier permitted)
  607 
  608 In case `e1`, lookupGRE_FieldLabel will return Nothing.  In case `e2`,
  609 lookupGRE_FieldLabel will return the GRE for `A.x`, but then the guard
  610 will fail because the field RdrName `B.x` is qualified and pickGREs
  611 rejects the GRE.  In case `e3`, lookupGRE_FieldLabel will return the
  612 GRE for `A.x` and the guard will succeed because the field RdrName `x`
  613 is unqualified.
  614 
  615 
  616 Note [DisambiguateRecordFields for updates]
  617 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  618 When we are looking up record fields in record update, we can take advantage of
  619 the fact that we know we are looking for a field, even though we do not know the
  620 data constructor name (as in Note [DisambiguateRecordFields]), provided the
  621 -XDisambiguateRecordFields flag is on.
  622 
  623 For example, consider:
  624 
  625    module N where
  626      f = ()
  627 
  628    {-# LANGUAGE DisambiguateRecordFields #-}
  629    module M where
  630      import N (f)
  631      data T = MkT { f :: Int }
  632      t = MkT { f = 1 }  -- unambiguous because MkT determines which field we mean
  633      u = t { f = 2 }    -- unambiguous because we ignore the non-field 'f'
  634 
  635 This works by lookupRecFieldOcc_update using 'WantField :: FieldsOrSelectors'
  636 when looking up the field name, so that 'filterFieldGREs' will later ignore any
  637 non-fields in scope.  Of course, if a record update has two fields in scope with
  638 the same name, it is still ambiguous.
  639 
  640 If we do not find anything when looking only for fields, we try again allowing
  641 fields or non-fields.  This leads to a better error message if the user
  642 mistakenly tries to use a non-field name in a record update:
  643 
  644     f = ()
  645     e x = x { f = () }
  646 
  647 Unlike with constructors or pattern-matching, we do not allow the module
  648 qualifier to be omitted, because we do not have a data constructor from which to
  649 determine it.
  650 
  651 
  652 Note [Fall back on lookupGlobalOccRn in lookupRecFieldOcc]
  653 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  654 Whenever we fail to find the field or it is not in scope, mb_field
  655 will be False, and we fall back on looking it up normally using
  656 lookupGlobalOccRn.  We don't report an error immediately because the
  657 actual problem might be located elsewhere.  For example (#9975):
  658 
  659    data Test = Test { x :: Int }
  660    pattern Test wat = Test { x = wat }
  661 
  662 Here there are multiple declarations of Test (as a data constructor
  663 and as a pattern synonym), which will be reported as an error.  We
  664 shouldn't also report an error about the occurrence of `x` in the
  665 pattern synonym RHS.  However, if the pattern synonym gets added to
  666 the environment first, we will try and fail to find `x` amongst the
  667 (nonexistent) fields of the pattern synonym.
  668 
  669 Alternatively, the scope check can fail due to Template Haskell.
  670 Consider (#12130):
  671 
  672    module Foo where
  673      import M
  674      b = $(funny)
  675 
  676    module M(funny) where
  677      data T = MkT { x :: Int }
  678      funny :: Q Exp
  679      funny = [| MkT { x = 3 } |]
  680 
  681 When we splice, `MkT` is not lexically in scope, so
  682 lookupGRE_FieldLabel will fail.  But there is no need for
  683 disambiguation anyway, because `x` is an original name, and
  684 lookupGlobalOccRn will find it.
  685 -}
  686 
  687 
  688 
  689 -- | Used in export lists to lookup the children.
  690 lookupSubBndrOcc_helper :: Bool -> Bool -> Name -> RdrName
  691                         -> RnM ChildLookupResult
  692 lookupSubBndrOcc_helper must_have_parent warn_if_deprec parent rdr_name
  693   | isUnboundName parent
  694     -- Avoid an error cascade
  695   = return (FoundChild NoParent (NormalGreName (mkUnboundNameRdr rdr_name)))
  696 
  697   | otherwise = do
  698   gre_env <- getGlobalRdrEnv
  699 
  700   let original_gres = lookupGlobalRdrEnv gre_env (rdrNameOcc rdr_name)
  701   -- Disambiguate the lookup based on the parent information.
  702   -- The remaining GREs are things that we *could* export here, note that
  703   -- this includes things which have `NoParent`. Those are sorted in
  704   -- `checkPatSynParent`.
  705   traceRn "parent" (ppr parent)
  706   traceRn "lookupExportChild original_gres:" (ppr original_gres)
  707   traceRn "lookupExportChild picked_gres:" (ppr (picked_gres original_gres) $$ ppr must_have_parent)
  708   case picked_gres original_gres of
  709     NoOccurrence ->
  710       noMatchingParentErr original_gres
  711     UniqueOccurrence g ->
  712       if must_have_parent then noMatchingParentErr original_gres
  713                           else checkFld g
  714     DisambiguatedOccurrence g ->
  715       checkFld g
  716     AmbiguousOccurrence gres ->
  717       mkNameClashErr gres
  718     where
  719         -- Convert into FieldLabel if necessary
  720         checkFld :: GlobalRdrElt -> RnM ChildLookupResult
  721         checkFld g@GRE{gre_name,gre_par} = do
  722           addUsedGRE warn_if_deprec g
  723           return $ FoundChild gre_par gre_name
  724 
  725         -- Called when we find no matching GREs after disambiguation but
  726         -- there are three situations where this happens.
  727         -- 1. There were none to begin with.
  728         -- 2. None of the matching ones were the parent but
  729         --  a. They were from an overloaded record field so we can report
  730         --     a better error
  731         --  b. The original lookup was actually ambiguous.
  732         --     For example, the case where overloading is off and two
  733         --     record fields are in scope from different record
  734         --     constructors, neither of which is the parent.
  735         noMatchingParentErr :: [GlobalRdrElt] -> RnM ChildLookupResult
  736         noMatchingParentErr original_gres = do
  737           traceRn "npe" (ppr original_gres)
  738           dup_fields_ok <- xoptM LangExt.DuplicateRecordFields
  739           case original_gres of
  740             [] ->  return NameNotFound
  741             [g] -> return $ IncorrectParent parent
  742                               (gre_name g)
  743                               [p | Just p <- [getParent g]]
  744             gss@(g:gss'@(_:_)) ->
  745               if all isRecFldGRE gss && dup_fields_ok
  746                 then return $
  747                       IncorrectParent parent
  748                         (gre_name g)
  749                         [p | x <- gss, Just p <- [getParent x]]
  750                 else mkNameClashErr $ g NE.:| gss'
  751 
  752         mkNameClashErr :: NE.NonEmpty GlobalRdrElt -> RnM ChildLookupResult
  753         mkNameClashErr gres = do
  754           addNameClashErrRn rdr_name gres
  755           return (FoundChild (gre_par (NE.head gres)) (gre_name (NE.head gres)))
  756 
  757         getParent :: GlobalRdrElt -> Maybe Name
  758         getParent (GRE { gre_par = p } ) =
  759           case p of
  760             ParentIs cur_parent -> Just cur_parent
  761             NoParent -> Nothing
  762 
  763         picked_gres :: [GlobalRdrElt] -> DisambigInfo
  764         -- For Unqual, find GREs that are in scope qualified or unqualified
  765         -- For Qual,   find GREs that are in scope with that qualification
  766         picked_gres gres
  767           | isUnqual rdr_name
  768           = mconcat (map right_parent gres)
  769           | otherwise
  770           = mconcat (map right_parent (pickGREs rdr_name gres))
  771 
  772         right_parent :: GlobalRdrElt -> DisambigInfo
  773         right_parent p
  774           = case getParent p of
  775                Just cur_parent
  776                   | parent == cur_parent -> DisambiguatedOccurrence p
  777                   | otherwise            -> NoOccurrence
  778                Nothing                   -> UniqueOccurrence p
  779 
  780 
  781 -- This domain specific datatype is used to record why we decided it was
  782 -- possible that a GRE could be exported with a parent.
  783 data DisambigInfo
  784        = NoOccurrence
  785           -- The GRE could never be exported. It has the wrong parent.
  786        | UniqueOccurrence GlobalRdrElt
  787           -- The GRE has no parent. It could be a pattern synonym.
  788        | DisambiguatedOccurrence GlobalRdrElt
  789           -- The parent of the GRE is the correct parent
  790        | AmbiguousOccurrence (NE.NonEmpty GlobalRdrElt)
  791           -- For example, two normal identifiers with the same name are in
  792           -- scope. They will both be resolved to "UniqueOccurrence" and the
  793           -- monoid will combine them to this failing case.
  794 
  795 instance Outputable DisambigInfo where
  796   ppr NoOccurrence = text "NoOccurence"
  797   ppr (UniqueOccurrence gre) = text "UniqueOccurrence:" <+> ppr gre
  798   ppr (DisambiguatedOccurrence gre) = text "DiambiguatedOccurrence:" <+> ppr gre
  799   ppr (AmbiguousOccurrence gres)    = text "Ambiguous:" <+> ppr gres
  800 
  801 instance Semi.Semigroup DisambigInfo where
  802   -- This is the key line: We prefer disambiguated occurrences to other
  803   -- names.
  804   _ <> DisambiguatedOccurrence g' = DisambiguatedOccurrence g'
  805   DisambiguatedOccurrence g' <> _ = DisambiguatedOccurrence g'
  806 
  807   NoOccurrence <> m = m
  808   m <> NoOccurrence = m
  809   UniqueOccurrence g <> UniqueOccurrence g'
  810     = AmbiguousOccurrence $ g NE.:| [g']
  811   UniqueOccurrence g <> AmbiguousOccurrence gs
  812     = AmbiguousOccurrence (g `NE.cons` gs)
  813   AmbiguousOccurrence gs <> UniqueOccurrence g'
  814     = AmbiguousOccurrence (g' `NE.cons` gs)
  815   AmbiguousOccurrence gs <> AmbiguousOccurrence gs'
  816     = AmbiguousOccurrence (gs Semi.<> gs')
  817 
  818 instance Monoid DisambigInfo where
  819   mempty = NoOccurrence
  820   mappend = (Semi.<>)
  821 
  822 -- Lookup SubBndrOcc can never be ambiguous
  823 --
  824 -- Records the result of looking up a child.
  825 data ChildLookupResult
  826       = NameNotFound                --  We couldn't find a suitable name
  827       | IncorrectParent Name        -- Parent
  828                         GreName     -- Child we were looking for
  829                         [Name]      -- List of possible parents
  830       | FoundChild Parent GreName   --  We resolved to a child
  831 
  832 -- | Specialised version of msum for RnM ChildLookupResult
  833 combineChildLookupResult :: [RnM ChildLookupResult] -> RnM ChildLookupResult
  834 combineChildLookupResult [] = return NameNotFound
  835 combineChildLookupResult (x:xs) = do
  836   res <- x
  837   case res of
  838     NameNotFound -> combineChildLookupResult xs
  839     _ -> return res
  840 
  841 instance Outputable ChildLookupResult where
  842   ppr NameNotFound = text "NameNotFound"
  843   ppr (FoundChild p n) = text "Found:" <+> ppr p <+> ppr n
  844   ppr (IncorrectParent p n ns) = text "IncorrectParent"
  845                                   <+> hsep [ppr p, ppr n, ppr ns]
  846 
  847 lookupSubBndrOcc :: Bool
  848                  -> Name     -- Parent
  849                  -> SDoc
  850                  -> RdrName
  851                  -> RnM (Either SDoc Name)
  852 -- Find all the things the rdr-name maps to
  853 -- and pick the one with the right parent namep
  854 lookupSubBndrOcc warn_if_deprec the_parent doc rdr_name = do
  855   res <-
  856     lookupExactOrOrig rdr_name (FoundChild NoParent . NormalGreName) $
  857       -- This happens for built-in classes, see mod052 for example
  858       lookupSubBndrOcc_helper True warn_if_deprec the_parent rdr_name
  859   case res of
  860     NameNotFound -> return (Left (unknownSubordinateErr doc rdr_name))
  861     FoundChild _p child -> return (Right (greNameMangledName child))
  862     IncorrectParent {}
  863          -- See [Mismatched class methods and associated type families]
  864          -- in TcInstDecls.
  865       -> return $ Left (unknownSubordinateErr doc rdr_name)
  866 
  867 {-
  868 Note [Family instance binders]
  869 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  870 Consider
  871   data family F a
  872   data instance F T = X1 | X2
  873 
  874 The 'data instance' decl has an *occurrence* of F (and T), and *binds*
  875 X1 and X2.  (This is unlike a normal data type declaration which would
  876 bind F too.)  So we want an AvailTC F [X1,X2].
  877 
  878 Now consider a similar pair:
  879   class C a where
  880     data G a
  881   instance C S where
  882     data G S = Y1 | Y2
  883 
  884 The 'data G S' *binds* Y1 and Y2, and has an *occurrence* of G.
  885 
  886 But there is a small complication: in an instance decl, we don't use
  887 qualified names on the LHS; instead we use the class to disambiguate.
  888 Thus:
  889   module M where
  890     import Blib( G )
  891     class C a where
  892       data G a
  893     instance C S where
  894       data G S = Y1 | Y2
  895 Even though there are two G's in scope (M.G and Blib.G), the occurrence
  896 of 'G' in the 'instance C S' decl is unambiguous, because C has only
  897 one associated type called G. This is exactly what happens for methods,
  898 and it is only consistent to do the same thing for types. That's the
  899 role of the function lookupTcdName; the (Maybe Name) give the class of
  900 the encloseing instance decl, if any.
  901 
  902 Note [Looking up Exact RdrNames]
  903 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  904 Exact RdrNames are generated by:
  905 
  906 * Template Haskell (See Note [Binders in Template Haskell] in GHC.ThToHs)
  907 * Derived instances (See Note [Auxiliary binders] in GHC.Tc.Deriv.Generate)
  908 
  909 For data types and classes have Exact system Names in the binding
  910 positions for constructors, TyCons etc.  For example
  911     [d| data T = MkT Int |]
  912 when we splice in and convert to HsSyn RdrName, we'll get
  913     data (Exact (system Name "T")) = (Exact (system Name "MkT")) ...
  914 These System names are generated by GHC.ThToHs.thRdrName
  915 
  916 But, constructors and the like need External Names, not System Names!
  917 So we do the following
  918 
  919  * In GHC.Rename.Env.newTopSrcBinder we spot Exact RdrNames that wrap a
  920    non-External Name, and make an External name for it. This is
  921    the name that goes in the GlobalRdrEnv
  922 
  923  * When looking up an occurrence of an Exact name, done in
  924    GHC.Rename.Env.lookupExactOcc, we find the Name with the right unique in the
  925    GlobalRdrEnv, and use the one from the envt -- it will be an
  926    External Name in the case of the data type/constructor above.
  927 
  928  * Exact names are also use for purely local binders generated
  929    by TH, such as    \x_33. x_33
  930    Both binder and occurrence are Exact RdrNames.  The occurrence
  931    gets looked up in the LocalRdrEnv by GHC.Rename.Env.lookupOccRn, and
  932    misses, because lookupLocalRdrEnv always returns Nothing for
  933    an Exact Name.  Now we fall through to lookupExactOcc, which
  934    will find the Name is not in the GlobalRdrEnv, so we just use
  935    the Exact supplied Name.
  936 
  937 Note [Splicing Exact names]
  938 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  939 Consider the splice $(do { x <- newName "x"; return (VarE x) })
  940 This will generate a (HsExpr RdrName) term that mentions the
  941 Exact RdrName "x_56" (or whatever), but does not bind it.  So
  942 when looking such Exact names we want to check that it's in scope,
  943 otherwise the type checker will get confused.  To do this we need to
  944 keep track of all the Names in scope, and the LocalRdrEnv does just that;
  945 we consult it with RdrName.inLocalRdrEnvScope.
  946 
  947 There is another wrinkle.  With TH and -XDataKinds, consider
  948    $( [d| data Nat = Zero
  949           data T = MkT (Proxy 'Zero)  |] )
  950 After splicing, but before renaming we get this:
  951    data Nat_77{tc} = Zero_78{d}
  952    data T_79{tc} = MkT_80{d} (Proxy 'Zero_78{tc})  |] )
  953 The occurrence of 'Zero in the data type for T has the right unique,
  954 but it has a TcClsName name-space in its OccName.  (This is set by
  955 the ctxt_ns argument of Convert.thRdrName.)  When we check that is
  956 in scope in the GlobalRdrEnv, we need to look up the DataName namespace
  957 too.  (An alternative would be to make the GlobalRdrEnv also have
  958 a Name -> GRE mapping.)
  959 
  960 Note [Template Haskell ambiguity]
  961 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  962 The GlobalRdrEnv invariant says that if
  963   occ -> [gre1, ..., gren]
  964 then the gres have distinct Names (INVARIANT 1 of GlobalRdrEnv).
  965 This is guaranteed by extendGlobalRdrEnvRn (the dups check in add_gre).
  966 
  967 So how can we get multiple gres in lookupExactOcc_maybe?  Because in
  968 TH we might use the same TH NameU in two different name spaces.
  969 eg (#7241):
  970    $(newName "Foo" >>= \o -> return [DataD [] o [] [RecC o []] [''Show]])
  971 Here we generate a type constructor and data constructor with the same
  972 unique, but different name spaces.
  973 
  974 It'd be nicer to rule this out in extendGlobalRdrEnvRn, but that would
  975 mean looking up the OccName in every name-space, just in case, and that
  976 seems a bit brutal.  So it's just done here on lookup.  But we might
  977 need to revisit that choice.
  978 
  979 Note [Usage for sub-bndrs]
  980 ~~~~~~~~~~~~~~~~~~~~~~~~~~
  981 If you have this
  982    import qualified M( C( f ) )
  983    instance M.C T where
  984      f x = x
  985 then is the qualified import M.f used?  Obviously yes.
  986 But the RdrName used in the instance decl is unqualified.  In effect,
  987 we fill in the qualification by looking for f's whose class is M.C
  988 But when adding to the UsedRdrNames we must make that qualification
  989 explicit (saying "used  M.f"), otherwise we get "Redundant import of M.f".
  990 
  991 So we make up a suitable (fake) RdrName.  But be careful
  992    import qualified M
  993    import M( C(f) )
  994    instance C T where
  995      f x = x
  996 Here we want to record a use of 'f', not of 'M.f', otherwise
  997 we'll miss the fact that the qualified import is redundant.
  998 
  999 --------------------------------------------------
 1000 --              Occurrences
 1001 --------------------------------------------------
 1002 -}
 1003 
 1004 
 1005 lookupLocatedOccRn :: GenLocated (SrcSpanAnn' ann) RdrName
 1006                    -> TcRn (GenLocated (SrcSpanAnn' ann) Name)
 1007 lookupLocatedOccRn = wrapLocMA lookupOccRn
 1008 
 1009 lookupLocatedOccRnConstr :: GenLocated (SrcSpanAnn' ann) RdrName
 1010                          -> TcRn (GenLocated (SrcSpanAnn' ann) Name)
 1011 lookupLocatedOccRnConstr = wrapLocMA lookupOccRnConstr
 1012 
 1013 lookupLocatedOccRnRecField :: GenLocated (SrcSpanAnn' ann) RdrName
 1014                            -> TcRn (GenLocated (SrcSpanAnn' ann) Name)
 1015 lookupLocatedOccRnRecField = wrapLocMA lookupOccRnRecField
 1016 
 1017 lookupLocatedOccRnNone :: GenLocated (SrcSpanAnn' ann) RdrName
 1018                        -> TcRn (GenLocated (SrcSpanAnn' ann) Name)
 1019 lookupLocatedOccRnNone = wrapLocMA lookupOccRnNone
 1020 
 1021 lookupLocalOccRn_maybe :: RdrName -> RnM (Maybe Name)
 1022 -- Just look in the local environment
 1023 lookupLocalOccRn_maybe rdr_name
 1024   = do { local_env <- getLocalRdrEnv
 1025        ; return (lookupLocalRdrEnv local_env rdr_name) }
 1026 
 1027 lookupLocalOccThLvl_maybe :: Name -> RnM (Maybe (TopLevelFlag, ThLevel))
 1028 -- Just look in the local environment
 1029 lookupLocalOccThLvl_maybe name
 1030   = do { lcl_env <- getLclEnv
 1031        ; return (lookupNameEnv (tcl_th_bndrs lcl_env) name) }
 1032 
 1033 -- lookupOccRn' looks up an occurrence of a RdrName, and uses its argument to
 1034 -- determine what kind of suggestions should be displayed if it is not in scope
 1035 lookupOccRn' :: WhatLooking -> RdrName -> RnM Name
 1036 lookupOccRn' which_suggest rdr_name
 1037   = do { mb_name <- lookupOccRn_maybe rdr_name
 1038        ; case mb_name of
 1039            Just name -> return name
 1040            Nothing   -> reportUnboundName' which_suggest rdr_name }
 1041 
 1042 -- lookupOccRn looks up an occurrence of a RdrName and displays suggestions if
 1043 -- it is not in scope
 1044 lookupOccRn :: RdrName -> RnM Name
 1045 lookupOccRn = lookupOccRn' WL_Anything
 1046 
 1047 -- lookupOccRnConstr looks up an occurrence of a RdrName and displays
 1048 -- constructors and pattern synonyms as suggestions if it is not in scope
 1049 lookupOccRnConstr :: RdrName -> RnM Name
 1050 lookupOccRnConstr = lookupOccRn' WL_Constructor
 1051 
 1052 -- lookupOccRnRecField looks up an occurrence of a RdrName and displays
 1053 -- record fields as suggestions if it is not in scope
 1054 lookupOccRnRecField :: RdrName -> RnM Name
 1055 lookupOccRnRecField = lookupOccRn' WL_RecField
 1056 
 1057 -- lookupOccRnRecField looks up an occurrence of a RdrName and displays
 1058 -- no suggestions if it is not in scope
 1059 lookupOccRnNone :: RdrName -> RnM Name
 1060 lookupOccRnNone = lookupOccRn' WL_None
 1061 
 1062 -- Only used in one place, to rename pattern synonym binders.
 1063 -- See Note [Renaming pattern synonym variables] in GHC.Rename.Bind
 1064 lookupLocalOccRn :: RdrName -> RnM Name
 1065 lookupLocalOccRn rdr_name
 1066   = do { mb_name <- lookupLocalOccRn_maybe rdr_name
 1067        ; case mb_name of
 1068            Just name -> return name
 1069            Nothing   -> unboundName (LF WL_Anything WL_LocalOnly) rdr_name }
 1070 
 1071 -- lookupTypeOccRn looks up an optionally promoted RdrName.
 1072 -- Used for looking up type variables.
 1073 lookupTypeOccRn :: RdrName -> RnM Name
 1074 -- see Note [Demotion]
 1075 lookupTypeOccRn rdr_name
 1076   | isVarOcc (rdrNameOcc rdr_name)  -- See Note [Promoted variables in types]
 1077   = badVarInType rdr_name
 1078   | otherwise
 1079   = do { mb_name <- lookupOccRn_maybe rdr_name
 1080        ; case mb_name of
 1081              Just name -> return name
 1082              Nothing   -> lookup_demoted rdr_name }
 1083 
 1084 lookup_demoted :: RdrName -> RnM Name
 1085 lookup_demoted rdr_name
 1086   | Just demoted_rdr <- demoteRdrName rdr_name
 1087     -- Maybe it's the name of a *data* constructor
 1088   = do { data_kinds <- xoptM LangExt.DataKinds
 1089        ; star_is_type <- xoptM LangExt.StarIsType
 1090        ; let star_info = starInfo star_is_type rdr_name
 1091        ; if data_kinds
 1092             then do { mb_demoted_name <- lookupOccRn_maybe demoted_rdr
 1093                     ; case mb_demoted_name of
 1094                         Nothing -> unboundNameX looking_for rdr_name star_info
 1095                         Just demoted_name ->
 1096                           do { let msg = TcRnUnknownMessage $
 1097                                      mkPlainDiagnostic (WarningWithFlag Opt_WarnUntickedPromotedConstructors)
 1098                                                        noHints
 1099                                                        (untickedPromConstrWarn demoted_name)
 1100                              ; addDiagnostic msg
 1101                              ; return demoted_name } }
 1102             else do { -- We need to check if a data constructor of this name is
 1103                       -- in scope to give good error messages. However, we do
 1104                       -- not want to give an additional error if the data
 1105                       -- constructor happens to be out of scope! See #13947.
 1106                       mb_demoted_name <- discardErrs $
 1107                                          lookupOccRn_maybe demoted_rdr
 1108                     ; let suggestion | isJust mb_demoted_name = suggest_dk
 1109                                      | otherwise = star_info
 1110                     ; unboundNameX looking_for rdr_name suggestion } }
 1111 
 1112   | otherwise
 1113   = reportUnboundName' (lf_which looking_for) rdr_name
 1114 
 1115   where
 1116     looking_for = LF WL_Constructor WL_Anywhere
 1117     suggest_dk = text "A data constructor of that name is in scope; did you mean DataKinds?"
 1118     untickedPromConstrWarn name =
 1119       text "Unticked promoted constructor" <> colon <+> quotes (ppr name) <> dot
 1120       $$
 1121       hsep [ text "Use"
 1122            , quotes (char '\'' <> ppr name)
 1123            , text "instead of"
 1124            , quotes (ppr name) <> dot ]
 1125 
 1126 -- If the given RdrName can be promoted to the type level and its promoted variant is in scope,
 1127 -- lookup_promoted returns the corresponding type-level Name.
 1128 -- Otherwise, the function returns Nothing.
 1129 -- See Note [Promotion] below.
 1130 lookup_promoted :: RdrName -> RnM (Maybe Name)
 1131 lookup_promoted rdr_name
 1132   | Just promoted_rdr <- promoteRdrName rdr_name
 1133   = lookupOccRn_maybe promoted_rdr
 1134   | otherwise
 1135   = return Nothing
 1136 
 1137 badVarInType :: RdrName -> RnM Name
 1138 badVarInType rdr_name
 1139   = do { addErr (TcRnUnknownMessage $ mkPlainError noHints
 1140            (text "Illegal promoted term variable in a type:"
 1141                  <+> ppr rdr_name))
 1142        ; return (mkUnboundNameRdr rdr_name) }
 1143 
 1144 {- Note [Promoted variables in types]
 1145 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 1146 Consider this (#12686):
 1147    x = True
 1148    data Bad = Bad 'x
 1149 
 1150 The parser treats the quote in 'x as saying "use the term
 1151 namespace", so we'll get (Bad x{v}), with 'x' in the
 1152 VarName namespace.  If we don't test for this, the renamer
 1153 will happily rename it to the x bound at top level, and then
 1154 the typecheck falls over because it doesn't have 'x' in scope
 1155 when kind-checking.
 1156 
 1157 Note [Demotion]
 1158 ~~~~~~~~~~~~~~~
 1159 When the user writes:
 1160   data Nat = Zero | Succ Nat
 1161   foo :: f Zero -> Int
 1162 
 1163 'Zero' in the type signature of 'foo' is parsed as:
 1164   HsTyVar ("Zero", TcClsName)
 1165 
 1166 When the renamer hits this occurrence of 'Zero' it's going to realise
 1167 that it's not in scope. But because it is renaming a type, it knows
 1168 that 'Zero' might be a promoted data constructor, so it will demote
 1169 its namespace to DataName and do a second lookup.
 1170 
 1171 The final result (after the renamer) will be:
 1172   HsTyVar ("Zero", DataName)
 1173 
 1174 Note [Promotion]
 1175 ~~~~~~~~~~~~~~~
 1176 When the user mentions a type constructor or a type variable in a
 1177 term-level context, then we report that a value identifier was expected
 1178 instead of a type-level one. That makes error messages more precise.
 1179 Previously, such errors contained only the info that a given value was out of scope (#18740).
 1180 We promote the namespace of RdrName and look up after that
 1181 (see the functions promotedRdrName and lookup_promoted).
 1182 
 1183 In particular, we have the following error message
 1184   ā€¢ Illegal term-level use of the type constructor ā€˜Intā€™
 1185       imported from ā€˜Preludeā€™ (and originally defined in ā€˜GHC.Typesā€™)
 1186   ā€¢ In the first argument of ā€˜idā€™, namely ā€˜Intā€™
 1187     In the expression: id Int
 1188     In an equation for ā€˜xā€™: x = id Int
 1189 
 1190 when the user writes the following declaration
 1191 
 1192   x = id Int
 1193 -}
 1194 
 1195 lookupOccRnX_maybe :: (RdrName -> RnM (Maybe r)) -> (Name -> r) -> RdrName
 1196                    -> RnM (Maybe r)
 1197 lookupOccRnX_maybe globalLookup wrapper rdr_name
 1198   = runMaybeT . msum . map MaybeT $
 1199       [ fmap wrapper <$> lookupLocalOccRn_maybe rdr_name
 1200       , globalLookup rdr_name ]
 1201 
 1202 -- Used outside this module only by TH name reification (lookupName, lookupThName_maybe)
 1203 lookupOccRn_maybe :: RdrName -> RnM (Maybe Name)
 1204 lookupOccRn_maybe = lookupOccRnX_maybe lookupGlobalOccRn_maybe id
 1205 
 1206 -- | Look up a 'RdrName' used as a variable in an expression.
 1207 --
 1208 -- This may be a local variable, global variable, or one or more record selector
 1209 -- functions.  It will not return record fields created with the
 1210 -- @NoFieldSelectors@ extension (see Note [NoFieldSelectors]).
 1211 --
 1212 -- If the name is not in scope at the term level, but its promoted equivalent is
 1213 -- in scope at the type level, the lookup will succeed (so that the type-checker
 1214 -- can report a more informative error later).  See Note [Promotion].
 1215 --
 1216 lookupExprOccRn :: RdrName -> RnM (Maybe GreName)
 1217 lookupExprOccRn rdr_name
 1218   = do { mb_name <- lookupOccRnX_maybe global_lookup NormalGreName rdr_name
 1219        ; case mb_name of
 1220            Nothing   -> fmap @Maybe NormalGreName <$> lookup_promoted rdr_name
 1221                         -- See Note [Promotion].
 1222                         -- We try looking up the name as a
 1223                         -- type constructor or type variable, if
 1224                         -- we failed to look up the name at the term level.
 1225            p         -> return p }
 1226 
 1227   where
 1228     global_lookup :: RdrName -> RnM (Maybe GreName)
 1229     global_lookup  rdr_name =
 1230       do { mb_name <- lookupGlobalOccRn_overloaded NoDuplicateRecordFields WantNormal rdr_name
 1231          ; case mb_name of
 1232              Just (UnambiguousGre name) -> return (Just name)
 1233              Just _ -> panic "GHC.Rename.Env.global_lookup: The impossible happened!"
 1234              Nothing -> return Nothing
 1235          }
 1236 
 1237 lookupGlobalOccRn_maybe :: RdrName -> RnM (Maybe Name)
 1238 -- Looks up a RdrName occurrence in the top-level
 1239 -- environment, including using lookupQualifiedNameGHCi
 1240 -- for the GHCi case, but first tries to find an Exact or Orig name.
 1241 -- No filter function; does not report an error on failure
 1242 -- See Note [Errors in lookup functions]
 1243 -- Uses addUsedRdrName to record use and deprecations
 1244 --
 1245 -- Used directly only by getLocalNonValBinders (new_assoc).
 1246 lookupGlobalOccRn_maybe rdr_name =
 1247   lookupExactOrOrig_maybe rdr_name id (lookupGlobalOccRn_base WantNormal rdr_name)
 1248 
 1249 lookupGlobalOccRn :: RdrName -> RnM Name
 1250 -- lookupGlobalOccRn is like lookupOccRn, except that it looks in the global
 1251 -- environment.  Adds an error message if the RdrName is not in scope.
 1252 -- You usually want to use "lookupOccRn" which also looks in the local
 1253 -- environment.
 1254 --
 1255 -- Used by exports_from_avail
 1256 lookupGlobalOccRn = lookupGlobalOccRn' WantNormal
 1257 
 1258 lookupGlobalOccRn' :: FieldsOrSelectors -> RdrName -> RnM Name
 1259 lookupGlobalOccRn' fos rdr_name =
 1260   lookupExactOrOrig rdr_name id $ do
 1261     mn <- lookupGlobalOccRn_base fos rdr_name
 1262     case mn of
 1263       Just n -> return n
 1264       Nothing -> do { traceRn "lookupGlobalOccRn" (ppr rdr_name)
 1265                     ; unboundName (LF which_suggest WL_Global) rdr_name }
 1266         where which_suggest = case fos of
 1267                 WantNormal -> WL_Anything
 1268                 WantBoth   -> WL_RecField
 1269                 WantField  -> WL_RecField
 1270 
 1271 -- Looks up a RdrName occurrence in the GlobalRdrEnv and with
 1272 -- lookupQualifiedNameGHCi. Does not try to find an Exact or Orig name first.
 1273 -- lookupQualifiedNameGHCi here is used when we're in GHCi and a name like
 1274 -- 'Data.Map.elems' is typed, even if you didn't import Data.Map
 1275 lookupGlobalOccRn_base :: FieldsOrSelectors -> RdrName -> RnM (Maybe Name)
 1276 lookupGlobalOccRn_base fos rdr_name =
 1277   runMaybeT . msum . map MaybeT $
 1278     [ fmap greMangledName <$> lookupGreRn_maybe fos rdr_name
 1279     , fmap greNameMangledName <$> lookupOneQualifiedNameGHCi fos rdr_name ]
 1280                       -- This test is not expensive,
 1281                       -- and only happens for failed lookups
 1282 
 1283 lookupInfoOccRn :: RdrName -> RnM [Name]
 1284 -- lookupInfoOccRn is intended for use in GHCi's ":info" command
 1285 -- It finds all the GREs that RdrName could mean, not complaining
 1286 -- about ambiguity, but rather returning them all
 1287 -- C.f. #9881
 1288 -- lookupInfoOccRn is also used in situations where we check for
 1289 -- at least one definition of the RdrName, not complaining about
 1290 -- multiple definitions. (See #17832)
 1291 lookupInfoOccRn rdr_name =
 1292   lookupExactOrOrig rdr_name (:[]) $
 1293     do { rdr_env <- getGlobalRdrEnv
 1294        ; let ns = map greMangledName (lookupGRE_RdrName' rdr_name rdr_env)
 1295        ; qual_ns <- map greNameMangledName <$> lookupQualifiedNameGHCi WantBoth rdr_name
 1296        ; return (ns ++ (qual_ns `minusList` ns)) }
 1297 
 1298 -- | Like 'lookupOccRn_maybe', but with a more informative result if
 1299 -- the 'RdrName' happens to be a record selector:
 1300 --
 1301 --   * Nothing                 -> name not in scope (no error reported)
 1302 --   * Just (UnambiguousGre x) -> name uniquely refers to x,
 1303 --                                or there is a name clash (reported)
 1304 --   * Just AmbiguousFields    -> name refers to two or more record fields
 1305 --                                (no error reported)
 1306 --
 1307 -- See Note [ Unbound vs Ambiguous Names ].
 1308 lookupGlobalOccRn_overloaded :: DuplicateRecordFields -> FieldsOrSelectors -> RdrName
 1309                              -> RnM (Maybe AmbiguousResult)
 1310 lookupGlobalOccRn_overloaded dup_fields_ok fos rdr_name =
 1311   lookupExactOrOrig_maybe rdr_name (fmap (UnambiguousGre . NormalGreName)) $
 1312     do { res <- lookupGreRn_helper fos rdr_name
 1313        ; case res of
 1314            GreNotFound -> fmap UnambiguousGre <$> lookupOneQualifiedNameGHCi fos rdr_name
 1315            OneNameMatch gre -> return $ Just (UnambiguousGre (gre_name gre))
 1316            MultipleNames gres
 1317              | all isRecFldGRE gres
 1318              , dup_fields_ok == DuplicateRecordFields -> return $ Just AmbiguousFields
 1319              | otherwise -> do
 1320                   addNameClashErrRn rdr_name gres
 1321                   return (Just (UnambiguousGre (gre_name (NE.head gres)))) }
 1322 
 1323 
 1324 -- | Result of looking up an occurrence that might be an ambiguous field.
 1325 data AmbiguousResult
 1326     = UnambiguousGre GreName
 1327     -- ^ Occurrence picked out a single name, which may or may not belong to a
 1328     -- field (or might be unbound, if an error has been reported already, per
 1329     -- Note [ Unbound vs Ambiguous Names ]).
 1330     | AmbiguousFields
 1331     -- ^ Occurrence picked out two or more fields, and no non-fields.  For now
 1332     -- this is allowed by DuplicateRecordFields in certain circumstances, as the
 1333     -- type-checker may be able to disambiguate later.
 1334 
 1335 
 1336 {-
 1337 Note [NoFieldSelectors]
 1338 ~~~~~~~~~~~~~~~~~~~~~~~
 1339 The NoFieldSelectors extension allows record fields to be defined without
 1340 bringing the corresponding selector functions into scope.  However, such fields
 1341 may still be used in contexts such as record construction, pattern matching or
 1342 update. This requires us to distinguish contexts in which selectors are required
 1343 from those in which any field may be used.  For example:
 1344 
 1345   {-# LANGUAGE NoFieldSelectors #-}
 1346   module M (T(foo), foo) where  -- T(foo) refers to the field,
 1347                                 -- unadorned foo to the value binding
 1348     data T = MkT { foo :: Int }
 1349     foo = ()
 1350 
 1351     bar = foo -- refers to the value binding, field ignored
 1352 
 1353   module N where
 1354     import M (T(..))
 1355     baz = MkT { foo = 3 } -- refers to the field
 1356     oops = foo -- an error: the field is in scope but the value binding is not
 1357 
 1358 Each 'FieldLabel' indicates (in the 'flHasFieldSelector' field) whether the
 1359 FieldSelectors extension was enabled in the defining module.  This allows them
 1360 to be filtered out by 'filterFieldGREs'.
 1361 
 1362 Even when NoFieldSelectors is in use, we still generate selector functions
 1363 internally. For example, the expression
 1364    getField @"foo" t
 1365 or (with dot-notation)
 1366    t.foo
 1367 extracts the `foo` field of t::T, and hence needs the selector function
 1368 (see Note [HasField instances] in GHC.Tc.Instance.Class).  In order to avoid
 1369 name clashes with normal bindings reusing the names, selector names for such
 1370 fields are mangled just as for DuplicateRecordFields (see Note [FieldLabel] in
 1371 GHC.Types.FieldLabel).
 1372 
 1373 
 1374 In many of the name lookup functions in this module we pass a FieldsOrSelectors
 1375 value, indicating what we are looking for:
 1376 
 1377  * WantNormal: fields are in scope only if they have an accompanying selector
 1378    function, e.g. we are looking up a variable in an expression
 1379    (lookupExprOccRn).
 1380 
 1381  * WantBoth: any name or field will do, regardless of whether the selector
 1382    function is available, e.g. record updates (lookupRecFieldOcc_update) with
 1383    NoDisambiguateRecordFields.
 1384 
 1385  * WantField: any field will do, regardless of whether the selector function is
 1386    available, but ignoring any non-field names, e.g. record updates
 1387    (lookupRecFieldOcc_update) with DisambiguateRecordFields.
 1388 
 1389 -----------------------------------------------------------------------------------
 1390   Context                                  FieldsOrSelectors
 1391 -----------------------------------------------------------------------------------
 1392   Record construction/pattern match        WantBoth if NoDisambiguateRecordFields
 1393   e.g. MkT { foo = 3 }                     (DisambiguateRecordFields is separate)
 1394 
 1395   Record update                            WantBoth if NoDisambiguateRecordFields
 1396   e.g. e { foo = 3 }                       WantField if DisambiguateRecordFields
 1397 
 1398   :info in GHCi                            WantBoth
 1399 
 1400   Variable occurrence in expression        WantNormal
 1401   Type variable, data constructor
 1402   Pretty much everything else
 1403 -----------------------------------------------------------------------------------
 1404 -}
 1405 
 1406 -- | When looking up GREs, we may or may not want to include fields that were
 1407 -- defined in modules with @NoFieldSelectors@ enabled.  See Note
 1408 -- [NoFieldSelectors].
 1409 data FieldsOrSelectors
 1410     = WantNormal -- ^ Include normal names, and fields with selectors, but
 1411                  -- ignore fields without selectors.
 1412     | WantBoth   -- ^ Include normal names and all fields (regardless of whether
 1413                  -- they have selectors).
 1414     | WantField  -- ^ Include only fields, with or without selectors, ignoring
 1415                  -- any non-fields in scope.
 1416   deriving Eq
 1417 
 1418 filterFieldGREs :: FieldsOrSelectors -> [GlobalRdrElt] -> [GlobalRdrElt]
 1419 filterFieldGREs fos = filter (allowGreName fos . gre_name)
 1420 
 1421 allowGreName :: FieldsOrSelectors -> GreName -> Bool
 1422 allowGreName WantBoth   _                 = True
 1423 allowGreName WantNormal (FieldGreName fl) = flHasFieldSelector fl == FieldSelectors
 1424 allowGreName WantNormal (NormalGreName _) = True
 1425 allowGreName WantField  (FieldGreName  _) = True
 1426 allowGreName WantField  (NormalGreName _) = False
 1427 
 1428 
 1429 --------------------------------------------------
 1430 --      Lookup in the Global RdrEnv of the module
 1431 --------------------------------------------------
 1432 
 1433 data GreLookupResult = GreNotFound
 1434                      | OneNameMatch GlobalRdrElt
 1435                      | MultipleNames (NE.NonEmpty GlobalRdrElt)
 1436 
 1437 lookupGreRn_maybe :: FieldsOrSelectors -> RdrName -> RnM (Maybe GlobalRdrElt)
 1438 -- Look up the RdrName in the GlobalRdrEnv
 1439 --   Exactly one binding: records it as "used", return (Just gre)
 1440 --   No bindings:         return Nothing
 1441 --   Many bindings:       report "ambiguous", return an arbitrary (Just gre)
 1442 -- Uses addUsedRdrName to record use and deprecations
 1443 lookupGreRn_maybe fos rdr_name
 1444   = do
 1445       res <- lookupGreRn_helper fos rdr_name
 1446       case res of
 1447         OneNameMatch gre ->  return $ Just gre
 1448         MultipleNames gres -> do
 1449           traceRn "lookupGreRn_maybe:NameClash" (ppr gres)
 1450           addNameClashErrRn rdr_name gres
 1451           return $ Just (NE.head gres)
 1452         GreNotFound -> return Nothing
 1453 
 1454 {-
 1455 
 1456 Note [ Unbound vs Ambiguous Names ]
 1457 
 1458 lookupGreRn_maybe deals with failures in two different ways. If a name
 1459 is unbound then we return a `Nothing` but if the name is ambiguous
 1460 then we raise an error and return a dummy name.
 1461 
 1462 The reason for this is that when we call `lookupGreRn_maybe` we are
 1463 speculatively looking for whatever we are looking up. If we don't find it,
 1464 then we might have been looking for the wrong thing and can keep trying.
 1465 On the other hand, if we find a clash then there is no way to recover as
 1466 we found the thing we were looking for but can no longer resolve which
 1467 the correct one is.
 1468 
 1469 One example of this is in `lookupTypeOccRn` which first looks in the type
 1470 constructor namespace before looking in the data constructor namespace to
 1471 deal with `DataKinds`.
 1472 
 1473 There is however, as always, one exception to this scheme. If we find
 1474 an ambiguous occurrence of a record selector and DuplicateRecordFields
 1475 is enabled then we defer the selection until the typechecker.
 1476 
 1477 -}
 1478 
 1479 
 1480 
 1481 
 1482 -- Internal Function
 1483 lookupGreRn_helper :: FieldsOrSelectors -> RdrName -> RnM GreLookupResult
 1484 lookupGreRn_helper fos rdr_name
 1485   = do  { env <- getGlobalRdrEnv
 1486         ; case filterFieldGREs fos (lookupGRE_RdrName' rdr_name env) of
 1487             []    -> return GreNotFound
 1488             [gre] -> do { addUsedGRE True gre
 1489                         ; return (OneNameMatch gre) }
 1490             -- Don't record usage for ambiguous names
 1491             -- until we know which is meant
 1492             (gre:gres) -> return (MultipleNames (gre NE.:| gres)) }
 1493 
 1494 lookupGreAvailRn :: RdrName -> RnM (Name, AvailInfo)
 1495 -- Used in export lists
 1496 -- If not found or ambiguous, add error message, and fake with UnboundName
 1497 -- Uses addUsedRdrName to record use and deprecations
 1498 lookupGreAvailRn rdr_name
 1499   = do
 1500       mb_gre <- lookupGreRn_helper WantNormal rdr_name
 1501       case mb_gre of
 1502         GreNotFound ->
 1503           do
 1504             traceRn "lookupGreAvailRn" (ppr rdr_name)
 1505             name <- unboundName (LF WL_Anything WL_Global) rdr_name
 1506             return (name, avail name)
 1507         MultipleNames gres ->
 1508           do
 1509             addNameClashErrRn rdr_name gres
 1510             let unbound_name = mkUnboundNameRdr rdr_name
 1511             return (unbound_name, avail unbound_name)
 1512                         -- Returning an unbound name here prevents an error
 1513                         -- cascade
 1514         OneNameMatch gre ->
 1515           return (greMangledName gre, availFromGRE gre)
 1516 
 1517 
 1518 {-
 1519 *********************************************************
 1520 *                                                      *
 1521                 Deprecations
 1522 *                                                      *
 1523 *********************************************************
 1524 
 1525 Note [Handling of deprecations]
 1526 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 1527 * We report deprecations at each *occurrence* of the deprecated thing
 1528   (see #5867)
 1529 
 1530 * We do not report deprecations for locally-defined names. For a
 1531   start, we may be exporting a deprecated thing. Also we may use a
 1532   deprecated thing in the defn of another deprecated things.  We may
 1533   even use a deprecated thing in the defn of a non-deprecated thing,
 1534   when changing a module's interface.
 1535 
 1536 * addUsedGREs: we do not report deprecations for sub-binders:
 1537      - the ".." completion for records
 1538      - the ".." in an export item 'T(..)'
 1539      - the things exported by a module export 'module M'
 1540 -}
 1541 
 1542 addUsedDataCons :: GlobalRdrEnv -> TyCon -> RnM ()
 1543 -- Remember use of in-scope data constructors (#7969)
 1544 addUsedDataCons rdr_env tycon
 1545   = addUsedGREs [ gre
 1546                 | dc <- tyConDataCons tycon
 1547                 , Just gre <- [lookupGRE_Name rdr_env (dataConName dc)] ]
 1548 
 1549 addUsedGRE :: Bool -> GlobalRdrElt -> RnM ()
 1550 -- Called for both local and imported things
 1551 -- Add usage *and* warn if deprecated
 1552 addUsedGRE warn_if_deprec gre
 1553   = do { when warn_if_deprec (warnIfDeprecated gre)
 1554        ; unless (isLocalGRE gre) $
 1555          do { env <- getGblEnv
 1556             ; traceRn "addUsedGRE" (ppr gre)
 1557             ; updMutVar (tcg_used_gres env) (gre :) } }
 1558 
 1559 addUsedGREs :: [GlobalRdrElt] -> RnM ()
 1560 -- Record uses of any *imported* GREs
 1561 -- Used for recording used sub-bndrs
 1562 -- NB: no call to warnIfDeprecated; see Note [Handling of deprecations]
 1563 addUsedGREs gres
 1564   | null imp_gres = return ()
 1565   | otherwise     = do { env <- getGblEnv
 1566                        ; traceRn "addUsedGREs" (ppr imp_gres)
 1567                        ; updMutVar (tcg_used_gres env) (imp_gres ++) }
 1568   where
 1569     imp_gres = filterOut isLocalGRE gres
 1570 
 1571 warnIfDeprecated :: GlobalRdrElt -> RnM ()
 1572 warnIfDeprecated gre@(GRE { gre_imp = iss })
 1573   | Just imp_spec <- headMaybe iss
 1574   = do { dflags <- getDynFlags
 1575        ; this_mod <- getModule
 1576        ; when (wopt Opt_WarnWarningsDeprecations dflags &&
 1577                not (nameIsLocalOrFrom this_mod name)) $
 1578                    -- See Note [Handling of deprecations]
 1579          do { iface <- loadInterfaceForName doc name
 1580             ; case lookupImpDeprec iface gre of
 1581                 Just txt -> do
 1582                   let msg = TcRnUnknownMessage $
 1583                               mkPlainDiagnostic (WarningWithFlag Opt_WarnWarningsDeprecations)
 1584                                                 noHints
 1585                                                 (mk_msg imp_spec txt)
 1586 
 1587                   addDiagnostic msg
 1588                 Nothing  -> return () } }
 1589   | otherwise
 1590   = return ()
 1591   where
 1592     occ = greOccName gre
 1593     name = greMangledName gre
 1594     name_mod = assertPpr (isExternalName name) (ppr name) (nameModule name)
 1595     doc = text "The name" <+> quotes (ppr occ) <+> text "is mentioned explicitly"
 1596 
 1597     mk_msg imp_spec txt
 1598       = sep [ sep [ text "In the use of"
 1599                     <+> pprNonVarNameSpace (occNameSpace occ)
 1600                     <+> quotes (ppr occ)
 1601                   , parens imp_msg <> colon ]
 1602             , pprWarningTxtForMsg txt ]
 1603       where
 1604         imp_mod  = importSpecModule imp_spec
 1605         imp_msg  = text "imported from" <+> ppr imp_mod <> extra
 1606         extra | imp_mod == moduleName name_mod = Outputable.empty
 1607               | otherwise = text ", but defined in" <+> ppr name_mod
 1608 
 1609 lookupImpDeprec :: ModIface -> GlobalRdrElt -> Maybe WarningTxt
 1610 lookupImpDeprec iface gre
 1611   = mi_warn_fn (mi_final_exts iface) (greOccName gre) `mplus`  -- Bleat if the thing,
 1612     case gre_par gre of                      -- or its parent, is warn'd
 1613        ParentIs  p              -> mi_warn_fn (mi_final_exts iface) (nameOccName p)
 1614        NoParent                 -> Nothing
 1615 
 1616 {-
 1617 Note [Used names with interface not loaded]
 1618 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 1619 It's (just) possible to find a used
 1620 Name whose interface hasn't been loaded:
 1621 
 1622 a) It might be a WiredInName; in that case we may not load
 1623    its interface (although we could).
 1624 
 1625 b) It might be GHC.Real.fromRational, or GHC.Num.fromInteger
 1626    These are seen as "used" by the renamer (if -XRebindableSyntax)
 1627    is on), but the typechecker may discard their uses
 1628    if in fact the in-scope fromRational is GHC.Read.fromRational,
 1629    (see tcPat.tcOverloadedLit), and the typechecker sees that the type
 1630    is fixed, say, to GHC.Base.Float (see Inst.lookupSimpleInst).
 1631    In that obscure case it won't force the interface in.
 1632 
 1633 In both cases we simply don't permit deprecations;
 1634 this is, after all, wired-in stuff.
 1635 
 1636 
 1637 *********************************************************
 1638 *                                                      *
 1639                 GHCi support
 1640 *                                                      *
 1641 *********************************************************
 1642 
 1643 A qualified name on the command line can refer to any module at
 1644 all: we try to load the interface if we don't already have it, just
 1645 as if there was an "import qualified M" declaration for every
 1646 module.
 1647 
 1648 For example, writing `Data.List.sort` will load the interface file for
 1649 `Data.List` as if the user had written `import qualified Data.List`.
 1650 
 1651 If we fail we just return Nothing, rather than bleating
 1652 about "attempting to use module ā€˜Dā€™ (./D.hs) which is not loaded"
 1653 which is what loadSrcInterface does.
 1654 
 1655 It is enabled by default and disabled by the flag
 1656 `-fno-implicit-import-qualified`.
 1657 
 1658 Note [Safe Haskell and GHCi]
 1659 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 1660 We DON'T do this Safe Haskell as we need to check imports. We can
 1661 and should instead check the qualified import but at the moment
 1662 this requires some refactoring so leave as a TODO
 1663 
 1664 Note [DuplicateRecordFields and -fimplicit-import-qualified]
 1665 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 1666 When DuplicateRecordFields is used, a single module can export the same OccName
 1667 multiple times, for example:
 1668 
 1669   module M where
 1670     data S = MkS { foo :: Int }
 1671     data T = MkT { foo :: Int }
 1672 
 1673 Now if we refer to M.foo via -fimplicit-import-qualified, we need to report an
 1674 ambiguity error.
 1675 
 1676 -}
 1677 
 1678 
 1679 -- | Like 'lookupQualifiedNameGHCi' but returning at most one name, reporting an
 1680 -- ambiguity error if there are more than one.
 1681 lookupOneQualifiedNameGHCi :: FieldsOrSelectors -> RdrName -> RnM (Maybe GreName)
 1682 lookupOneQualifiedNameGHCi fos rdr_name = do
 1683     gnames <- lookupQualifiedNameGHCi fos rdr_name
 1684     case gnames of
 1685       []              -> return Nothing
 1686       [gname]         -> return (Just gname)
 1687       (gname:gnames') -> do addNameClashErrRn rdr_name (toGRE gname NE.:| map toGRE gnames')
 1688                             return (Just (NormalGreName (mkUnboundNameRdr rdr_name)))
 1689   where
 1690     -- Fake a GRE so we can report a sensible name clash error if
 1691     -- -fimplicit-import-qualified is used with a module that exports the same
 1692     -- field name multiple times (see
 1693     -- Note [DuplicateRecordFields and -fimplicit-import-qualified]).
 1694     toGRE gname = GRE { gre_name = gname, gre_par = NoParent, gre_lcl = False, gre_imp = unitBag is }
 1695     is = ImpSpec { is_decl = ImpDeclSpec { is_mod = mod, is_as = mod, is_qual = True, is_dloc = noSrcSpan }
 1696                  , is_item = ImpAll }
 1697     -- If -fimplicit-import-qualified succeeded, the name must be qualified.
 1698     (mod, _) = fromMaybe (pprPanic "lookupOneQualifiedNameGHCi" (ppr rdr_name)) (isQual_maybe rdr_name)
 1699 
 1700 
 1701 -- | Look up *all* the names to which the 'RdrName' may refer in GHCi (using
 1702 -- @-fimplicit-import-qualified@).  This will normally be zero or one, but may
 1703 -- be more in the presence of @DuplicateRecordFields@.
 1704 lookupQualifiedNameGHCi :: FieldsOrSelectors -> RdrName -> RnM [GreName]
 1705 lookupQualifiedNameGHCi fos rdr_name
 1706   = -- We want to behave as we would for a source file import here,
 1707     -- and respect hiddenness of modules/packages, hence loadSrcInterface.
 1708     do { dflags  <- getDynFlags
 1709        ; is_ghci <- getIsGHCi
 1710        ; go_for_it dflags is_ghci }
 1711 
 1712   where
 1713     go_for_it dflags is_ghci
 1714       | Just (mod,occ) <- isQual_maybe rdr_name
 1715       , is_ghci
 1716       , gopt Opt_ImplicitImportQualified dflags   -- Enables this GHCi behaviour
 1717       , not (safeDirectImpsReq dflags)            -- See Note [Safe Haskell and GHCi]
 1718       = do { res <- loadSrcInterface_maybe doc mod NotBoot NoPkgQual
 1719            ; case res of
 1720                 Succeeded iface
 1721                   -> return [ gname
 1722                             | avail <- mi_exports iface
 1723                             , gname <- availGreNames avail
 1724                             , occName gname == occ
 1725                             -- Include a field if it has a selector or we are looking for all fields;
 1726                             -- see Note [NoFieldSelectors].
 1727                             , allowGreName fos gname
 1728                             ]
 1729 
 1730                 _ -> -- Either we couldn't load the interface, or
 1731                      -- we could but we didn't find the name in it
 1732                      do { traceRn "lookupQualifiedNameGHCi" (ppr rdr_name)
 1733                         ; return [] } }
 1734 
 1735       | otherwise
 1736       = do { traceRn "lookupQualifiedNameGHCi: off" (ppr rdr_name)
 1737            ; return [] }
 1738 
 1739     doc = text "Need to find" <+> ppr rdr_name
 1740 
 1741 {-
 1742 Note [Looking up signature names]
 1743 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 1744 lookupSigOccRn is used for type signatures and pragmas
 1745 Is this valid?
 1746   module A
 1747         import M( f )
 1748         f :: Int -> Int
 1749         f x = x
 1750 It's clear that the 'f' in the signature must refer to A.f
 1751 The Haskell98 report does not stipulate this, but it will!
 1752 So we must treat the 'f' in the signature in the same way
 1753 as the binding occurrence of 'f', using lookupBndrRn
 1754 
 1755 However, consider this case:
 1756         import M( f )
 1757         f :: Int -> Int
 1758         g x = x
 1759 We don't want to say 'f' is out of scope; instead, we want to
 1760 return the imported 'f', so that later on the renamer will
 1761 correctly report "misplaced type sig".
 1762 
 1763 Note [Signatures for top level things]
 1764 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 1765 data HsSigCtxt = ... | TopSigCtxt NameSet | ....
 1766 
 1767 * The NameSet says what is bound in this group of bindings.
 1768   We can't use isLocalGRE from the GlobalRdrEnv, because of this:
 1769        f x = x
 1770        $( ...some TH splice... )
 1771        f :: Int -> Int
 1772   When we encounter the signature for 'f', the binding for 'f'
 1773   will be in the GlobalRdrEnv, and will be a LocalDef. Yet the
 1774   signature is mis-placed
 1775 
 1776 * For type signatures the NameSet should be the names bound by the
 1777   value bindings; for fixity declarations, the NameSet should also
 1778   include class sigs and record selectors
 1779 
 1780       infix 3 `f`          -- Yes, ok
 1781       f :: C a => a -> a   -- No, not ok
 1782       class C a where
 1783         f :: a -> a
 1784 -}
 1785 
 1786 data HsSigCtxt
 1787   = TopSigCtxt NameSet       -- At top level, binding these names
 1788                              -- See Note [Signatures for top level things]
 1789   | LocalBindCtxt NameSet    -- In a local binding, binding these names
 1790   | ClsDeclCtxt   Name       -- Class decl for this class
 1791   | InstDeclCtxt  NameSet    -- Instance decl whose user-written method
 1792                              -- bindings are for these methods
 1793   | HsBootCtxt NameSet       -- Top level of a hs-boot file, binding these names
 1794   | RoleAnnotCtxt NameSet    -- A role annotation, with the names of all types
 1795                              -- in the group
 1796 
 1797 instance Outputable HsSigCtxt where
 1798     ppr (TopSigCtxt ns) = text "TopSigCtxt" <+> ppr ns
 1799     ppr (LocalBindCtxt ns) = text "LocalBindCtxt" <+> ppr ns
 1800     ppr (ClsDeclCtxt n) = text "ClsDeclCtxt" <+> ppr n
 1801     ppr (InstDeclCtxt ns) = text "InstDeclCtxt" <+> ppr ns
 1802     ppr (HsBootCtxt ns) = text "HsBootCtxt" <+> ppr ns
 1803     ppr (RoleAnnotCtxt ns) = text "RoleAnnotCtxt" <+> ppr ns
 1804 
 1805 lookupSigOccRn :: HsSigCtxt
 1806                -> Sig GhcPs
 1807                -> LocatedA RdrName -> RnM (LocatedA Name)
 1808 lookupSigOccRn ctxt sig = lookupSigCtxtOccRn ctxt (hsSigDoc sig)
 1809 
 1810 lookupSigOccRnN :: HsSigCtxt
 1811                -> Sig GhcPs
 1812                -> LocatedN RdrName -> RnM (LocatedN Name)
 1813 lookupSigOccRnN ctxt sig = lookupSigCtxtOccRnN ctxt (hsSigDoc sig)
 1814 
 1815 
 1816 -- | Lookup a name in relation to the names in a 'HsSigCtxt'
 1817 lookupSigCtxtOccRnN :: HsSigCtxt
 1818                     -> SDoc         -- ^ description of thing we're looking up,
 1819                                    -- like "type family"
 1820                     -> LocatedN RdrName -> RnM (LocatedN Name)
 1821 lookupSigCtxtOccRnN ctxt what
 1822   = wrapLocMA $ \ rdr_name ->
 1823     do { mb_name <- lookupBindGroupOcc ctxt what rdr_name
 1824        ; case mb_name of
 1825            Left err   -> do { addErr (TcRnUnknownMessage $ mkPlainError noHints err)
 1826                             ; return (mkUnboundNameRdr rdr_name) }
 1827            Right name -> return name }
 1828 
 1829 -- | Lookup a name in relation to the names in a 'HsSigCtxt'
 1830 lookupSigCtxtOccRn :: HsSigCtxt
 1831                    -> SDoc         -- ^ description of thing we're looking up,
 1832                                    -- like "type family"
 1833                    -> LocatedA RdrName -> RnM (LocatedA Name)
 1834 lookupSigCtxtOccRn ctxt what
 1835   = wrapLocMA $ \ rdr_name ->
 1836     do { mb_name <- lookupBindGroupOcc ctxt what rdr_name
 1837        ; case mb_name of
 1838            Left err   -> do { addErr (TcRnUnknownMessage $ mkPlainError noHints err)
 1839                             ; return (mkUnboundNameRdr rdr_name) }
 1840            Right name -> return name }
 1841 
 1842 lookupBindGroupOcc :: HsSigCtxt
 1843                    -> SDoc
 1844                    -> RdrName -> RnM (Either SDoc Name)
 1845 -- Looks up the RdrName, expecting it to resolve to one of the
 1846 -- bound names passed in.  If not, return an appropriate error message
 1847 --
 1848 -- See Note [Looking up signature names]
 1849 lookupBindGroupOcc ctxt what rdr_name
 1850   | Just n <- isExact_maybe rdr_name
 1851   = lookupExactOcc_either n   -- allow for the possibility of missing Exacts;
 1852                               -- see Note [dataTcOccs and Exact Names]
 1853       -- Maybe we should check the side conditions
 1854       -- but it's a pain, and Exact things only show
 1855       -- up when you know what you are doing
 1856 
 1857   | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
 1858   = do { n' <- lookupOrig rdr_mod rdr_occ
 1859        ; return (Right n') }
 1860 
 1861   | otherwise
 1862   = case ctxt of
 1863       HsBootCtxt ns    -> lookup_top (`elemNameSet` ns)
 1864       TopSigCtxt ns    -> lookup_top (`elemNameSet` ns)
 1865       RoleAnnotCtxt ns -> lookup_top (`elemNameSet` ns)
 1866       LocalBindCtxt ns -> lookup_group ns
 1867       ClsDeclCtxt  cls -> lookup_cls_op cls
 1868       InstDeclCtxt ns  -> if uniqSetAny isUnboundName ns -- #16610
 1869                           then return (Right $ mkUnboundNameRdr rdr_name)
 1870                           else lookup_top (`elemNameSet` ns)
 1871   where
 1872     lookup_cls_op cls
 1873       = lookupSubBndrOcc True cls doc rdr_name
 1874       where
 1875         doc = text "method of class" <+> quotes (ppr cls)
 1876 
 1877     lookup_top keep_me
 1878       = do { env <- getGlobalRdrEnv
 1879            ; dflags <- getDynFlags
 1880            ; let all_gres = lookupGlobalRdrEnv env (rdrNameOcc rdr_name)
 1881                  names_in_scope = -- If rdr_name lacks a binding, only
 1882                                   -- recommend alternatives from related
 1883                                   -- namespaces. See #17593.
 1884                                   filter (\n -> nameSpacesRelated dflags WL_Anything
 1885                                                   (rdrNameSpace rdr_name)
 1886                                                   (nameNameSpace n))
 1887                                 $ map greMangledName
 1888                                 $ filter isLocalGRE
 1889                                 $ globalRdrEnvElts env
 1890                  candidates_msg = candidates names_in_scope
 1891            ; case filter (keep_me . greMangledName) all_gres of
 1892                [] | null all_gres -> bale_out_with candidates_msg
 1893                   | otherwise     -> bale_out_with local_msg
 1894                (gre:_)            -> return (Right (greMangledName gre)) }
 1895 
 1896     lookup_group bound_names  -- Look in the local envt (not top level)
 1897       = do { mname <- lookupLocalOccRn_maybe rdr_name
 1898            ; env <- getLocalRdrEnv
 1899            ; let candidates_msg = candidates $ localRdrEnvElts env
 1900            ; case mname of
 1901                Just n
 1902                  | n `elemNameSet` bound_names -> return (Right n)
 1903                  | otherwise                   -> bale_out_with local_msg
 1904                Nothing                         -> bale_out_with candidates_msg }
 1905 
 1906     bale_out_with msg
 1907         = return (Left (sep [ text "The" <+> what
 1908                                 <+> text "for" <+> quotes (ppr rdr_name)
 1909                            , nest 2 $ text "lacks an accompanying binding"]
 1910                        $$ nest 2 msg))
 1911 
 1912     local_msg = parens $ text "The"  <+> what <+> text "must be given where"
 1913                            <+> quotes (ppr rdr_name) <+> text "is declared"
 1914 
 1915     -- Identify all similar names and produce a message listing them
 1916     candidates :: [Name] -> SDoc
 1917     candidates names_in_scope
 1918       = case similar_names of
 1919           []  -> Outputable.empty
 1920           [n] -> text "Perhaps you meant" <+> pp_item n
 1921           _   -> sep [ text "Perhaps you meant one of these:"
 1922                      , nest 2 (pprWithCommas pp_item similar_names) ]
 1923       where
 1924         similar_names
 1925           = fuzzyLookup (unpackFS $ occNameFS $ rdrNameOcc rdr_name)
 1926                         $ map (\x -> ((unpackFS $ occNameFS $ nameOccName x), x))
 1927                               names_in_scope
 1928 
 1929         pp_item x = quotes (ppr x) <+> parens (pprDefinedAt x)
 1930 
 1931 
 1932 ---------------
 1933 lookupLocalTcNames :: HsSigCtxt -> SDoc -> RdrName -> RnM [(RdrName, Name)]
 1934 -- GHC extension: look up both the tycon and data con or variable.
 1935 -- Used for top-level fixity signatures and deprecations.
 1936 -- Complain if neither is in scope.
 1937 -- See Note [Fixity signature lookup]
 1938 lookupLocalTcNames ctxt what rdr_name
 1939   = do { mb_gres <- mapM lookup (dataTcOccs rdr_name)
 1940        ; let (errs, names) = partitionEithers mb_gres
 1941        ; when (null names) $
 1942           addErr (TcRnUnknownMessage $ mkPlainError noHints (head errs)) -- Bleat about one only
 1943        ; return names }
 1944   where
 1945     lookup rdr = do { this_mod <- getModule
 1946                     ; nameEither <- lookupBindGroupOcc ctxt what rdr
 1947                     ; return (guard_builtin_syntax this_mod rdr nameEither) }
 1948 
 1949     -- Guard against the built-in syntax (ex: `infixl 6 :`), see #15233
 1950     guard_builtin_syntax this_mod rdr (Right name)
 1951       | Just _ <- isBuiltInOcc_maybe (occName rdr)
 1952       , this_mod /= nameModule name
 1953       = Left (hsep [text "Illegal", what, text "of built-in syntax:", ppr rdr])
 1954       | otherwise
 1955       = Right (rdr, name)
 1956     guard_builtin_syntax _ _ (Left err) = Left err
 1957 
 1958 dataTcOccs :: RdrName -> [RdrName]
 1959 -- Return both the given name and the same name promoted to the TcClsName
 1960 -- namespace.  This is useful when we aren't sure which we are looking at.
 1961 -- See also Note [dataTcOccs and Exact Names]
 1962 dataTcOccs rdr_name
 1963   | isDataOcc occ || isVarOcc occ
 1964   = [rdr_name, rdr_name_tc]
 1965   | otherwise
 1966   = [rdr_name]
 1967   where
 1968     occ = rdrNameOcc rdr_name
 1969     rdr_name_tc =
 1970       case rdr_name of
 1971         -- The (~) type operator is always in scope, so we need a special case
 1972         -- for it here, or else  :info (~)  fails in GHCi.
 1973         -- See Note [eqTyCon (~) is built-in syntax]
 1974         Unqual occ | occNameFS occ == fsLit "~" -> eqTyCon_RDR
 1975         _ -> setRdrNameSpace rdr_name tcName
 1976 
 1977 {-
 1978 Note [dataTcOccs and Exact Names]
 1979 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 1980 Exact RdrNames can occur in code generated by Template Haskell, and generally
 1981 those references are, well, exact. However, the TH `Name` type isn't expressive
 1982 enough to always track the correct namespace information, so we sometimes get
 1983 the right Unique but wrong namespace. Thus, we still have to do the double-lookup
 1984 for Exact RdrNames.
 1985 
 1986 There is also an awkward situation for built-in syntax. Example in GHCi
 1987    :info []
 1988 This parses as the Exact RdrName for nilDataCon, but we also want
 1989 the list type constructor.
 1990 
 1991 Note that setRdrNameSpace on an Exact name requires the Name to be External,
 1992 which it always is for built in syntax.
 1993 -}
 1994 
 1995 
 1996 
 1997 {-
 1998 ************************************************************************
 1999 *                                                                      *
 2000                         Rebindable names
 2001         Dealing with rebindable syntax is driven by the
 2002         Opt_RebindableSyntax dynamic flag.
 2003 
 2004         In "deriving" code we don't want to use rebindable syntax
 2005         so we switch off the flag locally
 2006 
 2007 *                                                                      *
 2008 ************************************************************************
 2009 
 2010 Haskell 98 says that when you say "3" you get the "fromInteger" from the
 2011 Standard Prelude, regardless of what is in scope.   However, to experiment
 2012 with having a language that is less coupled to the standard prelude, we're
 2013 trying a non-standard extension that instead gives you whatever "Prelude.fromInteger"
 2014 happens to be in scope.  Then you can
 2015         import Prelude ()
 2016         import MyPrelude as Prelude
 2017 to get the desired effect.
 2018 
 2019 At the moment this just happens for
 2020   * fromInteger, fromRational on literals (in expressions and patterns)
 2021   * negate (in expressions)
 2022   * minus  (arising from n+k patterns)
 2023   * "do" notation
 2024 
 2025 We store the relevant Name in the HsSyn tree, in
 2026   * HsIntegral/HsFractional/HsIsString
 2027   * NegApp
 2028   * NPlusKPat
 2029   * HsDo
 2030 respectively.  Initially, we just store the "standard" name (GHC.Builtin.Names.fromIntegralName,
 2031 fromRationalName etc), but the renamer changes this to the appropriate user
 2032 name if Opt_NoImplicitPrelude is on.  That is what lookupSyntax does.
 2033 
 2034 We treat the original (standard) names as free-vars too, because the type checker
 2035 checks the type of the user thing against the type of the standard thing.
 2036 -}
 2037 
 2038 lookupIfThenElse :: RnM (Maybe Name)
 2039 -- Looks up "ifThenElse" if rebindable syntax is on
 2040 lookupIfThenElse
 2041   = do { rebindable_on <- xoptM LangExt.RebindableSyntax
 2042        ; if not rebindable_on
 2043          then return Nothing
 2044          else do { ite <- lookupOccRnNone (mkVarUnqual (fsLit "ifThenElse"))
 2045                  ; return (Just ite) } }
 2046 
 2047 lookupSyntaxName :: Name                 -- ^ The standard name
 2048                  -> RnM (Name, FreeVars) -- ^ Possibly a non-standard name
 2049 -- Lookup a Name that may be subject to Rebindable Syntax (RS).
 2050 --
 2051 -- - When RS is off, just return the supplied (standard) Name
 2052 --
 2053 -- - When RS is on, look up the OccName of the supplied Name; return
 2054 --   what we find, or the supplied Name if there is nothing in scope
 2055 lookupSyntaxName std_name
 2056   = do { rebind <- xoptM LangExt.RebindableSyntax
 2057        ; if not rebind
 2058          then return (std_name, emptyFVs)
 2059          else do { nm <- lookupOccRnNone (mkRdrUnqual (nameOccName std_name))
 2060                  ; return (nm, unitFV nm) } }
 2061 
 2062 lookupSyntaxExpr :: Name                          -- ^ The standard name
 2063                  -> RnM (HsExpr GhcRn, FreeVars)  -- ^ Possibly a non-standard name
 2064 lookupSyntaxExpr std_name
 2065   = do { (name, fvs) <- lookupSyntaxName std_name
 2066        ; return (nl_HsVar name, fvs) }
 2067 
 2068 lookupSyntax :: Name                             -- The standard name
 2069              -> RnM (SyntaxExpr GhcRn, FreeVars) -- Possibly a non-standard
 2070                                                  -- name
 2071 lookupSyntax std_name
 2072   = do { (expr, fvs) <- lookupSyntaxExpr std_name
 2073        ; return (mkSyntaxExpr expr, fvs) }
 2074 
 2075 lookupSyntaxNames :: [Name]                         -- Standard names
 2076      -> RnM ([HsExpr GhcRn], FreeVars) -- See comments with HsExpr.ReboundNames
 2077    -- this works with CmdTop, which wants HsExprs, not SyntaxExprs
 2078 lookupSyntaxNames std_names
 2079   = do { rebindable_on <- xoptM LangExt.RebindableSyntax
 2080        ; if not rebindable_on then
 2081              return (map (HsVar noExtField . noLocA) std_names, emptyFVs)
 2082         else
 2083           do { usr_names <-
 2084                  mapM (lookupOccRnNone . mkRdrUnqual . nameOccName) std_names
 2085              ; return (map (HsVar noExtField . noLocA) usr_names, mkFVs usr_names) } }
 2086 
 2087 
 2088 {-
 2089 Note [QualifiedDo]
 2090 ~~~~~~~~~~~~~~~~~~
 2091 QualifiedDo is implemented using the same placeholders for operation names in
 2092 the AST that were devised for RebindableSyntax. Whenever the renamer checks
 2093 which names to use for do syntax, it first checks if the do block is qualified
 2094 (e.g. M.do { stmts }), in which case it searches for qualified names. If the
 2095 qualified names are not in scope, an error is produced. If the do block is not
 2096 qualified, the renamer does the usual search of the names which considers
 2097 whether RebindableSyntax is enabled or not. Dealing with QualifiedDo is driven
 2098 by the Opt_QualifiedDo dynamic flag.
 2099 -}
 2100 
 2101 -- Lookup operations for a qualified do. If the context is not a qualified
 2102 -- do, then use lookupSyntaxExpr. See Note [QualifiedDo].
 2103 lookupQualifiedDoExpr :: HsStmtContext p -> Name -> RnM (HsExpr GhcRn, FreeVars)
 2104 lookupQualifiedDoExpr ctxt std_name
 2105   = first nl_HsVar <$> lookupQualifiedDoName ctxt std_name
 2106 
 2107 -- Like lookupQualifiedDoExpr but for producing SyntaxExpr.
 2108 -- See Note [QualifiedDo].
 2109 lookupQualifiedDo
 2110   :: HsStmtContext p
 2111   -> Name
 2112   -> RnM (SyntaxExpr GhcRn, FreeVars)
 2113 lookupQualifiedDo ctxt std_name
 2114   = first mkSyntaxExpr <$> lookupQualifiedDoExpr ctxt std_name
 2115 
 2116 lookupNameWithQualifier :: Name -> ModuleName -> RnM (Name, FreeVars)
 2117 lookupNameWithQualifier std_name modName
 2118   = do { qname <- lookupOccRnNone (mkRdrQual modName (nameOccName std_name))
 2119        ; return (qname, unitFV qname) }
 2120 
 2121 -- See Note [QualifiedDo].
 2122 lookupQualifiedDoName
 2123   :: HsStmtContext p
 2124   -> Name
 2125   -> RnM (Name, FreeVars)
 2126 lookupQualifiedDoName ctxt std_name
 2127   = case qualifiedDoModuleName_maybe ctxt of
 2128       Nothing -> lookupSyntaxName std_name
 2129       Just modName -> lookupNameWithQualifier std_name modName
 2130 
 2131 
 2132 -- Error messages
 2133 
 2134 opDeclErr :: RdrName -> TcRnMessage
 2135 opDeclErr n
 2136   = TcRnUnknownMessage $ mkPlainError noHints $
 2137     hang (text "Illegal declaration of a type or class operator" <+> quotes (ppr n))
 2138        2 (text "Use TypeOperators to declare operators in type and declarations")
 2139 
 2140 badOrigBinding :: RdrName -> TcRnMessage
 2141 badOrigBinding name
 2142   | Just _ <- isBuiltInOcc_maybe occ
 2143   = TcRnUnknownMessage $ mkPlainError noHints $ text "Illegal binding of built-in syntax:" <+> ppr occ
 2144     -- Use an OccName here because we don't want to print Prelude.(,)
 2145   | otherwise
 2146   = TcRnUnknownMessage $ mkPlainError noHints $
 2147     text "Cannot redefine a Name retrieved by a Template Haskell quote:" <+> ppr name
 2148     -- This can happen when one tries to use a Template Haskell splice to
 2149     -- define a top-level identifier with an already existing name, e.g.,
 2150     --
 2151     --   $(pure [ValD (VarP 'succ) (NormalB (ConE 'True)) []])
 2152     --
 2153     -- (See #13968.)
 2154   where
 2155     occ = rdrNameOcc $ filterCTuple name