never executed always true always false
    1 
    2 {-# LANGUAGE DerivingStrategies         #-}
    3 {-# LANGUAGE ExistentialQuantification  #-}
    4 {-# LANGUAGE GADTs                      #-}
    5 {-# LANGUAGE GeneralizedNewtypeDeriving #-}
    6 {-# LANGUAGE PatternSynonyms            #-}
    7 
    8 {-
    9 (c) The University of Glasgow 2006-2012
   10 (c) The GRASP Project, Glasgow University, 1992-2002
   11 
   12 -}
   13 
   14 -- | Various types used during typechecking.
   15 --
   16 -- Please see "GHC.Tc.Utils.Monad" as well for operations on these types. You probably
   17 -- want to import it, instead of this module.
   18 --
   19 -- All the monads exported here are built on top of the same IOEnv monad. The
   20 -- monad functions like a Reader monad in the way it passes the environment
   21 -- around. This is done to allow the environment to be manipulated in a stack
   22 -- like fashion when entering expressions... etc.
   23 --
   24 -- For state that is global and should be returned at the end (e.g not part
   25 -- of the stack mechanism), you should use a TcRef (= IORef) to store them.
   26 module GHC.Tc.Types(
   27         TcRnIf, TcRn, TcM, RnM, IfM, IfL, IfG, -- The monad is opaque outside this module
   28         TcRef,
   29 
   30         -- The environment types
   31         Env(..),
   32         TcGblEnv(..), TcLclEnv(..),
   33         setLclEnvTcLevel, getLclEnvTcLevel,
   34         setLclEnvLoc, getLclEnvLoc,
   35         IfGblEnv(..), IfLclEnv(..),
   36         tcVisibleOrphanMods,
   37         RewriteEnv(..),
   38 
   39         -- Frontend types (shouldn't really be here)
   40         FrontendResult(..),
   41 
   42         -- Renamer types
   43         ErrCtxt, RecFieldEnv, pushErrCtxt, pushErrCtxtSameOrigin,
   44         ImportAvails(..), emptyImportAvails, plusImportAvails,
   45         WhereFrom(..), mkModDeps,
   46 
   47         -- Typechecker types
   48         TcTypeEnv, TcBinderStack, TcBinder(..),
   49         TcTyThing(..), PromotionErr(..),
   50         IdBindingInfo(..), ClosedTypeId, RhsNames,
   51         IsGroupClosed(..),
   52         SelfBootInfo(..),
   53         tcTyThingCategory, pprTcTyThingCategory,
   54         peCategory, pprPECategory,
   55         CompleteMatch, CompleteMatches,
   56 
   57         -- Template Haskell
   58         ThStage(..), SpliceType(..), PendingStuff(..),
   59         topStage, topAnnStage, topSpliceStage,
   60         ThLevel, impLevel, outerLevel, thLevel,
   61         ForeignSrcLang(..), THDocs, DocLoc(..),
   62         ThBindEnv,
   63 
   64         -- Arrows
   65         ArrowCtxt(..),
   66 
   67         -- TcSigInfo
   68         TcSigFun, TcSigInfo(..), TcIdSigInfo(..),
   69         TcIdSigInst(..), TcPatSynInfo(..),
   70         isPartialSig, hasCompleteSig,
   71 
   72         -- Misc other types
   73         TcId, TcIdSet,
   74         NameShape(..),
   75         removeBindingShadowing,
   76         getPlatform,
   77 
   78         -- Constraint solver plugins
   79         TcPlugin(..),
   80         TcPluginSolveResult(TcPluginContradiction, TcPluginOk, ..),
   81         TcPluginRewriteResult(..),
   82         TcPluginSolver, TcPluginRewriter,
   83         TcPluginM(runTcPluginM), unsafeTcPluginTcM,
   84 
   85         -- Defaulting plugin
   86         DefaultingPlugin(..), DefaultingProposal(..),
   87         FillDefaulting, DefaultingPluginResult,
   88 
   89         -- Role annotations
   90         RoleAnnotEnv, emptyRoleAnnotEnv, mkRoleAnnotEnv,
   91         lookupRoleAnnot, getRoleAnnots,
   92 
   93         -- Linting
   94         lintGblEnv,
   95 
   96         -- Diagnostics
   97         TcRnMessage
   98   ) where
   99 
  100 import GHC.Prelude
  101 import GHC.Platform
  102 
  103 import GHC.Driver.Env
  104 import GHC.Driver.Session
  105 import {-# SOURCE #-} GHC.Driver.Hooks
  106 
  107 import GHC.Hs
  108 
  109 import GHC.Tc.Utils.TcType
  110 import GHC.Tc.Types.Constraint
  111 import GHC.Tc.Types.Origin
  112 import GHC.Tc.Types.Evidence
  113 import {-# SOURCE #-} GHC.Tc.Errors.Hole.FitTypes ( HoleFitPlugin )
  114 import GHC.Tc.Errors.Types
  115 
  116 import GHC.Core.Reduction ( Reduction(..) )
  117 import GHC.Core.Type
  118 import GHC.Core.TyCon  ( TyCon, tyConKind )
  119 import GHC.Core.PatSyn ( PatSyn )
  120 import GHC.Core.Lint   ( lintAxioms )
  121 import GHC.Core.UsageEnv
  122 import GHC.Core.InstEnv
  123 import GHC.Core.FamInstEnv
  124 import GHC.Core.Predicate
  125 
  126 import GHC.Types.Id         ( idType, idName )
  127 import GHC.Types.FieldLabel ( FieldLabel )
  128 import GHC.Types.Fixity.Env
  129 import GHC.Types.Annotations
  130 import GHC.Types.CompleteMatch
  131 import GHC.Types.Name.Reader
  132 import GHC.Types.Name
  133 import GHC.Types.Name.Env
  134 import GHC.Types.Name.Set
  135 import GHC.Types.Avail
  136 import GHC.Types.Var
  137 import GHC.Types.Var.Env
  138 import GHC.Types.TypeEnv
  139 import GHC.Types.TyThing
  140 import GHC.Types.SourceFile
  141 import GHC.Types.SrcLoc
  142 import GHC.Types.Var.Set
  143 import GHC.Types.Unique.FM
  144 import GHC.Types.Basic
  145 import GHC.Types.CostCentre.State
  146 import GHC.Types.HpcInfo
  147 
  148 import GHC.Data.IOEnv
  149 import GHC.Data.Bag
  150 import GHC.Data.List.SetOps
  151 
  152 import GHC.Unit
  153 import GHC.Unit.Module.Warnings
  154 import GHC.Unit.Module.Deps
  155 import GHC.Unit.Module.ModDetails
  156 
  157 import GHC.Utils.Error
  158 import GHC.Utils.Outputable
  159 import GHC.Utils.Fingerprint
  160 import GHC.Utils.Misc
  161 import GHC.Utils.Panic
  162 import GHC.Utils.Logger
  163 
  164 import GHC.Builtin.Names ( isUnboundName )
  165 
  166 import Data.Set      ( Set )
  167 import qualified Data.Set as S
  168 import Data.Map ( Map )
  169 import Data.Dynamic  ( Dynamic )
  170 import Data.Typeable ( TypeRep )
  171 import Data.Maybe    ( mapMaybe )
  172 import GHCi.Message
  173 import GHCi.RemoteTypes
  174 
  175 import qualified Language.Haskell.TH as TH
  176 import GHC.Driver.Env.KnotVars
  177 
  178 -- | A 'NameShape' is a substitution on 'Name's that can be used
  179 -- to refine the identities of a hole while we are renaming interfaces
  180 -- (see "GHC.Iface.Rename").  Specifically, a 'NameShape' for
  181 -- 'ns_module_name' @A@, defines a mapping from @{A.T}@
  182 -- (for some 'OccName' @T@) to some arbitrary other 'Name'.
  183 --
  184 -- The most intruiging thing about a 'NameShape', however, is
  185 -- how it's constructed.  A 'NameShape' is *implied* by the
  186 -- exported 'AvailInfo's of the implementor of an interface:
  187 -- if an implementor of signature @\<H>@ exports @M.T@, you implicitly
  188 -- define a substitution from @{H.T}@ to @M.T@.  So a 'NameShape'
  189 -- is computed from the list of 'AvailInfo's that are exported
  190 -- by the implementation of a module, or successively merged
  191 -- together by the export lists of signatures which are joining
  192 -- together.
  193 --
  194 -- It's not the most obvious way to go about doing this, but it
  195 -- does seem to work!
  196 --
  197 -- NB: Can't boot this and put it in NameShape because then we
  198 -- start pulling in too many DynFlags things.
  199 data NameShape = NameShape {
  200         ns_mod_name :: ModuleName,
  201         ns_exports :: [AvailInfo],
  202         ns_map :: OccEnv Name
  203     }
  204 
  205 
  206 {-
  207 ************************************************************************
  208 *                                                                      *
  209                Standard monad definition for TcRn
  210     All the combinators for the monad can be found in GHC.Tc.Utils.Monad
  211 *                                                                      *
  212 ************************************************************************
  213 
  214 The monad itself has to be defined here, because it is mentioned by ErrCtxt
  215 -}
  216 
  217 type TcRnIf a b = IOEnv (Env a b)
  218 type TcRn       = TcRnIf TcGblEnv TcLclEnv    -- Type inference
  219 type IfM lcl    = TcRnIf IfGblEnv lcl         -- Iface stuff
  220 type IfG        = IfM ()                      --    Top level
  221 type IfL        = IfM IfLclEnv                --    Nested
  222 
  223 -- TcRn is the type-checking and renaming monad: the main monad that
  224 -- most type-checking takes place in.  The global environment is
  225 -- 'TcGblEnv', which tracks all of the top-level type-checking
  226 -- information we've accumulated while checking a module, while the
  227 -- local environment is 'TcLclEnv', which tracks local information as
  228 -- we move inside expressions.
  229 
  230 -- | Historical "renaming monad" (now it's just 'TcRn').
  231 type RnM  = TcRn
  232 
  233 -- | Historical "type-checking monad" (now it's just 'TcRn').
  234 type TcM  = TcRn
  235 
  236 -- We 'stack' these envs through the Reader like monad infrastructure
  237 -- as we move into an expression (although the change is focused in
  238 -- the lcl type).
  239 data Env gbl lcl
  240   = Env {
  241         env_top  :: !HscEnv, -- Top-level stuff that never changes
  242                              -- Includes all info about imported things
  243                              -- BangPattern is to fix leak, see #15111
  244 
  245         env_um   :: !Char,   -- Mask for Uniques
  246 
  247         env_gbl  :: gbl,     -- Info about things defined at the top level
  248                              -- of the module being compiled
  249 
  250         env_lcl  :: lcl      -- Nested stuff; changes as we go into
  251     }
  252 
  253 instance ContainsDynFlags (Env gbl lcl) where
  254     extractDynFlags env = hsc_dflags (env_top env)
  255 
  256 instance ContainsHooks (Env gbl lcl) where
  257     extractHooks env = hsc_hooks (env_top env)
  258 
  259 instance ContainsLogger (Env gbl lcl) where
  260     extractLogger env = hsc_logger (env_top env)
  261 
  262 instance ContainsModule gbl => ContainsModule (Env gbl lcl) where
  263     extractModule env = extractModule (env_gbl env)
  264 
  265 {-
  266 ************************************************************************
  267 *                                                                      *
  268 *                            RewriteEnv
  269 *                     The rewriting environment
  270 *                                                                      *
  271 ************************************************************************
  272 -}
  273 
  274 -- | A 'RewriteEnv' carries the necessary context for performing rewrites
  275 -- (i.e. type family reductions and following filled-in metavariables)
  276 -- in the solver.
  277 data RewriteEnv
  278   = FE { fe_loc     :: !CtLoc
  279        -- ^ In which context are we rewriting?
  280        --
  281        -- Type-checking plugins might want to use this location information
  282        -- when emitting new Wanted constraints when rewriting type family
  283        -- applications. This ensures that such Wanted constraints will,
  284        -- when unsolved, give rise to error messages with the
  285        -- correct source location.
  286 
  287        -- Within GHC, we use this field to keep track of reduction depth.
  288        -- See Note [Rewriter CtLoc] in GHC.Tc.Solver.Rewrite.
  289        , fe_flavour :: !CtFlavour
  290        , fe_eq_rel  :: !EqRel
  291        -- ^ At what role are we rewriting?
  292        --
  293        -- See Note [Rewriter EqRels] in GHC.Tc.Solver.Rewrite
  294        }
  295 -- RewriteEnv is mostly used in @GHC.Tc.Solver.Rewrite@, but it is defined
  296 -- here so that it can also be passed to rewriting plugins.
  297 -- See the 'tcPluginRewrite' field of 'TcPlugin'.
  298 
  299 
  300 {-
  301 ************************************************************************
  302 *                                                                      *
  303                 The interface environments
  304               Used when dealing with IfaceDecls
  305 *                                                                      *
  306 ************************************************************************
  307 -}
  308 
  309 data IfGblEnv
  310   = IfGblEnv {
  311         -- Some information about where this environment came from;
  312         -- useful for debugging.
  313         if_doc :: SDoc,
  314         -- The type environment for the module being compiled,
  315         -- in case the interface refers back to it via a reference that
  316         -- was originally a hi-boot file.
  317         -- We need the module name so we can test when it's appropriate
  318         -- to look in this env.
  319         -- See Note [Tying the knot] in GHC.IfaceToCore
  320         if_rec_types :: (KnotVars (IfG TypeEnv))
  321                 -- Allows a read effect, so it can be in a mutable
  322                 -- variable; c.f. handling the external package type env
  323                 -- Nothing => interactive stuff, no loops possible
  324     }
  325 
  326 data IfLclEnv
  327   = IfLclEnv {
  328         -- The module for the current IfaceDecl
  329         -- So if we see   f = \x -> x
  330         -- it means M.f = \x -> x, where M is the if_mod
  331         -- NB: This is a semantic module, see
  332         -- Note [Identity versus semantic module]
  333         if_mod :: !Module,
  334 
  335         -- Whether or not the IfaceDecl came from a boot
  336         -- file or not; we'll use this to choose between
  337         -- NoUnfolding and BootUnfolding
  338         if_boot :: IsBootInterface,
  339 
  340         -- The field is used only for error reporting
  341         -- if (say) there's a Lint error in it
  342         if_loc :: SDoc,
  343                 -- Where the interface came from:
  344                 --      .hi file, or GHCi state, or ext core
  345                 -- plus which bit is currently being examined
  346 
  347         if_nsubst :: Maybe NameShape,
  348 
  349         -- This field is used to make sure "implicit" declarations
  350         -- (anything that cannot be exported in mi_exports) get
  351         -- wired up correctly in typecheckIfacesForMerging.  Most
  352         -- of the time it's @Nothing@.  See Note [Resolving never-exported Names]
  353         -- in GHC.IfaceToCore.
  354         if_implicits_env :: Maybe TypeEnv,
  355 
  356         if_tv_env  :: FastStringEnv TyVar,     -- Nested tyvar bindings
  357         if_id_env  :: FastStringEnv Id         -- Nested id binding
  358     }
  359 
  360 {-
  361 ************************************************************************
  362 *                                                                      *
  363                 Global typechecker environment
  364 *                                                                      *
  365 ************************************************************************
  366 -}
  367 
  368 -- | 'FrontendResult' describes the result of running the frontend of a Haskell
  369 -- module. Currently one always gets a 'FrontendTypecheck', since running the
  370 -- frontend involves typechecking a program. hs-sig merges are not handled here.
  371 --
  372 -- This data type really should be in GHC.Driver.Env, but it needs
  373 -- to have a TcGblEnv which is only defined here.
  374 data FrontendResult
  375         = FrontendTypecheck TcGblEnv
  376 
  377 -- Note [Identity versus semantic module]
  378 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  379 -- When typechecking an hsig file, it is convenient to keep track
  380 -- of two different "this module" identifiers:
  381 --
  382 --      - The IDENTITY module is simply thisPackage + the module
  383 --        name; i.e. it uniquely *identifies* the interface file
  384 --        we're compiling.  For example, p[A=<A>]:A is an
  385 --        identity module identifying the requirement named A
  386 --        from library p.
  387 --
  388 --      - The SEMANTIC module, which is the actual module that
  389 --        this signature is intended to represent (e.g. if
  390 --        we have a identity module p[A=base:Data.IORef]:A,
  391 --        then the semantic module is base:Data.IORef)
  392 --
  393 -- Which one should you use?
  394 --
  395 --      - In the desugarer and later phases of compilation,
  396 --        identity and semantic modules coincide, since we never compile
  397 --        signatures (we just generate blank object files for
  398 --        hsig files.)
  399 --
  400 --        A corrolary of this is that the following invariant holds at any point
  401 --        past desugaring,
  402 --
  403 --            if I have a Module, this_mod, in hand representing the module
  404 --            currently being compiled,
  405 --            then moduleUnit this_mod == thisPackage dflags
  406 --
  407 --      - For any code involving Names, we want semantic modules.
  408 --        See lookupIfaceTop in GHC.Iface.Env, mkIface and addFingerprints
  409 --        in GHC.Iface.{Make,Recomp}, and tcLookupGlobal in GHC.Tc.Utils.Env
  410 --
  411 --      - When reading interfaces, we want the identity module to
  412 --        identify the specific interface we want (such interfaces
  413 --        should never be loaded into the EPS).  However, if a
  414 --        hole module <A> is requested, we look for A.hi
  415 --        in the home library we are compiling.  (See GHC.Iface.Load.)
  416 --        Similarly, in GHC.Rename.Names we check for self-imports using
  417 --        identity modules, to allow signatures to import their implementor.
  418 --
  419 --      - For recompilation avoidance, you want the identity module,
  420 --        since that will actually say the specific interface you
  421 --        want to track (and recompile if it changes)
  422 
  423 -- | 'TcGblEnv' describes the top-level of the module at the
  424 -- point at which the typechecker is finished work.
  425 -- It is this structure that is handed on to the desugarer
  426 -- For state that needs to be updated during the typechecking
  427 -- phase and returned at end, use a 'TcRef' (= 'IORef').
  428 data TcGblEnv
  429   = TcGblEnv {
  430         tcg_mod     :: Module,         -- ^ Module being compiled
  431         tcg_semantic_mod :: Module,    -- ^ If a signature, the backing module
  432             -- See also Note [Identity versus semantic module]
  433         tcg_src     :: HscSource,
  434           -- ^ What kind of module (regular Haskell, hs-boot, hsig)
  435 
  436         tcg_rdr_env :: GlobalRdrEnv,   -- ^ Top level envt; used during renaming
  437         tcg_default :: Maybe [Type],
  438           -- ^ Types used for defaulting. @Nothing@ => no @default@ decl
  439 
  440         tcg_fix_env   :: FixityEnv,     -- ^ Just for things in this module
  441         tcg_field_env :: RecFieldEnv,   -- ^ Just for things in this module
  442                                         -- See Note [The interactive package] in "GHC.Runtime.Context"
  443 
  444         tcg_type_env :: TypeEnv,
  445           -- ^ Global type env for the module we are compiling now.  All
  446           -- TyCons and Classes (for this module) end up in here right away,
  447           -- along with their derived constructors, selectors.
  448           --
  449           -- (Ids defined in this module start in the local envt, though they
  450           --  move to the global envt during zonking)
  451           --
  452           -- NB: for what "things in this module" means, see
  453           -- Note [The interactive package] in "GHC.Runtime.Context"
  454 
  455         tcg_type_env_var :: KnotVars (IORef TypeEnv),
  456                 -- Used only to initialise the interface-file
  457                 -- typechecker in initIfaceTcRn, so that it can see stuff
  458                 -- bound in this module when dealing with hi-boot recursions
  459                 -- Updated at intervals (e.g. after dealing with types and classes)
  460 
  461         tcg_inst_env     :: !InstEnv,
  462           -- ^ Instance envt for all /home-package/ modules;
  463           -- Includes the dfuns in tcg_insts
  464           -- NB. BangPattern is to fix a leak, see #15111
  465         tcg_fam_inst_env :: !FamInstEnv, -- ^ Ditto for family instances
  466           -- NB. BangPattern is to fix a leak, see #15111
  467         tcg_ann_env      :: AnnEnv,     -- ^ And for annotations
  468 
  469                 -- Now a bunch of things about this module that are simply
  470                 -- accumulated, but never consulted until the end.
  471                 -- Nevertheless, it's convenient to accumulate them along
  472                 -- with the rest of the info from this module.
  473         tcg_exports :: [AvailInfo],     -- ^ What is exported
  474         tcg_imports :: ImportAvails,
  475           -- ^ Information about what was imported from where, including
  476           -- things bound in this module. Also store Safe Haskell info
  477           -- here about transitive trusted package requirements.
  478           --
  479           -- There are not many uses of this field, so you can grep for
  480           -- all them.
  481           --
  482           -- The ImportAvails records information about the following
  483           -- things:
  484           --
  485           --    1. All of the modules you directly imported (tcRnImports)
  486           --    2. The orphans (only!) of all imported modules in a GHCi
  487           --       session (runTcInteractive)
  488           --    3. The module that instantiated a signature
  489           --    4. Each of the signatures that merged in
  490           --
  491           -- It is used in the following ways:
  492           --    - imp_orphs is used to determine what orphan modules should be
  493           --      visible in the context (tcVisibleOrphanMods)
  494           --    - imp_finsts is used to determine what family instances should
  495           --      be visible (tcExtendLocalFamInstEnv)
  496           --    - To resolve the meaning of the export list of a module
  497           --      (tcRnExports)
  498           --    - imp_mods is used to compute usage info (mkIfaceTc, deSugar)
  499           --    - imp_trust_own_pkg is used for Safe Haskell in interfaces
  500           --      (mkIfaceTc, as well as in "GHC.Driver.Main")
  501           --    - To create the Dependencies field in interface (mkDependencies)
  502 
  503           -- These three fields track unused bindings and imports
  504           -- See Note [Tracking unused binding and imports]
  505         tcg_dus       :: DefUses,
  506         tcg_used_gres :: TcRef [GlobalRdrElt],
  507         tcg_keep      :: TcRef NameSet,
  508 
  509         tcg_th_used :: TcRef Bool,
  510           -- ^ @True@ \<=> Template Haskell syntax used.
  511           --
  512           -- We need this so that we can generate a dependency on the
  513           -- Template Haskell package, because the desugarer is going
  514           -- to emit loads of references to TH symbols.  The reference
  515           -- is implicit rather than explicit, so we have to zap a
  516           -- mutable variable.
  517 
  518         tcg_th_splice_used :: TcRef Bool,
  519           -- ^ @True@ \<=> A Template Haskell splice was used.
  520           --
  521           -- Splices disable recompilation avoidance (see #481)
  522 
  523         tcg_dfun_n  :: TcRef OccSet,
  524           -- ^ Allows us to choose unique DFun names.
  525 
  526         tcg_merged :: [(Module, Fingerprint)],
  527           -- ^ The requirements we merged with; we always have to recompile
  528           -- if any of these changed.
  529 
  530         -- The next fields accumulate the payload of the module
  531         -- The binds, rules and foreign-decl fields are collected
  532         -- initially in un-zonked form and are finally zonked in tcRnSrcDecls
  533 
  534         tcg_rn_exports :: Maybe [(LIE GhcRn, Avails)],
  535                 -- Nothing <=> no explicit export list
  536                 -- Is always Nothing if we don't want to retain renamed
  537                 -- exports.
  538                 -- If present contains each renamed export list item
  539                 -- together with its exported names.
  540 
  541         tcg_rn_imports :: [LImportDecl GhcRn],
  542                 -- Keep the renamed imports regardless.  They are not
  543                 -- voluminous and are needed if you want to report unused imports
  544 
  545         tcg_rn_decls :: Maybe (HsGroup GhcRn),
  546           -- ^ Renamed decls, maybe.  @Nothing@ \<=> Don't retain renamed
  547           -- decls.
  548 
  549         tcg_dependent_files :: TcRef [FilePath], -- ^ dependencies from addDependentFile
  550 
  551         tcg_th_topdecls :: TcRef [LHsDecl GhcPs],
  552         -- ^ Top-level declarations from addTopDecls
  553 
  554         tcg_th_foreign_files :: TcRef [(ForeignSrcLang, FilePath)],
  555         -- ^ Foreign files emitted from TH.
  556 
  557         tcg_th_topnames :: TcRef NameSet,
  558         -- ^ Exact names bound in top-level declarations in tcg_th_topdecls
  559 
  560         tcg_th_modfinalizers :: TcRef [(TcLclEnv, ThModFinalizers)],
  561         -- ^ Template Haskell module finalizers.
  562         --
  563         -- They can use particular local environments.
  564 
  565         tcg_th_coreplugins :: TcRef [String],
  566         -- ^ Core plugins added by Template Haskell code.
  567 
  568         tcg_th_state :: TcRef (Map TypeRep Dynamic),
  569         tcg_th_remote_state :: TcRef (Maybe (ForeignRef (IORef QState))),
  570         -- ^ Template Haskell state
  571 
  572         tcg_th_docs   :: TcRef THDocs,
  573         -- ^ Docs added in Template Haskell via @putDoc@.
  574 
  575         tcg_ev_binds  :: Bag EvBind,        -- Top-level evidence bindings
  576 
  577         -- Things defined in this module, or (in GHCi)
  578         -- in the declarations for a single GHCi command.
  579         -- For the latter, see Note [The interactive package] in
  580         -- GHC.Runtime.Context
  581         tcg_tr_module :: Maybe Id,   -- Id for $trModule :: GHC.Unit.Module
  582                                              -- for which every module has a top-level defn
  583                                              -- except in GHCi in which case we have Nothing
  584         tcg_binds     :: LHsBinds GhcTc,     -- Value bindings in this module
  585         tcg_sigs      :: NameSet,            -- ...Top-level names that *lack* a signature
  586         tcg_imp_specs :: [LTcSpecPrag],      -- ...SPECIALISE prags for imported Ids
  587         tcg_warns     :: Warnings,           -- ...Warnings and deprecations
  588         tcg_anns      :: [Annotation],       -- ...Annotations
  589         tcg_tcs       :: [TyCon],            -- ...TyCons and Classes
  590         tcg_ksigs     :: NameSet,            -- ...Top-level TyCon names that *lack* a signature
  591         tcg_insts     :: [ClsInst],          -- ...Instances
  592         tcg_fam_insts :: [FamInst],          -- ...Family instances
  593         tcg_rules     :: [LRuleDecl GhcTc],  -- ...Rules
  594         tcg_fords     :: [LForeignDecl GhcTc], -- ...Foreign import & exports
  595         tcg_patsyns   :: [PatSyn],            -- ...Pattern synonyms
  596 
  597         tcg_doc_hdr   :: Maybe LHsDocString, -- ^ Maybe Haddock header docs
  598         tcg_hpc       :: !AnyHpcUsage,       -- ^ @True@ if any part of the
  599                                              --  prog uses hpc instrumentation.
  600            -- NB. BangPattern is to fix a leak, see #15111
  601 
  602         tcg_self_boot :: SelfBootInfo,       -- ^ Whether this module has a
  603                                              -- corresponding hi-boot file
  604 
  605         tcg_main      :: Maybe Name,         -- ^ The Name of the main
  606                                              -- function, if this module is
  607                                              -- the main module.
  608 
  609         tcg_safe_infer :: TcRef Bool,
  610         -- ^ Has the typechecker inferred this module as -XSafe (Safe Haskell)?
  611         -- See Note [Safe Haskell Overlapping Instances Implementation],
  612         -- although this is used for more than just that failure case.
  613 
  614         tcg_safe_infer_reasons :: TcRef (Messages TcRnMessage),
  615         -- ^ Unreported reasons why tcg_safe_infer is False.
  616         -- INVARIANT: If this Messages is non-empty, then tcg_safe_infer is False.
  617         -- It may be that tcg_safe_infer is False but this is empty, if no reasons
  618         -- are supplied (#19714), or if those reasons have already been
  619         -- reported by GHC.Driver.Main.markUnsafeInfer
  620 
  621         tcg_tc_plugin_solvers :: [TcPluginSolver],
  622         -- ^ A list of user-defined type-checking plugins for constraint solving.
  623 
  624         tcg_tc_plugin_rewriters :: UniqFM TyCon [TcPluginRewriter],
  625         -- ^ A collection of all the user-defined type-checking plugins for rewriting
  626         -- type family applications, collated by their type family 'TyCon's.
  627 
  628         tcg_defaulting_plugins :: [FillDefaulting],
  629         -- ^ A list of user-defined plugins for type defaulting plugins.
  630 
  631         tcg_hf_plugins :: [HoleFitPlugin],
  632         -- ^ A list of user-defined plugins for hole fit suggestions.
  633 
  634         tcg_top_loc :: RealSrcSpan,
  635         -- ^ The RealSrcSpan this module came from
  636 
  637         tcg_static_wc :: TcRef WantedConstraints,
  638           -- ^ Wanted constraints of static forms.
  639         -- See Note [Constraints in static forms].
  640         tcg_complete_matches :: !CompleteMatches,
  641 
  642         -- ^ Tracking indices for cost centre annotations
  643         tcg_cc_st   :: TcRef CostCentreState,
  644 
  645         tcg_next_wrapper_num :: TcRef (ModuleEnv Int)
  646         -- ^ See Note [Generating fresh names for FFI wrappers]
  647     }
  648 
  649 -- NB: topModIdentity, not topModSemantic!
  650 -- Definition sites of orphan identities will be identity modules, not semantic
  651 -- modules.
  652 
  653 -- Note [Constraints in static forms]
  654 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  655 --
  656 -- When a static form produces constraints like
  657 --
  658 -- f :: StaticPtr (Bool -> String)
  659 -- f = static show
  660 --
  661 -- we collect them in tcg_static_wc and resolve them at the end
  662 -- of type checking. They need to be resolved separately because
  663 -- we don't want to resolve them in the context of the enclosing
  664 -- expression. Consider
  665 --
  666 -- g :: Show a => StaticPtr (a -> String)
  667 -- g = static show
  668 --
  669 -- If the @Show a0@ constraint that the body of the static form produces was
  670 -- resolved in the context of the enclosing expression, then the body of the
  671 -- static form wouldn't be closed because the Show dictionary would come from
  672 -- g's context instead of coming from the top level.
  673 
  674 tcVisibleOrphanMods :: TcGblEnv -> ModuleSet
  675 tcVisibleOrphanMods tcg_env
  676     = mkModuleSet (tcg_mod tcg_env : imp_orphs (tcg_imports tcg_env))
  677 
  678 instance ContainsModule TcGblEnv where
  679     extractModule env = tcg_semantic_mod env
  680 
  681 type RecFieldEnv = NameEnv [FieldLabel]
  682         -- Maps a constructor name *in this module*
  683         -- to the fields for that constructor.
  684         -- This is used when dealing with ".." notation in record
  685         -- construction and pattern matching.
  686         -- The FieldEnv deals *only* with constructors defined in *this*
  687         -- module.  For imported modules, we get the same info from the
  688         -- TypeEnv
  689 
  690 data SelfBootInfo
  691   = NoSelfBoot    -- No corresponding hi-boot file
  692   | SelfBoot
  693        { sb_mds :: ModDetails   -- There was a hi-boot file,
  694        , sb_tcs :: NameSet }    -- defining these TyCons,
  695 -- What is sb_tcs used for?  See Note [Extra dependencies from .hs-boot files]
  696 -- in GHC.Rename.Module
  697 
  698 
  699 {- Note [Tracking unused binding and imports]
  700 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  701 We gather three sorts of usage information
  702 
  703  * tcg_dus :: DefUses (defs/uses)
  704       Records what is defined in this module and what is used.
  705 
  706       Records *defined* Names (local, top-level)
  707           and *used*    Names (local or imported)
  708 
  709       Used (a) to report "defined but not used"
  710                (see GHC.Rename.Names.reportUnusedNames)
  711            (b) to generate version-tracking usage info in interface
  712                files (see GHC.Iface.Make.mkUsedNames)
  713    This usage info is mainly gathered by the renamer's
  714    gathering of free-variables
  715 
  716  * tcg_used_gres :: TcRef [GlobalRdrElt]
  717       Records occurrences of imported entities.
  718 
  719       Used only to report unused import declarations
  720 
  721       Records each *occurrence* an *imported* (not locally-defined) entity.
  722       The occurrence is recorded by keeping a GlobalRdrElt for it.
  723       These is not the GRE that is in the GlobalRdrEnv; rather it
  724       is recorded *after* the filtering done by pickGREs.  So it reflect
  725       /how that occurrence is in scope/.   See Note [GRE filtering] in
  726       RdrName.
  727 
  728   * tcg_keep :: TcRef NameSet
  729       Records names of the type constructors, data constructors, and Ids that
  730       are used by the constraint solver.
  731 
  732       The typechecker may use find that some imported or
  733       locally-defined things are used, even though they
  734       do not appear to be mentioned in the source code:
  735 
  736       (a) The to/from functions for generic data types
  737 
  738       (b) Top-level variables appearing free in the RHS of an
  739           orphan rule
  740 
  741       (c) Top-level variables appearing free in a TH bracket
  742           See Note [Keeping things alive for Template Haskell]
  743           in GHC.Rename.Splice
  744 
  745       (d) The data constructor of a newtype that is used
  746           to solve a Coercible instance (e.g. #10347). Example
  747               module T10347 (N, mkN) where
  748                 import Data.Coerce
  749                 newtype N a = MkN Int
  750                 mkN :: Int -> N a
  751                 mkN = coerce
  752 
  753           Then we wish to record `MkN` as used, since it is (morally)
  754           used to perform the coercion in `mkN`. To do so, the
  755           Coercible solver updates tcg_keep's TcRef whenever it
  756           encounters a use of `coerce` that crosses newtype boundaries.
  757 
  758       (e) Record fields that are used to solve HasField constraints
  759           (see Note [Unused name reporting and HasField] in GHC.Tc.Instance.Class)
  760 
  761       The tcg_keep field is used in two distinct ways:
  762 
  763       * Desugar.addExportFlagsAndRules.  Where things like (a-c) are locally
  764         defined, we should give them an Exported flag, so that the
  765         simplifier does not discard them as dead code, and so that they are
  766         exposed in the interface file (but not to export to the user).
  767 
  768       * GHC.Rename.Names.reportUnusedNames.  Where newtype data constructors
  769         like (d) are imported, we don't want to report them as unused.
  770 
  771 
  772 ************************************************************************
  773 *                                                                      *
  774                 The local typechecker environment
  775 *                                                                      *
  776 ************************************************************************
  777 
  778 Note [The Global-Env/Local-Env story]
  779 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  780 During type checking, we keep in the tcg_type_env
  781         * All types and classes
  782         * All Ids derived from types and classes (constructors, selectors)
  783 
  784 At the end of type checking, we zonk the local bindings,
  785 and as we do so we add to the tcg_type_env
  786         * Locally defined top-level Ids
  787 
  788 Why?  Because they are now Ids not TcIds.  This final GlobalEnv is
  789         a) fed back (via the knot) to typechecking the
  790            unfoldings of interface signatures
  791         b) used in the ModDetails of this module
  792 -}
  793 
  794 data TcLclEnv           -- Changes as we move inside an expression
  795                         -- Discarded after typecheck/rename; not passed on to desugarer
  796   = TcLclEnv {
  797         tcl_loc        :: RealSrcSpan,     -- Source span
  798         tcl_ctxt       :: [ErrCtxt],       -- Error context, innermost on top
  799         tcl_in_gen_code :: Bool,           -- See Note [Rebindable syntax and HsExpansion]
  800         tcl_tclvl      :: TcLevel,
  801 
  802         tcl_th_ctxt    :: ThStage,         -- Template Haskell context
  803         tcl_th_bndrs   :: ThBindEnv,       -- and binder info
  804             -- The ThBindEnv records the TH binding level of in-scope Names
  805             -- defined in this module (not imported)
  806             -- We can't put this info in the TypeEnv because it's needed
  807             -- (and extended) in the renamer, for untyed splices
  808 
  809         tcl_arrow_ctxt :: ArrowCtxt,       -- Arrow-notation context
  810 
  811         tcl_rdr :: LocalRdrEnv,         -- Local name envt
  812                 -- Maintained during renaming, of course, but also during
  813                 -- type checking, solely so that when renaming a Template-Haskell
  814                 -- splice we have the right environment for the renamer.
  815                 --
  816                 --   Does *not* include global name envt; may shadow it
  817                 --   Includes both ordinary variables and type variables;
  818                 --   they are kept distinct because tyvar have a different
  819                 --   occurrence constructor (Name.TvOcc)
  820                 -- We still need the unsullied global name env so that
  821                 --   we can look up record field names
  822 
  823         tcl_env  :: TcTypeEnv,    -- The local type environment:
  824                                   -- Ids and TyVars defined in this module
  825 
  826         tcl_usage :: TcRef UsageEnv, -- Required multiplicity of bindings is accumulated here.
  827 
  828 
  829         tcl_bndrs :: TcBinderStack,   -- Used for reporting relevant bindings,
  830                                       -- and for tidying types
  831 
  832         tcl_lie  :: TcRef WantedConstraints,    -- Place to accumulate type constraints
  833         tcl_errs :: TcRef (Messages TcRnMessage)     -- Place to accumulate diagnostics
  834     }
  835 
  836 setLclEnvTcLevel :: TcLclEnv -> TcLevel -> TcLclEnv
  837 setLclEnvTcLevel env lvl = env { tcl_tclvl = lvl }
  838 
  839 getLclEnvTcLevel :: TcLclEnv -> TcLevel
  840 getLclEnvTcLevel = tcl_tclvl
  841 
  842 setLclEnvLoc :: TcLclEnv -> RealSrcSpan -> TcLclEnv
  843 setLclEnvLoc env loc = env { tcl_loc = loc }
  844 
  845 getLclEnvLoc :: TcLclEnv -> RealSrcSpan
  846 getLclEnvLoc = tcl_loc
  847 
  848 type ErrCtxt = (Bool, TidyEnv -> TcM (TidyEnv, SDoc))
  849         -- Monadic so that we have a chance
  850         -- to deal with bound type variables just before error
  851         -- message construction
  852 
  853         -- Bool:  True <=> this is a landmark context; do not
  854         --                 discard it when trimming for display
  855 
  856 -- These are here to avoid module loops: one might expect them
  857 -- in GHC.Tc.Types.Constraint, but they refer to ErrCtxt which refers to TcM.
  858 -- Easier to just keep these definitions here, alongside TcM.
  859 pushErrCtxt :: CtOrigin -> ErrCtxt -> CtLoc -> CtLoc
  860 pushErrCtxt o err loc@(CtLoc { ctl_env = lcl })
  861   = loc { ctl_origin = o, ctl_env = lcl { tcl_ctxt = err : tcl_ctxt lcl } }
  862 
  863 pushErrCtxtSameOrigin :: ErrCtxt -> CtLoc -> CtLoc
  864 -- Just add information w/o updating the origin!
  865 pushErrCtxtSameOrigin err loc@(CtLoc { ctl_env = lcl })
  866   = loc { ctl_env = lcl { tcl_ctxt = err : tcl_ctxt lcl } }
  867 
  868 type TcTypeEnv = NameEnv TcTyThing
  869 
  870 type ThBindEnv = NameEnv (TopLevelFlag, ThLevel)
  871    -- Domain = all Ids bound in this module (ie not imported)
  872    -- The TopLevelFlag tells if the binding is syntactically top level.
  873    -- We need to know this, because the cross-stage persistence story allows
  874    -- cross-stage at arbitrary types if the Id is bound at top level.
  875    --
  876    -- Nota bene: a ThLevel of 'outerLevel' is *not* the same as being
  877    -- bound at top level!  See Note [Template Haskell levels] in GHC.Tc.Gen.Splice
  878 
  879 {- Note [Given Insts]
  880    ~~~~~~~~~~~~~~~~~~
  881 Because of GADTs, we have to pass inwards the Insts provided by type signatures
  882 and existential contexts. Consider
  883         data T a where { T1 :: b -> b -> T [b] }
  884         f :: Eq a => T a -> Bool
  885         f (T1 x y) = [x]==[y]
  886 
  887 The constructor T1 binds an existential variable 'b', and we need Eq [b].
  888 Well, we have it, because Eq a refines to Eq [b], but we can only spot that if we
  889 pass it inwards.
  890 
  891 -}
  892 
  893 -- | Type alias for 'IORef'; the convention is we'll use this for mutable
  894 -- bits of data in 'TcGblEnv' which are updated during typechecking and
  895 -- returned at the end.
  896 type TcRef a     = IORef a
  897 -- ToDo: when should I refer to it as a 'TcId' instead of an 'Id'?
  898 type TcId        = Id
  899 type TcIdSet     = IdSet
  900 
  901 ---------------------------
  902 -- The TcBinderStack
  903 ---------------------------
  904 
  905 type TcBinderStack = [TcBinder]
  906    -- This is a stack of locally-bound ids and tyvars,
  907    --   innermost on top
  908    -- Used only in error reporting (relevantBindings in TcError),
  909    --   and in tidying
  910    -- We can't use the tcl_env type environment, because it doesn't
  911    --   keep track of the nesting order
  912 
  913 data TcBinder
  914   = TcIdBndr
  915        TcId
  916        TopLevelFlag    -- Tells whether the binding is syntactically top-level
  917                        -- (The monomorphic Ids for a recursive group count
  918                        --  as not-top-level for this purpose.)
  919 
  920   | TcIdBndr_ExpType  -- Variant that allows the type to be specified as
  921                       -- an ExpType
  922        Name
  923        ExpType
  924        TopLevelFlag
  925 
  926   | TcTvBndr          -- e.g.   case x of P (y::a) -> blah
  927        Name           -- We bind the lexical name "a" to the type of y,
  928        TyVar          -- which might be an utterly different (perhaps
  929                       -- existential) tyvar
  930 
  931 instance Outputable TcBinder where
  932    ppr (TcIdBndr id top_lvl)           = ppr id <> brackets (ppr top_lvl)
  933    ppr (TcIdBndr_ExpType id _ top_lvl) = ppr id <> brackets (ppr top_lvl)
  934    ppr (TcTvBndr name tv)              = ppr name <+> ppr tv
  935 
  936 instance HasOccName TcBinder where
  937     occName (TcIdBndr id _)             = occName (idName id)
  938     occName (TcIdBndr_ExpType name _ _) = occName name
  939     occName (TcTvBndr name _)           = occName name
  940 
  941 -- fixes #12177
  942 -- Builds up a list of bindings whose OccName has not been seen before
  943 -- i.e., If    ys  = removeBindingShadowing xs
  944 -- then
  945 --  - ys is obtained from xs by deleting some elements
  946 --  - ys has no duplicate OccNames
  947 --  - The first duplicated OccName in xs is retained in ys
  948 -- Overloaded so that it can be used for both GlobalRdrElt in typed-hole
  949 -- substitutions and TcBinder when looking for relevant bindings.
  950 removeBindingShadowing :: HasOccName a => [a] -> [a]
  951 removeBindingShadowing bindings = reverse $ fst $ foldl
  952     (\(bindingAcc, seenNames) binding ->
  953     if occName binding `elemOccSet` seenNames -- if we've seen it
  954         then (bindingAcc, seenNames)              -- skip it
  955         else (binding:bindingAcc, extendOccSet seenNames (occName binding)))
  956     ([], emptyOccSet) bindings
  957 
  958 
  959 -- | Get target platform
  960 getPlatform :: TcM Platform
  961 getPlatform = targetPlatform <$> getDynFlags
  962 
  963 ---------------------------
  964 -- Template Haskell stages and levels
  965 ---------------------------
  966 
  967 data SpliceType = Typed | Untyped
  968 
  969 data ThStage    -- See Note [Template Haskell state diagram]
  970                 -- and Note [Template Haskell levels] in GHC.Tc.Gen.Splice
  971     -- Start at:   Comp
  972     -- At bracket: wrap current stage in Brack
  973     -- At splice:  currently Brack: return to previous stage
  974     --             currently Comp/Splice: compile and run
  975   = Splice SpliceType -- Inside a top-level splice
  976                       -- This code will be run *at compile time*;
  977                       --   the result replaces the splice
  978                       -- Binding level = 0
  979 
  980   | RunSplice (TcRef [ForeignRef (TH.Q ())])
  981       -- Set when running a splice, i.e. NOT when renaming or typechecking the
  982       -- Haskell code for the splice. See Note [RunSplice ThLevel].
  983       --
  984       -- Contains a list of mod finalizers collected while executing the splice.
  985       --
  986       -- 'addModFinalizer' inserts finalizers here, and from here they are taken
  987       -- to construct an @HsSpliced@ annotation for untyped splices. See Note
  988       -- [Delaying modFinalizers in untyped splices] in GHC.Rename.Splice.
  989       --
  990       -- For typed splices, the typechecker takes finalizers from here and
  991       -- inserts them in the list of finalizers in the global environment.
  992       --
  993       -- See Note [Collecting modFinalizers in typed splices] in "GHC.Tc.Gen.Splice".
  994 
  995   | Comp        -- Ordinary Haskell code
  996                 -- Binding level = 1
  997 
  998   | Brack                       -- Inside brackets
  999       ThStage                   --   Enclosing stage
 1000       PendingStuff
 1001 
 1002 data PendingStuff
 1003   = RnPendingUntyped              -- Renaming the inside of an *untyped* bracket
 1004       (TcRef [PendingRnSplice])   -- Pending splices in here
 1005 
 1006   | RnPendingTyped                -- Renaming the inside of a *typed* bracket
 1007 
 1008   | TcPending                     -- Typechecking the inside of a typed bracket
 1009       (TcRef [PendingTcSplice])   --   Accumulate pending splices here
 1010       (TcRef WantedConstraints)   --     and type constraints here
 1011       QuoteWrapper                -- A type variable and evidence variable
 1012                                   -- for the overall monad of
 1013                                   -- the bracket. Splices are checked
 1014                                   -- against this monad. The evidence
 1015                                   -- variable is used for desugaring
 1016                                   -- `lift`.
 1017 
 1018 
 1019 topStage, topAnnStage, topSpliceStage :: ThStage
 1020 topStage       = Comp
 1021 topAnnStage    = Splice Untyped
 1022 topSpliceStage = Splice Untyped
 1023 
 1024 instance Outputable ThStage where
 1025    ppr (Splice _)    = text "Splice"
 1026    ppr (RunSplice _) = text "RunSplice"
 1027    ppr Comp          = text "Comp"
 1028    ppr (Brack s _)   = text "Brack" <> parens (ppr s)
 1029 
 1030 type ThLevel = Int
 1031     -- NB: see Note [Template Haskell levels] in GHC.Tc.Gen.Splice
 1032     -- Incremented when going inside a bracket,
 1033     -- decremented when going inside a splice
 1034     -- NB: ThLevel is one greater than the 'n' in Fig 2 of the
 1035     --     original "Template meta-programming for Haskell" paper
 1036 
 1037 impLevel, outerLevel :: ThLevel
 1038 impLevel = 0    -- Imported things; they can be used inside a top level splice
 1039 outerLevel = 1  -- Things defined outside brackets
 1040 
 1041 thLevel :: ThStage -> ThLevel
 1042 thLevel (Splice _)    = 0
 1043 thLevel Comp          = 1
 1044 thLevel (Brack s _)   = thLevel s + 1
 1045 thLevel (RunSplice _) = panic "thLevel: called when running a splice"
 1046                         -- See Note [RunSplice ThLevel].
 1047 
 1048 {- Node [RunSplice ThLevel]
 1049 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 1050 The 'RunSplice' stage is set when executing a splice, and only when running a
 1051 splice. In particular it is not set when the splice is renamed or typechecked.
 1052 
 1053 'RunSplice' is needed to provide a reference where 'addModFinalizer' can insert
 1054 the finalizer (see Note [Delaying modFinalizers in untyped splices]), and
 1055 'addModFinalizer' runs when doing Q things. Therefore, It doesn't make sense to
 1056 set 'RunSplice' when renaming or typechecking the splice, where 'Splice',
 1057 'Brack' or 'Comp' are used instead.
 1058 
 1059 -}
 1060 
 1061 ---------------------------
 1062 -- Arrow-notation context
 1063 ---------------------------
 1064 
 1065 {- Note [Escaping the arrow scope]
 1066 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 1067 In arrow notation, a variable bound by a proc (or enclosed let/kappa)
 1068 is not in scope to the left of an arrow tail (-<) or the head of (|..|).
 1069 For example
 1070 
 1071         proc x -> (e1 -< e2)
 1072 
 1073 Here, x is not in scope in e1, but it is in scope in e2.  This can get
 1074 a bit complicated:
 1075 
 1076         let x = 3 in
 1077         proc y -> (proc z -> e1) -< e2
 1078 
 1079 Here, x and z are in scope in e1, but y is not.
 1080 
 1081 We implement this by
 1082 recording the environment when passing a proc (using newArrowScope),
 1083 and returning to that (using escapeArrowScope) on the left of -< and the
 1084 head of (|..|).
 1085 
 1086 All this can be dealt with by the *renamer*. But the type checker needs
 1087 to be involved too.  Example (arrowfail001)
 1088   class Foo a where foo :: a -> ()
 1089   data Bar = forall a. Foo a => Bar a
 1090   get :: Bar -> ()
 1091   get = proc x -> case x of Bar a -> foo -< a
 1092 Here the call of 'foo' gives rise to a (Foo a) constraint that should not
 1093 be captured by the pattern match on 'Bar'.  Rather it should join the
 1094 constraints from further out.  So we must capture the constraint bag
 1095 from further out in the ArrowCtxt that we push inwards.
 1096 -}
 1097 
 1098 data ArrowCtxt   -- Note [Escaping the arrow scope]
 1099   = NoArrowCtxt
 1100   | ArrowCtxt LocalRdrEnv (TcRef WantedConstraints)
 1101 
 1102 
 1103 ---------------------------
 1104 -- TcTyThing
 1105 ---------------------------
 1106 
 1107 -- | A typecheckable thing available in a local context.  Could be
 1108 -- 'AGlobal' 'TyThing', but also lexically scoped variables, etc.
 1109 -- See "GHC.Tc.Utils.Env" for how to retrieve a 'TyThing' given a 'Name'.
 1110 data TcTyThing
 1111   = AGlobal TyThing             -- Used only in the return type of a lookup
 1112 
 1113   | ATcId           -- Ids defined in this module; may not be fully zonked
 1114       { tct_id   :: TcId
 1115       , tct_info :: IdBindingInfo   -- See Note [Meaning of IdBindingInfo]
 1116       }
 1117 
 1118   | ATyVar  Name TcTyVar   -- See Note [Type variables in the type environment]
 1119 
 1120   | ATcTyCon TyCon   -- Used temporarily, during kind checking, for the
 1121                      -- tycons and clases in this recursive group
 1122                      -- The TyCon is always a TcTyCon.  Its kind
 1123                      -- can be a mono-kind or a poly-kind; in TcTyClsDcls see
 1124                      -- Note [Type checking recursive type and class declarations]
 1125 
 1126   | APromotionErr PromotionErr
 1127 
 1128 data PromotionErr
 1129   = TyConPE          -- TyCon used in a kind before we are ready
 1130                      --     data T :: T -> * where ...
 1131   | ClassPE          -- Ditto Class
 1132 
 1133   | FamDataConPE     -- Data constructor for a data family
 1134                      -- See Note [AFamDataCon: not promoting data family constructors]
 1135                      -- in GHC.Tc.Utils.Env.
 1136   | ConstrainedDataConPE PredType
 1137                      -- Data constructor with a non-equality context
 1138                      -- See Note [Don't promote data constructors with
 1139                      --           non-equality contexts] in GHC.Tc.Gen.HsType
 1140   | PatSynPE         -- Pattern synonyms
 1141                      -- See Note [Don't promote pattern synonyms] in GHC.Tc.Utils.Env
 1142 
 1143   | RecDataConPE     -- Data constructor in a recursive loop
 1144                      -- See Note [Recursion and promoting data constructors] in GHC.Tc.TyCl
 1145   | NoDataKindsTC    -- -XDataKinds not enabled (for a tycon)
 1146   | NoDataKindsDC    -- -XDataKinds not enabled (for a datacon)
 1147 
 1148 instance Outputable TcTyThing where     -- Debugging only
 1149    ppr (AGlobal g)      = ppr g
 1150    ppr elt@(ATcId {})   = text "Identifier" <>
 1151                           brackets (ppr (tct_id elt) <> dcolon
 1152                                  <> ppr (varType (tct_id elt)) <> comma
 1153                                  <+> ppr (tct_info elt))
 1154    ppr (ATyVar n tv)    = text "Type variable" <+> quotes (ppr n) <+> equals <+> ppr tv
 1155                             <+> dcolon <+> ppr (varType tv)
 1156    ppr (ATcTyCon tc)    = text "ATcTyCon" <+> ppr tc <+> dcolon <+> ppr (tyConKind tc)
 1157    ppr (APromotionErr err) = text "APromotionErr" <+> ppr err
 1158 
 1159 -- | IdBindingInfo describes how an Id is bound.
 1160 --
 1161 -- It is used for the following purposes:
 1162 -- a) for static forms in 'GHC.Tc.Gen.Expr.checkClosedInStaticForm' and
 1163 -- b) to figure out when a nested binding can be generalised,
 1164 --    in 'GHC.Tc.Gen.Bind.decideGeneralisationPlan'.
 1165 --
 1166 data IdBindingInfo -- See Note [Meaning of IdBindingInfo and ClosedTypeId]
 1167     = NotLetBound
 1168     | ClosedLet
 1169     | NonClosedLet
 1170          RhsNames        -- Used for (static e) checks only
 1171          ClosedTypeId    -- Used for generalisation checks
 1172                          -- and for (static e) checks
 1173 
 1174 -- | IsGroupClosed describes a group of mutually-recursive bindings
 1175 data IsGroupClosed
 1176   = IsGroupClosed
 1177       (NameEnv RhsNames)  -- Free var info for the RHS of each binding in the goup
 1178                           -- Used only for (static e) checks
 1179 
 1180       ClosedTypeId        -- True <=> all the free vars of the group are
 1181                           --          imported or ClosedLet or
 1182                           --          NonClosedLet with ClosedTypeId=True.
 1183                           --          In particular, no tyvars, no NotLetBound
 1184 
 1185 type RhsNames = NameSet   -- Names of variables, mentioned on the RHS of
 1186                           -- a definition, that are not Global or ClosedLet
 1187 
 1188 type ClosedTypeId = Bool
 1189   -- See Note [Meaning of IdBindingInfo and ClosedTypeId]
 1190 
 1191 {- Note [Meaning of IdBindingInfo]
 1192 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 1193 NotLetBound means that
 1194   the Id is not let-bound (e.g. it is bound in a
 1195   lambda-abstraction or in a case pattern)
 1196 
 1197 ClosedLet means that
 1198    - The Id is let-bound,
 1199    - Any free term variables are also Global or ClosedLet
 1200    - Its type has no free variables (NB: a top-level binding subject
 1201      to the MR might have free vars in its type)
 1202    These ClosedLets can definitely be floated to top level; and we
 1203    may need to do so for static forms.
 1204 
 1205    Property:   ClosedLet
 1206              is equivalent to
 1207                NonClosedLet emptyNameSet True
 1208 
 1209 (NonClosedLet (fvs::RhsNames) (cl::ClosedTypeId)) means that
 1210    - The Id is let-bound
 1211 
 1212    - The fvs::RhsNames contains the free names of the RHS,
 1213      excluding Global and ClosedLet ones.
 1214 
 1215    - For the ClosedTypeId field see Note [Bindings with closed types]
 1216 
 1217 For (static e) to be valid, we need for every 'x' free in 'e',
 1218 that x's binding is floatable to the top level.  Specifically:
 1219    * x's RhsNames must be empty
 1220    * x's type has no free variables
 1221 See Note [Grand plan for static forms] in "GHC.Iface.Tidy.StaticPtrTable".
 1222 This test is made in GHC.Tc.Gen.Expr.checkClosedInStaticForm.
 1223 Actually knowing x's RhsNames (rather than just its emptiness
 1224 or otherwise) is just so we can produce better error messages
 1225 
 1226 Note [Bindings with closed types: ClosedTypeId]
 1227 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 1228 Consider
 1229 
 1230   f x = let g ys = map not ys
 1231         in ...
 1232 
 1233 Can we generalise 'g' under the OutsideIn algorithm?  Yes,
 1234 because all g's free variables are top-level; that is they themselves
 1235 have no free type variables, and it is the type variables in the
 1236 environment that makes things tricky for OutsideIn generalisation.
 1237 
 1238 Here's the invariant:
 1239    If an Id has ClosedTypeId=True (in its IdBindingInfo), then
 1240    the Id's type is /definitely/ closed (has no free type variables).
 1241    Specifically,
 1242        a) The Id's actual type is closed (has no free tyvars)
 1243        b) Either the Id has a (closed) user-supplied type signature
 1244           or all its free variables are Global/ClosedLet
 1245              or NonClosedLet with ClosedTypeId=True.
 1246           In particular, none are NotLetBound.
 1247 
 1248 Why is (b) needed?   Consider
 1249     \x. (x :: Int, let y = x+1 in ...)
 1250 Initially x::alpha.  If we happen to typecheck the 'let' before the
 1251 (x::Int), y's type will have a free tyvar; but if the other way round
 1252 it won't.  So we treat any let-bound variable with a free
 1253 non-let-bound variable as not ClosedTypeId, regardless of what the
 1254 free vars of its type actually are.
 1255 
 1256 But if it has a signature, all is well:
 1257    \x. ...(let { y::Int; y = x+1 } in
 1258            let { v = y+2 } in ...)...
 1259 Here the signature on 'v' makes 'y' a ClosedTypeId, so we can
 1260 generalise 'v'.
 1261 
 1262 Note that:
 1263 
 1264   * A top-level binding may not have ClosedTypeId=True, if it suffers
 1265     from the MR
 1266 
 1267   * A nested binding may be closed (eg 'g' in the example we started
 1268     with). Indeed, that's the point; whether a function is defined at
 1269     top level or nested is orthogonal to the question of whether or
 1270     not it is closed.
 1271 
 1272   * A binding may be non-closed because it mentions a lexically scoped
 1273     *type variable*  Eg
 1274         f :: forall a. blah
 1275         f x = let g y = ...(y::a)...
 1276 
 1277 Under OutsideIn we are free to generalise an Id all of whose free
 1278 variables have ClosedTypeId=True (or imported).  This is an extension
 1279 compared to the JFP paper on OutsideIn, which used "top-level" as a
 1280 proxy for "closed".  (It's not a good proxy anyway -- the MR can make
 1281 a top-level binding with a free type variable.)
 1282 
 1283 Note [Type variables in the type environment]
 1284 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 1285 The type environment has a binding for each lexically-scoped
 1286 type variable that is in scope.  For example
 1287 
 1288   f :: forall a. a -> a
 1289   f x = (x :: a)
 1290 
 1291   g1 :: [a] -> a
 1292   g1 (ys :: [b]) = head ys :: b
 1293 
 1294   g2 :: [Int] -> Int
 1295   g2 (ys :: [c]) = head ys :: c
 1296 
 1297 * The forall'd variable 'a' in the signature scopes over f's RHS.
 1298 
 1299 * The pattern-bound type variable 'b' in 'g1' scopes over g1's
 1300   RHS; note that it is bound to a skolem 'a' which is not itself
 1301   lexically in scope.
 1302 
 1303 * The pattern-bound type variable 'c' in 'g2' is bound to
 1304   Int; that is, pattern-bound type variables can stand for
 1305   arbitrary types. (see
 1306     GHC proposal #128 "Allow ScopedTypeVariables to refer to types"
 1307     https://github.com/ghc-proposals/ghc-proposals/pull/128,
 1308   and the paper
 1309     "Type variables in patterns", Haskell Symposium 2018.
 1310 
 1311 
 1312 This is implemented by the constructor
 1313    ATyVar Name TcTyVar
 1314 in the type environment.
 1315 
 1316 * The Name is the name of the original, lexically scoped type
 1317   variable
 1318 
 1319 * The TcTyVar is sometimes a skolem (like in 'f'), and sometimes
 1320   a unification variable (like in 'g1', 'g2').  We never zonk the
 1321   type environment so in the latter case it always stays as a
 1322   unification variable, although that variable may be later
 1323   unified with a type (such as Int in 'g2').
 1324 -}
 1325 
 1326 instance Outputable IdBindingInfo where
 1327   ppr NotLetBound = text "NotLetBound"
 1328   ppr ClosedLet = text "TopLevelLet"
 1329   ppr (NonClosedLet fvs closed_type) =
 1330     text "TopLevelLet" <+> ppr fvs <+> ppr closed_type
 1331 
 1332 instance Outputable PromotionErr where
 1333   ppr ClassPE                     = text "ClassPE"
 1334   ppr TyConPE                     = text "TyConPE"
 1335   ppr PatSynPE                    = text "PatSynPE"
 1336   ppr FamDataConPE                = text "FamDataConPE"
 1337   ppr (ConstrainedDataConPE pred) = text "ConstrainedDataConPE"
 1338                                       <+> parens (ppr pred)
 1339   ppr RecDataConPE                = text "RecDataConPE"
 1340   ppr NoDataKindsTC               = text "NoDataKindsTC"
 1341   ppr NoDataKindsDC               = text "NoDataKindsDC"
 1342 
 1343 --------------
 1344 pprTcTyThingCategory :: TcTyThing -> SDoc
 1345 pprTcTyThingCategory = text . capitalise . tcTyThingCategory
 1346 
 1347 tcTyThingCategory :: TcTyThing -> String
 1348 tcTyThingCategory (AGlobal thing)    = tyThingCategory thing
 1349 tcTyThingCategory (ATyVar {})        = "type variable"
 1350 tcTyThingCategory (ATcId {})         = "local identifier"
 1351 tcTyThingCategory (ATcTyCon {})      = "local tycon"
 1352 tcTyThingCategory (APromotionErr pe) = peCategory pe
 1353 
 1354 --------------
 1355 pprPECategory :: PromotionErr -> SDoc
 1356 pprPECategory = text . capitalise . peCategory
 1357 
 1358 peCategory :: PromotionErr -> String
 1359 peCategory ClassPE                = "class"
 1360 peCategory TyConPE                = "type constructor"
 1361 peCategory PatSynPE               = "pattern synonym"
 1362 peCategory FamDataConPE           = "data constructor"
 1363 peCategory ConstrainedDataConPE{} = "data constructor"
 1364 peCategory RecDataConPE           = "data constructor"
 1365 peCategory NoDataKindsTC          = "type constructor"
 1366 peCategory NoDataKindsDC          = "data constructor"
 1367 
 1368 {-
 1369 ************************************************************************
 1370 *                                                                      *
 1371         Operations over ImportAvails
 1372 *                                                                      *
 1373 ************************************************************************
 1374 -}
 1375 
 1376 
 1377 mkModDeps :: Set ModuleNameWithIsBoot
 1378           -> ModuleNameEnv ModuleNameWithIsBoot
 1379 mkModDeps deps = S.foldl' add emptyUFM deps
 1380   where
 1381     add env elt = addToUFM env (gwib_mod elt) elt
 1382 
 1383 plusModDeps :: ModuleNameEnv ModuleNameWithIsBoot
 1384             -> ModuleNameEnv ModuleNameWithIsBoot
 1385             -> ModuleNameEnv ModuleNameWithIsBoot
 1386 plusModDeps = plusUFM_C plus_mod_dep
 1387   where
 1388     plus_mod_dep r1@(GWIB { gwib_mod = m1, gwib_isBoot = boot1 })
 1389                  r2@(GWIB {gwib_mod = m2, gwib_isBoot = boot2})
 1390       | assertPpr (m1 == m2) ((ppr m1 <+> ppr m2) $$ (ppr (boot1 == IsBoot) <+> ppr (boot2 == IsBoot)))
 1391         boot1 == IsBoot = r2
 1392       | otherwise = r1
 1393       -- If either side can "see" a non-hi-boot interface, use that
 1394       -- Reusing existing tuples saves 10% of allocations on test
 1395       -- perf/compiler/MultiLayerModules
 1396 
 1397 emptyImportAvails :: ImportAvails
 1398 emptyImportAvails = ImportAvails { imp_mods          = emptyModuleEnv,
 1399                                    imp_direct_dep_mods = emptyUFM,
 1400                                    imp_dep_direct_pkgs = S.empty,
 1401                                    imp_sig_mods      = [],
 1402                                    imp_trust_pkgs    = S.empty,
 1403                                    imp_trust_own_pkg = False,
 1404                                    imp_boot_mods   = emptyUFM,
 1405                                    imp_orphs         = [],
 1406                                    imp_finsts        = [] }
 1407 
 1408 -- | Union two ImportAvails
 1409 --
 1410 -- This function is a key part of Import handling, basically
 1411 -- for each import we create a separate ImportAvails structure
 1412 -- and then union them all together with this function.
 1413 plusImportAvails ::  ImportAvails ->  ImportAvails ->  ImportAvails
 1414 plusImportAvails
 1415   (ImportAvails { imp_mods = mods1,
 1416                   imp_direct_dep_mods = ddmods1,
 1417                   imp_dep_direct_pkgs = ddpkgs1,
 1418                   imp_boot_mods = srs1,
 1419                   imp_sig_mods = sig_mods1,
 1420                   imp_trust_pkgs = tpkgs1, imp_trust_own_pkg = tself1,
 1421                   imp_orphs = orphs1, imp_finsts = finsts1 })
 1422   (ImportAvails { imp_mods = mods2,
 1423                   imp_direct_dep_mods = ddmods2,
 1424                   imp_dep_direct_pkgs = ddpkgs2,
 1425                   imp_boot_mods = srcs2,
 1426                   imp_sig_mods = sig_mods2,
 1427                   imp_trust_pkgs = tpkgs2, imp_trust_own_pkg = tself2,
 1428                   imp_orphs = orphs2, imp_finsts = finsts2 })
 1429   = ImportAvails { imp_mods          = plusModuleEnv_C (++) mods1 mods2,
 1430                    imp_direct_dep_mods = ddmods1 `plusModDeps` ddmods2,
 1431                    imp_dep_direct_pkgs      = ddpkgs1 `S.union` ddpkgs2,
 1432                    imp_trust_pkgs    = tpkgs1 `S.union` tpkgs2,
 1433                    imp_trust_own_pkg = tself1 || tself2,
 1434                    imp_boot_mods   = srs1 `plusModDeps` srcs2,
 1435                    imp_sig_mods      = sig_mods1 `unionLists` sig_mods2,
 1436                    imp_orphs         = orphs1 `unionLists` orphs2,
 1437                    imp_finsts        = finsts1 `unionLists` finsts2 }
 1438 
 1439 {-
 1440 ************************************************************************
 1441 *                                                                      *
 1442 \subsection{Where from}
 1443 *                                                                      *
 1444 ************************************************************************
 1445 
 1446 The @WhereFrom@ type controls where the renamer looks for an interface file
 1447 -}
 1448 
 1449 data WhereFrom
 1450   = ImportByUser IsBootInterface        -- Ordinary user import (perhaps {-# SOURCE #-})
 1451   | ImportBySystem                      -- Non user import.
 1452   | ImportByPlugin                      -- Importing a plugin;
 1453                                         -- See Note [Care with plugin imports] in GHC.Iface.Load
 1454 
 1455 instance Outputable WhereFrom where
 1456   ppr (ImportByUser IsBoot)                = text "{- SOURCE -}"
 1457   ppr (ImportByUser NotBoot)               = empty
 1458   ppr ImportBySystem                       = text "{- SYSTEM -}"
 1459   ppr ImportByPlugin                       = text "{- PLUGIN -}"
 1460 
 1461 
 1462 {- *********************************************************************
 1463 *                                                                      *
 1464                 Type signatures
 1465 *                                                                      *
 1466 ********************************************************************* -}
 1467 
 1468 -- These data types need to be here only because
 1469 -- GHC.Tc.Solver uses them, and GHC.Tc.Solver is fairly
 1470 -- low down in the module hierarchy
 1471 
 1472 type TcSigFun  = Name -> Maybe TcSigInfo
 1473 
 1474 data TcSigInfo = TcIdSig     TcIdSigInfo
 1475                | TcPatSynSig TcPatSynInfo
 1476 
 1477 data TcIdSigInfo   -- See Note [Complete and partial type signatures]
 1478   = CompleteSig    -- A complete signature with no wildcards,
 1479                    -- so the complete polymorphic type is known.
 1480       { sig_bndr :: TcId          -- The polymorphic Id with that type
 1481 
 1482       , sig_ctxt :: UserTypeCtxt  -- In the case of type-class default methods,
 1483                                   -- the Name in the FunSigCtxt is not the same
 1484                                   -- as the TcId; the former is 'op', while the
 1485                                   -- latter is '$dmop' or some such
 1486 
 1487       , sig_loc  :: SrcSpan       -- Location of the type signature
 1488       }
 1489 
 1490   | PartialSig     -- A partial type signature (i.e. includes one or more
 1491                    -- wildcards). In this case it doesn't make sense to give
 1492                    -- the polymorphic Id, because we are going to /infer/ its
 1493                    -- type, so we can't make the polymorphic Id ab-initio
 1494       { psig_name  :: Name   -- Name of the function; used when report wildcards
 1495       , psig_hs_ty :: LHsSigWcType GhcRn  -- The original partial signature in
 1496                                           -- HsSyn form
 1497       , sig_ctxt   :: UserTypeCtxt
 1498       , sig_loc    :: SrcSpan            -- Location of the type signature
 1499       }
 1500 
 1501 
 1502 {- Note [Complete and partial type signatures]
 1503 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 1504 A type signature is partial when it contains one or more wildcards
 1505 (= type holes).  The wildcard can either be:
 1506 * A (type) wildcard occurring in sig_theta or sig_tau. These are
 1507   stored in sig_wcs.
 1508       f :: Bool -> _
 1509       g :: Eq _a => _a -> _a -> Bool
 1510 * Or an extra-constraints wildcard, stored in sig_cts:
 1511       h :: (Num a, _) => a -> a
 1512 
 1513 A type signature is a complete type signature when there are no
 1514 wildcards in the type signature, i.e. iff sig_wcs is empty and
 1515 sig_extra_cts is Nothing.
 1516 -}
 1517 
 1518 data TcIdSigInst
 1519   = TISI { sig_inst_sig :: TcIdSigInfo
 1520 
 1521          , sig_inst_skols :: [(Name, InvisTVBinder)]
 1522                -- Instantiated type and kind variables, TyVarTvs
 1523                -- The Name is the Name that the renamer chose;
 1524                --   but the TcTyVar may come from instantiating
 1525                --   the type and hence have a different unique.
 1526                -- No need to keep track of whether they are truly lexically
 1527                --   scoped because the renamer has named them uniquely
 1528                -- See Note [Binding scoped type variables] in GHC.Tc.Gen.Sig
 1529                --
 1530                -- NB: The order of sig_inst_skols is irrelevant
 1531                --     for a CompleteSig, but for a PartialSig see
 1532                --     Note [Quantified variables in partial type signatures]
 1533 
 1534          , sig_inst_theta  :: TcThetaType
 1535                -- Instantiated theta.  In the case of a
 1536                -- PartialSig, sig_theta does not include
 1537                -- the extra-constraints wildcard
 1538 
 1539          , sig_inst_tau :: TcSigmaType   -- Instantiated tau
 1540                -- See Note [sig_inst_tau may be polymorphic]
 1541 
 1542          -- Relevant for partial signature only
 1543          , sig_inst_wcs   :: [(Name, TcTyVar)]
 1544                -- Like sig_inst_skols, but for /named/ wildcards (_a etc).
 1545                -- The named wildcards scope over the binding, and hence
 1546                -- their Names may appear in type signatures in the binding
 1547 
 1548          , sig_inst_wcx   :: Maybe TcType
 1549                -- Extra-constraints wildcard to fill in, if any
 1550                -- If this exists, it is surely of the form (meta_tv |> co)
 1551                -- (where the co might be reflexive). This is filled in
 1552                -- only from the return value of GHC.Tc.Gen.HsType.tcAnonWildCardOcc
 1553          }
 1554 
 1555 {- Note [sig_inst_tau may be polymorphic]
 1556 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 1557 Note that "sig_inst_tau" might actually be a polymorphic type,
 1558 if the original function had a signature like
 1559    forall a. Eq a => forall b. Ord b => ....
 1560 But that's ok: tcMatchesFun (called by tcRhs) can deal with that
 1561 It happens, too!  See Note [Polymorphic methods] in GHC.Tc.TyCl.Class.
 1562 
 1563 Note [Quantified variables in partial type signatures]
 1564 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 1565 Consider
 1566    f :: forall a b. _ -> a -> _ -> b
 1567    f (x,y) p q = q
 1568 
 1569 Then we expect f's final type to be
 1570   f :: forall {x,y}. forall a b. (x,y) -> a -> b -> b
 1571 
 1572 Note that x,y are Inferred, and can't be use for visible type
 1573 application (VTA).  But a,b are Specified, and remain Specified
 1574 in the final type, so we can use VTA for them.  (Exception: if
 1575 it turns out that a's kind mentions b we need to reorder them
 1576 with scopedSort.)
 1577 
 1578 The sig_inst_skols of the TISI from a partial signature records
 1579 that original order, and is used to get the variables of f's
 1580 final type in the correct order.
 1581 
 1582 
 1583 Note [Wildcards in partial signatures]
 1584 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 1585 The wildcards in psig_wcs may stand for a type mentioning
 1586 the universally-quantified tyvars of psig_ty
 1587 
 1588 E.g.  f :: forall a. _ -> a
 1589       f x = x
 1590 We get sig_inst_skols = [a]
 1591        sig_inst_tau   = _22 -> a
 1592        sig_inst_wcs   = [_22]
 1593 and _22 in the end is unified with the type 'a'
 1594 
 1595 Moreover the kind of a wildcard in sig_inst_wcs may mention
 1596 the universally-quantified tyvars sig_inst_skols
 1597 e.g.   f :: t a -> t _
 1598 Here we get
 1599    sig_inst_skols = [k:*, (t::k ->*), (a::k)]
 1600    sig_inst_tau   = t a -> t _22
 1601    sig_inst_wcs   = [ _22::k ]
 1602 -}
 1603 
 1604 data TcPatSynInfo
 1605   = TPSI {
 1606         patsig_name           :: Name,
 1607         patsig_implicit_bndrs :: [InvisTVBinder], -- Implicitly-bound kind vars (Inferred) and
 1608                                                   -- implicitly-bound type vars (Specified)
 1609           -- See Note [The pattern-synonym signature splitting rule] in GHC.Tc.TyCl.PatSyn
 1610         patsig_univ_bndrs     :: [InvisTVBinder], -- Bound by explicit user forall
 1611         patsig_req            :: TcThetaType,
 1612         patsig_ex_bndrs       :: [InvisTVBinder], -- Bound by explicit user forall
 1613         patsig_prov           :: TcThetaType,
 1614         patsig_body_ty        :: TcSigmaType
 1615     }
 1616 
 1617 instance Outputable TcSigInfo where
 1618   ppr (TcIdSig     idsi) = ppr idsi
 1619   ppr (TcPatSynSig tpsi) = text "TcPatSynInfo" <+> ppr tpsi
 1620 
 1621 instance Outputable TcIdSigInfo where
 1622     ppr (CompleteSig { sig_bndr = bndr })
 1623         = ppr bndr <+> dcolon <+> ppr (idType bndr)
 1624     ppr (PartialSig { psig_name = name, psig_hs_ty = hs_ty })
 1625         = text "psig" <+> ppr name <+> dcolon <+> ppr hs_ty
 1626 
 1627 instance Outputable TcIdSigInst where
 1628     ppr (TISI { sig_inst_sig = sig, sig_inst_skols = skols
 1629               , sig_inst_theta = theta, sig_inst_tau = tau })
 1630         = hang (ppr sig) 2 (vcat [ ppr skols, ppr theta <+> darrow <+> ppr tau ])
 1631 
 1632 instance Outputable TcPatSynInfo where
 1633     ppr (TPSI{ patsig_name = name}) = ppr name
 1634 
 1635 isPartialSig :: TcIdSigInst -> Bool
 1636 isPartialSig (TISI { sig_inst_sig = PartialSig {} }) = True
 1637 isPartialSig _                                       = False
 1638 
 1639 -- | No signature or a partial signature
 1640 hasCompleteSig :: TcSigFun -> Name -> Bool
 1641 hasCompleteSig sig_fn name
 1642   = case sig_fn name of
 1643       Just (TcIdSig (CompleteSig {})) -> True
 1644       _                               -> False
 1645 
 1646 
 1647 {-
 1648 Constraint Solver Plugins
 1649 -------------------------
 1650 -}
 1651 
 1652 -- | The @solve@ function of a type-checking plugin takes in Given, Derived
 1653 -- and Wanted constraints, and should return a 'TcPluginSolveResult'
 1654 -- indicating which Wanted constraints it could solve, or whether any are
 1655 -- insoluble.
 1656 type TcPluginSolver = [Ct] -- ^ Givens
 1657                    -> [Ct] -- ^ Deriveds
 1658                    -> [Ct] -- ^ Wanteds
 1659                    -> TcPluginM TcPluginSolveResult
 1660 
 1661 -- | For rewriting type family applications, a type-checking plugin provides
 1662 -- a function of this type for each type family 'TyCon'.
 1663 --
 1664 -- The function is provided with the current set of Given constraints, together
 1665 -- with the arguments to the type family.
 1666 -- The type family application will always be fully saturated.
 1667 type TcPluginRewriter
 1668   =  RewriteEnv -- ^ Rewriter environment
 1669   -> [Ct]       -- ^ Givens
 1670   -> [TcType]   -- ^ type family arguments
 1671   -> TcPluginM TcPluginRewriteResult
 1672 
 1673 -- | 'TcPluginM' is the monad in which type-checking plugins operate.
 1674 newtype TcPluginM a = TcPluginM { runTcPluginM :: TcM a }
 1675   deriving newtype (Functor, Applicative, Monad, MonadFail)
 1676 
 1677 -- | This function provides an escape for direct access to
 1678 -- the 'TcM` monad.  It should not be used lightly, and
 1679 -- the provided 'TcPluginM' API should be favoured instead.
 1680 unsafeTcPluginTcM :: TcM a -> TcPluginM a
 1681 unsafeTcPluginTcM = TcPluginM
 1682 
 1683 data TcPlugin = forall s. TcPlugin
 1684   { tcPluginInit :: TcPluginM s
 1685     -- ^ Initialize plugin, when entering type-checker.
 1686 
 1687   , tcPluginSolve :: s -> EvBindsVar -> TcPluginSolver
 1688     -- ^ Solve some constraints.
 1689     --
 1690     -- This function will be invoked at two points in the constraint solving
 1691     -- process: once to simplify Given constraints, and once to solve
 1692     -- Wanted constraints. In the first case (and only in the first case),
 1693     -- no Wanted constraints will be passed to the plugin.
 1694     --
 1695     -- The plugin can either return a contradiction,
 1696     -- or specify that it has solved some constraints (with evidence),
 1697     -- and possibly emit additional constraints. These returned constraints
 1698     -- must be Givens in the first case, and Wanteds in the second.
 1699     --
 1700     -- Use @ \\ _ _ _ _ _ -> pure $ TcPluginOK [] [] @ if your plugin
 1701     -- does not provide this functionality.
 1702 
 1703   , tcPluginRewrite :: s -> UniqFM TyCon TcPluginRewriter
 1704     -- ^ Rewrite saturated type family applications.
 1705     --
 1706     -- The plugin is expected to supply a mapping from type family names to
 1707     -- rewriting functions. For each type family 'TyCon', the plugin should
 1708     -- provide a function which takes in the given constraints and arguments
 1709     -- of a saturated type family application, and return a possible rewriting.
 1710     -- See 'TcPluginRewriter' for the expected shape of such a function.
 1711     --
 1712     -- Use @ \\ _ -> emptyUFM @ if your plugin does not provide this functionality.
 1713 
 1714   , tcPluginStop :: s -> TcPluginM ()
 1715    -- ^ Clean up after the plugin, when exiting the type-checker.
 1716   }
 1717 
 1718 -- | The plugin found a contradiction.
 1719 -- The returned constraints are removed from the inert set,
 1720 -- and recorded as insoluble.
 1721 --
 1722 -- The returned list of constraints should never be empty.
 1723 pattern TcPluginContradiction :: [Ct] -> TcPluginSolveResult
 1724 pattern TcPluginContradiction insols
 1725   = TcPluginSolveResult
 1726   { tcPluginInsolubleCts = insols
 1727   , tcPluginSolvedCts    = []
 1728   , tcPluginNewCts       = [] }
 1729 
 1730 -- | The plugin has not found any contradictions,
 1731 --
 1732 -- The first field is for constraints that were solved.
 1733 -- The second field contains new work, that should be processed by
 1734 -- the constraint solver.
 1735 pattern TcPluginOk :: [(EvTerm, Ct)] -> [Ct] -> TcPluginSolveResult
 1736 pattern TcPluginOk solved new
 1737   = TcPluginSolveResult
 1738   { tcPluginInsolubleCts = []
 1739   , tcPluginSolvedCts    = solved
 1740   , tcPluginNewCts       = new }
 1741 
 1742 -- | Result of running a solver plugin.
 1743 data TcPluginSolveResult
 1744   = TcPluginSolveResult
 1745   { -- | Insoluble constraints found by the plugin.
 1746     --
 1747     -- These constraints will be added to the inert set,
 1748     -- and reported as insoluble to the user.
 1749     tcPluginInsolubleCts :: [Ct]
 1750     -- | Solved constraints, together with their evidence.
 1751     --
 1752     -- These are removed from the inert set, and the
 1753     -- evidence for them is recorded.
 1754   , tcPluginSolvedCts :: [(EvTerm, Ct)]
 1755     -- | New constraints that the plugin wishes to emit.
 1756     --
 1757     -- These will be added to the work list.
 1758   , tcPluginNewCts :: [Ct]
 1759   }
 1760 
 1761 data TcPluginRewriteResult
 1762   =
 1763   -- | The plugin does not rewrite the type family application.
 1764     TcPluginNoRewrite
 1765 
 1766   -- | The plugin rewrites the type family application
 1767   -- providing a rewriting together with evidence: a 'Reduction',
 1768   -- which contains the rewritten type together with a 'Coercion'
 1769   -- whose right-hand-side type is the rewritten type.
 1770   --
 1771   -- The plugin can also emit additional Wanted constraints.
 1772   | TcPluginRewriteTo
 1773     { tcPluginReduction    :: !Reduction
 1774     , tcRewriterNewWanteds :: [Ct]
 1775     }
 1776 
 1777 -- | A collection of candidate default types for a type variable.
 1778 data DefaultingProposal
 1779   = DefaultingProposal
 1780     { deProposalTyVar :: TcTyVar
 1781       -- ^ The type variable to default.
 1782     , deProposalCandidates :: [Type]
 1783       -- ^ Candidate types to default the type variable to.
 1784     , deProposalCts :: [Ct]
 1785       -- ^ The constraints against which defaults are checked.
 1786     }
 1787 
 1788 instance Outputable DefaultingProposal where
 1789   ppr p = text "DefaultingProposal"
 1790           <+> ppr (deProposalTyVar p)
 1791           <+> ppr (deProposalCandidates p)
 1792           <+> ppr (deProposalCts p)
 1793 
 1794 type DefaultingPluginResult = [DefaultingProposal]
 1795 type FillDefaulting = WantedConstraints -> TcPluginM DefaultingPluginResult
 1796 
 1797 -- | A plugin for controlling defaulting.
 1798 data DefaultingPlugin = forall s. DefaultingPlugin
 1799   { dePluginInit :: TcPluginM s
 1800     -- ^ Initialize plugin, when entering type-checker.
 1801   , dePluginRun :: s -> FillDefaulting
 1802     -- ^ Default some types
 1803   , dePluginStop :: s -> TcPluginM ()
 1804    -- ^ Clean up after the plugin, when exiting the type-checker.
 1805   }
 1806 
 1807 {- *********************************************************************
 1808 *                                                                      *
 1809                         Role annotations
 1810 *                                                                      *
 1811 ********************************************************************* -}
 1812 
 1813 type RoleAnnotEnv = NameEnv (LRoleAnnotDecl GhcRn)
 1814 
 1815 mkRoleAnnotEnv :: [LRoleAnnotDecl GhcRn] -> RoleAnnotEnv
 1816 mkRoleAnnotEnv role_annot_decls
 1817  = mkNameEnv [ (name, ra_decl)
 1818              | ra_decl <- role_annot_decls
 1819              , let name = roleAnnotDeclName (unLoc ra_decl)
 1820              , not (isUnboundName name) ]
 1821        -- Some of the role annots will be unbound;
 1822        -- we don't wish to include these
 1823 
 1824 emptyRoleAnnotEnv :: RoleAnnotEnv
 1825 emptyRoleAnnotEnv = emptyNameEnv
 1826 
 1827 lookupRoleAnnot :: RoleAnnotEnv -> Name -> Maybe (LRoleAnnotDecl GhcRn)
 1828 lookupRoleAnnot = lookupNameEnv
 1829 
 1830 getRoleAnnots :: [Name] -> RoleAnnotEnv -> [LRoleAnnotDecl GhcRn]
 1831 getRoleAnnots bndrs role_env
 1832   = mapMaybe (lookupRoleAnnot role_env) bndrs
 1833 
 1834 {- *********************************************************************
 1835 *                                                                      *
 1836                   Linting a TcGblEnv
 1837 *                                                                      *
 1838 ********************************************************************* -}
 1839 
 1840 -- | Check the 'TcGblEnv' for consistency. Currently, only checks
 1841 -- axioms, but should check other aspects, too.
 1842 lintGblEnv :: Logger -> DynFlags -> TcGblEnv -> TcM ()
 1843 lintGblEnv logger dflags tcg_env =
 1844   liftIO $ lintAxioms logger dflags (text "TcGblEnv axioms") axioms
 1845   where
 1846     axioms = typeEnvCoAxioms (tcg_type_env tcg_env)
 1847 
 1848 -- | This is a mirror of Template Haskell's DocLoc, but the TH names are
 1849 -- resolved to GHC names.
 1850 data DocLoc = DeclDoc Name
 1851             | ArgDoc Name Int
 1852             | InstDoc Name
 1853             | ModuleDoc
 1854   deriving (Eq, Ord)
 1855 
 1856 -- | The current collection of docs that Template Haskell has built up via
 1857 -- putDoc.
 1858 type THDocs = Map DocLoc String