{-# LANGUAGE CPP #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NondecreasingIndentation #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE MultiWayIf #-}

{-# OPTIONS_GHC -Wno-incomplete-record-updates #-}

{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998

-}

-- | Typechecking a whole module
--
-- https://gitlab.haskell.org/ghc/ghc/wikis/commentary/compiler/type-checker
module GHC.Tc.Module (
        tcRnStmt, tcRnExpr, TcRnExprMode(..), tcRnType,
        tcRnImportDecls,
        tcRnLookupRdrName,
        getModuleInterface,
        tcRnDeclsi,
        isGHCiMonad,
        runTcInteractive,    -- Used by GHC API clients (#8878)
        withTcPlugins,       -- Used by GHC API clients (#20499)
        withHoleFitPlugins,  -- Used by GHC API clients (#20499)
        tcRnLookupName,
        tcRnGetInfo,
        tcRnModule, tcRnModuleTcRnM,
        tcTopSrcDecls,
        rnTopSrcDecls,
        checkBootDecl, checkHiBootIface',
        findExtraSigImports,
        implicitRequirements,
        checkUnit,
        mergeSignatures,
        tcRnMergeSignatures,
        instantiateSignature,
        tcRnInstantiateSignature,
        loadUnqualIfaces,
        -- More private...
        checkBootDeclM,
        getRenamedStuff, RenamedStuff
    ) where

import GHC.Prelude

import GHC.Driver.Env
import GHC.Driver.Plugins
import GHC.Driver.DynFlags
import GHC.Driver.Config.Diagnostic

import GHC.Tc.Errors.Hole.Plugin ( HoleFitPluginR (..) )
import GHC.Tc.Errors.Types
import {-# SOURCE #-} GHC.Tc.Gen.Splice ( finishTH, runRemoteModFinalizers )
import GHC.Tc.Gen.HsType
import GHC.Tc.Validity( checkValidType )
import GHC.Tc.Gen.Match
import GHC.Tc.Utils.Unify( checkConstraints, tcSubTypeSigma )
import GHC.Tc.Zonk.Type
import GHC.Tc.Gen.Expr
import GHC.Tc.Gen.App( tcInferSigma )
import GHC.Tc.Utils.Monad
import GHC.Tc.Gen.Export
import GHC.Tc.Types.Evidence
import GHC.Tc.Types.Constraint
import GHC.Tc.Types.Origin
import GHC.Tc.Instance.Family
import GHC.Tc.Gen.Annotation
import GHC.Tc.Gen.Bind
import GHC.Tc.Gen.Default
import GHC.Tc.Utils.Env
import GHC.Tc.Gen.Rule
import GHC.Tc.Gen.Foreign
import GHC.Tc.TyCl.Instance
import GHC.Tc.Utils.TcMType
import GHC.Tc.Utils.TcType
import GHC.Tc.Solver
import GHC.Tc.TyCl
import GHC.Tc.Instance.Typeable ( mkTypeableBinds )
import GHC.Tc.Utils.Backpack
import GHC.Tc.Zonk.TcType

import GHC.Rename.Bind ( rejectBootDecls )
import GHC.Rename.Splice ( rnTopSpliceDecls, traceSplice, SpliceInfo(..) )
import GHC.Rename.HsType
import GHC.Rename.Expr
import GHC.Rename.Fixity ( lookupFixityRn )
import GHC.Rename.Names
import GHC.Rename.Env
import GHC.Rename.Module
import GHC.Rename.Doc
import GHC.Rename.Utils ( mkNameClashErr, mkRnSyntaxExpr )

import GHC.Iface.Decl    ( coAxiomToIfaceDecl )
import GHC.Iface.Env     ( externaliseName )
import GHC.Iface.Load

import GHC.Builtin.Types ( mkListTy, anyTypeOfKind )
import GHC.Builtin.Names
import GHC.Builtin.Utils

import GHC.Hs hiding ( FunDep(..) )
import GHC.Hs.Dump

import GHC.Core.PatSyn
import GHC.Core.Predicate ( classMethodTy )
import GHC.Core.InstEnv
import GHC.Core.TyCon
import GHC.Core.DataCon
import GHC.Core.TyCo.Rep
import GHC.Core.Type
import GHC.Core.Class
import GHC.Core.Coercion.Axiom
import GHC.Core.Reduction ( Reduction(..) )
import GHC.Core.TyCo.Ppr( debugPprType )
import GHC.Core.FamInstEnv
   ( FamInst, pprFamInst, famInstsRepTyCons, orphNamesOfFamInst
   , famInstEnvElts, extendFamInstEnvList, normaliseType )

import GHC.Parser.Header       ( mkPrelImports )

import GHC.IfaceToCore

import GHC.Runtime.Context

import GHC.Utils.Error
import GHC.Utils.Outputable as Outputable
import GHC.Utils.Panic
import GHC.Utils.Misc
import GHC.Utils.Logger

import GHC.Types.Error
import GHC.Types.Name.Reader
import GHC.Types.DefaultEnv ( DefaultEnv, ClassDefaults (ClassDefaults, cd_class, cd_types),
                              emptyDefaultEnv, isEmptyDefaultEnv, unitDefaultEnv, lookupDefaultEnv )
import GHC.Types.Fixity.Env
import GHC.Types.Id as Id
import GHC.Types.Id.Info( IdDetails(..) )
import GHC.Types.Var.Env
import GHC.Types.TypeEnv
import GHC.Types.Unique.FM
import GHC.Types.Name
import GHC.Types.Name.Env
import GHC.Types.Name.Set
import GHC.Types.Avail
import GHC.Types.Basic hiding( SuccessFlag(..) )
import GHC.Types.Annotations
import GHC.Types.SrcLoc
import GHC.Types.SourceFile
import GHC.Types.PkgQual
import qualified GHC.LanguageExtensions as LangExt

import GHC.Unit.External
import GHC.Unit.Types
import GHC.Unit.State
import GHC.Unit.Home
import GHC.Unit.Module
import GHC.Unit.Module.Warnings
import GHC.Unit.Module.ModSummary
import GHC.Unit.Module.ModIface
import GHC.Unit.Module.ModDetails
import GHC.Unit.Module.Deps

import GHC.Data.FastString
import GHC.Data.Maybe
import GHC.Data.List.SetOps
import GHC.Data.Bag
import qualified GHC.Data.BooleanFormula as BF

import Control.Arrow ( second )
import Control.DeepSeq
import Control.Monad
import Control.Monad.Trans.Writer.CPS
import Data.Data ( Data )
import Data.Functor.Classes ( liftEq )
import Data.List ( sort, sortBy )
import Data.List.NonEmpty ( NonEmpty (..) )
import qualified Data.List.NonEmpty as NE
import Data.Ord
import qualified Data.Set as S
import qualified Data.Map as M
import Data.Foldable ( for_ )
import Data.Traversable ( for )



{-
************************************************************************
*                                                                      *
        Typecheck and rename a module
*                                                                      *
************************************************************************
-}

-- | Top level entry point for typechecker and renamer
tcRnModule :: HscEnv
           -> ModSummary
           -> Bool              -- True <=> save renamed syntax
           -> HsParsedModule
           -> IO (Messages TcRnMessage, Maybe TcGblEnv)

tcRnModule :: HscEnv
-> ModSummary
-> Bool
-> HsParsedModule
-> IO (Messages TcRnMessage, Maybe TcGblEnv)
tcRnModule HscEnv
hsc_env ModSummary
mod_sum Bool
save_rn_syntax
   parsedModule :: HsParsedModule
parsedModule@HsParsedModule {hpm_module :: HsParsedModule -> Located (HsModule GhcPs)
hpm_module= L SrcSpan
loc HsModule GhcPs
this_module}
 | RealSrcSpan RealSrcSpan
real_loc Maybe BufSpan
_ <- SrcSpan
loc
 = Logger
-> SDoc
-> ((Messages TcRnMessage, Maybe TcGblEnv) -> ())
-> IO (Messages TcRnMessage, Maybe TcGblEnv)
-> IO (Messages TcRnMessage, Maybe TcGblEnv)
forall (m :: * -> *) a.
MonadIO m =>
Logger -> SDoc -> (a -> ()) -> m a -> m a
withTiming Logger
logger
              (String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"Renamer/typechecker"SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+>SDoc -> SDoc
forall doc. IsLine doc => doc -> doc
brackets (Module -> SDoc
forall a. Outputable a => a -> SDoc
ppr Module
this_mod))
              (() -> (Messages TcRnMessage, Maybe TcGblEnv) -> ()
forall a b. a -> b -> a
const ()) (IO (Messages TcRnMessage, Maybe TcGblEnv)
 -> IO (Messages TcRnMessage, Maybe TcGblEnv))
-> IO (Messages TcRnMessage, Maybe TcGblEnv)
-> IO (Messages TcRnMessage, Maybe TcGblEnv)
forall a b. (a -> b) -> a -> b
$
   HscEnv
-> HscSource
-> Bool
-> Module
-> RealSrcSpan
-> TcM TcGblEnv
-> IO (Messages TcRnMessage, Maybe TcGblEnv)
forall r.
HscEnv
-> HscSource
-> Bool
-> Module
-> RealSrcSpan
-> TcM r
-> IO (Messages TcRnMessage, Maybe r)
initTc HscEnv
hsc_env HscSource
hsc_src Bool
save_rn_syntax Module
this_mod RealSrcSpan
real_loc (TcM TcGblEnv -> IO (Messages TcRnMessage, Maybe TcGblEnv))
-> TcM TcGblEnv -> IO (Messages TcRnMessage, Maybe TcGblEnv)
forall a b. (a -> b) -> a -> b
$
          HscEnv -> TcM TcGblEnv -> TcM TcGblEnv
forall a. HscEnv -> TcM a -> TcM a
withTcPlugins HscEnv
hsc_env (TcM TcGblEnv -> TcM TcGblEnv) -> TcM TcGblEnv -> TcM TcGblEnv
forall a b. (a -> b) -> a -> b
$
          HscEnv -> TcM TcGblEnv -> TcM TcGblEnv
forall a. HscEnv -> TcM a -> TcM a
withDefaultingPlugins HscEnv
hsc_env (TcM TcGblEnv -> TcM TcGblEnv) -> TcM TcGblEnv -> TcM TcGblEnv
forall a b. (a -> b) -> a -> b
$
          HscEnv -> TcM TcGblEnv -> TcM TcGblEnv
forall a. HscEnv -> TcM a -> TcM a
withHoleFitPlugins HscEnv
hsc_env (TcM TcGblEnv -> TcM TcGblEnv) -> TcM TcGblEnv -> TcM TcGblEnv
forall a b. (a -> b) -> a -> b
$

          HscEnv
-> ModSummary
-> HsParsedModule
-> (Module, SrcSpan)
-> TcM TcGblEnv
tcRnModuleTcRnM HscEnv
hsc_env ModSummary
mod_sum HsParsedModule
parsedModule (Module, SrcSpan)
pair

  | Bool
otherwise
  = (Messages TcRnMessage, Maybe TcGblEnv)
-> IO (Messages TcRnMessage, Maybe TcGblEnv)
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (MsgEnvelope TcRnMessage
err_msg MsgEnvelope TcRnMessage
-> Messages TcRnMessage -> Messages TcRnMessage
forall e. MsgEnvelope e -> Messages e -> Messages e
`addMessage` Messages TcRnMessage
forall e. Messages e
emptyMessages, Maybe TcGblEnv
forall a. Maybe a
Nothing)

  where
    hsc_src :: HscSource
hsc_src = ModSummary -> HscSource
ms_hsc_src ModSummary
mod_sum
    logger :: Logger
logger  = HscEnv -> Logger
hsc_logger HscEnv
hsc_env
    home_unit :: HomeUnit
home_unit = HscEnv -> HomeUnit
hsc_home_unit HscEnv
hsc_env
    err_msg :: MsgEnvelope TcRnMessage
err_msg = SrcSpan -> TcRnMessage -> MsgEnvelope TcRnMessage
forall e. Diagnostic e => SrcSpan -> e -> MsgEnvelope e
mkPlainErrorMsgEnvelope SrcSpan
loc (TcRnMessage -> MsgEnvelope TcRnMessage)
-> TcRnMessage -> MsgEnvelope TcRnMessage
forall a b. (a -> b) -> a -> b
$
              Module -> TcRnMessage
TcRnModMissingRealSrcSpan Module
this_mod

    pair :: (Module, SrcSpan)
    pair :: (Module, SrcSpan)
pair@(Module
this_mod,SrcSpan
_)
      | Just (L SrcSpanAnnA
mod_loc ModuleName
mod) <- HsModule GhcPs -> Maybe (XRec GhcPs ModuleName)
forall p. HsModule p -> Maybe (XRec p ModuleName)
hsmodName HsModule GhcPs
this_module
      = (HomeUnit -> ModuleName -> Module
mkHomeModule HomeUnit
home_unit ModuleName
mod, SrcSpanAnnA -> SrcSpan
forall a. HasLoc a => a -> SrcSpan
locA SrcSpanAnnA
mod_loc)

      | Bool
otherwise   -- 'module M where' is omitted
      = (HomeUnit -> ModuleName -> Module
mkHomeModule HomeUnit
home_unit ModuleName
mAIN_NAME, SrcLoc -> SrcSpan
srcLocSpan (SrcSpan -> SrcLoc
srcSpanStart SrcSpan
loc))




tcRnModuleTcRnM :: HscEnv
                -> ModSummary
                -> HsParsedModule
                -> (Module, SrcSpan)
                -> TcRn TcGblEnv
-- Factored out separately from tcRnModule so that a Core plugin can
-- call the type checker directly
tcRnModuleTcRnM :: HscEnv
-> ModSummary
-> HsParsedModule
-> (Module, SrcSpan)
-> TcM TcGblEnv
tcRnModuleTcRnM HscEnv
hsc_env ModSummary
mod_sum
                (HsParsedModule {
                   hpm_module :: HsParsedModule -> Located (HsModule GhcPs)
hpm_module =
                      (L SrcSpan
loc (HsModule (XModulePs EpAnn AnnsModule
_ EpLayout
_ Maybe (LWarningTxt GhcPs)
mod_deprec Maybe (LHsDoc GhcPs)
maybe_doc_hdr)
                                       Maybe (XRec GhcPs ModuleName)
maybe_mod Maybe (XRec GhcPs [XRec GhcPs (IE GhcPs)])
export_ies [LImportDecl GhcPs]
import_decls [LHsDecl GhcPs]
local_decls)),
                   hpm_src_files :: HsParsedModule -> [String]
hpm_src_files = [String]
src_files
                })
                (Module
this_mod, SrcSpan
prel_imp_loc)
 = SrcSpan -> TcM TcGblEnv -> TcM TcGblEnv
forall a. SrcSpan -> TcRn a -> TcRn a
setSrcSpan SrcSpan
loc (TcM TcGblEnv -> TcM TcGblEnv) -> TcM TcGblEnv -> TcM TcGblEnv
forall a b. (a -> b) -> a -> b
$
   do { let { explicit_mod_hdr :: Bool
explicit_mod_hdr = Maybe (GenLocated SrcSpanAnnA ModuleName) -> Bool
forall a. Maybe a -> Bool
isJust Maybe (XRec GhcPs ModuleName)
Maybe (GenLocated SrcSpanAnnA ModuleName)
maybe_mod
            ; hsc_src :: HscSource
hsc_src          = ModSummary -> HscSource
ms_hsc_src ModSummary
mod_sum }
      ; -- Load the hi-boot interface for this module, if any
        -- We do this now so that the boot_names can be passed
        -- to tcTyAndClassDecls, because the boot_names are
        -- automatically considered to be loop breakers
        tcg_env <- TcM TcGblEnv
forall gbl lcl. TcRnIf gbl lcl gbl
getGblEnv
      ; boot_info <- tcHiBootIface hsc_src this_mod
      ; setGblEnv (tcg_env { tcg_self_boot = boot_info })
        $ do
        { -- Deal with imports; first add implicit prelude
          implicit_prelude <- xoptM LangExt.ImplicitPrelude
        ; let { prel_imports = ModuleName
-> SrcSpan -> Bool -> [LImportDecl GhcPs] -> [LImportDecl GhcPs]
mkPrelImports (Module -> ModuleName
forall unit. GenModule unit -> ModuleName
moduleName Module
this_mod) SrcSpan
prel_imp_loc
                               Bool
implicit_prelude [LImportDecl GhcPs]
import_decls }

        ; when (notNull prel_imports) $ do
            addDiagnostic TcRnImplicitImportOfPrelude

        ; -- TODO This is a little skeevy; maybe handle a bit more directly
          let { simplifyImport (L SrcSpanAnnA
_ ImportDecl GhcPs
idecl) =
                  ( UnitEnv -> ModuleName -> RawPkgQual -> PkgQual
renameRawPkgQual (HscEnv -> UnitEnv
hsc_unit_env HscEnv
hsc_env) (GenLocated SrcSpanAnnA ModuleName -> ModuleName
forall l e. GenLocated l e -> e
unLoc (GenLocated SrcSpanAnnA ModuleName -> ModuleName)
-> GenLocated SrcSpanAnnA ModuleName -> ModuleName
forall a b. (a -> b) -> a -> b
$ ImportDecl GhcPs -> XRec GhcPs ModuleName
forall pass. ImportDecl pass -> XRec pass ModuleName
ideclName ImportDecl GhcPs
idecl) (ImportDecl GhcPs -> ImportDeclPkgQual GhcPs
forall pass. ImportDecl pass -> ImportDeclPkgQual pass
ideclPkgQual ImportDecl GhcPs
idecl)
                  , GenLocated SrcSpanAnnA ModuleName -> GenLocated SrcSpan ModuleName
forall a e b.
(HasLoc (GenLocated a e), HasAnnotation b) =>
GenLocated a e -> GenLocated b e
reLoc (GenLocated SrcSpanAnnA ModuleName
 -> GenLocated SrcSpan ModuleName)
-> GenLocated SrcSpanAnnA ModuleName
-> GenLocated SrcSpan ModuleName
forall a b. (a -> b) -> a -> b
$ ImportDecl GhcPs -> XRec GhcPs ModuleName
forall pass. ImportDecl pass -> XRec pass ModuleName
ideclName ImportDecl GhcPs
idecl)
              }
        ; raw_sig_imports <- liftIO
                             $ findExtraSigImports hsc_env hsc_src
                                 (moduleName this_mod)
        ; raw_req_imports <- liftIO
                             $ implicitRequirements hsc_env
                                (map simplifyImport (prel_imports
                                                     ++ import_decls))
        ; let { mkImport ModuleName
mod_name = ImportDecl pass -> GenLocated e (ImportDecl pass)
forall e a. HasAnnotation e => a -> GenLocated e a
noLocA
                (ImportDecl pass -> GenLocated e (ImportDecl pass))
-> ImportDecl pass -> GenLocated e (ImportDecl pass)
forall a b. (a -> b) -> a -> b
$ (ModuleName -> ImportDecl GhcPs
simpleImportDecl ModuleName
mod_name)
                  { ideclImportList = Just (Exactly, noLocA [])}}
        ; let { withReason String
t [a]
imps = (a -> (a, t)) -> [a] -> [(a, t)]
forall a b. (a -> b) -> [a] -> [b]
map (,String -> t
forall doc. IsLine doc => String -> doc
text String
t) [a]
imps }
        ; let { all_imports = String
-> [GenLocated SrcSpanAnnA (ImportDecl GhcPs)]
-> [(GenLocated SrcSpanAnnA (ImportDecl GhcPs), SDoc)]
forall {t} {a}. IsLine t => String -> [a] -> [(a, t)]
withReason String
"is implicitly imported" [LImportDecl GhcPs]
[GenLocated SrcSpanAnnA (ImportDecl GhcPs)]
prel_imports
                  [(GenLocated SrcSpanAnnA (ImportDecl GhcPs), SDoc)]
-> [(GenLocated SrcSpanAnnA (ImportDecl GhcPs), SDoc)]
-> [(GenLocated SrcSpanAnnA (ImportDecl GhcPs), SDoc)]
forall a. [a] -> [a] -> [a]
++ String
-> [GenLocated SrcSpanAnnA (ImportDecl GhcPs)]
-> [(GenLocated SrcSpanAnnA (ImportDecl GhcPs), SDoc)]
forall {t} {a}. IsLine t => String -> [a] -> [(a, t)]
withReason String
"is directly imported" [LImportDecl GhcPs]
[GenLocated SrcSpanAnnA (ImportDecl GhcPs)]
import_decls
                  [(GenLocated SrcSpanAnnA (ImportDecl GhcPs), SDoc)]
-> [(GenLocated SrcSpanAnnA (ImportDecl GhcPs), SDoc)]
-> [(GenLocated SrcSpanAnnA (ImportDecl GhcPs), SDoc)]
forall a. [a] -> [a] -> [a]
++ String
-> [GenLocated SrcSpanAnnA (ImportDecl GhcPs)]
-> [(GenLocated SrcSpanAnnA (ImportDecl GhcPs), SDoc)]
forall {t} {a}. IsLine t => String -> [a] -> [(a, t)]
withReason String
"is an extra sig import" ((ModuleName -> GenLocated SrcSpanAnnA (ImportDecl GhcPs))
-> [ModuleName] -> [GenLocated SrcSpanAnnA (ImportDecl GhcPs)]
forall a b. (a -> b) -> [a] -> [b]
map ModuleName -> GenLocated SrcSpanAnnA (ImportDecl GhcPs)
forall {pass} {e} {e}.
(XCImportDecl pass ~ XImportDeclPass,
 XRec pass [XRec pass (IE pass)]
 ~ GenLocated e [XRec pass (IE pass)],
 XRec pass ModuleName ~ GenLocated SrcSpanAnnA ModuleName,
 ImportDeclPkgQual pass ~ RawPkgQual, HasAnnotation e,
 HasAnnotation e) =>
ModuleName -> GenLocated e (ImportDecl pass)
mkImport [ModuleName]
raw_sig_imports)
                  [(GenLocated SrcSpanAnnA (ImportDecl GhcPs), SDoc)]
-> [(GenLocated SrcSpanAnnA (ImportDecl GhcPs), SDoc)]
-> [(GenLocated SrcSpanAnnA (ImportDecl GhcPs), SDoc)]
forall a. [a] -> [a] -> [a]
++ String
-> [GenLocated SrcSpanAnnA (ImportDecl GhcPs)]
-> [(GenLocated SrcSpanAnnA (ImportDecl GhcPs), SDoc)]
forall {t} {a}. IsLine t => String -> [a] -> [(a, t)]
withReason String
"is an implicit req import" ((ModuleName -> GenLocated SrcSpanAnnA (ImportDecl GhcPs))
-> [ModuleName] -> [GenLocated SrcSpanAnnA (ImportDecl GhcPs)]
forall a b. (a -> b) -> [a] -> [b]
map ModuleName -> GenLocated SrcSpanAnnA (ImportDecl GhcPs)
forall {pass} {e} {e}.
(XCImportDecl pass ~ XImportDeclPass,
 XRec pass [XRec pass (IE pass)]
 ~ GenLocated e [XRec pass (IE pass)],
 XRec pass ModuleName ~ GenLocated SrcSpanAnnA ModuleName,
 ImportDeclPkgQual pass ~ RawPkgQual, HasAnnotation e,
 HasAnnotation e) =>
ModuleName -> GenLocated e (ImportDecl pass)
mkImport [ModuleName]
raw_req_imports) }
        ; -- OK now finally rename the imports
          (defaultImportsByClass, tcg_env) <-
            {-# SCC "tcRnImports" #-} tcRnImports hsc_env all_imports

        -- Put a version of the header without identifier info into the tcg_env
        -- Make sure to do this before 'tcRnSrcDecls', because we need the
        -- module header when we're splicing TH, since it can be accessed via
        -- 'getDoc'.
        -- We will rename it properly after renaming everything else so that
        -- haddock can link the identifiers
        ; tcg_env <- return (tcg_env
                              { tcg_hdr_info = (fmap (\(WithHsDocIdentifiers HsDocString
str [Located (IdP GhcPs)]
_) -> HsDocString
-> [Located (IdP (GhcPass 'Renamed))] -> HsDoc (GhcPass 'Renamed)
forall a pass.
a -> [Located (IdP pass)] -> WithHsDocIdentifiers a pass
WithHsDocIdentifiers HsDocString
str [])
                                                <$> maybe_doc_hdr , maybe_mod ) })
        ; -- If the whole module is warned about or deprecated
          -- (via mod_deprec) record that in tcg_warns. If we do thereby add
          -- a WarnAll, it will override any subsequent deprecations added to tcg_warns
        ; tcg_env1 <- case mod_deprec of
                             Just (L SrcSpanAnnP
_ WarningTxt GhcPs
txt) -> do { txt' <- WarningTxt GhcPs -> RnM (WarningTxt (GhcPass 'Renamed))
rnWarningTxt WarningTxt GhcPs
txt
                                                  ; pure $ tcg_env {tcg_warns = WarnAll txt'}
                                                  }
                             Maybe (LWarningTxt GhcPs)
Nothing            -> TcGblEnv -> TcM TcGblEnv
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (f :: * -> *) a. Applicative f => a -> f a
pure TcGblEnv
tcg_env
        ; setGblEnv tcg_env1
          $ do { -- Rename and type check the declarations
                 traceRn "rn1a" empty
               ; tcg_env <-
                   case hsc_src of
                    HsBootOrSig HsBootOrSig
boot_or_sig ->
                      do { tcg_env <- HsBootOrSig -> [LHsDecl GhcPs] -> TcM TcGblEnv
tcRnHsBootDecls HsBootOrSig
boot_or_sig [LHsDecl GhcPs]
local_decls
                         ; traceRn "rn4a: before exports" empty
                         ; tcg_env <- setGblEnv tcg_env $
                                      rnExports explicit_mod_hdr export_ies
                         ; traceRn "rn4b: after exports" empty
                         ; return tcg_env
                         }
                    HscSource
HsSrcFile ->
                      {-# SCC "tcRnSrcDecls" #-}
                        Bool
-> Maybe (GenLocated SrcSpanAnnLI [XRec GhcPs (IE GhcPs)])
-> [LHsDecl GhcPs]
-> TcM TcGblEnv
tcRnSrcDecls Bool
explicit_mod_hdr Maybe (XRec GhcPs [XRec GhcPs (IE GhcPs)])
Maybe (GenLocated SrcSpanAnnLI [XRec GhcPs (IE GhcPs)])
export_ies [LHsDecl GhcPs]
local_decls

               ; whenM (goptM Opt_DoCoreLinting) $
                 lintGblEnv (hsc_logger hsc_env) (hsc_dflags hsc_env) tcg_env

               ; setGblEnv tcg_env
                 $ do { -- Compare hi-boot iface (if any) with the real thing
                        -- Must be done after processing the exports
                        tcg_env <- checkHiBootIface tcg_env boot_info
                      ; -- The new type env is already available to stuff
                        -- slurped from interface files, via
                        -- GHC.Tc.Utils.Env.setGlobalTypeEnv. It's important that this
                        -- includes the stuff in checkHiBootIface,
                        -- because the latter might add new bindings for
                        -- boot_dfuns, which may be mentioned in imported
                        -- unfoldings.
                      ; -- Report unused names
                        -- Do this /after/ type inference, so that when reporting
                        -- a function with no type signature we can give the
                        -- inferred type
                      ; reportUnusedNames tcg_env hsc_src
                      ; reportClashingDefaultImports defaultImportsByClass (tcg_default tcg_env)

                      -- Rename the module header properly after we have renamed everything else
                      ; maybe_doc_hdr <- traverse rnLHsDoc maybe_doc_hdr;
                      ; tcg_env <- return (tcg_env
                                            { tcg_hdr_info = (maybe_doc_hdr, maybe_mod) })

                      ; -- add extra source files to tcg_dependent_files
                        addDependentFiles src_files
                        -- Ensure plugins run with the same tcg_env that we pass in
                      ; setGblEnv tcg_env
                        $ do { tcg_env <- runTypecheckerPlugin mod_sum tcg_env
                             ; -- Dump output and return
                               tcDump tcg_env
                             ; return tcg_env
                             }
                      }
               }
        }
      }

{- Note [Disambiguation of multiple default declarations]

See Note [Named default declarations] in GHC.Tc.Gen.Default

Only a single default declaration can be in effect in any single module for
any particular class.

* Two declarations for the same class explicitly declared in the same module
  are considered a static error.

* Definition: given two default declarations for the same class

  default C (Type_1a , … , Type_ma)
  default C (Type_1b , … , Type_nb)

  if the first type sequence Type_1a , … , Type_ma is a sub-sequence of the
  second sequence Type_1b , … , Type_nb (i.e., the former can be obtained by
  removing a number of Type_ib items from the latter), we say that the second
  declaration *subsumes* the first one.

* A default declaration in a module takes precedence over any imported default
  declarations for the same class. However the compiler warns the user if an
  imported declaration is not subsumed by the local declaration.

* For any two imported default declarations for the same class where one
  subsumes the other, we ignore the subsumed declaration.

* If a class has neither a local default declaration nor an imported default
  declaration that subsumes all other imported default declarations for the
  class, the conflict between the imports is unresolvable. The effect is to
  ignore all default declarations for the class, so that no declaration is in
  effect in the module. The compiler emits a warning in this case, but no
  error.
-}

-- See Note [Disambiguation of multiple default declarations]
-- | Warn about any imported default declaration that is not subsumed by either
-- a local or an imported default declaration.
reportClashingDefaultImports :: [NonEmpty ClassDefaults] -> DefaultEnv -> TcM ()
reportClashingDefaultImports :: [NonEmpty ClassDefaults]
-> DefaultEnv -> IOEnv (Env TcGblEnv TcLclEnv) ()
reportClashingDefaultImports [NonEmpty ClassDefaults]
importsByClass DefaultEnv
local = (NonEmpty ClassDefaults -> IOEnv (Env TcGblEnv TcLclEnv) ())
-> [NonEmpty ClassDefaults] -> IOEnv (Env TcGblEnv TcLclEnv) ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ NonEmpty ClassDefaults -> IOEnv (Env TcGblEnv TcLclEnv) ()
check [NonEmpty ClassDefaults]
importsByClass
  where
    check :: NonEmpty ClassDefaults -> IOEnv (Env TcGblEnv TcLclEnv) ()
check cds :: NonEmpty ClassDefaults
cds@(ClassDefaults{cd_class :: ClassDefaults -> TyCon
cd_class = TyCon
cls} :| [ClassDefaults]
_) = do
      let cdLocal :: Maybe ClassDefaults
cdLocal  = DefaultEnv -> Name -> Maybe ClassDefaults
lookupDefaultEnv DefaultEnv
local (TyCon -> Name
tyConName TyCon
cls)
      case Maybe ClassDefaults
cdLocal of
        Just ClassDefaults{cd_types :: ClassDefaults -> [Type]
cd_types = [Type]
localTypes}
          | (ClassDefaults -> Bool) -> NonEmpty ClassDefaults -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all (([Type] -> [Type] -> Bool
`isTypeSubsequenceOf` [Type]
localTypes) ([Type] -> Bool)
-> (ClassDefaults -> [Type]) -> ClassDefaults -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ClassDefaults -> [Type]
cd_types) NonEmpty ClassDefaults
cds -> () -> IOEnv (Env TcGblEnv TcLclEnv) ()
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
        Maybe ClassDefaults
Nothing
          | Bool -> Bool
not (DefaultEnv -> Bool
isEmptyDefaultEnv (DefaultEnv -> Bool) -> DefaultEnv -> Bool
forall a b. (a -> b) -> a -> b
$ NonEmpty ClassDefaults -> DefaultEnv
subsume NonEmpty ClassDefaults
cds) -> () -> IOEnv (Env TcGblEnv TcLclEnv) ()
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
        Maybe ClassDefaults
_ -> do
          warn_default <- WarningFlag -> TcRnIf TcGblEnv TcLclEnv Bool
forall gbl lcl. WarningFlag -> TcRnIf gbl lcl Bool
woptM WarningFlag
Opt_WarnTypeDefaults
          diagnosticTc warn_default $
            TcRnWarnClashingDefaultImports cls (cd_types <$> cdLocal) cds

-- | Collapse a non-empty list of @default@ declarations for the same class to
-- the single declaration among them that subsumes all others, or to no
-- declaration otherwise.
subsume :: NonEmpty ClassDefaults -> DefaultEnv
subsume :: NonEmpty ClassDefaults -> DefaultEnv
subsume (ClassDefaults
deft :| []) = ClassDefaults -> DefaultEnv
unitDefaultEnv ClassDefaults
deft
subsume (ClassDefaults
deft :| ClassDefaults
deft' : [ClassDefaults]
defts)
  | ClassDefaults -> [Type]
cd_types ClassDefaults
deft  [Type] -> [Type] -> Bool
`isTypeSubsequenceOf` ClassDefaults -> [Type]
cd_types ClassDefaults
deft' = NonEmpty ClassDefaults -> DefaultEnv
subsume (ClassDefaults
deft' ClassDefaults -> [ClassDefaults] -> NonEmpty ClassDefaults
forall a. a -> [a] -> NonEmpty a
:| [ClassDefaults]
defts)
  | ClassDefaults -> [Type]
cd_types ClassDefaults
deft' [Type] -> [Type] -> Bool
`isTypeSubsequenceOf` ClassDefaults -> [Type]
cd_types ClassDefaults
deft  = NonEmpty ClassDefaults -> DefaultEnv
subsume (ClassDefaults
deft  ClassDefaults -> [ClassDefaults] -> NonEmpty ClassDefaults
forall a. a -> [a] -> NonEmpty a
:| [ClassDefaults]
defts)
  | Bool
otherwise = DefaultEnv
emptyDefaultEnv

isTypeSubsequenceOf :: [Type] -> [Type] -> Bool
isTypeSubsequenceOf :: [Type] -> [Type] -> Bool
isTypeSubsequenceOf [] [Type]
_ = Bool
True
isTypeSubsequenceOf [Type]
_ [] = Bool
False
isTypeSubsequenceOf (Type
t1:[Type]
t1s) (Type
t2:[Type]
t2s)
  | HasDebugCallStack => Type -> Type -> Bool
Type -> Type -> Bool
tcEqType Type
t1 Type
t2 = [Type] -> [Type] -> Bool
isTypeSubsequenceOf [Type]
t1s [Type]
t2s
  | Bool
otherwise = [Type] -> [Type] -> Bool
isTypeSubsequenceOf (Type
t1Type -> [Type] -> [Type]
forall a. a -> [a] -> [a]
:[Type]
t1s) [Type]
t2s

{-
************************************************************************
*                                                                      *
                Import declarations
*                                                                      *
************************************************************************
-}

tcRnImports :: HscEnv -> [(LImportDecl GhcPs, SDoc)] -> TcM ([NonEmpty ClassDefaults], TcGblEnv)
tcRnImports :: HscEnv
-> [(LImportDecl GhcPs, SDoc)]
-> TcM ([NonEmpty ClassDefaults], TcGblEnv)
tcRnImports HscEnv
hsc_env [(LImportDecl GhcPs, SDoc)]
import_decls
  = do  { (rn_imports, imp_user_spec, rdr_env, imports, defaults, hpc_info) <- [(LImportDecl GhcPs, SDoc)]
-> RnM
     ([LImportDecl (GhcPass 'Renamed)], [ImportUserSpec], GlobalRdrEnv,
      ImportAvails, [(Module, IfaceDefault)], Bool)
rnImports [(LImportDecl GhcPs, SDoc)]
import_decls ;

        ; this_mod <- getModule
        ; gbl_env <- getGblEnv
        ; let unitId = HomeUnit -> UnitId
forall u. GenHomeUnit u -> UnitId
homeUnitId (HomeUnit -> UnitId) -> HomeUnit -> UnitId
forall a b. (a -> b) -> a -> b
$ HscEnv -> HomeUnit
hsc_home_unit HscEnv
hsc_env
              mnwib = ModuleName -> IsBootInterface -> ModuleNameWithIsBoot
forall mod. mod -> IsBootInterface -> GenWithIsBoot mod
GWIB (Module -> ModuleName
forall unit. GenModule unit -> ModuleName
moduleName Module
this_mod)(HscSource -> IsBootInterface
hscSourceToIsBoot (TcGblEnv -> HscSource
tcg_src TcGblEnv
gbl_env))
        ; let { -- We want instance declarations from all home-package
                -- modules below this one, including boot modules, except
                -- ourselves.  The 'except ourselves' is so that we don't
                -- get the instances from this module's hs-boot file.  This
                -- filtering also ensures that we don't see instances from
                -- modules batch (@--make@) compiled before this one, but
                -- which are not below this one.
              ; (home_insts, home_fam_insts) =

                    hptInstancesBelow hsc_env unitId mnwib

              } ;

                -- Record boot-file info in the EPS, so that it's
                -- visible to loadHiBootInterface in tcRnSrcDecls,
                -- and any other incrementally-performed imports
              ; when (isOneShot (ghcMode (hsc_dflags hsc_env))) $ do {
                  updateEps_ $ \ExternalPackageState
eps  -> ExternalPackageState
eps { eps_is_boot = imp_boot_mods imports }
               }

                -- Type check the imported default declarations
        ; tc_defaults <- initIfaceTcRn (tcIfaceDefaults this_mod defaults)
                -- Update the gbl env
        ; updGblEnv ( \ TcGblEnv
gbl ->
            TcGblEnv
gbl {
              tcg_rdr_env      = tcg_rdr_env gbl `plusGlobalRdrEnv` rdr_env,
              tcg_imports      = tcg_imports gbl `plusImportAvails` imports,
              tcg_import_decls = imp_user_spec,
              tcg_rn_imports   = rn_imports,
              tcg_default      = foldMap subsume tc_defaults,
              tcg_inst_env     = tcg_inst_env gbl `unionInstEnv` home_insts,
              tcg_fam_inst_env = extendFamInstEnvList (tcg_fam_inst_env gbl)
                                                      home_fam_insts,
              tcg_hpc          = hpc_info
            }) $ do {

        ; traceRn "rn1" (ppr (imp_direct_dep_mods imports))
                -- Fail if there are any errors so far
                -- The error printing (if needed) takes advantage
                -- of the tcg_env we have now set
--      ; traceIf (text "rdr_env: " <+> ppr rdr_env)
        ; failIfErrsM

                -- Load any orphan-module (including orphan family
                -- instance-module) interfaces, so that their rules and
                -- instance decls will be found.  But filter out a
                -- self hs-boot: these instances will be checked when
                -- we define them locally.
                -- (We don't need to load non-orphan family instance
                -- modules until we either try to use the instances they
                -- define, or define our own family instances, at which
                -- point we need to check them for consistency.)
        ; loadModuleInterfaces (text "Loading orphan modules")
                               (filter (/= this_mod) (imp_orphs imports))

                -- Check type-family consistency between imports.
                -- See Note [The type family instance consistency story]
        ; traceRn "rn1: checking family instance consistency {" empty
        ; let { dir_imp_mods = Map Module [ImportedBy] -> [Module]
forall k a. Map k a -> [k]
M.keys
                             (Map Module [ImportedBy] -> [Module])
-> (ImportAvails -> Map Module [ImportedBy])
-> ImportAvails
-> [Module]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ImportAvails -> Map Module [ImportedBy]
imp_mods
                             (ImportAvails -> [Module]) -> ImportAvails -> [Module]
forall a b. (a -> b) -> a -> b
$ ImportAvails
imports }
        ; logger <- getLogger
        ; withTiming logger (text "ConsistencyCheck"<+>brackets (ppr this_mod)) (const ())
            $ checkFamInstConsistency dir_imp_mods
        ; traceRn "rn1: } checking family instance consistency" empty

        ; gbl_env <- getGblEnv
        ; return (tc_defaults, gbl_env) } }

{-
************************************************************************
*                                                                      *
        Type-checking the top level of a module
*                                                                      *
************************************************************************
-}

tcRnSrcDecls :: Bool  -- False => no 'module M(..) where' header at all
             -> Maybe (LocatedLI [LIE GhcPs])
             -> [LHsDecl GhcPs]               -- Declarations
             -> TcM TcGblEnv
tcRnSrcDecls :: Bool
-> Maybe (GenLocated SrcSpanAnnLI [XRec GhcPs (IE GhcPs)])
-> [LHsDecl GhcPs]
-> TcM TcGblEnv
tcRnSrcDecls Bool
explicit_mod_hdr Maybe (GenLocated SrcSpanAnnLI [XRec GhcPs (IE GhcPs)])
export_ies [LHsDecl GhcPs]
decls
 = do { -- Do all the declarations
      ; (tcg_env, tcl_env, lie) <- [LHsDecl GhcPs] -> TcM (TcGblEnv, TcLclEnv, WantedConstraints)
tc_rn_src_decls [LHsDecl GhcPs]
decls

      ------ Simplify constraints ---------
      --
      -- We do this after checkMainType, so that we use the type
      -- info that checkMainType adds
      --
      -- We do it with both global and local env in scope:
      --  * the global env exposes the instances to simplifyTop,
      --    and affects how names are rendered in error messages
      --  * the local env exposes the local Ids to simplifyTop,
      --    so that we get better error messages (monomorphism restriction)
      ; new_ev_binds <- {-# SCC "simplifyTop" #-}
                        restoreEnvs (tcg_env, tcl_env) $
                        do { lie_main <- checkMainType tcg_env
                           ; simplifyTop (lie `andWC` lie_main) }

        -- Emit Typeable bindings
      ; tcg_env <- setGblEnv tcg_env $
                   mkTypeableBinds

      ; traceTc "Tc9" empty
      ; failIfErrsM    -- Stop now if if there have been errors
                       -- Continuing is a waste of time; and we may get debug
                       -- warnings when zonking about strangely-typed TyCons!

        -- Zonk the final code.  This must be done last.
        -- Even simplifyTop may do some unification.
        -- This pass also warns about missing type signatures
      ; (id_env, ev_binds', binds', fords', imp_specs', rules')
            <- zonkTcGblEnv new_ev_binds tcg_env

      --------- Run finalizers --------------
      -- Finalizers must run after constraints are simplified, lest types
      --    might not be complete when using reify (see #12777).
      -- and also after we zonk the first time because we run typed splices
      --    in the zonker which gives rise to the finalisers.
      ; let -- init_tcg_env:
            --   * Remove accumulated bindings, rules and so on from
            --     TcGblEnv.  They are now in ev_binds', binds', etc.
            --   * Add the zonked Ids from the value bindings to tcg_type_env
            --     Up to now these Ids are only in tcl_env's type-envt
            init_tcg_env = TcGblEnv
tcg_env { tcg_binds     = []
                                   , tcg_ev_binds  = emptyBag
                                   , tcg_imp_specs = []
                                   , tcg_rules     = []
                                   , tcg_fords     = []
                                   , tcg_type_env  = tcg_type_env tcg_env
                                                     `plusTypeEnv` id_env }
      ; (tcg_env, tcl_env) <- setGblEnv init_tcg_env
                              run_th_modfinalizers
      ; finishTH
      ; traceTc "Tc11" empty

      --------- Deal with the exports ----------
      -- Can't be done earlier, because the export list must "see"
      -- the declarations created by the finalizers
      ; tcg_env <- restoreEnvs (tcg_env, tcl_env) $
                   rnExports explicit_mod_hdr export_ies

      --------- Emit the ':Main.main = runMainIO main' declaration ----------
      -- Do this /after/ rnExports, so that it can consult
      -- the tcg_exports created by rnExports
      ; (tcg_env, main_ev_binds)
           <- restoreEnvs (tcg_env, tcl_env) $
              do { (tcg_env, lie) <- captureTopConstraints $
                                     checkMain explicit_mod_hdr export_ies
                 ; ev_binds <- simplifyTop lie
                 ; return (tcg_env, ev_binds) }

      ; failIfErrsM    -- Stop now if if there have been errors
                       -- Continuing is a waste of time; and we may get debug
                       -- warnings when zonking about strangely-typed TyCons!

      ---------- Final zonking ---------------
      -- Zonk the new bindings arising from running the finalisers,
      -- and main. This won't give rise to any more finalisers as you
      -- can't nest finalisers inside finalisers.
      ; (id_env_mf, ev_binds_mf, binds_mf, fords_mf, imp_specs_mf, rules_mf)
            <- zonkTcGblEnv main_ev_binds tcg_env

      ; let { !final_type_env = TcGblEnv -> TypeEnv
tcg_type_env TcGblEnv
tcg_env
                                TypeEnv -> TypeEnv -> TypeEnv
`plusTypeEnv` TypeEnv
id_env_mf
              -- Add the zonked Ids from the value bindings (they were in tcl_env)
              -- Force !final_type_env, lest we retain an old reference
              -- to the previous tcg_env

            ; tcg_env' = TcGblEnv
tcg_env
                          { tcg_binds     = binds'     ++ binds_mf
                          , tcg_ev_binds  = ev_binds' `unionBags` ev_binds_mf
                          , tcg_imp_specs = imp_specs' ++ imp_specs_mf
                          , tcg_rules     = rules'     ++ rules_mf
                          , tcg_fords     = fords'     ++ fords_mf } } ;

      ; setGlobalTypeEnv tcg_env' final_type_env
   }

zonkTcGblEnv :: Bag EvBind -> TcGblEnv
             -> TcM (TypeEnv, Bag EvBind, LHsBinds GhcTc,
                       [LForeignDecl GhcTc], [LTcSpecPrag], [LRuleDecl GhcTc])
zonkTcGblEnv :: Bag EvBind
-> TcGblEnv
-> TcM
     (TypeEnv, Bag EvBind, LHsBinds GhcTc, [LForeignDecl GhcTc],
      [LTcSpecPrag], [LRuleDecl GhcTc])
zonkTcGblEnv Bag EvBind
ev_binds tcg_env :: TcGblEnv
tcg_env@(TcGblEnv { tcg_binds :: TcGblEnv -> LHsBinds GhcTc
tcg_binds     = LHsBinds GhcTc
binds
                                        , tcg_ev_binds :: TcGblEnv -> Bag EvBind
tcg_ev_binds  = Bag EvBind
cur_ev_binds
                                        , tcg_imp_specs :: TcGblEnv -> [LTcSpecPrag]
tcg_imp_specs = [LTcSpecPrag]
imp_specs
                                        , tcg_rules :: TcGblEnv -> [LRuleDecl GhcTc]
tcg_rules     = [LRuleDecl GhcTc]
rules
                                        , tcg_fords :: TcGblEnv -> [LForeignDecl GhcTc]
tcg_fords     = [LForeignDecl GhcTc]
fords })
  = {-# SCC "zonkTopDecls" #-}
    TcGblEnv
-> TcM
     (TypeEnv, Bag EvBind, LHsBinds GhcTc, [LForeignDecl GhcTc],
      [LTcSpecPrag], [LRuleDecl GhcTc])
-> TcM
     (TypeEnv, Bag EvBind, LHsBinds GhcTc, [LForeignDecl GhcTc],
      [LTcSpecPrag], [LRuleDecl GhcTc])
forall gbl' lcl a gbl.
gbl' -> TcRnIf gbl' lcl a -> TcRnIf gbl lcl a
setGblEnv TcGblEnv
tcg_env (TcM
   (TypeEnv, Bag EvBind, LHsBinds GhcTc, [LForeignDecl GhcTc],
    [LTcSpecPrag], [LRuleDecl GhcTc])
 -> TcM
      (TypeEnv, Bag EvBind, LHsBinds GhcTc, [LForeignDecl GhcTc],
       [LTcSpecPrag], [LRuleDecl GhcTc]))
-> TcM
     (TypeEnv, Bag EvBind, LHsBinds GhcTc, [LForeignDecl GhcTc],
      [LTcSpecPrag], [LRuleDecl GhcTc])
-> TcM
     (TypeEnv, Bag EvBind, LHsBinds GhcTc, [LForeignDecl GhcTc],
      [LTcSpecPrag], [LRuleDecl GhcTc])
forall a b. (a -> b) -> a -> b
$ -- This sets the GlobalRdrEnv which is used when rendering
                        --   error messages during zonking (notably levity errors)
    do { let all_ev_binds :: Bag EvBind
all_ev_binds = Bag EvBind
cur_ev_binds Bag EvBind -> Bag EvBind -> Bag EvBind
forall a. Bag a -> Bag a -> Bag a
`unionBags` Bag EvBind
ev_binds
       ; Bag EvBind
-> LHsBinds GhcTc
-> [LRuleDecl GhcTc]
-> [LTcSpecPrag]
-> [LForeignDecl GhcTc]
-> TcM
     (TypeEnv, Bag EvBind, LHsBinds GhcTc, [LForeignDecl GhcTc],
      [LTcSpecPrag], [LRuleDecl GhcTc])
zonkTopDecls Bag EvBind
all_ev_binds LHsBinds GhcTc
binds [LRuleDecl GhcTc]
rules [LTcSpecPrag]
imp_specs [LForeignDecl GhcTc]
fords }

-- | Runs TH finalizers and renames and typechecks the top-level declarations
-- that they could introduce.
run_th_modfinalizers :: TcM (TcGblEnv, TcLclEnv)
run_th_modfinalizers :: TcRnIf TcGblEnv TcLclEnv (TcGblEnv, TcLclEnv)
run_th_modfinalizers = do
  th_modfinalizers_var <- (TcGblEnv -> TcRef [(TcLclEnv, ThModFinalizers)])
-> TcM TcGblEnv
-> IOEnv
     (Env TcGblEnv TcLclEnv) (TcRef [(TcLclEnv, ThModFinalizers)])
forall a b.
(a -> b)
-> IOEnv (Env TcGblEnv TcLclEnv) a
-> IOEnv (Env TcGblEnv TcLclEnv) b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap TcGblEnv -> TcRef [(TcLclEnv, ThModFinalizers)]
tcg_th_modfinalizers TcM TcGblEnv
forall gbl lcl. TcRnIf gbl lcl gbl
getGblEnv
  th_modfinalizers <- readTcRef th_modfinalizers_var
  if null th_modfinalizers
  then getEnvs
  else do
    writeTcRef th_modfinalizers_var []
    let run_finalizer (TcLclEnv
lcl_env, ThModFinalizers
f) =
            TcLclEnv
-> IOEnv (Env TcGblEnv TcLclEnv) ()
-> IOEnv (Env TcGblEnv TcLclEnv) ()
forall gbl a.
TcLclEnv -> TcRnIf gbl TcLclEnv a -> TcRnIf gbl TcLclEnv a
restoreLclEnv TcLclEnv
lcl_env (ThModFinalizers -> IOEnv (Env TcGblEnv TcLclEnv) ()
runRemoteModFinalizers ThModFinalizers
f)

    (_, lie_th) <- captureTopConstraints $
                   mapM_ run_finalizer th_modfinalizers

      -- Finalizers can add top-level declarations with addTopDecls, so
      -- we have to run tc_rn_src_decls to get them
    (tcg_env, tcl_env, lie_top_decls) <- tc_rn_src_decls []

    restoreEnvs (tcg_env, tcl_env) $ do
      -- Subsequent rounds of finalizers run after any new constraints are
      -- simplified, or some types might not be complete when using reify
      -- (see #12777).
      new_ev_binds <- {-# SCC "simplifyTop2" #-}
                      simplifyTop (lie_th `andWC` lie_top_decls)
      addTopEvBinds new_ev_binds run_th_modfinalizers
        -- addTopDecls can add declarations which add new finalizers.

tc_rn_src_decls :: [LHsDecl GhcPs]
                -> TcM (TcGblEnv, TcLclEnv, WantedConstraints)
-- Loops around dealing with each top level inter-splice group
-- in turn, until it's dealt with the entire module
-- Never emits constraints; calls captureTopConstraints internally
tc_rn_src_decls :: [LHsDecl GhcPs] -> TcM (TcGblEnv, TcLclEnv, WantedConstraints)
tc_rn_src_decls [LHsDecl GhcPs]
ds
 = {-# SCC "tc_rn_src_decls" #-}
   do { (first_group, group_tail) <- [LHsDecl GhcPs]
-> RnM (HsGroup GhcPs, Maybe (SpliceDecl GhcPs, [LHsDecl GhcPs]))
findSplice [LHsDecl GhcPs]
ds
                -- If ds is [] we get ([], Nothing)

        -- Deal with decls up to, but not including, the first splice
      ; (tcg_env, rn_decls) <- rnTopSrcDecls first_group
                -- rnTopSrcDecls fails if there are any errors

        -- Get TH-generated top-level declarations and make sure they don't
        -- contain any splices since we don't handle that at the moment
        --
        -- The plumbing here is a bit odd: see #10853
      ; th_topdecls_var <- fmap tcg_th_topdecls getGblEnv
      ; th_ds <- readTcRef th_topdecls_var
      ; writeTcRef th_topdecls_var []

      ; (tcg_env, rn_decls) <-
            if null th_ds
            then return (tcg_env, rn_decls)
            else do { (th_group, th_group_tail) <- findSplice th_ds
                    ; case th_group_tail of
                        { Maybe (SpliceDecl GhcPs, [GenLocated SrcSpanAnnA (HsDecl GhcPs)])
Nothing -> () -> IOEnv (Env TcGblEnv TcLclEnv) ()
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return ()
                        ; Just (SpliceDecl XSpliceDecl GhcPs
_ (L SrcSpanAnnA
loc HsUntypedSplice GhcPs
_) SpliceDecoration
_, [GenLocated SrcSpanAnnA (HsDecl GhcPs)]
_) ->
                            SrcSpanAnnA
-> IOEnv (Env TcGblEnv TcLclEnv) ()
-> IOEnv (Env TcGblEnv TcLclEnv) ()
forall ann a. EpAnn ann -> TcRn a -> TcRn a
setSrcSpanA SrcSpanAnnA
loc (IOEnv (Env TcGblEnv TcLclEnv) ()
 -> IOEnv (Env TcGblEnv TcLclEnv) ())
-> IOEnv (Env TcGblEnv TcLclEnv) ()
-> IOEnv (Env TcGblEnv TcLclEnv) ()
forall a b. (a -> b) -> a -> b
$ TcRnMessage -> IOEnv (Env TcGblEnv TcLclEnv) ()
addErr (TcRnMessage -> IOEnv (Env TcGblEnv TcLclEnv) ())
-> TcRnMessage -> IOEnv (Env TcGblEnv TcLclEnv) ()
forall a b. (a -> b) -> a -> b
$
                            THError -> TcRnMessage
TcRnTHError (THError -> TcRnMessage) -> THError -> TcRnMessage
forall a b. (a -> b) -> a -> b
$ AddTopDeclsError -> THError
AddTopDeclsError
                              AddTopDeclsError
AddTopDeclsUnexpectedDeclarationSplice
                        }
                      -- Rename TH-generated top-level declarations
                    ; (tcg_env, th_rn_decls) <- setGblEnv tcg_env
                        $ rnTopSrcDecls th_group

                      -- Dump generated top-level declarations
                    ; let msg = String
"top-level declarations added with 'addTopDecls'"
                    ; traceSplice
                        $ SpliceInfo { spliceDescription = msg
                                     , spliceIsDecl    = True
                                     , spliceSource    = Nothing
                                     , spliceGenerated = ppr th_rn_decls }
                    ; return (tcg_env, appendGroups rn_decls th_rn_decls)
                    }

      -- Type check all declarations
      -- NB: set the env **before** captureTopConstraints so that error messages
      -- get reported w.r.t. the right GlobalRdrEnv. It is for this reason that
      -- the captureTopConstraints must go here, not in tcRnSrcDecls.
      ; ((tcg_env, tcl_env), lie1) <- setGblEnv tcg_env $
                                      captureTopConstraints $
                                      tcTopSrcDecls rn_decls

        -- If there is no splice, we're nearly done
      ; restoreEnvs (tcg_env, tcl_env) $
        case group_tail of
          { Maybe (SpliceDecl GhcPs, [GenLocated SrcSpanAnnA (HsDecl GhcPs)])
Nothing -> (TcGblEnv, TcLclEnv, WantedConstraints)
-> TcM (TcGblEnv, TcLclEnv, WantedConstraints)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (TcGblEnv
tcg_env, TcLclEnv
tcl_env, WantedConstraints
lie1)

            -- If there's a splice, we must carry on
          ; Just (SpliceDecl XSpliceDecl GhcPs
_ (L SrcSpanAnnA
_ HsUntypedSplice GhcPs
splice) SpliceDecoration
_, [GenLocated SrcSpanAnnA (HsDecl GhcPs)]
rest_ds) ->
            do {
                 -- We need to simplify any constraints from the previous declaration
                 -- group, or else we might reify metavariables, as in #16980.
               ; ev_binds1 <- WantedConstraints -> TcRn (Bag EvBind)
simplifyTop WantedConstraints
lie1

                 -- Rename the splice expression, and get its supporting decls
               ; (spliced_decls, splice_fvs) <- rnTopSpliceDecls splice

                 -- Glue them on the front of the remaining decls and loop
               ; setGblEnv (tcg_env `addTcgDUs` usesOnly splice_fvs) $
                 addTopEvBinds ev_binds1                             $
                 tc_rn_src_decls (spliced_decls ++ rest_ds)
               }
          }
      }

{-
************************************************************************
*                                                                      *
        Compiling hs-boot source files, and
        comparing the hi-boot interface with the real thing
*                                                                      *
************************************************************************
-}

tcRnHsBootDecls :: HsBootOrSig -> [LHsDecl GhcPs] -> TcM TcGblEnv
tcRnHsBootDecls :: HsBootOrSig -> [LHsDecl GhcPs] -> TcM TcGblEnv
tcRnHsBootDecls HsBootOrSig
boot_or_sig [LHsDecl GhcPs]
decls
   = do { (first_group, group_tail) <- [LHsDecl GhcPs]
-> RnM (HsGroup GhcPs, Maybe (SpliceDecl GhcPs, [LHsDecl GhcPs]))
findSplice [LHsDecl GhcPs]
decls

                -- Rename the declarations
        ; (tcg_env, HsGroup { hs_tyclds = tycl_decls
                            , hs_derivds = deriv_decls
                            , hs_fords  = for_decls
                            , hs_defds  = def_decls
                            , hs_ruleds = rule_decls
                            , hs_annds  = _
                            , hs_valds  = XValBindsLR (NValBinds val_binds val_sigs) })
              <- rnTopSrcDecls first_group

        ; (gbl_env, lie) <- setGblEnv tcg_env $ captureTopConstraints $ do {
              -- NB: setGblEnv **before** captureTopConstraints so that
              -- if the latter reports errors, it knows what's in scope

                -- Check for illegal declarations
        ; case group_tail of
             Just (SpliceDecl XSpliceDecl GhcPs
_ XRec GhcPs (HsUntypedSplice GhcPs)
d SpliceDecoration
_, [GenLocated SrcSpanAnnA (HsDecl GhcPs)]
_) -> HsBootOrSig
-> (NonEmpty (GenLocated SrcSpanAnnA (HsUntypedSplice GhcPs))
    -> BadBootDecls)
-> [GenLocated SrcSpanAnnA (HsUntypedSplice GhcPs)]
-> IOEnv (Env TcGblEnv TcLclEnv) ()
forall decl.
HsBootOrSig
-> (NonEmpty (LocatedA decl) -> BadBootDecls)
-> [LocatedA decl]
-> IOEnv (Env TcGblEnv TcLclEnv) ()
rejectBootDecls HsBootOrSig
boot_or_sig NonEmpty (GenLocated SrcSpanAnnA (HsUntypedSplice GhcPs))
-> BadBootDecls
BootSpliceDecls [XRec GhcPs (HsUntypedSplice GhcPs)
GenLocated SrcSpanAnnA (HsUntypedSplice GhcPs)
d]
             Maybe (SpliceDecl GhcPs, [GenLocated SrcSpanAnnA (HsDecl GhcPs)])
Nothing                    -> () -> IOEnv (Env TcGblEnv TcLclEnv) ()
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return ()
        ; rejectBootDecls boot_or_sig BootForeignDecls for_decls
        ; rejectBootDecls boot_or_sig BootDefaultDecls def_decls
        ; rejectBootDecls boot_or_sig BootRuleDecls    rule_decls

                -- Typecheck type/class/instance decls
        ; traceTc "Tc2 (boot)" empty
        ; (tcg_env, inst_infos, _deriv_binds, _th_bndrs)
             <- tcTyClsInstDecls tycl_decls deriv_decls def_decls val_binds
        ; setGblEnv tcg_env     $ do {

        -- Emit Typeable bindings
        ; tcg_env <- mkTypeableBinds
        ; setGblEnv tcg_env $ do {

                -- Typecheck value declarations
        ; traceTc "Tc5" empty
        ; val_ids <- tcHsBootSigs val_binds val_sigs

                -- Wrap up
                -- No simplification or zonking to do
        ; traceTc "Tc7a" empty
        ; gbl_env <- getGblEnv

                -- Make the final type-env
                -- Include the dfun_ids so that their type sigs
                -- are written into the interface file.
        ; let { type_env0 = TcGblEnv -> TypeEnv
tcg_type_env TcGblEnv
gbl_env
              ; type_env1 = TypeEnv -> [Id] -> TypeEnv
extendTypeEnvWithIds TypeEnv
type_env0 [Id]
val_ids
              ; type_env2 = TypeEnv -> [Id] -> TypeEnv
extendTypeEnvWithIds TypeEnv
type_env1 [Id]
dfun_ids
              ; dfun_ids = (InstInfo (GhcPass 'Renamed) -> Id)
-> [InstInfo (GhcPass 'Renamed)] -> [Id]
forall a b. (a -> b) -> [a] -> [b]
map InstInfo (GhcPass 'Renamed) -> Id
forall a. InstInfo a -> Id
iDFunId [InstInfo (GhcPass 'Renamed)]
inst_infos
              }

        ; setGlobalTypeEnv gbl_env type_env2
   }}}
   ; traceTc "boot" (ppr lie); return gbl_env }

{-
Once we've typechecked the body of the module, we want to compare what
we've found (gathered in a TypeEnv) with the hi-boot details (if any).
-}

checkHiBootIface :: TcGblEnv -> SelfBootInfo -> TcM TcGblEnv
-- Compare the hi-boot file for this module (if there is one)
-- with the type environment we've just come up with
-- In the common case where there is no hi-boot file, the list
-- of boot_names is empty.

checkHiBootIface :: TcGblEnv -> SelfBootInfo -> TcM TcGblEnv
checkHiBootIface TcGblEnv
tcg_env SelfBootInfo
boot_info
  | SelfBootInfo
NoSelfBoot <- SelfBootInfo
boot_info  -- Common case
  = TcGblEnv -> TcM TcGblEnv
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return TcGblEnv
tcg_env

  | HscSource
HsBootFile <- TcGblEnv -> HscSource
tcg_src TcGblEnv
tcg_env   -- Current module is already a hs-boot file!
  = TcGblEnv -> TcM TcGblEnv
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return TcGblEnv
tcg_env

  | SelfBoot { sb_mds :: SelfBootInfo -> ModDetails
sb_mds = ModDetails
boot_details } <- SelfBootInfo
boot_info
  , TcGblEnv { tcg_binds :: TcGblEnv -> LHsBinds GhcTc
tcg_binds    = LHsBinds GhcTc
binds
             , tcg_insts :: TcGblEnv -> [ClsInst]
tcg_insts    = [ClsInst]
local_insts
             , tcg_type_env :: TcGblEnv -> TypeEnv
tcg_type_env = TypeEnv
local_type_env
             , tcg_exports :: TcGblEnv -> [AvailInfo]
tcg_exports  = [AvailInfo]
local_exports } <- TcGblEnv
tcg_env
  = do  { -- This code is tricky, see Note [DFun knot-tying]
        ; imp_prs <- [ClsInst] -> TypeEnv -> [AvailInfo] -> ModDetails -> TcM [(Id, Id)]
checkHiBootIface' [ClsInst]
local_insts TypeEnv
local_type_env
                                       [AvailInfo]
local_exports ModDetails
boot_details

        -- Now add the impedance-matching boot bindings:
        --
        --  - dfun bindings  $fxblah = $fblah
        --  - record bindings fld{var} = fld{rec field of ..}
        --
        -- to (a) the type envt, and (b) the top-level bindings
        ; let boot_impedance_bds = ((Id, Id) -> Id) -> [(Id, Id)] -> [Id]
forall a b. (a -> b) -> [a] -> [b]
map (Id, Id) -> Id
forall a b. (a, b) -> a
fst [(Id, Id)]
imp_prs
              type_env'          = TypeEnv -> [Id] -> TypeEnv
extendTypeEnvWithIds TypeEnv
local_type_env [Id]
boot_impedance_bds
              impedance_binds    =  [ IdP GhcTc -> LHsExpr GhcTc -> LHsBind GhcTc
mkVarBind IdP GhcTc
Id
boot_id (IdP GhcTc -> LHsExpr GhcTc
forall (p :: Pass) a.
IsSrcSpanAnn p a =>
IdP (GhcPass p) -> LHsExpr (GhcPass p)
nlHsVar IdP GhcTc
Id
id)
                                    | (Id
boot_id, Id
id) <- [(Id, Id)]
imp_prs ]
              tcg_env_w_binds
                = TcGblEnv
tcg_env { tcg_binds = binds ++ impedance_binds }

        ; type_env' `seq`
             -- Why the seq?  Without, we will put a TypeEnv thunk in
             -- tcg_type_env_var.  That thunk will eventually get
             -- forced if we are typechecking interfaces, but that
             -- is no good if we are trying to typecheck the very
             -- DFun we were going to put in.
             -- TODO: Maybe setGlobalTypeEnv should be strict.
          setGlobalTypeEnv tcg_env_w_binds type_env' }

{- Note [DFun impedance matching]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We return a list of "impedance-matching" bindings for the dfuns
defined in the hs-boot file, such as
          $fxEqT = $fEqT
We need these because the module and hi-boot file might differ in
the name it chose for the dfun: the name of a dfun is not
uniquely determined by its type; there might be multiple dfuns
which, individually, would map to the same name (in which case
we have to disambiguate them.)  There's no way for the hi file
to know exactly what disambiguation to use... without looking
at the hi-boot file itself.

In fact, the names will always differ because we always pick names
prefixed with "$fx" for boot dfuns, and "$f" for real dfuns
(so that this impedance matching is always possible).

Note [Record field impedance matching]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When a hs-boot file defines a function whose implementation in the hs file
is a record selector, we have to do something similar to Note [DFun impedance matching].

Example:

  -- M.hs-boot
  module M where
    data A
    fld :: A -> ()

  -- M.hs
  module M where
    data A = MkA { fld :: () }

Recall from Note [Record field namespacing] in GHC.Types.Name.Occurrence that
record fields have their own namespaces. This means that M.hs exports the Id
fld{record selector of MkA} :: A -> (), while M.hs-boot exports the Id
fld{variable} :: A -> ().

To remedy this, we add an impedance-matching binding in M.hs:

  fld{variable} :: A -> ()
  fld{variable} = fld{record selector of MkA}

Note that we imperatively need to add a binding for fld{variable} in M.hs, as we
might have an exact Name reference to it (e.g. in a module that imports M.hs-boot).
Not doing so would cause Core Lint errors, at the very least.

These bindings are returned by the check_export in checkHiBootIface', and
added to the DFun impedance-matching bindings.

[Wrinkle: exports]

  We MUST NOT add fld{variable} to the export list of M.hs, as this
  would mean that M.hs exports both a record field and variable with the same
  occNameFS, which would cause ambiguity errors at use-sites.
  It's OK to only export the field name even though the boot-file exported
  the variable: name resolution will take care of that.

Another situation is that we are re-exporting, e.g. (with M as above):

  -- N.hs-boot
  module N ( module M ) where
    import {-# SOURCE #-} M

  -- N.hs
  module N ( module M where )
    import M

In this case, N.hs-boot re-exports the variable fld, and N re-exports the
record field fld, but not the variable fld. We don't need to do anything in
this situation; in particular, don't re-export the variable name from N.hs,
as per [Wrinkle: exports] above.

Note [DFun knot-tying]
~~~~~~~~~~~~~~~~~~~~~~
The 'SelfBootInfo' that is fed into 'checkHiBootIface' comes from
typechecking the hi-boot file that we are presently implementing.
Suppose we are typechecking the module A: when we typecheck the
hi-boot file, whenever we see an identifier A.T, we knot-tie this
identifier to the *local* type environment (via if_rec_types.)  The
contract then is that we don't *look* at 'SelfBootInfo' until we've
finished typechecking the module and updated the type environment with
the new tycons and ids.

This most works well, but there is one problem: DFuns!  We do not want
to look at the mb_insts of the ModDetails in SelfBootInfo, because a
dfun in one of those ClsInsts is gotten (in GHC.IfaceToCore.tcIfaceInst) by a
(lazily evaluated) lookup in the if_rec_types.  We could extend the
type env, do a setGloblaTypeEnv etc; but that all seems very indirect.
It is much more directly simply to extract the DFunIds from the
md_types of the SelfBootInfo.

See #4003, #16038 for why we need to take care here.
-}

checkHiBootIface' :: [ClsInst] -> TypeEnv -> [AvailInfo]
                  -> ModDetails -> TcM [(Id, Id)]
-- Variant which doesn't require a full TcGblEnv; you could get the
-- local components from another ModDetails.
checkHiBootIface' :: [ClsInst] -> TypeEnv -> [AvailInfo] -> ModDetails -> TcM [(Id, Id)]
checkHiBootIface'
        [ClsInst]
local_insts TypeEnv
local_type_env [AvailInfo]
local_exports
        (ModDetails { md_types :: ModDetails -> TypeEnv
md_types = TypeEnv
boot_type_env
                    , md_fam_insts :: ModDetails -> [FamInst]
md_fam_insts = [FamInst]
boot_fam_insts
                    , md_exports :: ModDetails -> [AvailInfo]
md_exports = [AvailInfo]
boot_exports })
  = do  { String -> SDoc -> IOEnv (Env TcGblEnv TcLclEnv) ()
traceTc String
"checkHiBootIface" (SDoc -> IOEnv (Env TcGblEnv TcLclEnv) ())
-> SDoc -> IOEnv (Env TcGblEnv TcLclEnv) ()
forall a b. (a -> b) -> a -> b
$ [SDoc] -> SDoc
forall doc. IsDoc doc => [doc] -> doc
vcat
             [ TypeEnv -> SDoc
forall a. Outputable a => a -> SDoc
ppr TypeEnv
boot_type_env, [AvailInfo] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [AvailInfo]
boot_exports ]

        ; mod <- TcGblEnv -> Module
tcg_mod (TcGblEnv -> Module)
-> TcM TcGblEnv -> IOEnv (Env TcGblEnv TcLclEnv) Module
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> TcM TcGblEnv
forall gbl lcl. TcRnIf gbl lcl gbl
getGblEnv

        -- don't perform type-checking for ghc-prim:GHC.Prim module.
        -- The interface (see ghcPrimIface in GHC.Iface.Load) exports entities
        -- not found in the module code.
        ; if mod == gHC_PRIM then pure [] else do {

        ; gre_env <- getGlobalRdrEnv

                -- Check the exports of the boot module, one by one
        ; fld_prs <- mapMaybeM (check_export gre_env) boot_exports

                -- Check for no family instances
        ; unless (null boot_fam_insts) $
            panic ("GHC.Tc.Module.checkHiBootIface: Cannot handle family " ++
                   "instances in boot files yet...")
            -- FIXME: Why?  The actual comparison is not hard, but what would
            --        be the equivalent to the dfun bindings returned for class
            --        instances?  We can't easily equate tycons...

                -- Check instance declarations
                -- and generate an impedance-matching binding
        ; dfun_prs <- mapMaybeM check_cls_inst boot_dfuns

        ; failIfErrsM

        ; return (fld_prs ++ dfun_prs) }}

  where
    boot_dfun_names :: [Name]
boot_dfun_names = (Id -> Name) -> [Id] -> [Name]
forall a b. (a -> b) -> [a] -> [b]
map Id -> Name
idName [Id]
boot_dfuns
    boot_dfuns :: [Id]
boot_dfuns      = (Id -> Bool) -> [Id] -> [Id]
forall a. (a -> Bool) -> [a] -> [a]
filter Id -> Bool
isDFunId ([Id] -> [Id]) -> [Id] -> [Id]
forall a b. (a -> b) -> a -> b
$ TypeEnv -> [Id]
typeEnvIds TypeEnv
boot_type_env
       -- NB: boot_dfuns is /not/ defined thus: map instanceDFunId md_insts
       --     We don't want to look at md_insts!
       --     Why not?  See Note [DFun knot-tying]

    check_export :: GlobalRdrEnv
-> AvailInfo -> IOEnv (Env TcGblEnv TcLclEnv) (Maybe (Id, Id))
check_export GlobalRdrEnv
gre_env AvailInfo
boot_avail     -- boot_avail is exported by the boot iface
      | Name
name Name -> [Name] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [Name]
boot_dfun_names
      = Maybe (Id, Id) -> IOEnv (Env TcGblEnv TcLclEnv) (Maybe (Id, Id))
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe (Id, Id)
forall a. Maybe a
Nothing

        -- Check that the actual module exports the same thing
      | Name
missing_name:[Name]
_ <- [Name]
missing_names
      = -- Lookup might have failed because the hs-boot file defines a variable
        -- that is implemented in the hs file as a record selector, which
        -- lives in a different namespace.
        --
        -- See Note [Record field impedance matching].
        let missing_occ :: OccName
missing_occ = Name -> OccName
nameOccName Name
missing_name
            mb_ok :: GlobalRdrElt -> Maybe (GlobalRdrElt, Maybe Id)
            mb_ok :: GlobalRdrElt -> Maybe (GlobalRdrElt, Maybe Id)
mb_ok GlobalRdrElt
gre
              -- Ensure that this GRE refers to an Id that is exported.
              | Maybe AvailInfo -> Bool
forall a. Maybe a -> Bool
isNothing (Maybe AvailInfo -> Bool) -> Maybe AvailInfo -> Bool
forall a b. (a -> b) -> a -> b
$ NameEnv AvailInfo -> Name -> Maybe AvailInfo
forall a. NameEnv a -> Name -> Maybe a
lookupNameEnv NameEnv AvailInfo
local_export_env (GlobalRdrElt -> Name
forall info. GlobalRdrEltX info -> Name
greName GlobalRdrElt
gre)
              = Maybe (GlobalRdrElt, Maybe Id)
forall a. Maybe a
Nothing
              -- We locally define the field: create an impedance-matching
              -- binding for the variable.
              | Just (AnId Id
id) <- TypeEnv -> Name -> Maybe TyThing
lookupTypeEnv TypeEnv
local_type_env (GlobalRdrElt -> Name
forall info. GlobalRdrEltX info -> Name
greName GlobalRdrElt
gre)
              = (GlobalRdrElt, Maybe Id) -> Maybe (GlobalRdrElt, Maybe Id)
forall a. a -> Maybe a
Just (GlobalRdrElt
gre, Id -> Maybe Id
forall a. a -> Maybe a
Just Id
id)
              -- We are re-exporting the field but not the variable: not a problem,
              -- as per [Wrinkle: exports] in Note [Record field impedance matching].
              | Bool
otherwise
              = (GlobalRdrElt, Maybe Id) -> Maybe (GlobalRdrElt, Maybe Id)
forall a. a -> Maybe a
Just (GlobalRdrElt
gre, Maybe Id
forall a. Maybe a
Nothing)
            matching_flds :: [GlobalRdrElt]
matching_flds
              | OccName -> Bool
isVarOcc OccName
missing_occ -- (This only applies to variables.)
              = GlobalRdrEnv -> LookupGRE GREInfo -> [GlobalRdrElt]
forall info.
GlobalRdrEnvX info -> LookupGRE info -> [GlobalRdrEltX info]
lookupGRE GlobalRdrEnv
gre_env (LookupGRE GREInfo -> [GlobalRdrElt])
-> LookupGRE GREInfo -> [GlobalRdrElt]
forall a b. (a -> b) -> a -> b
$
                OccName -> WhichGREs GREInfo -> LookupGRE GREInfo
forall info. OccName -> WhichGREs info -> LookupGRE info
LookupOccName OccName
missing_occ (FieldsOrSelectors -> WhichGREs GREInfo
RelevantGREsFOS FieldsOrSelectors
WantField)
              | Bool
otherwise
              = [] -- BootFldReexport T18999_NoDisambiguateRecordFields T16745A

        in case (GlobalRdrElt -> Maybe (GlobalRdrElt, Maybe Id))
-> [GlobalRdrElt] -> [(GlobalRdrElt, Maybe Id)]
forall a b. (a -> Maybe b) -> [a] -> [b]
mapMaybe GlobalRdrElt -> Maybe (GlobalRdrElt, Maybe Id)
mb_ok ([GlobalRdrElt] -> [(GlobalRdrElt, Maybe Id)])
-> [GlobalRdrElt] -> [(GlobalRdrElt, Maybe Id)]
forall a b. (a -> b) -> a -> b
$ [GlobalRdrElt]
matching_flds of

          -- At least 2 matches: report an ambiguity error.
          (GlobalRdrElt
gre1,Maybe Id
_):(GlobalRdrElt
gre2,Maybe Id
_):[(GlobalRdrElt, Maybe Id)]
gres_ids -> do
           SrcSpan -> TcRnMessage -> IOEnv (Env TcGblEnv TcLclEnv) ()
addErrAt (Name -> SrcSpan
nameSrcSpan Name
missing_name) (TcRnMessage -> IOEnv (Env TcGblEnv TcLclEnv) ())
-> TcRnMessage -> IOEnv (Env TcGblEnv TcLclEnv) ()
forall a b. (a -> b) -> a -> b
$
             GlobalRdrEnv -> RdrName -> NonEmpty GlobalRdrElt -> TcRnMessage
mkNameClashErr GlobalRdrEnv
gre_env (Name -> RdrName
nameRdrName Name
missing_name)
               (GlobalRdrElt
gre1 GlobalRdrElt -> [GlobalRdrElt] -> NonEmpty GlobalRdrElt
forall a. a -> [a] -> NonEmpty a
NE.:| GlobalRdrElt
gre2 GlobalRdrElt -> [GlobalRdrElt] -> [GlobalRdrElt]
forall a. a -> [a] -> [a]
: ((GlobalRdrElt, Maybe Id) -> GlobalRdrElt)
-> [(GlobalRdrElt, Maybe Id)] -> [GlobalRdrElt]
forall a b. (a -> b) -> [a] -> [b]
map (GlobalRdrElt, Maybe Id) -> GlobalRdrElt
forall a b. (a, b) -> a
fst [(GlobalRdrElt, Maybe Id)]
gres_ids)
           Maybe (Id, Id) -> IOEnv (Env TcGblEnv TcLclEnv) (Maybe (Id, Id))
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe (Id, Id)
forall a. Maybe a
Nothing

          -- Single match: resolve the issue.
          [(GlobalRdrElt
_,Maybe Id
mb_fld_id)] ->
            -- See Note [Record field impedance matching].
            Maybe Id
-> (Id -> IOEnv (Env TcGblEnv TcLclEnv) (Id, Id))
-> IOEnv (Env TcGblEnv TcLclEnv) (Maybe (Id, Id))
forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
t a -> (a -> f b) -> f (t b)
for Maybe Id
mb_fld_id ((Id -> IOEnv (Env TcGblEnv TcLclEnv) (Id, Id))
 -> IOEnv (Env TcGblEnv TcLclEnv) (Maybe (Id, Id)))
-> (Id -> IOEnv (Env TcGblEnv TcLclEnv) (Id, Id))
-> IOEnv (Env TcGblEnv TcLclEnv) (Maybe (Id, Id))
forall a b. (a -> b) -> a -> b
$ \ Id
fld_id -> do
              let local_boot_var :: Id
local_boot_var =
                    Name -> Type -> Id
Id.mkExportedVanillaId Name
missing_name (Id -> Type
idType Id
fld_id)
              (Id, Id) -> IOEnv (Env TcGblEnv TcLclEnv) (Id, Id)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Id
local_boot_var, Id
fld_id)

          -- Otherwise: report that the hs file does not export something
          -- that the hs-boot file exports.
          [] -> do
           SrcSpan -> TcRnMessage -> IOEnv (Env TcGblEnv TcLclEnv) ()
addErrAt (Name -> SrcSpan
nameSrcSpan Name
missing_name)
             (HsBootOrSig -> Name -> MissingBootThing -> TcRnMessage
missingBootThing HsBootOrSig
HsBoot Name
missing_name MissingBootThing
MissingBootExport)
           Maybe (Id, Id) -> IOEnv (Env TcGblEnv TcLclEnv) (Maybe (Id, Id))
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe (Id, Id)
forall a. Maybe a
Nothing

        -- If the boot module does not *define* the thing, we are done
        -- (it simply re-exports it, and names match, so nothing further to do)
      | Maybe TyThing -> Bool
forall a. Maybe a -> Bool
isNothing Maybe TyThing
mb_boot_thing
      = Maybe (Id, Id) -> IOEnv (Env TcGblEnv TcLclEnv) (Maybe (Id, Id))
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe (Id, Id)
forall a. Maybe a
Nothing

        -- Check that the actual module also defines the thing, and
        -- then compare the definitions
      | Just TyThing
real_thing <- TypeEnv -> Name -> Maybe TyThing
lookupTypeEnv TypeEnv
local_type_env Name
name,
        Just TyThing
boot_thing <- Maybe TyThing
mb_boot_thing
      = do HsBootOrSig
-> TyThing -> TyThing -> IOEnv (Env TcGblEnv TcLclEnv) ()
checkBootDeclM HsBootOrSig
HsBoot TyThing
boot_thing TyThing
real_thing
           Maybe (Id, Id) -> IOEnv (Env TcGblEnv TcLclEnv) (Maybe (Id, Id))
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe (Id, Id)
forall a. Maybe a
Nothing

      | Bool
otherwise
      = do TcRnMessage -> IOEnv (Env TcGblEnv TcLclEnv) ()
addErrTc (HsBootOrSig -> Name -> MissingBootThing -> TcRnMessage
missingBootThing HsBootOrSig
HsBoot Name
name MissingBootThing
MissingBootDefinition)
           Maybe (Id, Id) -> IOEnv (Env TcGblEnv TcLclEnv) (Maybe (Id, Id))
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe (Id, Id)
forall a. Maybe a
Nothing
      where
        name :: Name
name          = AvailInfo -> Name
availName AvailInfo
boot_avail
        mb_boot_thing :: Maybe TyThing
mb_boot_thing = TypeEnv -> Name -> Maybe TyThing
lookupTypeEnv TypeEnv
boot_type_env Name
name
        missing_names :: [Name]
missing_names = case NameEnv AvailInfo -> Name -> Maybe AvailInfo
forall a. NameEnv a -> Name -> Maybe a
lookupNameEnv NameEnv AvailInfo
local_export_env Name
name of
                          Maybe AvailInfo
Nothing    -> [Name
name]
                          Just AvailInfo
avail -> AvailInfo -> [Name]
availNames AvailInfo
boot_avail
                            [Name] -> [Name] -> [Name]
forall a. Ord a => [a] -> [a] -> [a]
`minusList` AvailInfo -> [Name]
availNames AvailInfo
avail

    local_export_env :: NameEnv AvailInfo
    local_export_env :: NameEnv AvailInfo
local_export_env = [AvailInfo] -> NameEnv AvailInfo
availsToNameEnv [AvailInfo]
local_exports

    check_cls_inst :: DFunId -> TcM (Maybe (Id,Id))
        -- Returns a pair of the boot dfun in terms of the equivalent
        -- real dfun. Delicate (like checkBootDecl) because it depends
        -- on the types lining up precisely even to the ordering of
        -- the type variables in the foralls.
    check_cls_inst :: Id -> IOEnv (Env TcGblEnv TcLclEnv) (Maybe (Id, Id))
check_cls_inst Id
boot_dfun
      | (Id
real_dfun : [Id]
_) <- Id -> [Id]
find_real_dfun Id
boot_dfun
      , let dfun_name :: Name
dfun_name = Id -> Name
idName Id
boot_dfun
            local_boot_dfun :: Id
local_boot_dfun = Name -> Type -> Id
Id.mkExportedVanillaId Name
dfun_name (Id -> Type
idType Id
real_dfun)
      = Maybe (Id, Id) -> IOEnv (Env TcGblEnv TcLclEnv) (Maybe (Id, Id))
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Maybe (Id, Id) -> IOEnv (Env TcGblEnv TcLclEnv) (Maybe (Id, Id)))
-> Maybe (Id, Id) -> IOEnv (Env TcGblEnv TcLclEnv) (Maybe (Id, Id))
forall a b. (a -> b) -> a -> b
$ (Id, Id) -> Maybe (Id, Id)
forall a. a -> Maybe a
Just (Id
local_boot_dfun, Id
real_dfun)
          -- Two tricky points here:
          --
          --  * The local_boot_fun should have a Name from the /boot-file/,
          --    but type from the dfun defined in /this module/.
          --    That ensures that the TyCon etc inside the type are
          --    the ones defined in this module, not the ones gotten
          --    from the hi-boot file, which may have a lot less info
          --    (#8743, comment:10).
          --
          --  * The DFunIds from boot_details are /GlobalIds/, because
          --    they come from typechecking M.hi-boot.
          --    But all bindings in this module should be for /LocalIds/,
          --    otherwise dependency analysis fails (#16038). This
          --    is another reason for using mkExportedVanillaId, rather
          --    that modifying boot_dfun, to make local_boot_fun.
          --
          -- See Note [DFun impedance matching].

      | Bool
otherwise
      = SrcSpan
-> IOEnv (Env TcGblEnv TcLclEnv) (Maybe (Id, Id))
-> IOEnv (Env TcGblEnv TcLclEnv) (Maybe (Id, Id))
forall a. SrcSpan -> TcRn a -> TcRn a
setSrcSpan (Name -> SrcSpan
nameSrcSpan (Id -> Name
forall a. NamedThing a => a -> Name
getName Id
boot_dfun)) (IOEnv (Env TcGblEnv TcLclEnv) (Maybe (Id, Id))
 -> IOEnv (Env TcGblEnv TcLclEnv) (Maybe (Id, Id)))
-> IOEnv (Env TcGblEnv TcLclEnv) (Maybe (Id, Id))
-> IOEnv (Env TcGblEnv TcLclEnv) (Maybe (Id, Id))
forall a b. (a -> b) -> a -> b
$
        do { String -> SDoc -> IOEnv (Env TcGblEnv TcLclEnv) ()
traceTc String
"check_cls_inst" (SDoc -> IOEnv (Env TcGblEnv TcLclEnv) ())
-> SDoc -> IOEnv (Env TcGblEnv TcLclEnv) ()
forall a b. (a -> b) -> a -> b
$ [SDoc] -> SDoc
forall doc. IsDoc doc => [doc] -> doc
vcat
                [ String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"local_insts"  SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+>
                     [SDoc] -> SDoc
forall doc. IsDoc doc => [doc] -> doc
vcat ((ClsInst -> SDoc) -> [ClsInst] -> [SDoc]
forall a b. (a -> b) -> [a] -> [b]
map (Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr (Type -> SDoc) -> (ClsInst -> Type) -> ClsInst -> SDoc
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Id -> Type
idType (Id -> Type) -> (ClsInst -> Id) -> ClsInst -> Type
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ClsInst -> Id
instanceDFunId) [ClsInst]
local_insts)
                , String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"boot_dfun_ty" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr (Id -> Type
idType Id
boot_dfun) ]

           ; TcRnMessage -> IOEnv (Env TcGblEnv TcLclEnv) ()
addErrTc (TcRnMessage -> IOEnv (Env TcGblEnv TcLclEnv) ())
-> TcRnMessage -> IOEnv (Env TcGblEnv TcLclEnv) ()
forall a b. (a -> b) -> a -> b
$ HsBootOrSig -> BootMismatch -> TcRnMessage
TcRnBootMismatch HsBootOrSig
HsBoot
                      (BootMismatch -> TcRnMessage) -> BootMismatch -> TcRnMessage
forall a b. (a -> b) -> a -> b
$ Id -> BootMismatch
MissingBootInstance Id
boot_dfun
           ; Maybe (Id, Id) -> IOEnv (Env TcGblEnv TcLclEnv) (Maybe (Id, Id))
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe (Id, Id)
forall a. Maybe a
Nothing }

    find_real_dfun :: DFunId -> [DFunId]
    find_real_dfun :: Id -> [Id]
find_real_dfun Id
boot_dfun
       = [Id
dfun | ClsInst
inst <- [ClsInst]
local_insts
               , let dfun :: Id
dfun = ClsInst -> Id
instanceDFunId ClsInst
inst
               , Id -> Type
idType Id
dfun HasCallStack => Type -> Type -> Bool
Type -> Type -> Bool
`eqType` Type
boot_dfun_ty ]
       where
          boot_dfun_ty :: Type
boot_dfun_ty   = Id -> Type
idType Id
boot_dfun


-- In general, to perform these checks we have to
-- compare the TyThing from the .hi-boot file to the TyThing
-- in the current source file.  We must be careful to allow alpha-renaming
-- where appropriate, and also the boot declaration is allowed to omit
-- constructors and class methods.
--
-- See rnfail055 for a good test of this stuff.

-- | Compares two things for equivalence between boot-file and normal code,
-- reporting an error if they don't match up.
checkBootDeclM :: HsBootOrSig
               -> TyThing -- ^ boot thing
               -> TyThing -- ^ real thing
               -> TcM ()
checkBootDeclM :: HsBootOrSig
-> TyThing -> TyThing -> IOEnv (Env TcGblEnv TcLclEnv) ()
checkBootDeclM HsBootOrSig
boot_or_sig TyThing
boot_thing TyThing
real_thing
  = [BootMismatchWhat]
-> (BootMismatchWhat -> IOEnv (Env TcGblEnv TcLclEnv) ())
-> IOEnv (Env TcGblEnv TcLclEnv) ()
forall (t :: * -> *) (f :: * -> *) a b.
(Foldable t, Applicative f) =>
t a -> (a -> f b) -> f ()
for_ [BootMismatchWhat]
boot_errs ((BootMismatchWhat -> IOEnv (Env TcGblEnv TcLclEnv) ())
 -> IOEnv (Env TcGblEnv TcLclEnv) ())
-> (BootMismatchWhat -> IOEnv (Env TcGblEnv TcLclEnv) ())
-> IOEnv (Env TcGblEnv TcLclEnv) ()
forall a b. (a -> b) -> a -> b
$ \ BootMismatchWhat
boot_err ->
      SrcSpan -> TcRnMessage -> IOEnv (Env TcGblEnv TcLclEnv) ()
addErrAt SrcSpan
span (TcRnMessage -> IOEnv (Env TcGblEnv TcLclEnv) ())
-> TcRnMessage -> IOEnv (Env TcGblEnv TcLclEnv) ()
forall a b. (a -> b) -> a -> b
$
        HsBootOrSig -> BootMismatch -> TcRnMessage
TcRnBootMismatch HsBootOrSig
boot_or_sig (BootMismatch -> TcRnMessage) -> BootMismatch -> TcRnMessage
forall a b. (a -> b) -> a -> b
$
        TyThing -> TyThing -> BootMismatchWhat -> BootMismatch
BootMismatch TyThing
boot_thing TyThing
real_thing BootMismatchWhat
boot_err
  where
    boot_errs :: [BootMismatchWhat]
boot_errs = Writer [BootMismatchWhat] () -> [BootMismatchWhat]
forall w a. Monoid w => Writer w a -> w
execWriter (Writer [BootMismatchWhat] () -> [BootMismatchWhat])
-> Writer [BootMismatchWhat] () -> [BootMismatchWhat]
forall a b. (a -> b) -> a -> b
$ HsBootOrSig -> TyThing -> TyThing -> Writer [BootMismatchWhat] ()
checkBootDecl HsBootOrSig
boot_or_sig TyThing
boot_thing TyThing
real_thing

    -- Here we use the span of the boot thing or, if it doesn't have a sensible
    -- span, that of the real thing,
    span :: SrcSpan
span
      | let span :: SrcSpan
span = Name -> SrcSpan
nameSrcSpan (TyThing -> Name
forall a. NamedThing a => a -> Name
getName TyThing
boot_thing)
      , SrcSpan -> Bool
isGoodSrcSpan SrcSpan
span
      = SrcSpan
span
      | Bool
otherwise
      = Name -> SrcSpan
nameSrcSpan (TyThing -> Name
forall a. NamedThing a => a -> Name
getName TyThing
real_thing)

-- | Writer monad for accumulating errors when comparing an hs-boot or
-- signature file with its implementing module.
type BootErrsM err = Writer [err] ()

-- | If the test in the first parameter is True, succeed.
-- Otherwise, record the given error.
check :: Bool -> err -> BootErrsM err
check :: forall err. Bool -> err -> BootErrsM err
check Bool
True  err
_   = BootErrsM err
forall err. BootErrsM err
checkSuccess
check Bool
False err
err = err -> BootErrsM err
forall err. err -> BootErrsM err
bootErr err
err

-- | Record an error.
bootErr :: err -> BootErrsM err
bootErr :: forall err. err -> BootErrsM err
bootErr err
err = [err] -> WriterT [err] Identity ()
forall w (m :: * -> *). (Monoid w, Monad m) => w -> WriterT w m ()
tell [err
err]

-- | A convenience synonym for a lack of errors, for @checkBootDecl@ and friends.
checkSuccess :: BootErrsM err
checkSuccess :: forall err. BootErrsM err
checkSuccess = () -> WriterT [err] Identity ()
forall a. a -> WriterT [err] Identity a
forall (m :: * -> *) a. Monad m => a -> m a
return ()

-- | Map over the error types in an error-accumulating computation.
embedErrs :: (err1 -> err2) -> BootErrsM err1 -> BootErrsM err2
embedErrs :: forall err1 err2.
(err1 -> err2) -> BootErrsM err1 -> BootErrsM err2
embedErrs err1 -> err2
f = (((), [err1]) -> ((), [err2]))
-> Writer [err1] () -> Writer [err2] ()
forall w w' a b.
(Monoid w, Monoid w') =>
((a, w) -> (b, w')) -> Writer w a -> Writer w' b
mapWriter (([err1] -> [err2]) -> ((), [err1]) -> ((), [err2])
forall b c d. (b -> c) -> (d, b) -> (d, c)
forall (a :: * -> * -> *) b c d.
Arrow a =>
a b c -> a (d, b) (d, c)
second ((err1 -> err2) -> [err1] -> [err2]
forall a b. (a -> b) -> [a] -> [b]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap err1 -> err2
f))

-- | Wrap up a list of errors into a single message.
wrapErrs :: (NE.NonEmpty err1 -> err2) -> BootErrsM err1 -> BootErrsM err2
wrapErrs :: forall err1 err2.
(NonEmpty err1 -> err2) -> BootErrsM err1 -> BootErrsM err2
wrapErrs NonEmpty err1 -> err2
f BootErrsM err1
w =
  case BootErrsM err1 -> [err1]
forall w a. Monoid w => Writer w a -> w
execWriter BootErrsM err1
w of
    []         -> BootErrsM err2
forall err. BootErrsM err
checkSuccess
    err1
err : [err1]
errs -> err2 -> BootErrsM err2
forall err. err -> BootErrsM err
bootErr (NonEmpty err1 -> err2
f (NonEmpty err1 -> err2) -> NonEmpty err1 -> err2
forall a b. (a -> b) -> a -> b
$ err1
err err1 -> [err1] -> NonEmpty err1
forall a. a -> [a] -> NonEmpty a
:| [err1]
errs)

-- | Compares the two things for equivalence between boot-file and normal
-- code. Returns @Nothing@ on success or @Just "some helpful info for user"@
-- failure. If the difference will be apparent to the user, @Just empty@ is
-- perfectly suitable.
checkBootDecl :: HsBootOrSig -> TyThing -> TyThing -> BootErrsM BootMismatchWhat

checkBootDecl :: HsBootOrSig -> TyThing -> TyThing -> Writer [BootMismatchWhat] ()
checkBootDecl HsBootOrSig
_ (AnId Id
id1) (AnId Id
id2)
  = Bool
-> Writer [BootMismatchWhat] () -> Writer [BootMismatchWhat] ()
forall a. HasCallStack => Bool -> a -> a
assert (Id
id1 Id -> Id -> Bool
forall a. Eq a => a -> a -> Bool
== Id
id2) (Writer [BootMismatchWhat] () -> Writer [BootMismatchWhat] ())
-> Writer [BootMismatchWhat] () -> Writer [BootMismatchWhat] ()
forall a b. (a -> b) -> a -> b
$
    Bool -> BootMismatchWhat -> Writer [BootMismatchWhat] ()
forall err. Bool -> err -> BootErrsM err
check (Id -> Type
idType Id
id1 HasCallStack => Type -> Type -> Bool
Type -> Type -> Bool
`eqType` Id -> Type
idType Id
id2)
          (Id -> Id -> BootMismatchWhat
BootMismatchedIdTypes Id
id1 Id
id2)

checkBootDecl HsBootOrSig
boot_or_sig (ATyCon TyCon
tc1) (ATyCon TyCon
tc2)
  = (NonEmpty BootTyConMismatch -> BootMismatchWhat)
-> BootErrsM BootTyConMismatch -> Writer [BootMismatchWhat] ()
forall err1 err2.
(NonEmpty err1 -> err2) -> BootErrsM err1 -> BootErrsM err2
wrapErrs (TyCon -> TyCon -> NonEmpty BootTyConMismatch -> BootMismatchWhat
BootMismatchedTyCons TyCon
tc1 TyCon
tc2) (BootErrsM BootTyConMismatch -> Writer [BootMismatchWhat] ())
-> BootErrsM BootTyConMismatch -> Writer [BootMismatchWhat] ()
forall a b. (a -> b) -> a -> b
$
    HsBootOrSig -> TyCon -> TyCon -> BootErrsM BootTyConMismatch
checkBootTyCon HsBootOrSig
boot_or_sig TyCon
tc1 TyCon
tc2

checkBootDecl HsBootOrSig
_ TyThing
t1 TyThing
t2
  = String -> SDoc -> Writer [BootMismatchWhat] ()
forall a. HasCallStack => String -> SDoc -> a
pprPanic String
"checkBootDecl" (TyThing -> SDoc
forall a. Outputable a => a -> SDoc
ppr TyThing
t1 SDoc -> SDoc -> SDoc
forall doc. IsDoc doc => doc -> doc -> doc
$$ TyThing -> SDoc
forall a. Outputable a => a -> SDoc
ppr TyThing
t2)

-- | Run the check provided for every pair of elements in the lists.
--
-- Records an error:
--
--  - when any two items at the same position in the two lists don't match
--    according to the given function,
--  - when the lists are of different lengths.
checkListBy :: (a -> a -> BootErrsM err) -> [a] -> [a]
            -> (BootListMismatches a err -> err2)
            -> BootErrsM err2
checkListBy :: forall a err err2.
(a -> a -> BootErrsM err)
-> [a]
-> [a]
-> (BootListMismatches a err -> err2)
-> BootErrsM err2
checkListBy a -> a -> BootErrsM err
check_fun [a]
as [a]
bs BootListMismatches a err -> err2
mk_err = (BootListMismatches a err -> err2)
-> BootErrsM (BootListMismatch a err) -> BootErrsM err2
forall err1 err2.
(NonEmpty err1 -> err2) -> BootErrsM err1 -> BootErrsM err2
wrapErrs BootListMismatches a err -> err2
mk_err (BootErrsM (BootListMismatch a err) -> BootErrsM err2)
-> BootErrsM (BootListMismatch a err) -> BootErrsM err2
forall a b. (a -> b) -> a -> b
$ Arity -> [a] -> [a] -> BootErrsM (BootListMismatch a err)
go Arity
1 [a]
as [a]
bs
  where
    go :: Arity -> [a] -> [a] -> BootErrsM (BootListMismatch a err)
go Arity
_  [] [] = BootErrsM (BootListMismatch a err)
forall err. BootErrsM err
checkSuccess
    go !Arity
i (a
x:[a]
xs) (a
y:[a]
ys) =
      do { (err -> BootListMismatch a err)
-> BootErrsM err -> BootErrsM (BootListMismatch a err)
forall err1 err2.
(err1 -> err2) -> BootErrsM err1 -> BootErrsM err2
embedErrs (Arity -> a -> a -> err -> BootListMismatch a err
forall item err.
Arity -> item -> item -> err -> BootListMismatch item err
MismatchedThing Arity
i a
x a
y) (BootErrsM err -> BootErrsM (BootListMismatch a err))
-> BootErrsM err -> BootErrsM (BootListMismatch a err)
forall a b. (a -> b) -> a -> b
$ a -> a -> BootErrsM err
check_fun a
x a
y
         ; Arity -> [a] -> [a] -> BootErrsM (BootListMismatch a err)
go (Arity
iArity -> Arity -> Arity
forall a. Num a => a -> a -> a
+Arity
1) [a]
xs [a]
ys }
    go Arity
_  [a]
_  [a]
_ = BootListMismatch a err -> BootErrsM (BootListMismatch a err)
forall err. err -> BootErrsM err
bootErr BootListMismatch a err
forall item err. BootListMismatch item err
MismatchedLength

----------------
checkBootTyCon :: HsBootOrSig -> TyCon -> TyCon -> BootErrsM BootTyConMismatch
checkBootTyCon :: HsBootOrSig -> TyCon -> TyCon -> BootErrsM BootTyConMismatch
checkBootTyCon HsBootOrSig
boot_or_sig TyCon
tc1 TyCon
tc2
  | Bool -> Bool
not (HasCallStack => Type -> Type -> Bool
Type -> Type -> Bool
eqType (TyCon -> Type
tyConKind TyCon
tc1) (TyCon -> Type
tyConKind TyCon
tc2))
  -- First off, check the kind
  = BootTyConMismatch -> BootErrsM BootTyConMismatch
forall err. err -> BootErrsM err
bootErr BootTyConMismatch
TyConKindMismatch

  | Just Class
c1 <- TyCon -> Maybe Class
tyConClass_maybe TyCon
tc1
  , Just Class
c2 <- TyCon -> Maybe Class
tyConClass_maybe TyCon
tc2
  , let ([Id]
clas_tvs1, [FunDep Id]
clas_fds1, [Type]
sc_theta1, [Id]
_, [ClassATItem]
ats1, [ClassOpItem]
op_stuff1)
          = Class
-> ([Id], [FunDep Id], [Type], [Id], [ClassATItem], [ClassOpItem])
classExtraBigSig Class
c1
        ([Id]
clas_tvs2, [FunDep Id]
clas_fds2, [Type]
sc_theta2, [Id]
_, [ClassATItem]
ats2, [ClassOpItem]
op_stuff2)
          = Class
-> ([Id], [FunDep Id], [Type], [Id], [ClassATItem], [ClassOpItem])
classExtraBigSig Class
c2
  , Just RnEnv2
env <- HasCallStack => RnEnv2 -> [Id] -> [Id] -> Maybe RnEnv2
RnEnv2 -> [Id] -> [Id] -> Maybe RnEnv2
eqVarBndrs RnEnv2
emptyRnEnv2 [Id]
clas_tvs1 [Id]
clas_tvs2
  = do { BootErrsM BootTyConMismatch
check_roles
       ; (BootClassMismatch -> BootTyConMismatch)
-> BootErrsM BootClassMismatch -> BootErrsM BootTyConMismatch
forall err1 err2.
(err1 -> err2) -> BootErrsM err1 -> BootErrsM err2
embedErrs (Class -> Class -> BootClassMismatch -> BootTyConMismatch
TyConMismatchedClasses Class
c1 Class
c2) (BootErrsM BootClassMismatch -> BootErrsM BootTyConMismatch)
-> BootErrsM BootClassMismatch -> BootErrsM BootTyConMismatch
forall a b. (a -> b) -> a -> b
$
    do { -- Checks kind of class
       ; Bool -> BootClassMismatch -> BootErrsM BootClassMismatch
forall err. Bool -> err -> BootErrsM err
check ((FunDep Id -> FunDep Id -> Bool)
-> [FunDep Id] -> [FunDep Id] -> Bool
forall a b. (a -> b -> Bool) -> [a] -> [b] -> Bool
forall (f :: * -> *) a b.
Eq1 f =>
(a -> b -> Bool) -> f a -> f b -> Bool
liftEq (RnEnv2 -> FunDep Id -> FunDep Id -> Bool
eqFD RnEnv2
env) [FunDep Id]
clas_fds1 [FunDep Id]
clas_fds2)
           BootClassMismatch
MismatchedFunDeps
       ; Bool -> BootErrsM BootClassMismatch -> BootErrsM BootClassMismatch
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (TyCon -> Bool
isAbstractTyCon TyCon
tc1) (BootErrsM BootClassMismatch -> BootErrsM BootClassMismatch)
-> BootErrsM BootClassMismatch -> BootErrsM BootClassMismatch
forall a b. (a -> b) -> a -> b
$
    do { Bool -> BootClassMismatch -> BootErrsM BootClassMismatch
forall err. Bool -> err -> BootErrsM err
check ((Type -> Type -> Bool) -> [Type] -> [Type] -> Bool
forall a b. (a -> b -> Bool) -> [a] -> [b] -> Bool
forall (f :: * -> *) a b.
Eq1 f =>
(a -> b -> Bool) -> f a -> f b -> Bool
liftEq (HasCallStack => RnEnv2 -> Type -> Type -> Bool
RnEnv2 -> Type -> Type -> Bool
eqTypeX RnEnv2
env) [Type]
sc_theta1 [Type]
sc_theta2)
           BootClassMismatch
MismatchedSuperclasses
       ; (ClassOpItem -> ClassOpItem -> BootErrsM BootMethodMismatch)
-> [ClassOpItem]
-> [ClassOpItem]
-> (BootListMismatches ClassOpItem BootMethodMismatch
    -> BootClassMismatch)
-> BootErrsM BootClassMismatch
forall a err err2.
(a -> a -> BootErrsM err)
-> [a]
-> [a]
-> (BootListMismatches a err -> err2)
-> BootErrsM err2
checkListBy (RnEnv2
-> HsBootOrSig
-> ClassOpItem
-> ClassOpItem
-> BootErrsM BootMethodMismatch
compatClassOp RnEnv2
env HsBootOrSig
boot_or_sig) [ClassOpItem]
op_stuff1 [ClassOpItem]
op_stuff2
           BootListMismatches ClassOpItem BootMethodMismatch
-> BootClassMismatch
MismatchedMethods
       ; (ClassATItem -> ClassATItem -> BootErrsM BootATMismatch)
-> [ClassATItem]
-> [ClassATItem]
-> (BootListMismatches ClassATItem BootATMismatch
    -> BootClassMismatch)
-> BootErrsM BootClassMismatch
forall a err err2.
(a -> a -> BootErrsM err)
-> [a]
-> [a]
-> (BootListMismatches a err -> err2)
-> BootErrsM err2
checkListBy (RnEnv2
-> HsBootOrSig
-> ClassATItem
-> ClassATItem
-> BootErrsM BootATMismatch
compatAT RnEnv2
env HsBootOrSig
boot_or_sig) [ClassATItem]
ats1 [ClassATItem]
ats2
           BootListMismatches ClassATItem BootATMismatch -> BootClassMismatch
MismatchedATs
       ; Bool -> BootClassMismatch -> BootErrsM BootClassMismatch
forall err. Bool -> err -> BootErrsM err
check (Class -> ClassMinimalDef
classMinimalDef Class
c1 ClassMinimalDef -> ClassMinimalDef -> Bool
forall (p :: Pass).
Uniquable (IdP (GhcPass p)) =>
BooleanFormula (GhcPass p) -> BooleanFormula (GhcPass p) -> Bool
`BF.implies` Class -> ClassMinimalDef
classMinimalDef Class
c2)
           BootClassMismatch
MismatchedMinimalPragmas
       } } }

  | Just Type
syn_rhs1 <- TyCon -> Maybe Type
synTyConRhs_maybe TyCon
tc1
  , Just Type
syn_rhs2 <- TyCon -> Maybe Type
synTyConRhs_maybe TyCon
tc2
  , Just RnEnv2
env <- HasCallStack => RnEnv2 -> [Id] -> [Id] -> Maybe RnEnv2
RnEnv2 -> [Id] -> [Id] -> Maybe RnEnv2
eqVarBndrs RnEnv2
emptyRnEnv2 (TyCon -> [Id]
tyConTyVars TyCon
tc1) (TyCon -> [Id]
tyConTyVars TyCon
tc2)
  = Bool -> BootErrsM BootTyConMismatch -> BootErrsM BootTyConMismatch
forall a. HasCallStack => Bool -> a -> a
assert (TyCon
tc1 TyCon -> TyCon -> Bool
forall a. Eq a => a -> a -> Bool
== TyCon
tc2) (BootErrsM BootTyConMismatch -> BootErrsM BootTyConMismatch)
-> BootErrsM BootTyConMismatch -> BootErrsM BootTyConMismatch
forall a b. (a -> b) -> a -> b
$
  do { BootErrsM BootTyConMismatch
check_roles
     ; Bool -> BootTyConMismatch -> BootErrsM BootTyConMismatch
forall err. Bool -> err -> BootErrsM err
check (HasCallStack => RnEnv2 -> Type -> Type -> Bool
RnEnv2 -> Type -> Type -> Bool
eqTypeX RnEnv2
env Type
syn_rhs1 Type
syn_rhs2) (BootTyConMismatch -> BootErrsM BootTyConMismatch)
-> BootTyConMismatch -> BootErrsM BootTyConMismatch
forall a b. (a -> b) -> a -> b
$
        Type -> Type -> BootTyConMismatch
TyConSynonymMismatch Type
syn_rhs1 Type
syn_rhs2 }

  -- This allows abstract 'data T a' to be implemented using 'type T = ...'
  -- and abstract 'class K a' to be implement using 'type K = ...'
  -- See Note [Synonyms implement abstract data]
  | HsBootOrSig
Hsig <- HsBootOrSig
boot_or_sig -- don't support for hs-boot yet
  , TyCon -> Bool
isAbstractTyCon TyCon
tc1
  , Just ([Id]
tvs, Type
ty) <- TyCon -> Maybe ([Id], Type)
synTyConDefn_maybe TyCon
tc2
  = TyCon -> TyCon -> [Id] -> Type -> BootErrsM BootTyConMismatch
checkSynAbsData TyCon
tc1 TyCon
tc2 [Id]
tvs Type
ty

  | Just FamTyConFlav
fam_flav1 <- TyCon -> Maybe FamTyConFlav
famTyConFlav_maybe TyCon
tc1
  , Just FamTyConFlav
fam_flav2 <- TyCon -> Maybe FamTyConFlav
famTyConFlav_maybe TyCon
tc2
  = Bool -> BootErrsM BootTyConMismatch -> BootErrsM BootTyConMismatch
forall a. HasCallStack => Bool -> a -> a
assert (TyCon
tc1 TyCon -> TyCon -> Bool
forall a. Eq a => a -> a -> Bool
== TyCon
tc2) (BootErrsM BootTyConMismatch -> BootErrsM BootTyConMismatch)
-> BootErrsM BootTyConMismatch -> BootErrsM BootTyConMismatch
forall a b. (a -> b) -> a -> b
$
    do { let injInfo1 :: Injectivity
injInfo1 = TyCon -> Injectivity
tyConInjectivityInfo TyCon
tc1
             injInfo2 :: Injectivity
injInfo2 = TyCon -> Injectivity
tyConInjectivityInfo TyCon
tc2
       ; -- check equality of roles, family flavours and injectivity annotations
         -- (NB: Type family roles are always nominal. But the check is
         -- harmless enough.)
       ; BootErrsM BootTyConMismatch
check_roles
       ; FamTyConFlav -> FamTyConFlav -> BootErrsM BootTyConMismatch
compatFamFlav FamTyConFlav
fam_flav1 FamTyConFlav
fam_flav2
       ; Bool -> BootTyConMismatch -> BootErrsM BootTyConMismatch
forall err. Bool -> err -> BootErrsM err
check (Injectivity
injInfo1 Injectivity -> Injectivity -> Bool
forall a. Eq a => a -> a -> Bool
== Injectivity
injInfo2) BootTyConMismatch
TyConInjectivityMismatch }

  | TyCon -> Bool
isAlgTyCon TyCon
tc1 Bool -> Bool -> Bool
&& TyCon -> Bool
isAlgTyCon TyCon
tc2
  , Just RnEnv2
env <- HasCallStack => RnEnv2 -> [Id] -> [Id] -> Maybe RnEnv2
RnEnv2 -> [Id] -> [Id] -> Maybe RnEnv2
eqVarBndrs RnEnv2
emptyRnEnv2 (TyCon -> [Id]
tyConTyVars TyCon
tc1) (TyCon -> [Id]
tyConTyVars TyCon
tc2)
  = Bool -> BootErrsM BootTyConMismatch -> BootErrsM BootTyConMismatch
forall a. HasCallStack => Bool -> a -> a
assert (TyCon
tc1 TyCon -> TyCon -> Bool
forall a. Eq a => a -> a -> Bool
== TyCon
tc2) (BootErrsM BootTyConMismatch -> BootErrsM BootTyConMismatch)
-> BootErrsM BootTyConMismatch -> BootErrsM BootTyConMismatch
forall a b. (a -> b) -> a -> b
$
  do { BootErrsM BootTyConMismatch
check_roles
     ; let rhs1 :: AlgTyConRhs
rhs1 = TyCon -> AlgTyConRhs
algTyConRhs TyCon
tc1
           rhs2 :: AlgTyConRhs
rhs2 = TyCon -> AlgTyConRhs
algTyConRhs TyCon
tc2
     ; (BootDataMismatch -> BootTyConMismatch)
-> BootErrsM BootDataMismatch -> BootErrsM BootTyConMismatch
forall err1 err2.
(err1 -> err2) -> BootErrsM err1 -> BootErrsM err2
embedErrs (AlgTyConRhs -> AlgTyConRhs -> BootDataMismatch -> BootTyConMismatch
TyConMismatchedData AlgTyConRhs
rhs1 AlgTyConRhs
rhs2) (BootErrsM BootDataMismatch -> BootErrsM BootTyConMismatch)
-> BootErrsM BootDataMismatch -> BootErrsM BootTyConMismatch
forall a b. (a -> b) -> a -> b
$
  do { Bool -> BootDataMismatch -> BootErrsM BootDataMismatch
forall err. Bool -> err -> BootErrsM err
check ((Type -> Type -> Bool) -> [Type] -> [Type] -> Bool
forall a b. (a -> b -> Bool) -> [a] -> [b] -> Bool
forall (f :: * -> *) a b.
Eq1 f =>
(a -> b -> Bool) -> f a -> f b -> Bool
liftEq (HasCallStack => RnEnv2 -> Type -> Type -> Bool
RnEnv2 -> Type -> Type -> Bool
eqTypeX RnEnv2
env)
                     (TyCon -> [Type]
tyConStupidTheta TyCon
tc1) (TyCon -> [Type]
tyConStupidTheta TyCon
tc2))
                      BootDataMismatch
MismatchedDatatypeContexts
     ; AlgTyConRhs -> AlgTyConRhs -> BootErrsM BootDataMismatch
compatAlgRhs AlgTyConRhs
rhs1 AlgTyConRhs
rhs2 } }

  | Bool
otherwise = BootTyConMismatch -> BootErrsM BootTyConMismatch
forall err. err -> BootErrsM err
bootErr BootTyConMismatch
TyConsVeryDifferent
                -- two very different types;
                -- should be obvious to the user what the problem is
  where
    check_roles :: BootErrsM BootTyConMismatch
check_roles = HsBootOrSig -> TyCon -> [Role] -> BootErrsM BootTyConMismatch
checkRoles HsBootOrSig
boot_or_sig TyCon
tc1 (TyCon -> [Role]
tyConRoles TyCon
tc2)


emptyRnEnv2 :: RnEnv2
emptyRnEnv2 :: RnEnv2
emptyRnEnv2 = InScopeSet -> RnEnv2
mkRnEnv2 InScopeSet
emptyInScopeSet

-- | Check that two class methods have compatible type signatures.
compatClassOp :: RnEnv2 -> HsBootOrSig -> ClassOpItem -> ClassOpItem -> BootErrsM BootMethodMismatch
compatClassOp :: RnEnv2
-> HsBootOrSig
-> ClassOpItem
-> ClassOpItem
-> BootErrsM BootMethodMismatch
compatClassOp RnEnv2
env HsBootOrSig
boot_or_sig (Id
id1, DefMethInfo
def_meth1) (Id
id2, DefMethInfo
def_meth2)
  = do { Bool -> BootMethodMismatch -> BootErrsM BootMethodMismatch
forall err. Bool -> err -> BootErrsM err
check (Name
name1 Name -> Name -> Bool
forall a. Eq a => a -> a -> Bool
== Name
name2) (BootMethodMismatch -> BootErrsM BootMethodMismatch)
-> BootMethodMismatch -> BootErrsM BootMethodMismatch
forall a b. (a -> b) -> a -> b
$
           BootMethodMismatch
MismatchedMethodNames
       ; Bool -> BootMethodMismatch -> BootErrsM BootMethodMismatch
forall err. Bool -> err -> BootErrsM err
check (HasCallStack => RnEnv2 -> Type -> Type -> Bool
RnEnv2 -> Type -> Type -> Bool
eqTypeX RnEnv2
env Type
op_ty1 Type
op_ty2) (BootMethodMismatch -> BootErrsM BootMethodMismatch)
-> BootMethodMismatch -> BootErrsM BootMethodMismatch
forall a b. (a -> b) -> a -> b
$
           Type -> Type -> BootMethodMismatch
MismatchedMethodTypes Type
op_ty1 Type
op_ty2
       ; case HsBootOrSig
boot_or_sig of
           HsBootOrSig
HsBoot ->
             Bool -> BootMethodMismatch -> BootErrsM BootMethodMismatch
forall err. Bool -> err -> BootErrsM err
check (((Name, DefMethSpec Type) -> (Name, DefMethSpec Type) -> Bool)
-> DefMethInfo -> DefMethInfo -> Bool
forall a b. (a -> b -> Bool) -> Maybe a -> Maybe b -> Bool
forall (f :: * -> *) a b.
Eq1 f =>
(a -> b -> Bool) -> f a -> f b -> Bool
liftEq (Name, DefMethSpec Type) -> (Name, DefMethSpec Type) -> Bool
eqDM DefMethInfo
def_meth1 DefMethInfo
def_meth2) (BootMethodMismatch -> BootErrsM BootMethodMismatch)
-> BootMethodMismatch -> BootErrsM BootMethodMismatch
forall a b. (a -> b) -> a -> b
$
               Bool -> BootMethodMismatch
MismatchedDefaultMethods Bool
False
           HsBootOrSig
Hsig ->
             Bool -> BootMethodMismatch -> BootErrsM BootMethodMismatch
forall err. Bool -> err -> BootErrsM err
check (Type -> DefMethInfo -> DefMethInfo -> Bool
subDM Type
op_ty1 DefMethInfo
def_meth1 DefMethInfo
def_meth2) (BootMethodMismatch -> BootErrsM BootMethodMismatch)
-> BootMethodMismatch -> BootErrsM BootMethodMismatch
forall a b. (a -> b) -> a -> b
$
               Bool -> BootMethodMismatch
MismatchedDefaultMethods Bool
True }
  where
    name1 :: Name
name1 = Id -> Name
idName Id
id1
    name2 :: Name
name2 = Id -> Name
idName Id
id2
    op_ty1 :: Type
op_ty1 = Id -> Type
classMethodTy Id
id1
    op_ty2 :: Type
op_ty2 = Id -> Type
classMethodTy Id
id2

    eqDM :: (Name, DefMethSpec Type) -> (Name, DefMethSpec Type) -> Bool
eqDM (Name
_, DefMethSpec Type
VanillaDM)    (Name
_, DefMethSpec Type
VanillaDM)    = Bool
True
    eqDM (Name
_, GenericDM Type
t1) (Name
_, GenericDM Type
t2) = HasCallStack => RnEnv2 -> Type -> Type -> Bool
RnEnv2 -> Type -> Type -> Bool
eqTypeX RnEnv2
env Type
t1 Type
t2
    eqDM (Name, DefMethSpec Type)
_ (Name, DefMethSpec Type)
_ = Bool
False

    -- NB: first argument is from hsig, second is from real impl.
    -- Order of pattern matching matters.
    subDM :: Type -> DefMethInfo -> DefMethInfo -> Bool
subDM Type
_ DefMethInfo
Nothing DefMethInfo
_ = Bool
True
    subDM Type
_ DefMethInfo
_ DefMethInfo
Nothing = Bool
False

    -- If the hsig wrote:
    --
    --   f :: a -> a
    --   default f :: a -> a
    --
    -- this should be validly implementable using an old-fashioned
    -- vanilla default method.
    subDM Type
t1 (Just (Name
_, GenericDM Type
gdm_t1)) (Just (Name
_, DefMethSpec Type
VanillaDM))
     = HasCallStack => Type -> Type -> Bool
Type -> Type -> Bool
eqType Type
t1 Type
gdm_t1   -- Take care (#22476).  Both t1 and gdm_t1 come
                             -- from tc1, so use eqType, and /not/ eqTypeX

    -- This case can occur when merging signatures
    subDM Type
t1 (Just (Name
_, DefMethSpec Type
VanillaDM)) (Just (Name
_, GenericDM Type
t2))
     = HasCallStack => RnEnv2 -> Type -> Type -> Bool
RnEnv2 -> Type -> Type -> Bool
eqTypeX RnEnv2
env Type
t1 Type
t2

    subDM Type
_ (Just (Name
_, DefMethSpec Type
VanillaDM)) (Just (Name
_, DefMethSpec Type
VanillaDM)) = Bool
True
    subDM Type
_ (Just (Name
_, GenericDM Type
t1)) (Just (Name
_, GenericDM Type
t2))
     = HasCallStack => RnEnv2 -> Type -> Type -> Bool
RnEnv2 -> Type -> Type -> Bool
eqTypeX RnEnv2
env Type
t1 Type
t2

-- | Check that two associated types are compatible.
compatAT :: RnEnv2 -> HsBootOrSig -> ClassATItem -> ClassATItem
         -> BootErrsM BootATMismatch
compatAT :: RnEnv2
-> HsBootOrSig
-> ClassATItem
-> ClassATItem
-> BootErrsM BootATMismatch
compatAT RnEnv2
env HsBootOrSig
boot_or_sig (ATI TyCon
tc1 Maybe (Type, TyFamEqnValidityInfo)
def_ats1) (ATI TyCon
tc2 Maybe (Type, TyFamEqnValidityInfo)
def_ats2)
  = do { (BootTyConMismatch -> BootATMismatch)
-> BootErrsM BootTyConMismatch -> BootErrsM BootATMismatch
forall err1 err2.
(err1 -> err2) -> BootErrsM err1 -> BootErrsM err2
embedErrs BootTyConMismatch -> BootATMismatch
MismatchedTyConAT (BootErrsM BootTyConMismatch -> BootErrsM BootATMismatch)
-> BootErrsM BootTyConMismatch -> BootErrsM BootATMismatch
forall a b. (a -> b) -> a -> b
$
           HsBootOrSig -> TyCon -> TyCon -> BootErrsM BootTyConMismatch
checkBootTyCon HsBootOrSig
boot_or_sig TyCon
tc1 TyCon
tc2
       ; Bool -> BootATMismatch -> BootErrsM BootATMismatch
forall err. Bool -> err -> BootErrsM err
check (Maybe (Type, TyFamEqnValidityInfo)
-> Maybe (Type, TyFamEqnValidityInfo) -> Bool
compatATDef Maybe (Type, TyFamEqnValidityInfo)
def_ats1 Maybe (Type, TyFamEqnValidityInfo)
def_ats2)
           BootATMismatch
MismatchedATDefaultType }

  where
    -- Ignore the location of the defaults
    compatATDef :: Maybe (Type, TyFamEqnValidityInfo)
-> Maybe (Type, TyFamEqnValidityInfo) -> Bool
compatATDef Maybe (Type, TyFamEqnValidityInfo)
Nothing             Maybe (Type, TyFamEqnValidityInfo)
Nothing             = Bool
True
    compatATDef (Just (Type
ty1, TyFamEqnValidityInfo
_loc1)) (Just (Type
ty2, TyFamEqnValidityInfo
_loc2)) = HasCallStack => RnEnv2 -> Type -> Type -> Bool
RnEnv2 -> Type -> Type -> Bool
eqTypeX RnEnv2
env Type
ty1 Type
ty2
    compatATDef Maybe (Type, TyFamEqnValidityInfo)
_ Maybe (Type, TyFamEqnValidityInfo)
_ = Bool
False

-- | Check that two functional dependencies are the same.
eqFD :: RnEnv2 -> FunDep TyVar -> FunDep TyVar -> Bool
eqFD :: RnEnv2 -> FunDep Id -> FunDep Id -> Bool
eqFD RnEnv2
env ([Id]
as1,[Id]
bs1) ([Id]
as2,[Id]
bs2) =
  (Type -> Type -> Bool) -> [Type] -> [Type] -> Bool
forall a b. (a -> b -> Bool) -> [a] -> [b] -> Bool
forall (f :: * -> *) a b.
Eq1 f =>
(a -> b -> Bool) -> f a -> f b -> Bool
liftEq (HasCallStack => RnEnv2 -> Type -> Type -> Bool
RnEnv2 -> Type -> Type -> Bool
eqTypeX RnEnv2
env) ([Id] -> [Type]
mkTyVarTys [Id]
as1) ([Id] -> [Type]
mkTyVarTys [Id]
as2) Bool -> Bool -> Bool
&&
  (Type -> Type -> Bool) -> [Type] -> [Type] -> Bool
forall a b. (a -> b -> Bool) -> [a] -> [b] -> Bool
forall (f :: * -> *) a b.
Eq1 f =>
(a -> b -> Bool) -> f a -> f b -> Bool
liftEq (HasCallStack => RnEnv2 -> Type -> Type -> Bool
RnEnv2 -> Type -> Type -> Bool
eqTypeX RnEnv2
env) ([Id] -> [Type]
mkTyVarTys [Id]
bs1) ([Id] -> [Type]
mkTyVarTys [Id]
bs2)

-- | Check compatibility of two type family flavours.
compatFamFlav :: FamTyConFlav -> FamTyConFlav -> BootErrsM BootTyConMismatch
compatFamFlav :: FamTyConFlav -> FamTyConFlav -> BootErrsM BootTyConMismatch
compatFamFlav FamTyConFlav
OpenSynFamilyTyCon   FamTyConFlav
OpenSynFamilyTyCon
  = BootErrsM BootTyConMismatch
forall err. BootErrsM err
checkSuccess
compatFamFlav (DataFamilyTyCon {}) (DataFamilyTyCon {})
  = BootErrsM BootTyConMismatch
forall err. BootErrsM err
checkSuccess
compatFamFlav FamTyConFlav
AbstractClosedSynFamilyTyCon FamTyConFlav
AbstractClosedSynFamilyTyCon
  = BootErrsM BootTyConMismatch
forall err. BootErrsM err
checkSuccess -- This case only happens for hsig merging.
compatFamFlav FamTyConFlav
AbstractClosedSynFamilyTyCon (ClosedSynFamilyTyCon {})
  = BootErrsM BootTyConMismatch
forall err. BootErrsM err
checkSuccess
compatFamFlav (ClosedSynFamilyTyCon {}) FamTyConFlav
AbstractClosedSynFamilyTyCon
  = BootErrsM BootTyConMismatch
forall err. BootErrsM err
checkSuccess
compatFamFlav (ClosedSynFamilyTyCon Maybe (CoAxiom Branched)
ax1) (ClosedSynFamilyTyCon Maybe (CoAxiom Branched)
ax2)
  = Maybe (CoAxiom Branched)
-> Maybe (CoAxiom Branched) -> BootErrsM BootTyConMismatch
forall (br :: BranchFlag) (br1 :: BranchFlag).
Maybe (CoAxiom br)
-> Maybe (CoAxiom br1) -> BootErrsM BootTyConMismatch
eqClosedFamilyAx Maybe (CoAxiom Branched)
ax1 Maybe (CoAxiom Branched)
ax2
compatFamFlav (BuiltInSynFamTyCon {}) (BuiltInSynFamTyCon {})
  = BootErrsM BootTyConMismatch
forall err. BootErrsM err
checkSuccess
compatFamFlav FamTyConFlav
flav1 FamTyConFlav
flav2
  = BootTyConMismatch -> BootErrsM BootTyConMismatch
forall err. err -> BootErrsM err
bootErr (BootTyConMismatch -> BootErrsM BootTyConMismatch)
-> BootTyConMismatch -> BootErrsM BootTyConMismatch
forall a b. (a -> b) -> a -> b
$ FamTyConFlav -> FamTyConFlav -> BootTyConMismatch
TyConFlavourMismatch FamTyConFlav
flav1 FamTyConFlav
flav2

-- | Check that two 'AlgTyConRhs's are compatible.
compatAlgRhs :: AlgTyConRhs -> AlgTyConRhs -> BootErrsM BootDataMismatch
compatAlgRhs :: AlgTyConRhs -> AlgTyConRhs -> BootErrsM BootDataMismatch
compatAlgRhs (AbstractTyCon {}) AlgTyConRhs
_rhs2 =
  BootErrsM BootDataMismatch
forall err. BootErrsM err
checkSuccess -- rhs2 is guaranteed to be injective, since it's an AlgTyCon
compatAlgRhs  tc1 :: AlgTyConRhs
tc1@DataTyCon{} tc2 :: AlgTyConRhs
tc2@DataTyCon{} =
  (DataCon -> DataCon -> BootErrsM BootDataConMismatch)
-> [DataCon]
-> [DataCon]
-> (BootListMismatches DataCon BootDataConMismatch
    -> BootDataMismatch)
-> BootErrsM BootDataMismatch
forall a err err2.
(a -> a -> BootErrsM err)
-> [a]
-> [a]
-> (BootListMismatches a err -> err2)
-> BootErrsM err2
checkListBy DataCon -> DataCon -> BootErrsM BootDataConMismatch
compatCon (AlgTyConRhs -> [DataCon]
data_cons AlgTyConRhs
tc1) (AlgTyConRhs -> [DataCon]
data_cons AlgTyConRhs
tc2) BootListMismatches DataCon BootDataConMismatch -> BootDataMismatch
MismatchedConstructors
compatAlgRhs  tc1 :: AlgTyConRhs
tc1@NewTyCon{ data_con :: AlgTyConRhs -> DataCon
data_con = DataCon
dc1 } tc2 :: AlgTyConRhs
tc2@NewTyCon{ data_con :: AlgTyConRhs -> DataCon
data_con = DataCon
dc2 } =
  (BootDataConMismatch -> BootDataMismatch)
-> BootErrsM BootDataConMismatch -> BootErrsM BootDataMismatch
forall err1 err2.
(err1 -> err2) -> BootErrsM err1 -> BootErrsM err2
embedErrs (BootListMismatches DataCon BootDataConMismatch -> BootDataMismatch
MismatchedConstructors (BootListMismatches DataCon BootDataConMismatch
 -> BootDataMismatch)
-> (BootDataConMismatch
    -> BootListMismatches DataCon BootDataConMismatch)
-> BootDataConMismatch
-> BootDataMismatch
forall b c a. (b -> c) -> (a -> b) -> a -> c
. BootListMismatch DataCon BootDataConMismatch
-> BootListMismatches DataCon BootDataConMismatch
forall a. a -> NonEmpty a
NE.singleton (BootListMismatch DataCon BootDataConMismatch
 -> BootListMismatches DataCon BootDataConMismatch)
-> (BootDataConMismatch
    -> BootListMismatch DataCon BootDataConMismatch)
-> BootDataConMismatch
-> BootListMismatches DataCon BootDataConMismatch
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Arity
-> DataCon
-> DataCon
-> BootDataConMismatch
-> BootListMismatch DataCon BootDataConMismatch
forall item err.
Arity -> item -> item -> err -> BootListMismatch item err
MismatchedThing Arity
1 DataCon
dc1 DataCon
dc2) (BootErrsM BootDataConMismatch -> BootErrsM BootDataMismatch)
-> BootErrsM BootDataConMismatch -> BootErrsM BootDataMismatch
forall a b. (a -> b) -> a -> b
$
    DataCon -> DataCon -> BootErrsM BootDataConMismatch
compatCon (AlgTyConRhs -> DataCon
data_con AlgTyConRhs
tc1) (AlgTyConRhs -> DataCon
data_con AlgTyConRhs
tc2)
compatAlgRhs AlgTyConRhs
_ AlgTyConRhs
_ = BootDataMismatch -> BootErrsM BootDataMismatch
forall err. err -> BootErrsM err
bootErr BootDataMismatch
MismatchedNewtypeVsData

-- | Check that two 'DataCon's are compatible.
compatCon :: DataCon -> DataCon -> BootErrsM BootDataConMismatch
compatCon :: DataCon -> DataCon -> BootErrsM BootDataConMismatch
compatCon DataCon
c1 DataCon
c2
  = do { Bool -> BootDataConMismatch -> BootErrsM BootDataConMismatch
forall err. Bool -> err -> BootErrsM err
check (DataCon -> Name
dataConName DataCon
c1 Name -> Name -> Bool
forall a. Eq a => a -> a -> Bool
== DataCon -> Name
dataConName DataCon
c2)
           BootDataConMismatch
MismatchedDataConNames
       ; Bool -> BootDataConMismatch -> BootErrsM BootDataConMismatch
forall err. Bool -> err -> BootErrsM err
check (DataCon -> Bool
dataConIsInfix DataCon
c1 Bool -> Bool -> Bool
forall a. Eq a => a -> a -> Bool
== DataCon -> Bool
dataConIsInfix DataCon
c2)
           BootDataConMismatch
MismatchedDataConFixities
       ; Bool -> BootDataConMismatch -> BootErrsM BootDataConMismatch
forall err. Bool -> err -> BootErrsM err
check ((HsImplBang -> HsImplBang -> Bool)
-> [HsImplBang] -> [HsImplBang] -> Bool
forall a b. (a -> b -> Bool) -> [a] -> [b] -> Bool
forall (f :: * -> *) a b.
Eq1 f =>
(a -> b -> Bool) -> f a -> f b -> Bool
liftEq HsImplBang -> HsImplBang -> Bool
eqHsBang (DataCon -> [HsImplBang]
dataConImplBangs DataCon
c1) (DataCon -> [HsImplBang]
dataConImplBangs DataCon
c2))
           BootDataConMismatch
MismatchedDataConBangs
       ; Bool -> BootDataConMismatch -> BootErrsM BootDataConMismatch
forall err. Bool -> err -> BootErrsM err
check ((FieldLabel -> Name) -> [FieldLabel] -> [Name]
forall a b. (a -> b) -> [a] -> [b]
map FieldLabel -> Name
flSelector (DataCon -> [FieldLabel]
dataConFieldLabels DataCon
c1) [Name] -> [Name] -> Bool
forall a. Eq a => a -> a -> Bool
== (FieldLabel -> Name) -> [FieldLabel] -> [Name]
forall a b. (a -> b) -> [a] -> [b]
map FieldLabel -> Name
flSelector (DataCon -> [FieldLabel]
dataConFieldLabels DataCon
c2))
           BootDataConMismatch
MismatchedDataConFieldLabels
       ; Bool -> BootDataConMismatch -> BootErrsM BootDataConMismatch
forall err. Bool -> err -> BootErrsM err
check (HasCallStack => Type -> Type -> Bool
Type -> Type -> Bool
eqType (DataCon -> Type
dataConWrapperType DataCon
c1) (DataCon -> Type
dataConWrapperType DataCon
c2))
           BootDataConMismatch
MismatchedDataConTypes }

eqClosedFamilyAx :: Maybe (CoAxiom br) -> Maybe (CoAxiom br1)
                 -> BootErrsM BootTyConMismatch
eqClosedFamilyAx :: forall (br :: BranchFlag) (br1 :: BranchFlag).
Maybe (CoAxiom br)
-> Maybe (CoAxiom br1) -> BootErrsM BootTyConMismatch
eqClosedFamilyAx Maybe (CoAxiom br)
Nothing Maybe (CoAxiom br1)
Nothing  = BootErrsM BootTyConMismatch
forall err. BootErrsM err
checkSuccess
eqClosedFamilyAx Maybe (CoAxiom br)
Nothing (Just CoAxiom br1
_) = BootTyConMismatch -> BootErrsM BootTyConMismatch
forall err. err -> BootErrsM err
bootErr (BootTyConMismatch -> BootErrsM BootTyConMismatch)
-> BootTyConMismatch -> BootErrsM BootTyConMismatch
forall a b. (a -> b) -> a -> b
$ BootListMismatches CoAxBranch BootAxiomBranchMismatch
-> BootTyConMismatch
TyConAxiomMismatch (BootListMismatches CoAxBranch BootAxiomBranchMismatch
 -> BootTyConMismatch)
-> BootListMismatches CoAxBranch BootAxiomBranchMismatch
-> BootTyConMismatch
forall a b. (a -> b) -> a -> b
$ BootListMismatch CoAxBranch BootAxiomBranchMismatch
-> BootListMismatches CoAxBranch BootAxiomBranchMismatch
forall a. a -> NonEmpty a
NE.singleton BootListMismatch CoAxBranch BootAxiomBranchMismatch
forall item err. BootListMismatch item err
MismatchedLength
eqClosedFamilyAx (Just CoAxiom br
_) Maybe (CoAxiom br1)
Nothing = BootTyConMismatch -> BootErrsM BootTyConMismatch
forall err. err -> BootErrsM err
bootErr (BootTyConMismatch -> BootErrsM BootTyConMismatch)
-> BootTyConMismatch -> BootErrsM BootTyConMismatch
forall a b. (a -> b) -> a -> b
$ BootListMismatches CoAxBranch BootAxiomBranchMismatch
-> BootTyConMismatch
TyConAxiomMismatch (BootListMismatches CoAxBranch BootAxiomBranchMismatch
 -> BootTyConMismatch)
-> BootListMismatches CoAxBranch BootAxiomBranchMismatch
-> BootTyConMismatch
forall a b. (a -> b) -> a -> b
$ BootListMismatch CoAxBranch BootAxiomBranchMismatch
-> BootListMismatches CoAxBranch BootAxiomBranchMismatch
forall a. a -> NonEmpty a
NE.singleton BootListMismatch CoAxBranch BootAxiomBranchMismatch
forall item err. BootListMismatch item err
MismatchedLength
eqClosedFamilyAx (Just (CoAxiom { co_ax_branches :: forall (br :: BranchFlag). CoAxiom br -> Branches br
co_ax_branches = Branches br
branches1 }))
                 (Just (CoAxiom { co_ax_branches :: forall (br :: BranchFlag). CoAxiom br -> Branches br
co_ax_branches = Branches br1
branches2 }))
  = (CoAxBranch -> CoAxBranch -> BootErrsM BootAxiomBranchMismatch)
-> [CoAxBranch]
-> [CoAxBranch]
-> (BootListMismatches CoAxBranch BootAxiomBranchMismatch
    -> BootTyConMismatch)
-> BootErrsM BootTyConMismatch
forall a err err2.
(a -> a -> BootErrsM err)
-> [a]
-> [a]
-> (BootListMismatches a err -> err2)
-> BootErrsM err2
checkListBy CoAxBranch -> CoAxBranch -> BootErrsM BootAxiomBranchMismatch
eqClosedFamilyBranch [CoAxBranch]
branch_list1 [CoAxBranch]
branch_list2
      BootListMismatches CoAxBranch BootAxiomBranchMismatch
-> BootTyConMismatch
TyConAxiomMismatch
  where
    branch_list1 :: [CoAxBranch]
branch_list1 = Branches br -> [CoAxBranch]
forall (br :: BranchFlag). Branches br -> [CoAxBranch]
fromBranches Branches br
branches1
    branch_list2 :: [CoAxBranch]
branch_list2 = Branches br1 -> [CoAxBranch]
forall (br :: BranchFlag). Branches br -> [CoAxBranch]
fromBranches Branches br1
branches2

eqClosedFamilyBranch :: CoAxBranch -> CoAxBranch -> BootErrsM BootAxiomBranchMismatch
eqClosedFamilyBranch :: CoAxBranch -> CoAxBranch -> BootErrsM BootAxiomBranchMismatch
eqClosedFamilyBranch (CoAxBranch { cab_tvs :: CoAxBranch -> [Id]
cab_tvs = [Id]
tvs1, cab_cvs :: CoAxBranch -> [Id]
cab_cvs = [Id]
cvs1
                                 , cab_lhs :: CoAxBranch -> [Type]
cab_lhs = [Type]
lhs1, cab_rhs :: CoAxBranch -> Type
cab_rhs = Type
rhs1 })
                     (CoAxBranch { cab_tvs :: CoAxBranch -> [Id]
cab_tvs = [Id]
tvs2, cab_cvs :: CoAxBranch -> [Id]
cab_cvs = [Id]
cvs2
                                 , cab_lhs :: CoAxBranch -> [Type]
cab_lhs = [Type]
lhs2, cab_rhs :: CoAxBranch -> Type
cab_rhs = Type
rhs2 })
  | Just RnEnv2
env1 <- HasCallStack => RnEnv2 -> [Id] -> [Id] -> Maybe RnEnv2
RnEnv2 -> [Id] -> [Id] -> Maybe RnEnv2
eqVarBndrs RnEnv2
emptyRnEnv2 [Id]
tvs1 [Id]
tvs2
  , Just RnEnv2
env  <- HasCallStack => RnEnv2 -> [Id] -> [Id] -> Maybe RnEnv2
RnEnv2 -> [Id] -> [Id] -> Maybe RnEnv2
eqVarBndrs RnEnv2
env1        [Id]
cvs1 [Id]
cvs2
  = do { Bool
-> BootAxiomBranchMismatch -> BootErrsM BootAxiomBranchMismatch
forall err. Bool -> err -> BootErrsM err
check ((Type -> Type -> Bool) -> [Type] -> [Type] -> Bool
forall a b. (a -> b -> Bool) -> [a] -> [b] -> Bool
forall (f :: * -> *) a b.
Eq1 f =>
(a -> b -> Bool) -> f a -> f b -> Bool
liftEq (HasCallStack => RnEnv2 -> Type -> Type -> Bool
RnEnv2 -> Type -> Type -> Bool
eqTypeX RnEnv2
env) [Type]
lhs1 [Type]
lhs2) BootAxiomBranchMismatch
MismatchedAxiomLHS
       ; Bool
-> BootAxiomBranchMismatch -> BootErrsM BootAxiomBranchMismatch
forall err. Bool -> err -> BootErrsM err
check (HasCallStack => RnEnv2 -> Type -> Type -> Bool
RnEnv2 -> Type -> Type -> Bool
eqTypeX RnEnv2
env Type
rhs1 Type
rhs2)          BootAxiomBranchMismatch
MismatchedAxiomRHS }
  | Bool
otherwise
  = BootAxiomBranchMismatch -> BootErrsM BootAxiomBranchMismatch
forall err. err -> BootErrsM err
bootErr BootAxiomBranchMismatch
MismatchedAxiomBinders

{- Note [Role subtyping]
~~~~~~~~~~~~~~~~~~~~~~~~
In the current formulation of roles, role subtyping is only OK if the
"abstract" TyCon was not representationally injective.  Among the most
notable examples of non representationally injective TyCons are abstract
data, which can be implemented via newtypes (which are not
representationally injective).  The key example is
in this example from #13140:

     -- In an hsig file
     data T a -- abstract!
     type role T nominal

     -- Elsewhere
     foo :: Coercible (T a) (T b) => a -> b
     foo x = x

We must NOT allow foo to typecheck, because if we instantiate
T with a concrete data type with a phantom role would cause
Coercible (T a) (T b) to be provable.  Fortunately, if T is not
representationally injective, we cannot make the inference that a ~N b if
T a ~R T b.

Unconditional role subtyping would be possible if we setup
an extra set of roles saying when we can project out coercions
(we call these proj-roles); then it would NOT be valid to instantiate T
with a data type at phantom since the proj-role subtyping check
would fail.  See #13140 for more details.

One consequence of this is we get no role subtyping for non-abstract
data types in signatures. Suppose you have:

     signature A where
         type role T nominal
         data T a = MkT

If you write this, we'll treat T as injective, and make inferences
like T a ~R T b ==> a ~N b (mkSelCo).  But if we can
subsequently replace T with one at phantom role, we would then be able to
infer things like T Int ~R T Bool which is bad news.

We could allow role subtyping here if we didn't treat *any* data types
defined in signatures as injective.  But this would be a bit surprising,
replacing a data type in a module with one in a signature could cause
your code to stop typechecking (whereas if you made the type abstract,
it is more understandable that the type checker knows less).

It would have been best if this was purely a question of defaults
(i.e., a user could explicitly ask for one behavior or another) but
the current role system isn't expressive enough to do this.
Having explicit proj-roles would solve this problem.
-}

checkRoles :: HsBootOrSig -> TyCon -> [Role] -> BootErrsM BootTyConMismatch
checkRoles :: HsBootOrSig -> TyCon -> [Role] -> BootErrsM BootTyConMismatch
checkRoles HsBootOrSig
boot_or_sig TyCon
tc1 [Role]
r2
  |  HsBootOrSig
boot_or_sig HsBootOrSig -> HsBootOrSig -> Bool
forall a. Eq a => a -> a -> Bool
== HsBootOrSig
HsBoot
  Bool -> Bool -> Bool
|| TyCon -> Role -> Bool
isInjectiveTyCon TyCon
tc1 Role
Representational -- See Note [Role subtyping]
  = Bool -> BootTyConMismatch -> BootErrsM BootTyConMismatch
forall err. Bool -> err -> BootErrsM err
check ([Role]
r1 [Role] -> [Role] -> Bool
forall a. Eq a => a -> a -> Bool
== [Role]
r2) (Bool -> BootTyConMismatch
TyConRoleMismatch Bool
False)
  | Bool
otherwise
  = Bool -> BootTyConMismatch -> BootErrsM BootTyConMismatch
forall err. Bool -> err -> BootErrsM err
check ([Role]
r2 [Role] -> [Role] -> Bool
forall {a}. Ord a => [a] -> [a] -> Bool
`rolesSubtypeOf` [Role]
r1) (Bool -> BootTyConMismatch
TyConRoleMismatch Bool
True)
  where

    r1 :: [Role]
r1 = TyCon -> [Role]
tyConRoles TyCon
tc1

    rolesSubtypeOf :: [a] -> [a] -> Bool
rolesSubtypeOf [] [] = Bool
True
    -- NB: this relation is the OPPOSITE of the subroling relation
    rolesSubtypeOf (a
x:[a]
xs) (a
y:[a]
ys) = a
x a -> a -> Bool
forall a. Ord a => a -> a -> Bool
>= a
y Bool -> Bool -> Bool
&& [a] -> [a] -> Bool
rolesSubtypeOf [a]
xs [a]
ys
    rolesSubtypeOf [a]
_ [a]
_ = Bool
False

{- Note [Synonyms implement abstract data]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
An abstract data type or class can be implemented using a type synonym,
but ONLY if:

  1. T, as a standalone occurrence, is a valid type
     (T is "curryable"), and

  2. T is valid in an instance head.

This gives rise to the following conditions under which we can implement
an abstract data declaration @data T@ using a type synonym @type T tvs = rhs@:

  1. The type synonym T is nullary (tvs is null).

  2. The rhs must not contain any foralls, quantified types, or type family
     applications.
     See 'invalidAbsDataSubTypes' which computes a collection of
     invalid subtypes.

See also 'HowAbstract' and Note [Skolem abstract data].
-}

-- | We are implementing an abstract data declaration of the form @data T@
-- in a signature file, with a type synonym @type T tvs = rhs@ in the
-- implementing module.
--
-- This function checks that the implementation is valid:
--
--  1. the type synonym T is nullary, i.e. tvs is null,
--  2. rhs doesn't contain any type families, foralls, or qualified types.
--
-- See Note [Synonyms implement abstract data]
checkSynAbsData :: TyCon   -- ^ @tc1@, the abstract data 'TyCon' we are implementing
                -> TyCon   -- ^ @tc2@, a type synonym @type T tvs = ty@
                           --   we are using to implement @tc1@
                -> [TyVar] -- ^ @tvs@
                -> Type    -- ^ @ty@
                -> BootErrsM BootTyConMismatch
checkSynAbsData :: TyCon -> TyCon -> [Id] -> Type -> BootErrsM BootTyConMismatch
checkSynAbsData TyCon
tc1 TyCon
tc2 [Id]
syn_tvs Type
syn_rhs
  -- We are implementing @data T@ with @type T tvs = rhs@.
  -- Check the conditions of Note [Synonyms implement abstract data].
  = do { -- (1): T is nullary.
       ; Bool -> BootTyConMismatch -> BootErrsM BootTyConMismatch
forall err. Bool -> err -> BootErrsM err
check ([Id] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Id]
syn_tvs) (BootTyConMismatch -> BootErrsM BootTyConMismatch)
-> BootTyConMismatch -> BootErrsM BootTyConMismatch
forall a b. (a -> b) -> a -> b
$
           SynAbstractDataError -> BootTyConMismatch
SynAbstractData SynAbstractDataError
SynAbsDataTySynNotNullary
         -- (2): the RHS of the type synonym is valid.
       ; case Type -> [Type]
invalidAbsDataSubTypes Type
syn_rhs of
          []       -> BootErrsM BootTyConMismatch
forall err. BootErrsM err
checkSuccess
          Type
err:[Type]
errs -> BootTyConMismatch -> BootErrsM BootTyConMismatch
forall err. err -> BootErrsM err
bootErr (BootTyConMismatch -> BootErrsM BootTyConMismatch)
-> BootTyConMismatch -> BootErrsM BootTyConMismatch
forall a b. (a -> b) -> a -> b
$ SynAbstractDataError -> BootTyConMismatch
SynAbstractData (SynAbstractDataError -> BootTyConMismatch)
-> SynAbstractDataError -> BootTyConMismatch
forall a b. (a -> b) -> a -> b
$
                      NonEmpty Type -> SynAbstractDataError
SynAbstractDataInvalidRHS (Type
err Type -> [Type] -> NonEmpty Type
forall a. a -> [a] -> NonEmpty a
:| [Type]
errs)
         -- NB: this allows implementing e.g. @data T :: Nat@ with @type T = 3@.
         -- See #15138.

  -- TODO: When it's a synonym implementing a class, we really
  -- should check that the fundeps are satisfied, but
  -- there is not an obvious way to do this for a constraint synonym.
  -- So for now, let it all through (it won't cause segfaults, anyway).
  -- Tracked at #12704.

         -- ... we also need to check roles.
       ; if | Just (TyCon
tc2', [Type]
args) <- HasDebugCallStack => Type -> Maybe (TyCon, [Type])
Type -> Maybe (TyCon, [Type])
tcSplitTyConApp_maybe Type
syn_rhs
            , [Id] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Id]
syn_tvs -- Don't report role errors unless the type synonym is nullary
            -> Bool -> BootErrsM BootTyConMismatch -> BootErrsM BootTyConMismatch
forall a. HasCallStack => Bool -> a -> a
assert ([Role] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null (TyCon -> [Role]
tyConRoles TyCon
tc2)) (BootErrsM BootTyConMismatch -> BootErrsM BootTyConMismatch)
-> BootErrsM BootTyConMismatch -> BootErrsM BootTyConMismatch
forall a b. (a -> b) -> a -> b
$
               -- If we have something like:
               --
               --  signature H where
               --      data T a
               --  module H where
               --      data K a b = ...
               --      type T = K Int
               --
               -- we need to drop the first role of K when comparing!
               HsBootOrSig -> TyCon -> [Role] -> BootErrsM BootTyConMismatch
checkRoles HsBootOrSig
Hsig TyCon
tc1 (Arity -> [Role] -> [Role]
forall a. Arity -> [a] -> [a]
drop ([Type] -> Arity
forall a. [a] -> Arity
forall (t :: * -> *) a. Foldable t => t a -> Arity
length [Type]
args) (TyCon -> [Role]
tyConRoles TyCon
tc2'))
            | Bool
otherwise
            -> BootErrsM BootTyConMismatch
forall err. BootErrsM err
checkSuccess
       }

{-
    -- Hypothetically, if we were allow to non-nullary type synonyms, here
    -- is how you would check the roles
    if length tvs == length roles1
    then checkRoles roles1 roles2
    else case tcSplitTyConApp_maybe ty of
            Just (tc2', args) ->
                checkRoles Hsig tc1 (drop (length args) (tyConRoles tc2') ++ roles2)
            Nothing -> Just roles_msg
-}

-- | Is this type a valid implementation of abstract data?
--
-- Returns a list of invalid sub-types encountered.
invalidAbsDataSubTypes :: Type -> [Type]
invalidAbsDataSubTypes :: Type -> [Type]
invalidAbsDataSubTypes = Writer [Type] () -> [Type]
forall w a. Monoid w => Writer w a -> w
execWriter (Writer [Type] () -> [Type])
-> (Type -> Writer [Type] ()) -> Type -> [Type]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Type -> Writer [Type] ()
go
  where
    go :: Type -> Writer [Type] ()
    go :: Type -> Writer [Type] ()
go Type
ty
      | Just Type
ty' <- Type -> Maybe Type
coreView Type
ty
      = Type -> Writer [Type] ()
go Type
ty'
    go TyVarTy{}
      = Writer [Type] ()
ok -- We report an error at the binding site of type variables,
           -- e.g. in the TySyn LHS or in the forall.
           -- It's not useful to report a second error for their occurrences
    go (AppTy Type
t1 Type
t2)
      = do { Type -> Writer [Type] ()
go Type
t1; Type -> Writer [Type] ()
go Type
t2 }
    go ty :: Type
ty@(TyConApp TyCon
tc [Type]
tys)
      | TyCon -> Bool
isTypeFamilyTyCon TyCon
tc
      = Type -> Writer [Type] ()
forall {m :: * -> *} {a}. Monad m => a -> WriterT [a] m ()
invalid Type
ty
      | Bool
otherwise
      = (Type -> Writer [Type] ()) -> [Type] -> Writer [Type] ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ Type -> Writer [Type] ()
go [Type]
tys
    go ty :: Type
ty@(ForAllTy{})
      = Type -> Writer [Type] ()
forall {m :: * -> *} {a}. Monad m => a -> WriterT [a] m ()
invalid Type
ty
    go ty :: Type
ty@(FunTy FunTyFlag
af Type
w Type
t1 Type
t2)
      | FunTyFlag
af FunTyFlag -> FunTyFlag -> Bool
forall a. Eq a => a -> a -> Bool
== FunTyFlag
FTF_T_T
      = do { Type -> Writer [Type] ()
go Type
w
           ; Type -> Writer [Type] ()
go (HasDebugCallStack => Type -> Type
Type -> Type
typeKind Type
t1) ; Type -> Writer [Type] ()
go Type
t1
           ; Type -> Writer [Type] ()
go (HasDebugCallStack => Type -> Type
Type -> Type
typeKind Type
t2) ; Type -> Writer [Type] ()
go Type
t2
           }
      | Bool
otherwise
      = Type -> Writer [Type] ()
forall {m :: * -> *} {a}. Monad m => a -> WriterT [a] m ()
invalid Type
ty
    go LitTy{}
      = Writer [Type] ()
ok
    go ty :: Type
ty@(CastTy{})
      = Type -> Writer [Type] ()
forall {m :: * -> *} {a}. Monad m => a -> WriterT [a] m ()
invalid Type
ty
    go ty :: Type
ty@(CoercionTy{})
      = Type -> Writer [Type] ()
forall {m :: * -> *} {a}. Monad m => a -> WriterT [a] m ()
invalid Type
ty

    ok :: Writer [Type] ()
ok         = () -> Writer [Type] ()
forall a. a -> WriterT [Type] Identity a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
    invalid :: a -> WriterT [a] m ()
invalid a
ty = [a] -> WriterT [a] m ()
forall w (m :: * -> *). (Monoid w, Monad m) => w -> WriterT w m ()
tell [a
ty]

{-
************************************************************************
*                                                                      *
        Type-checking the top level of a module (continued)
*                                                                      *
************************************************************************
-}

rnTopSrcDecls :: HsGroup GhcPs -> TcM (TcGblEnv, HsGroup GhcRn)
-- Fails if there are any errors
rnTopSrcDecls :: HsGroup GhcPs -> TcM (TcGblEnv, HsGroup (GhcPass 'Renamed))
rnTopSrcDecls HsGroup GhcPs
group
 = do { -- Rename the source decls
        String -> SDoc -> IOEnv (Env TcGblEnv TcLclEnv) ()
traceRn String
"rn12" SDoc
forall doc. IsOutput doc => doc
empty ;
        (tcg_env, rn_decls) <- TcM (TcGblEnv, HsGroup (GhcPass 'Renamed))
-> TcM (TcGblEnv, HsGroup (GhcPass 'Renamed))
forall r. TcM r -> TcM r
checkNoErrs (TcM (TcGblEnv, HsGroup (GhcPass 'Renamed))
 -> TcM (TcGblEnv, HsGroup (GhcPass 'Renamed)))
-> TcM (TcGblEnv, HsGroup (GhcPass 'Renamed))
-> TcM (TcGblEnv, HsGroup (GhcPass 'Renamed))
forall a b. (a -> b) -> a -> b
$ HsGroup GhcPs -> TcM (TcGblEnv, HsGroup (GhcPass 'Renamed))
rnSrcDecls HsGroup GhcPs
group ;
        traceRn "rn13" empty ;
        (tcg_env, rn_decls) <- runRenamerPlugin tcg_env rn_decls ;
        traceRn "rn13-plugin" empty ;

        -- save the renamed syntax, if we want it
        let { tcg_env'
                | Just HsGroup (GhcPass 'Renamed)
grp <- TcGblEnv -> Maybe (HsGroup (GhcPass 'Renamed))
tcg_rn_decls TcGblEnv
tcg_env
                  = TcGblEnv
tcg_env{ tcg_rn_decls = Just (appendGroups grp rn_decls) }
                | Bool
otherwise
                   = TcGblEnv
tcg_env };

                -- Dump trace of renaming part
        rnDump rn_decls ;
        return (tcg_env', rn_decls)
   }

tcTopSrcDecls :: HsGroup GhcRn -> TcM (TcGblEnv, TcLclEnv)
tcTopSrcDecls :: HsGroup (GhcPass 'Renamed)
-> TcRnIf TcGblEnv TcLclEnv (TcGblEnv, TcLclEnv)
tcTopSrcDecls (HsGroup { hs_tyclds :: forall p. HsGroup p -> [TyClGroup p]
hs_tyclds = [TyClGroup (GhcPass 'Renamed)]
tycl_decls,
                         hs_derivds :: forall p. HsGroup p -> [LDerivDecl p]
hs_derivds = [LDerivDecl (GhcPass 'Renamed)]
deriv_decls,
                         hs_fords :: forall p. HsGroup p -> [LForeignDecl p]
hs_fords  = [LForeignDecl (GhcPass 'Renamed)]
foreign_decls,
                         hs_defds :: forall p. HsGroup p -> [LDefaultDecl p]
hs_defds  = [LDefaultDecl (GhcPass 'Renamed)]
default_decls,
                         hs_annds :: forall p. HsGroup p -> [LAnnDecl p]
hs_annds  = [LAnnDecl (GhcPass 'Renamed)]
annotation_decls,
                         hs_ruleds :: forall p. HsGroup p -> [LRuleDecls p]
hs_ruleds = [LRuleDecls (GhcPass 'Renamed)]
rule_decls,
                         hs_valds :: forall p. HsGroup p -> HsValBinds p
hs_valds  = hs_val_binds :: HsValBindsLR (GhcPass 'Renamed) (GhcPass 'Renamed)
hs_val_binds@(XValBindsLR
                                              (NValBinds [(RecFlag, LHsBinds (GhcPass 'Renamed))]
val_binds [LSig (GhcPass 'Renamed)]
val_sigs)) })
 = do {         -- Type-check the type and class decls, and all imported decls
                -- The latter come in via tycl_decls
        String -> SDoc -> IOEnv (Env TcGblEnv TcLclEnv) ()
traceTc String
"Tc2 (src)" SDoc
forall doc. IsOutput doc => doc
empty ;

                -- Source-language instances, including derivings,
                -- and import the supporting declarations
        String -> SDoc -> IOEnv (Env TcGblEnv TcLclEnv) ()
traceTc String
"Tc3" SDoc
forall doc. IsOutput doc => doc
empty ;
        (tcg_env, inst_infos, th_bndrs,
         XValBindsLR (NValBinds deriv_binds deriv_sigs))
            <- [TyClGroup (GhcPass 'Renamed)]
-> [LDerivDecl (GhcPass 'Renamed)]
-> [LDefaultDecl (GhcPass 'Renamed)]
-> [(RecFlag, LHsBinds (GhcPass 'Renamed))]
-> TcM
     (TcGblEnv, [InstInfo (GhcPass 'Renamed)], ThBindEnv,
      HsValBindsLR (GhcPass 'Renamed) (GhcPass 'Renamed))
tcTyClsInstDecls [TyClGroup (GhcPass 'Renamed)]
tycl_decls [LDerivDecl (GhcPass 'Renamed)]
deriv_decls [LDefaultDecl (GhcPass 'Renamed)]
default_decls [(RecFlag, LHsBinds (GhcPass 'Renamed))]
val_binds ;

        updLclCtxt (\TcLclCtxt
tcl_env -> TcLclCtxt
tcl_env { tcl_th_bndrs = th_bndrs `plusNameEnv` tcl_th_bndrs tcl_env }) $
        setGblEnv tcg_env       $ do {

                -- Foreign import declarations next.
        traceTc "Tc4" empty ;
        (fi_ids, fi_decls, fi_gres) <- tcForeignImports foreign_decls ;
        tcExtendGlobalValEnv fi_ids     $ do {

                -- Value declarations next.
                -- It is important that we check the top-level value bindings
                -- before the GHC-generated derived bindings, since the latter
                -- may be defined in terms of the former. (For instance,
                -- the bindings produced in a Data instance.)
        traceTc "Tc5" empty ;
        tc_envs <- tcTopBinds val_binds val_sigs;
        restoreEnvs tc_envs $ do {

                -- Now GHC-generated derived bindings, generics, and selectors
                -- Do not generate warnings from compiler-generated code;
                -- hence the use of discardWarnings
        tc_envs@(tcg_env, tcl_env)
            <- discardWarnings (tcTopBinds deriv_binds deriv_sigs) ;
        restoreEnvs tc_envs $ do {  -- Environment doesn't change now

                -- Second pass over class and instance declarations,
                -- now using the kind-checked decls
        traceTc "Tc6" empty ;
        inst_binds <- tcInstDecls2 (tyClGroupTyClDecls tycl_decls) inst_infos ;

                -- Foreign exports
        traceTc "Tc7" empty ;
        (foe_binds, foe_decls, foe_gres) <- tcForeignExports foreign_decls ;

                -- Annotations
        annotations <- tcAnnotations annotation_decls ;

                -- Rules
        rules <- tcRules rule_decls ;

                -- Wrap up
        traceTc "Tc7a" empty ;
        let { all_binds = [GenLocated SrcSpanAnnA (HsBindLR GhcTc GhcTc)]
inst_binds [GenLocated SrcSpanAnnA (HsBindLR GhcTc GhcTc)]
-> [GenLocated SrcSpanAnnA (HsBindLR GhcTc GhcTc)]
-> [GenLocated SrcSpanAnnA (HsBindLR GhcTc GhcTc)]
forall a. [a] -> [a] -> [a]
++ [GenLocated SrcSpanAnnA (HsBindLR GhcTc GhcTc)]
foe_binds

            ; fo_gres = Bag GlobalRdrElt
fi_gres Bag GlobalRdrElt -> Bag GlobalRdrElt -> Bag GlobalRdrElt
forall a. Bag a -> Bag a -> Bag a
`unionBags` Bag GlobalRdrElt
foe_gres
            ; fo_fvs = (GlobalRdrElt -> FreeVars -> FreeVars)
-> FreeVars -> Bag GlobalRdrElt -> FreeVars
forall a b. (a -> b -> b) -> b -> Bag a -> b
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr (\GlobalRdrElt
gre FreeVars
fvs -> FreeVars
fvs FreeVars -> Name -> FreeVars
`addOneFV` (GlobalRdrElt -> Name
forall info. GlobalRdrEltX info -> Name
greName GlobalRdrElt
gre))
                                FreeVars
emptyFVs Bag GlobalRdrElt
fo_gres

            ; sig_names = [Name] -> FreeVars
mkNameSet (CollectFlag (GhcPass 'Renamed)
-> HsValBindsLR (GhcPass 'Renamed) (GhcPass 'Renamed)
-> [IdP (GhcPass 'Renamed)]
forall (idL :: Pass) idR.
CollectPass (GhcPass idL) =>
CollectFlag (GhcPass idL)
-> HsValBindsLR (GhcPass idL) idR -> [IdP (GhcPass idL)]
collectHsValBinders CollectFlag (GhcPass 'Renamed)
forall p. CollectFlag p
CollNoDictBinders HsValBindsLR (GhcPass 'Renamed) (GhcPass 'Renamed)
hs_val_binds)
                          FreeVars -> FreeVars -> FreeVars
`minusNameSet` [LSig (GhcPass 'Renamed)] -> FreeVars
getTypeSigNames [LSig (GhcPass 'Renamed)]
val_sigs

                -- Extend the GblEnv with the (as yet un-zonked)
                -- bindings, rules, foreign decls
            ; tcg_env' = TcGblEnv
tcg_env { tcg_binds   = tcg_binds tcg_env ++ all_binds
                                 , tcg_sigs    = tcg_sigs tcg_env `unionNameSet` sig_names
                                 , tcg_rules   = tcg_rules tcg_env
                                                      ++ flattenRuleDecls rules
                                 , tcg_anns    = tcg_anns tcg_env ++ annotations
                                 , tcg_ann_env = extendAnnEnvList (tcg_ann_env tcg_env) annotations
                                 , tcg_fords   = tcg_fords tcg_env ++ foe_decls ++ fi_decls
                                 , tcg_dus     = tcg_dus tcg_env `plusDU` usesOnly fo_fvs } } ;
                                 -- tcg_dus: see Note [Newtype constructor usage in foreign declarations]

        -- See Note [Newtype constructor usage in foreign declarations]
        addUsedGREs NoDeprecationWarnings (bagToList fo_gres) ;

        return (tcg_env', tcl_env)
    }}}}}

tcTopSrcDecls HsGroup (GhcPass 'Renamed)
_ = String -> TcRnIf TcGblEnv TcLclEnv (TcGblEnv, TcLclEnv)
forall a. HasCallStack => String -> a
panic String
"tcTopSrcDecls: ValBindsIn"

---------------------------
tcTyClsInstDecls :: [TyClGroup GhcRn]
                 -> [LDerivDecl GhcRn]
                 -> [LDefaultDecl GhcRn]
                 -> [(RecFlag, LHsBinds GhcRn)]
                 -> TcM (TcGblEnv,            -- The full inst env
                         [InstInfo GhcRn],    -- Source-code instance decls to
                                              -- process; contains all dfuns for
                                              -- this module
                          ThBindEnv,          -- TH binding levels
                          HsValBinds GhcRn)   -- Supporting bindings for derived
                                              -- instances

tcTyClsInstDecls :: [TyClGroup (GhcPass 'Renamed)]
-> [LDerivDecl (GhcPass 'Renamed)]
-> [LDefaultDecl (GhcPass 'Renamed)]
-> [(RecFlag, LHsBinds (GhcPass 'Renamed))]
-> TcM
     (TcGblEnv, [InstInfo (GhcPass 'Renamed)], ThBindEnv,
      HsValBindsLR (GhcPass 'Renamed) (GhcPass 'Renamed))
tcTyClsInstDecls [TyClGroup (GhcPass 'Renamed)]
tycl_decls [LDerivDecl (GhcPass 'Renamed)]
deriv_decls [LDefaultDecl (GhcPass 'Renamed)]
default_decls [(RecFlag, LHsBinds (GhcPass 'Renamed))]
binds
 = [LInstDecl (GhcPass 'Renamed)]
-> TcM
     (TcGblEnv, [InstInfo (GhcPass 'Renamed)], ThBindEnv,
      HsValBindsLR (GhcPass 'Renamed) (GhcPass 'Renamed))
-> TcM
     (TcGblEnv, [InstInfo (GhcPass 'Renamed)], ThBindEnv,
      HsValBindsLR (GhcPass 'Renamed) (GhcPass 'Renamed))
forall a. [LInstDecl (GhcPass 'Renamed)] -> TcM a -> TcM a
tcAddDataFamConPlaceholders ([TyClGroup (GhcPass 'Renamed)]
tycl_decls [TyClGroup (GhcPass 'Renamed)]
-> (TyClGroup (GhcPass 'Renamed)
    -> [GenLocated SrcSpanAnnA (InstDecl (GhcPass 'Renamed))])
-> [GenLocated SrcSpanAnnA (InstDecl (GhcPass 'Renamed))]
forall a b. [a] -> (a -> [b]) -> [b]
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= TyClGroup (GhcPass 'Renamed) -> [LInstDecl (GhcPass 'Renamed)]
TyClGroup (GhcPass 'Renamed)
-> [GenLocated SrcSpanAnnA (InstDecl (GhcPass 'Renamed))]
forall pass. TyClGroup pass -> [LInstDecl pass]
group_instds) (TcM
   (TcGblEnv, [InstInfo (GhcPass 'Renamed)], ThBindEnv,
    HsValBindsLR (GhcPass 'Renamed) (GhcPass 'Renamed))
 -> TcM
      (TcGblEnv, [InstInfo (GhcPass 'Renamed)], ThBindEnv,
       HsValBindsLR (GhcPass 'Renamed) (GhcPass 'Renamed)))
-> TcM
     (TcGblEnv, [InstInfo (GhcPass 'Renamed)], ThBindEnv,
      HsValBindsLR (GhcPass 'Renamed) (GhcPass 'Renamed))
-> TcM
     (TcGblEnv, [InstInfo (GhcPass 'Renamed)], ThBindEnv,
      HsValBindsLR (GhcPass 'Renamed) (GhcPass 'Renamed))
forall a b. (a -> b) -> a -> b
$
   [PatSynBind (GhcPass 'Renamed) (GhcPass 'Renamed)]
-> TcM
     (TcGblEnv, [InstInfo (GhcPass 'Renamed)], ThBindEnv,
      HsValBindsLR (GhcPass 'Renamed) (GhcPass 'Renamed))
-> TcM
     (TcGblEnv, [InstInfo (GhcPass 'Renamed)], ThBindEnv,
      HsValBindsLR (GhcPass 'Renamed) (GhcPass 'Renamed))
forall a.
[PatSynBind (GhcPass 'Renamed) (GhcPass 'Renamed)]
-> TcM a -> TcM a
tcAddPatSynPlaceholders ([(RecFlag, LHsBinds (GhcPass 'Renamed))]
-> [PatSynBind (GhcPass 'Renamed) (GhcPass 'Renamed)]
forall id.
UnXRec id =>
[(RecFlag, LHsBinds id)] -> [PatSynBind id id]
getPatSynBinds [(RecFlag, LHsBinds (GhcPass 'Renamed))]
binds) (TcM
   (TcGblEnv, [InstInfo (GhcPass 'Renamed)], ThBindEnv,
    HsValBindsLR (GhcPass 'Renamed) (GhcPass 'Renamed))
 -> TcM
      (TcGblEnv, [InstInfo (GhcPass 'Renamed)], ThBindEnv,
       HsValBindsLR (GhcPass 'Renamed) (GhcPass 'Renamed)))
-> TcM
     (TcGblEnv, [InstInfo (GhcPass 'Renamed)], ThBindEnv,
      HsValBindsLR (GhcPass 'Renamed) (GhcPass 'Renamed))
-> TcM
     (TcGblEnv, [InstInfo (GhcPass 'Renamed)], ThBindEnv,
      HsValBindsLR (GhcPass 'Renamed) (GhcPass 'Renamed))
forall a b. (a -> b) -> a -> b
$
   do { (tcg_env, inst_info, deriv_info, th_bndrs)
          <- [TyClGroup (GhcPass 'Renamed)]
-> TcM
     (TcGblEnv, [InstInfo (GhcPass 'Renamed)], [DerivInfo], ThBindEnv)
tcTyAndClassDecls [TyClGroup (GhcPass 'Renamed)]
tycl_decls ;

      ; setGblEnv tcg_env $ do {

          -- With the @TyClDecl@s and @InstDecl@s checked we're ready to
          -- process the deriving clauses, including data family deriving
          -- clauses discovered in @tcTyAndClassDecls@.
          --
          -- But only after we've typechecked 'default' declarations.
          -- See Note [Typechecking default declarations]
          defaults <- tcDefaults default_decls ;
          updGblEnv (\TcGblEnv
gbl -> TcGblEnv
gbl { tcg_default = defaults }) $ do {


          -- Careful to quit now in case there were instance errors, so that
          -- the deriving errors don't pile up as well.
          ; failIfErrsM
          ; (tcg_env', inst_info', val_binds)
              <- tcInstDeclsDeriv deriv_info deriv_decls
          ; setGblEnv tcg_env' $ do {
                failIfErrsM
              ; pure ( tcg_env', inst_info' ++ inst_info, th_bndrs, val_binds )
      }}}}

{- *********************************************************************
*                                                                      *
        Checking for 'main'
*                                                                      *
************************************************************************
-}

checkMainType :: TcGblEnv -> TcRn WantedConstraints
-- If this is the Main module, and it defines a function main,
--   check that its type is of form IO tau.
-- If not, do nothing
-- See Note [Dealing with main]
checkMainType :: TcGblEnv -> TcRn WantedConstraints
checkMainType TcGblEnv
tcg_env
  = do { hsc_env <- TcRnIf TcGblEnv TcLclEnv HscEnv
forall gbl lcl. TcRnIf gbl lcl HscEnv
getTopEnv
       ; if tcg_mod tcg_env /= mainModIs (hsc_HUE hsc_env)
         then return emptyWC else

    do { rdr_env <- getGlobalRdrEnv
       ; let dflags    = HscEnv -> DynFlags
hsc_dflags HscEnv
hsc_env
             main_occ  = DynFlags -> OccName
getMainOcc DynFlags
dflags
             main_gres = GlobalRdrEnv -> LookupGRE GREInfo -> [GlobalRdrElt]
forall info.
GlobalRdrEnvX info -> LookupGRE info -> [GlobalRdrEltX info]
lookupGRE GlobalRdrEnv
rdr_env (OccName -> WhichGREs GREInfo -> LookupGRE GREInfo
forall info. OccName -> WhichGREs info -> LookupGRE info
LookupOccName OccName
main_occ WhichGREs GREInfo
forall info. WhichGREs info
SameNameSpace)
       ; case filter isLocalGRE main_gres of {
            []         -> WantedConstraints -> TcRn WantedConstraints
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return WantedConstraints
emptyWC ;
            (GlobalRdrElt
_:GlobalRdrElt
_:[GlobalRdrElt]
_)    -> WantedConstraints -> TcRn WantedConstraints
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return WantedConstraints
emptyWC ;
            [GlobalRdrElt
main_gre] ->

    do { let main_name :: Name
main_name = GlobalRdrElt -> Name
forall info. GlobalRdrEltX info -> Name
greName GlobalRdrElt
main_gre
             ctxt :: UserTypeCtxt
ctxt      = Name -> ReportRedundantConstraints -> UserTypeCtxt
FunSigCtxt Name
main_name ReportRedundantConstraints
NoRRC
       ; main_id   <- Name -> TcM Id
tcLookupId Name
main_name
       ; (io_ty,_) <- getIOType
       ; let main_ty   = Id -> Type
idType Id
main_id
             eq_orig   = TypeEqOrigin { uo_actual :: Type
uo_actual   = Type
main_ty
                                      , uo_expected :: Type
uo_expected = Type
io_ty
                                      , uo_thing :: Maybe TypedThing
uo_thing    = Maybe TypedThing
forall a. Maybe a
Nothing
                                      , uo_visible :: Bool
uo_visible  = Bool
True }
       ; (_, lie)  <- captureTopConstraints       $
                      setMainCtxt main_name io_ty $
                      tcSubTypeSigma eq_orig ctxt main_ty io_ty
       ; return lie } } } }

checkMain :: Bool  -- False => no 'module M(..) where' header at all
          -> Maybe (LocatedLI [LIE GhcPs])  -- Export specs of Main module
          -> TcM TcGblEnv
-- If we are in module Main, check that 'main' is exported,
-- and generate the runMainIO binding that calls it
-- See Note [Dealing with main]
checkMain :: Bool
-> Maybe (GenLocated SrcSpanAnnLI [XRec GhcPs (IE GhcPs)])
-> TcM TcGblEnv
checkMain Bool
explicit_mod_hdr Maybe (GenLocated SrcSpanAnnLI [XRec GhcPs (IE GhcPs)])
export_ies
 = do { hsc_env  <- TcRnIf TcGblEnv TcLclEnv HscEnv
forall gbl lcl. TcRnIf gbl lcl HscEnv
getTopEnv
      ; tcg_env <- getGblEnv

      ; let dflags      = HscEnv -> DynFlags
hsc_dflags HscEnv
hsc_env
            main_mod    = HomeUnitEnv -> Module
mainModIs (HscEnv -> HomeUnitEnv
hsc_HUE HscEnv
hsc_env)
            main_occ    = DynFlags -> OccName
getMainOcc DynFlags
dflags

            exported_mains :: [Name]
            -- Exported things that are called 'main'
            exported_mains  = [ Name
name | AvailInfo
avail <- TcGblEnv -> [AvailInfo]
tcg_exports TcGblEnv
tcg_env
                                     , Name
name  <- AvailInfo -> [Name]
availNames AvailInfo
avail
                                     , Name -> OccName
nameOccName Name
name OccName -> OccName -> Bool
forall a. Eq a => a -> a -> Bool
== OccName
main_occ ]

      ; if | tcg_mod tcg_env /= main_mod
           -> -- Not the main module
              return tcg_env

           | [main_name] <- exported_mains
           -> -- The module indeed exports a function called 'main'
              generateMainBinding tcg_env main_name

           | otherwise
           -> assert (null exported_mains) $
              -- A fully-checked export list can't contain more
              -- than one function with the same OccName
              do { complain_no_main dflags main_mod main_occ
                 ; return tcg_env } }
  where
    complain_no_main :: DynFlags -> Module -> OccName -> IOEnv (Env TcGblEnv TcLclEnv) ()
complain_no_main DynFlags
dflags Module
main_mod OccName
main_occ
      = Bool
-> IOEnv (Env TcGblEnv TcLclEnv) ()
-> IOEnv (Env TcGblEnv TcLclEnv) ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (Bool
interactive Bool -> Bool -> Bool
&& Bool -> Bool
not Bool
explicit_mod_hdr) (IOEnv (Env TcGblEnv TcLclEnv) ()
 -> IOEnv (Env TcGblEnv TcLclEnv) ())
-> IOEnv (Env TcGblEnv TcLclEnv) ()
-> IOEnv (Env TcGblEnv TcLclEnv) ()
forall a b. (a -> b) -> a -> b
$
        TcRnMessage -> IOEnv (Env TcGblEnv TcLclEnv) ()
addErrTc (Module -> OccName -> TcRnMessage
noMainMsg Module
main_mod OccName
main_occ)          -- #12906
      where
        interactive :: Bool
interactive = DynFlags -> GhcLink
ghcLink DynFlags
dflags GhcLink -> GhcLink -> Bool
forall a. Eq a => a -> a -> Bool
== GhcLink
LinkInMemory
        -- Without an explicit module header...
        -- in interactive mode, don't worry about the absence of 'main'.
        -- in other modes, add error message and go on with typechecking.

    noMainMsg :: Module -> OccName -> TcRnMessage
noMainMsg Module
main_mod OccName
main_occ
      = Bool -> Module -> OccName -> TcRnMessage
TcRnMissingMain Bool
explicit_export_list Module
main_mod OccName
main_occ
    explicit_export_list :: Bool
explicit_export_list = Bool
explicit_mod_hdr Bool -> Bool -> Bool
&& Maybe (GenLocated SrcSpanAnnLI [GenLocated SrcSpanAnnA (IE GhcPs)])
-> Bool
forall a. Maybe a -> Bool
isJust Maybe (GenLocated SrcSpanAnnLI [XRec GhcPs (IE GhcPs)])
Maybe (GenLocated SrcSpanAnnLI [GenLocated SrcSpanAnnA (IE GhcPs)])
export_ies

-- | Get the unqualified name of the function to use as the \"main\" for the main module.
-- Either returns the default name or the one configured on the command line with -main-is
getMainOcc :: DynFlags -> OccName
getMainOcc :: DynFlags -> OccName
getMainOcc DynFlags
dflags = case DynFlags -> Maybe String
mainFunIs DynFlags
dflags of
                      Just String
fn -> FastString -> OccName
mkVarOccFS (String -> FastString
mkFastString String
fn)
                      Maybe String
Nothing -> FastString -> OccName
mkVarOccFS (String -> FastString
fsLit String
"main")

generateMainBinding :: TcGblEnv -> Name -> TcM TcGblEnv
-- There is a single exported 'main' function, called 'foo' (say),
-- which may be locally defined or imported
-- Define and typecheck the binding
--     :Main.main :: IO res_ty = runMainIO res_ty foo
-- This wraps the user's main function in the top-level stuff
-- defined in runMainIO (eg catching otherwise un-caught exceptions)
-- See Note [Dealing with main]
generateMainBinding :: TcGblEnv -> Name -> TcM TcGblEnv
generateMainBinding TcGblEnv
tcg_env Name
main_name = do
    { String -> SDoc -> IOEnv (Env TcGblEnv TcLclEnv) ()
traceTc String
"checkMain found" (Name -> SDoc
forall a. Outputable a => a -> SDoc
ppr Name
main_name)
    ; (io_ty, res_ty) <- TcM (Type, Type)
getIOType
    ; let loc = Name -> SrcSpan
forall a. NamedThing a => a -> SrcSpan
getSrcSpan Name
main_name
          main_expr_rn = SrcSpanAnnA
-> HsExpr (GhcPass 'Renamed)
-> GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed))
forall l e. l -> e -> GenLocated l e
L (SrcSpan -> SrcSpanAnnA
forall e. HasAnnotation e => SrcSpan -> e
noAnnSrcSpan SrcSpan
loc) (XVar (GhcPass 'Renamed)
-> LIdP (GhcPass 'Renamed) -> HsExpr (GhcPass 'Renamed)
forall p. XVar p -> LIdP p -> HsExpr p
HsVar XVar (GhcPass 'Renamed)
NoExtField
noExtField (SrcSpanAnnN -> Name -> GenLocated SrcSpanAnnN Name
forall l e. l -> e -> GenLocated l e
L (SrcSpan -> SrcSpanAnnN
forall e. HasAnnotation e => SrcSpan -> e
noAnnSrcSpan SrcSpan
loc) Name
main_name))
    ; (ev_binds, main_expr) <- setMainCtxt main_name io_ty $
                               tcCheckMonoExpr main_expr_rn io_ty

            -- See Note [Root-main Id]
            -- Construct the binding
            --      :Main.main :: IO res_ty = runMainIO res_ty main
    ; run_main_id <- tcLookupId runMainIOName
    ; let { root_main_name =  Unique -> Module -> OccName -> SrcSpan -> Name
mkExternalName Unique
rootMainKey Module
rOOT_MAIN
                               (FastString -> OccName
mkVarOccFS (String -> FastString
fsLit String
"main"))
                               (Name -> SrcSpan
forall a. NamedThing a => a -> SrcSpan
getSrcSpan Name
main_name)
          ; root_main_id = Name -> Type -> Id
Id.mkExportedVanillaId Name
root_main_name Type
io_ty
          ; co  = [Type] -> HsWrapper
mkWpTyApps [Type
res_ty]
          -- The ev_binds of the `main` function may contain deferred
          -- type errors when type of `main` is not `IO a`. The `ev_binds`
          -- must be put inside `runMainIO` to ensure the deferred type
          -- error can be emitted correctly. See #13838.
          ; rhs = LHsExpr GhcTc -> LHsExpr GhcTc -> LHsExpr GhcTc
forall (id :: Pass).
IsPass id =>
LHsExpr (GhcPass id)
-> LHsExpr (GhcPass id) -> LHsExpr (GhcPass id)
nlHsApp (HsWrapper -> LHsExpr GhcTc -> LHsExpr GhcTc
mkLHsWrap HsWrapper
co (IdP GhcTc -> LHsExpr GhcTc
forall (p :: Pass) a.
IsSrcSpanAnn p a =>
IdP (GhcPass p) -> LHsExpr (GhcPass p)
nlHsVar IdP GhcTc
Id
run_main_id)) (LHsExpr GhcTc -> LHsExpr GhcTc) -> LHsExpr GhcTc -> LHsExpr GhcTc
forall a b. (a -> b) -> a -> b
$
                    TcEvBinds -> LHsExpr GhcTc -> LHsExpr GhcTc
mkHsDictLet TcEvBinds
ev_binds LHsExpr GhcTc
main_expr
          ; main_bind = IdP GhcTc -> LHsExpr GhcTc -> LHsBind GhcTc
mkVarBind IdP GhcTc
Id
root_main_id LHsExpr GhcTc
rhs }

    ; return (tcg_env { tcg_main  = Just main_name
                      , tcg_binds = tcg_binds tcg_env
                                    ++ [main_bind]
                      , tcg_dus   = tcg_dus tcg_env
                                    `plusDU` usesOnly (unitFV main_name) })
                    -- Record the use of 'main', so that we don't
                    -- complain about it being defined but not used
    }

getIOType :: TcM (TcType, TcType)
-- Return (IO alpha, alpha) for fresh alpha
getIOType :: TcM (Type, Type)
getIOType = do { ioTyCon <- Name -> TcM TyCon
tcLookupTyCon Name
ioTyConName
               ; res_ty <- newFlexiTyVarTy liftedTypeKind
               ; return (mkTyConApp ioTyCon [res_ty], res_ty) }

setMainCtxt :: Name -> TcType -> TcM a -> TcM (TcEvBinds, a)
setMainCtxt :: forall a. Name -> Type -> TcM a -> TcM (TcEvBinds, a)
setMainCtxt Name
main_name Type
io_ty TcM a
thing_inside
  = SrcSpan -> TcRn (TcEvBinds, a) -> TcRn (TcEvBinds, a)
forall a. SrcSpan -> TcRn a -> TcRn a
setSrcSpan (Name -> SrcSpan
forall a. NamedThing a => a -> SrcSpan
getSrcSpan Name
main_name) (TcRn (TcEvBinds, a) -> TcRn (TcEvBinds, a))
-> TcRn (TcEvBinds, a) -> TcRn (TcEvBinds, a)
forall a b. (a -> b) -> a -> b
$
    SDoc -> TcRn (TcEvBinds, a) -> TcRn (TcEvBinds, a)
forall a. SDoc -> TcM a -> TcM a
addErrCtxt SDoc
main_ctxt              (TcRn (TcEvBinds, a) -> TcRn (TcEvBinds, a))
-> TcRn (TcEvBinds, a) -> TcRn (TcEvBinds, a)
forall a b. (a -> b) -> a -> b
$
    SkolemInfoAnon -> [Id] -> [Id] -> TcM a -> TcRn (TcEvBinds, a)
forall result.
SkolemInfoAnon
-> [Id] -> [Id] -> TcM result -> TcM (TcEvBinds, result)
checkConstraints SkolemInfoAnon
skol_info [] []  (TcM a -> TcRn (TcEvBinds, a)) -> TcM a -> TcRn (TcEvBinds, a)
forall a b. (a -> b) -> a -> b
$  -- Builds an implication if necessary
    TcM a
thing_inside                         -- e.g. with -fdefer-type-errors
  where
    skol_info :: SkolemInfoAnon
skol_info = UserTypeCtxt -> Type -> [(Name, Id)] -> SkolemInfoAnon
SigSkol (Name -> ReportRedundantConstraints -> UserTypeCtxt
FunSigCtxt Name
main_name ReportRedundantConstraints
NoRRC) Type
io_ty []
    main_ctxt :: SDoc
main_ctxt = String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"When checking the type of the"
                SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> OccName -> SDoc
ppMainFn (Name -> OccName
nameOccName Name
main_name)

{- Note [Dealing with main]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Dealing with the 'main' declaration is surprisingly tricky. Here are
the moving parts:

* The flag -main-is=M.foo allows you to set the main module to 'M',
  and the main function to 'foo'.  We access them through
      mainModIs  :: HscEnv -> Module     -- returns M
      getMainOcc :: DynFlags -> OccName  -- returns foo
  Of course usually M = Main, and foo = main.

* checkMainType: when typechecking module M, we add an extra check that
    foo :: IO tau, for some type tau.
  This avoids getting ambiguous-type errors from the monomorphism restriction
  applying to things like
      main = return ()
  Note that checkMainType does not consult the export list because
  we have not yet done rnExports (and can't do it until later).

* rnExports: checks the export list.  Very annoyingly, we can only do
  this after running any finalisers, which may add new declarations.
  That's why checkMainType and checkMain have to be separate.

* checkMain: does two things:
  - check that the export list does indeed export something called 'foo'
  - generateMainBinding: generate the root-main binding
       :Main.main = runMainIO M.foo
  See Note [Root-main Id]

An annoying consequence of having both checkMainType and checkMain is
that, when (but only when) -fdefer-type-errors is on, we may report an
ill-typed 'main' twice (as warnings): once in checkMainType and once
in checkMain. See test typecheck/should_fail/T13292.

We have the following tests to check this processing:
----------------+----------------------------------------------------------------------------------+
                |                                  Module Header:                                  |
                +-------------+-------------+-------------+-------------+-------------+------------+
                | module      | module Main | <No Header> | module Main |module       |module Main |
                |  Main(main) |             |             |   (module X)|   Main ()   |  (Sub.main)|
----------------+==================================================================================+
`main` function | ERROR:      | Main.main   | ERROR:      | Main.main   | ERROR:      | Sub.main   |
in Main module  |  Ambiguous  |             |  Ambiguous  |             |  `main` not |            |
and in imported |             |             |             |             |  exported   |            |
module Sub.     | T19397E1    | T16453M0    | T19397E2    | T16453M3    |             | T16453M1   |
                |             |             |             | X = Main    | Remark 2)   |            |
----------------+-------------+-------------+-------------+-------------+-------------+------------+
`main`function  | Sub.main    | ERROR:      | Sub.main    | Sub.main    | ERROR:      | Sub.main   |
only in imported|             | No `main` in|             |             |  `main` not |            |
submodule Sub.  |             |   `Main`    |             |             |  exported   |            |
                | T19397M0    | T16453E1    | T19397M1    | T16453M4    |             | T16453M5   |
                |             |             |             | X = Sub     | Remark 2)   |            |
----------------+-------------+-------------+-------------+-------------+-------------+------------+
`foo` function  | Sub.foo     | ERROR:      | Sub.foo     | Sub.foo     | ERROR:      | Sub.foo    |
in submodule    |             | No `foo` in |             |             |  `foo` not  |            |
Sub.            |             |   `Main`    |             |             |  exported   |            |
GHC option:     |             |             |             |             |             |            |
  -main-is foo  | T19397M2    | T19397E3    | T19397M3    | T19397M4    | T19397E4    | T16453M6   |
                | Remark 1)   |             |             | X = Sub     |             | Remark 3)  |
----------------+-------------+-------------+-------------+-------------+-------------+------------+

Remarks:
* The first line shows the exported `main` function or the error.
* The second line shows the coresponding test case.
* The module `Sub` contains the following functions:
     main :: IO ()
     foo :: IO ()
* Remark 1) Here the header is `Main (foo)`.
* Remark 2) Here we have no extra test case. It would exercise the same code path as `T19397E4`.
* Remark 3) Here the header is `Main (Sub.foo)`.


Note [Root-main Id]
~~~~~~~~~~~~~~~~~~~
The function that the RTS invokes is always :Main.main, which we call
root_main_id.  (Because GHC allows the user to have a module not
called Main as the main module, we can't rely on the main function
being called "Main.main".  That's why root_main_id has a fixed module
":Main".)

This is unusual: it's a LocalId whose Name has a Module from another
module. Tiresomely, we must filter it out again in GHC.Iface.Make, less we
get two defns for 'main' in the interface file!

When using `-fwrite-if-simplified-core` the root_main_id can end up in an interface file.
When the interface is read back in we have to add a special case when creating the
Id because otherwise we would go looking for the :Main module which obviously doesn't
exist. For this logic see GHC.IfaceToCore.mk_top_id.

There is also some similar (probably dead) logic in GHC.Rename.Env which says it
was added for External Core which faced a similar issue.


*********************************************************
*                                                       *
                GHCi stuff
*                                                       *
*********************************************************
-}

runTcInteractive :: HscEnv -> TcRn a -> IO (Messages TcRnMessage, Maybe a)
-- Initialise the tcg_inst_env with instances from all home modules.
-- This mimics the more selective call to hptInstances in tcRnImports
runTcInteractive :: forall a. HscEnv -> TcRn a -> IO (Messages TcRnMessage, Maybe a)
runTcInteractive HscEnv
hsc_env TcRn a
thing_inside
  = HscEnv -> TcRn a -> IO (Messages TcRnMessage, Maybe a)
forall a. HscEnv -> TcRn a -> IO (Messages TcRnMessage, Maybe a)
initTcInteractive HscEnv
hsc_env (TcRn a -> IO (Messages TcRnMessage, Maybe a))
-> TcRn a -> IO (Messages TcRnMessage, Maybe a)
forall a b. (a -> b) -> a -> b
$ HscEnv -> TcRn a -> TcRn a
forall a. HscEnv -> TcM a -> TcM a
withTcPlugins HscEnv
hsc_env (TcRn a -> TcRn a) -> TcRn a -> TcRn a
forall a b. (a -> b) -> a -> b
$
    HscEnv -> TcRn a -> TcRn a
forall a. HscEnv -> TcM a -> TcM a
withDefaultingPlugins HscEnv
hsc_env (TcRn a -> TcRn a) -> TcRn a -> TcRn a
forall a b. (a -> b) -> a -> b
$ HscEnv -> TcRn a -> TcRn a
forall a. HscEnv -> TcM a -> TcM a
withHoleFitPlugins HscEnv
hsc_env (TcRn a -> TcRn a) -> TcRn a -> TcRn a
forall a b. (a -> b) -> a -> b
$
    do { String -> SDoc -> IOEnv (Env TcGblEnv TcLclEnv) ()
traceTc String
"setInteractiveContext" (SDoc -> IOEnv (Env TcGblEnv TcLclEnv) ())
-> SDoc -> IOEnv (Env TcGblEnv TcLclEnv) ()
forall a b. (a -> b) -> a -> b
$
            [SDoc] -> SDoc
forall doc. IsDoc doc => [doc] -> doc
vcat [ String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"ic_tythings:" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> [SDoc] -> SDoc
forall doc. IsDoc doc => [doc] -> doc
vcat ((TyThing -> SDoc) -> [TyThing] -> [SDoc]
forall a b. (a -> b) -> [a] -> [b]
map TyThing -> SDoc
forall a. Outputable a => a -> SDoc
ppr (InteractiveContext -> [TyThing]
ic_tythings InteractiveContext
icxt))
                 , String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"ic_insts:" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> [SDoc] -> SDoc
forall doc. IsDoc doc => [doc] -> doc
vcat ((ClsInst -> SDoc) -> [ClsInst] -> [SDoc]
forall a b. (a -> b) -> [a] -> [b]
map (BindingSite -> Id -> SDoc
forall a. OutputableBndr a => BindingSite -> a -> SDoc
pprBndr BindingSite
LetBind (Id -> SDoc) -> (ClsInst -> Id) -> ClsInst -> SDoc
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ClsInst -> Id
instanceDFunId) (InstEnv -> [ClsInst]
instEnvElts InstEnv
ic_insts))
                 , String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"icReaderEnv (LocalDef)" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+>
                      [SDoc] -> SDoc
forall doc. IsDoc doc => [doc] -> doc
vcat (([GlobalRdrElt] -> SDoc) -> [[GlobalRdrElt]] -> [SDoc]
forall a b. (a -> b) -> [a] -> [b]
map [GlobalRdrElt] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [ [GlobalRdrElt]
local_gres | [GlobalRdrElt]
gres <- GlobalRdrEnv -> [[GlobalRdrElt]]
forall a. OccEnv a -> [a]
nonDetOccEnvElts (InteractiveContext -> GlobalRdrEnv
icReaderEnv InteractiveContext
icxt)
                                                 , let local_gres :: [GlobalRdrElt]
local_gres = (GlobalRdrElt -> Bool) -> [GlobalRdrElt] -> [GlobalRdrElt]
forall a. (a -> Bool) -> [a] -> [a]
filter GlobalRdrElt -> Bool
forall info. GlobalRdrEltX info -> Bool
isLocalGRE [GlobalRdrElt]
gres
                                                 , Bool -> Bool
not ([GlobalRdrElt] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [GlobalRdrElt]
local_gres) ]) ]

       ; let getOrphans :: ModuleName -> PkgQual -> IOEnv (Env TcGblEnv TcLclEnv) [Module]
getOrphans ModuleName
m PkgQual
mb_pkg = (ModIface_ 'ModIfaceFinal -> [Module])
-> IOEnv (Env TcGblEnv TcLclEnv) (ModIface_ 'ModIfaceFinal)
-> IOEnv (Env TcGblEnv TcLclEnv) [Module]
forall a b.
(a -> b)
-> IOEnv (Env TcGblEnv TcLclEnv) a
-> IOEnv (Env TcGblEnv TcLclEnv) b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (\ModIface_ 'ModIfaceFinal
iface -> ModIface_ 'ModIfaceFinal -> Module
forall (phase :: ModIfacePhase). ModIface_ phase -> Module
mi_module ModIface_ 'ModIfaceFinal
iface
                                          Module -> [Module] -> [Module]
forall a. a -> [a] -> [a]
: Dependencies -> [Module]
dep_orphs (ModIface_ 'ModIfaceFinal -> Dependencies
forall (phase :: ModIfacePhase). ModIface_ phase -> Dependencies
mi_deps ModIface_ 'ModIfaceFinal
iface))
                                 (SDoc
-> ModuleName
-> IsBootInterface
-> PkgQual
-> IOEnv (Env TcGblEnv TcLclEnv) (ModIface_ 'ModIfaceFinal)
loadSrcInterface (String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"runTcInteractive") ModuleName
m
                                                   IsBootInterface
NotBoot PkgQual
mb_pkg)

       ; !orphs <- ([[Module]] -> [Module])
-> IOEnv (Env TcGblEnv TcLclEnv) [[Module]]
-> IOEnv (Env TcGblEnv TcLclEnv) [Module]
forall a b.
(a -> b)
-> IOEnv (Env TcGblEnv TcLclEnv) a
-> IOEnv (Env TcGblEnv TcLclEnv) b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap ([Module] -> [Module]
forall a. NFData a => a -> a
force ([Module] -> [Module])
-> ([[Module]] -> [Module]) -> [[Module]] -> [Module]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [[Module]] -> [Module]
forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat) (IOEnv (Env TcGblEnv TcLclEnv) [[Module]]
 -> IOEnv (Env TcGblEnv TcLclEnv) [Module])
-> ((InteractiveImport -> IOEnv (Env TcGblEnv TcLclEnv) [Module])
    -> IOEnv (Env TcGblEnv TcLclEnv) [[Module]])
-> (InteractiveImport -> IOEnv (Env TcGblEnv TcLclEnv) [Module])
-> IOEnv (Env TcGblEnv TcLclEnv) [Module]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [InteractiveImport]
-> (InteractiveImport -> IOEnv (Env TcGblEnv TcLclEnv) [Module])
-> IOEnv (Env TcGblEnv TcLclEnv) [[Module]]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
t a -> (a -> m b) -> m (t b)
forM (InteractiveContext -> [InteractiveImport]
ic_imports InteractiveContext
icxt) ((InteractiveImport -> IOEnv (Env TcGblEnv TcLclEnv) [Module])
 -> IOEnv (Env TcGblEnv TcLclEnv) [Module])
-> (InteractiveImport -> IOEnv (Env TcGblEnv TcLclEnv) [Module])
-> IOEnv (Env TcGblEnv TcLclEnv) [Module]
forall a b. (a -> b) -> a -> b
$ \InteractiveImport
i ->
            case InteractiveImport
i of                   -- force above: see #15111
                IIModule ModuleName
n -> ModuleName -> PkgQual -> IOEnv (Env TcGblEnv TcLclEnv) [Module]
getOrphans ModuleName
n PkgQual
NoPkgQual
                IIDecl ImportDecl GhcPs
i   -> ModuleName -> PkgQual -> IOEnv (Env TcGblEnv TcLclEnv) [Module]
getOrphans (GenLocated SrcSpanAnnA ModuleName -> ModuleName
forall l e. GenLocated l e -> e
unLoc (ImportDecl GhcPs -> XRec GhcPs ModuleName
forall pass. ImportDecl pass -> XRec pass ModuleName
ideclName ImportDecl GhcPs
i))
                                         (UnitEnv -> ModuleName -> RawPkgQual -> PkgQual
renameRawPkgQual (HscEnv -> UnitEnv
hsc_unit_env HscEnv
hsc_env) (GenLocated SrcSpanAnnA ModuleName -> ModuleName
forall l e. GenLocated l e -> e
unLoc (GenLocated SrcSpanAnnA ModuleName -> ModuleName)
-> GenLocated SrcSpanAnnA ModuleName -> ModuleName
forall a b. (a -> b) -> a -> b
$ ImportDecl GhcPs -> XRec GhcPs ModuleName
forall pass. ImportDecl pass -> XRec pass ModuleName
ideclName ImportDecl GhcPs
i) (ImportDecl GhcPs -> ImportDeclPkgQual GhcPs
forall pass. ImportDecl pass -> ImportDeclPkgQual pass
ideclPkgQual ImportDecl GhcPs
i))

       ; let imports = ImportAvails
emptyImportAvails { imp_orphs = orphs }

             upd_envs (TcGblEnv
gbl_env, TcLclEnv
lcl_env) = (TcGblEnv
gbl_env', TcLclEnv
lcl_env')

               where
                 gbl_env' :: TcGblEnv
gbl_env' = TcGblEnv
gbl_env
                   { tcg_rdr_env      = icReaderEnv icxt
                   , tcg_type_env     = type_env
                   , tcg_inst_env     = tcg_inst_env gbl_env `unionInstEnv` ic_insts `unionInstEnv` home_insts
                   , tcg_fam_inst_env = extendFamInstEnvList
                              (extendFamInstEnvList (tcg_fam_inst_env gbl_env)
                                                    ic_finsts)
                              home_fam_insts
                   , tcg_fix_env      = ic_fix_env icxt
                   , tcg_default      = ic_default icxt
                        -- must calculate imp_orphs of the ImportAvails
                        -- so that instance visibility is done correctly
                   , tcg_imports      = imports }

                 lcl_env' :: TcLclEnv
lcl_env' = (TcLclCtxt -> TcLclCtxt) -> TcLclEnv -> TcLclEnv
modifyLclCtxt ([(Name, TcTyThing)] -> TcLclCtxt -> TcLclCtxt
tcExtendLocalTypeEnv [(Name, TcTyThing)]
lcl_ids) TcLclEnv
lcl_env

       ; updEnvs upd_envs thing_inside }
  where
    (InstEnv
home_insts, [FamInst]
home_fam_insts) = HscEnv -> (InstEnv, [FamInst])
hptAllInstances HscEnv
hsc_env

    icxt :: InteractiveContext
icxt                     = HscEnv -> InteractiveContext
hsc_IC HscEnv
hsc_env
    (InstEnv
ic_insts, [FamInst]
ic_finsts)    = InteractiveContext -> (InstEnv, [FamInst])
ic_instances InteractiveContext
icxt
    ([(Name, TcTyThing)]
lcl_ids, [TyThing]
top_ty_things) = (TyThing -> Either (Name, TcTyThing) TyThing)
-> [TyThing] -> ([(Name, TcTyThing)], [TyThing])
forall a b c. (a -> Either b c) -> [a] -> ([b], [c])
partitionWith TyThing -> Either (Name, TcTyThing) TyThing
is_closed (InteractiveContext -> [TyThing]
ic_tythings InteractiveContext
icxt)

    is_closed :: TyThing -> Either (Name, TcTyThing) TyThing
    -- Put Ids with free type variables (always RuntimeUnks)
    -- in the *local* type environment
    -- See Note [Initialising the type environment for GHCi]
    is_closed :: TyThing -> Either (Name, TcTyThing) TyThing
is_closed TyThing
thing
      | AnId Id
id <- TyThing
thing
      , Bool -> Bool
not (Id -> Bool
isTypeClosedLetBndr Id
id)
      = (Name, TcTyThing) -> Either (Name, TcTyThing) TyThing
forall a b. a -> Either a b
Left (Id -> Name
idName Id
id, ATcId { tct_id :: Id
tct_id = Id
id
                               , tct_info :: IdBindingInfo
tct_info = IdBindingInfo
NotLetBound })
      | Bool
otherwise
      = TyThing -> Either (Name, TcTyThing) TyThing
forall a b. b -> Either a b
Right TyThing
thing

    type_env1 :: TypeEnv
type_env1 = [TyThing] -> TypeEnv
mkTypeEnvWithImplicits [TyThing]
top_ty_things
    type_env :: TypeEnv
type_env  = TypeEnv -> [Id] -> TypeEnv
extendTypeEnvWithIds TypeEnv
type_env1
              ([Id] -> TypeEnv) -> [Id] -> TypeEnv
forall a b. (a -> b) -> a -> b
$ (ClsInst -> Id) -> [ClsInst] -> [Id]
forall a b. (a -> b) -> [a] -> [b]
map ClsInst -> Id
instanceDFunId (InstEnv -> [ClsInst]
instEnvElts InstEnv
ic_insts)
                -- Putting the dfuns in the type_env
                -- is just to keep Core Lint happy

{- Note [Initialising the type environment for GHCi]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Most of the Ids in ic_things, defined by the user in 'let' stmts,
have closed types. E.g.
   ghci> let foo x y = x && not y

However the GHCi debugger creates top-level bindings for Ids whose
types have free RuntimeUnk skolem variables, standing for unknown
types.  If we don't register these free TyVars as global TyVars then
the typechecker will try to quantify over them and fall over in
skolemiseQuantifiedTyVar. so we must add any free TyVars to the
typechecker's global TyVar set.  That is done by using
tcExtendLocalTypeEnv.

We do this by splitting out the Ids with open types, using 'is_closed'
to do the partition.  The top-level things go in the global TypeEnv;
the open, NotTopLevel, Ids, with free RuntimeUnk tyvars, go in the
local TypeEnv.

Note that we don't extend the local RdrEnv (tcl_rdr); all the in-scope
things are already in the interactive context's GlobalRdrEnv.
Extending the local RdrEnv isn't terrible, but it means there is an
entry for the same Name in both global and local RdrEnvs, and that
lead to duplicate "perhaps you meant..." suggestions (e.g. T5564).

We don't bother with the tcl_th_bndrs environment either.
-}

-- | The returned [Id] is the list of new Ids bound by this statement. It can
-- be used to extend the InteractiveContext via extendInteractiveContext.
--
-- The returned TypecheckedHsExpr is of type IO [ Any ], a list of the bound
-- values, coerced to Any.
tcRnStmt :: HscEnv -> GhciLStmt GhcPs
         -> IO (Messages TcRnMessage, Maybe ([Id], LHsExpr GhcTc, FixityEnv))
tcRnStmt :: HscEnv
-> GhciLStmt GhcPs
-> IO
     (Messages TcRnMessage, Maybe ([Id], LHsExpr GhcTc, FixityEnv))
tcRnStmt HscEnv
hsc_env GhciLStmt GhcPs
rdr_stmt
  = HscEnv
-> TcRn ([Id], LHsExpr GhcTc, FixityEnv)
-> IO
     (Messages TcRnMessage, Maybe ([Id], LHsExpr GhcTc, FixityEnv))
forall a. HscEnv -> TcRn a -> IO (Messages TcRnMessage, Maybe a)
runTcInteractive HscEnv
hsc_env (TcRn ([Id], LHsExpr GhcTc, FixityEnv)
 -> IO
      (Messages TcRnMessage, Maybe ([Id], LHsExpr GhcTc, FixityEnv)))
-> TcRn ([Id], LHsExpr GhcTc, FixityEnv)
-> IO
     (Messages TcRnMessage, Maybe ([Id], LHsExpr GhcTc, FixityEnv))
forall a b. (a -> b) -> a -> b
$ do {

    -- The real work is done here
    ((bound_ids, tc_expr), fix_env) <- GhciLStmt GhcPs -> TcM (PlanResult, FixityEnv)
tcUserStmt GhciLStmt GhcPs
rdr_stmt ;
    zonked_expr <- zonkTopLExpr tc_expr ;
    zonked_ids  <- zonkTopBndrs bound_ids ;

    failIfErrsM ;  -- we can't do the next step if there are
                   -- representation polymorphism errors
                   -- test case: ghci/scripts/T13202{,a}

        -- None of the Ids should be of unboxed type, because we
        -- cast them all to HValues in the end!
    mapM_ (addErr . TcRnGhciUnliftedBind) $
      filter (mightBeUnliftedType . idType) zonked_ids ;

    traceTc "tcs 1" empty ;
    this_mod <- getModule ;
    global_ids <- mapM (externaliseAndTidyId this_mod) zonked_ids ;
        -- Note [Interactively-bound Ids in GHCi] in GHC.Driver.Env

    traceOptTcRn Opt_D_dump_tc
        (vcat [text "Bound Ids" <+> pprWithCommas ppr global_ids,
               text "Typechecked expr" <+> ppr zonked_expr]) ;

    return (global_ids, zonked_expr, fix_env)
    }

{-
--------------------------------------------------------------------------
                Typechecking Stmts in GHCi

Here is the grand plan, implemented in tcUserStmt

        What you type                   The IO [HValue] that hscStmt returns
        -------------                   ------------------------------------
        let pat = expr          ==>     let pat = expr in return [coerce HVal x, coerce HVal y, ...]
                                        bindings: [x,y,...]

        pat <- expr             ==>     expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
                                        bindings: [x,y,...]

        expr (of IO type)       ==>     expr >>= \ it -> return [coerce HVal it]
          [NB: result not printed]      bindings: [it]

        expr (of non-IO type,   ==>     let it = expr in print it >> return [coerce HVal it]
          result showable)              bindings: [it]

        expr (of non-IO type,
          result not showable)  ==>     error
-}

-- | A plan is an attempt to lift some code into the IO monad.
type PlanResult = ([Id], LHsExpr GhcTc)
type Plan = TcM PlanResult

-- | Try the plans in order. If one fails (by raising an exn), try the next.
-- If one succeeds, take it.
runPlans :: NonEmpty Plan -> Plan
runPlans :: NonEmpty Plan -> Plan
runPlans = (TcM ([Id], GenLocated SrcSpanAnnA (HsExpr GhcTc))
 -> TcM ([Id], GenLocated SrcSpanAnnA (HsExpr GhcTc))
 -> TcM ([Id], GenLocated SrcSpanAnnA (HsExpr GhcTc)))
-> NonEmpty (TcM ([Id], GenLocated SrcSpanAnnA (HsExpr GhcTc)))
-> TcM ([Id], GenLocated SrcSpanAnnA (HsExpr GhcTc))
forall a. (a -> a -> a) -> NonEmpty a -> a
forall (t :: * -> *) a. Foldable t => (a -> a -> a) -> t a -> a
foldr1 ((TcM ([Id], GenLocated SrcSpanAnnA (HsExpr GhcTc))
 -> TcM ([Id], GenLocated SrcSpanAnnA (HsExpr GhcTc))
 -> TcM ([Id], GenLocated SrcSpanAnnA (HsExpr GhcTc)))
-> TcM ([Id], GenLocated SrcSpanAnnA (HsExpr GhcTc))
-> TcM ([Id], GenLocated SrcSpanAnnA (HsExpr GhcTc))
-> TcM ([Id], GenLocated SrcSpanAnnA (HsExpr GhcTc))
forall a b c. (a -> b -> c) -> b -> a -> c
flip TcM ([Id], GenLocated SrcSpanAnnA (HsExpr GhcTc))
-> TcM ([Id], GenLocated SrcSpanAnnA (HsExpr GhcTc))
-> TcM ([Id], GenLocated SrcSpanAnnA (HsExpr GhcTc))
forall r. TcM r -> TcM r -> TcM r
tryTcDiscardingErrs)

-- | Typecheck (and 'lift') a stmt entered by the user in GHCi into the
-- GHCi 'environment'.
--
-- By 'lift' and 'environment we mean that the code is changed to
-- execute properly in an IO monad. See Note [Interactively-bound Ids
-- in GHCi] in GHC.Driver.Env for more details. We do this lifting by trying
-- different ways ('plans') of lifting the code into the IO monad and
-- type checking each plan until one succeeds.
tcUserStmt :: GhciLStmt GhcPs -> TcM (PlanResult, FixityEnv)

-- An expression typed at the prompt is treated very specially
tcUserStmt :: GhciLStmt GhcPs -> TcM (PlanResult, FixityEnv)
tcUserStmt (L SrcSpanAnnA
loc (BodyStmt XBodyStmt GhcPs GhcPs (GenLocated SrcSpanAnnA (HsExpr GhcPs))
_ GenLocated SrcSpanAnnA (HsExpr GhcPs)
expr SyntaxExpr GhcPs
_ SyntaxExpr GhcPs
_))
  = do  { (rn_expr, fvs) <- TcM (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)), FreeVars)
-> TcM
     (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)), FreeVars)
forall r. TcM r -> TcM r
checkNoErrs (LHsExpr GhcPs -> RnM (LHsExpr (GhcPass 'Renamed), FreeVars)
rnLExpr LHsExpr GhcPs
GenLocated SrcSpanAnnA (HsExpr GhcPs)
expr)

        ; dumpOptTcRn Opt_D_dump_rn_ast "Renamer" FormatHaskell
            (showAstData NoBlankSrcSpan NoBlankEpAnnotations rn_expr)
               -- Don't try to typecheck if the renamer fails!
        ; ghciStep <- getGhciStepIO
        ; uniq <- newUnique
        ; let loc' = SrcSpan -> SrcSpanAnnN
forall e. HasAnnotation e => SrcSpan -> e
noAnnSrcSpan (SrcSpan -> SrcSpanAnnN) -> SrcSpan -> SrcSpanAnnN
forall a b. (a -> b) -> a -> b
$ SrcSpanAnnA -> SrcSpan
forall a. HasLoc a => a -> SrcSpan
locA SrcSpanAnnA
loc
        ; interPrintName <- getInteractivePrintName
        ; let fresh_it  = Unique -> SrcSpan -> Name
itName Unique
uniq (SrcSpanAnnA -> SrcSpan
forall a. HasLoc a => a -> SrcSpan
locA SrcSpanAnnA
loc)
              matches   = [HsMatchContext (LIdP (NoGhcTc (GhcPass 'Renamed)))
-> LocatedE [LPat (GhcPass 'Renamed)]
-> LHsExpr (GhcPass 'Renamed)
-> HsLocalBinds (GhcPass 'Renamed)
-> LMatch (GhcPass 'Renamed) (LHsExpr (GhcPass 'Renamed))
forall (p :: Pass).
IsPass p =>
HsMatchContext (LIdP (NoGhcTc (GhcPass p)))
-> LocatedE [LPat (GhcPass p)]
-> LHsExpr (GhcPass p)
-> HsLocalBinds (GhcPass p)
-> LMatch (GhcPass p) (LHsExpr (GhcPass p))
mkMatch (GenLocated SrcSpanAnnN Name
-> AnnFunRhs -> HsMatchContext (GenLocated SrcSpanAnnN Name)
forall fn. fn -> AnnFunRhs -> HsMatchContext fn
mkPrefixFunRhs (SrcSpanAnnN -> Name -> GenLocated SrcSpanAnnN Name
forall l e. l -> e -> GenLocated l e
L SrcSpanAnnN
loc' Name
fresh_it) AnnFunRhs
forall a. NoAnn a => a
noAnn) ([GenLocated SrcSpanAnnA (Pat (GhcPass 'Renamed))]
-> GenLocated
     EpaLocation [GenLocated SrcSpanAnnA (Pat (GhcPass 'Renamed))]
forall e a. HasAnnotation e => a -> GenLocated e a
noLocA []) LHsExpr (GhcPass 'Renamed)
GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed))
rn_expr
                                   HsLocalBinds (GhcPass 'Renamed)
forall (a :: Pass) (b :: Pass).
HsLocalBindsLR (GhcPass a) (GhcPass b)
emptyLocalBinds]
              -- [it = expr]
              the_bind  = SrcSpanAnnA
-> HsBindLR (GhcPass 'Renamed) (GhcPass 'Renamed)
-> GenLocated
     SrcSpanAnnA (HsBindLR (GhcPass 'Renamed) (GhcPass 'Renamed))
forall l e. l -> e -> GenLocated l e
L SrcSpanAnnA
loc (HsBindLR (GhcPass 'Renamed) (GhcPass 'Renamed)
 -> GenLocated
      SrcSpanAnnA (HsBindLR (GhcPass 'Renamed) (GhcPass 'Renamed)))
-> HsBindLR (GhcPass 'Renamed) (GhcPass 'Renamed)
-> GenLocated
     SrcSpanAnnA (HsBindLR (GhcPass 'Renamed) (GhcPass 'Renamed))
forall a b. (a -> b) -> a -> b
$ (Origin
-> GenLocated SrcSpanAnnN Name
-> [LMatch (GhcPass 'Renamed) (LHsExpr (GhcPass 'Renamed))]
-> HsBindLR (GhcPass 'Renamed) (GhcPass 'Renamed)
mkTopFunBind Origin
FromSource
                                     (SrcSpanAnnN -> Name -> GenLocated SrcSpanAnnN Name
forall l e. l -> e -> GenLocated l e
L SrcSpanAnnN
loc' Name
fresh_it) [LMatch (GhcPass 'Renamed) (LHsExpr (GhcPass 'Renamed))]
[GenLocated
   SrcSpanAnnA
   (Match
      (GhcPass 'Renamed)
      (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed))))]
matches)
                                         { fun_ext = fvs }
              -- Care here!  In GHCi the expression might have
              -- free variables, and they in turn may have free type variables
              -- (if we are at a breakpoint, say).  We must put those free vars

              -- [let it = expr]
              let_stmt  = SrcSpanAnnA
-> StmtLR
     (GhcPass 'Renamed)
     (GhcPass 'Renamed)
     (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))
-> GenLocated
     SrcSpanAnnA
     (StmtLR
        (GhcPass 'Renamed)
        (GhcPass 'Renamed)
        (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed))))
forall l e. l -> e -> GenLocated l e
L SrcSpanAnnA
loc (StmtLR
   (GhcPass 'Renamed)
   (GhcPass 'Renamed)
   (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))
 -> GenLocated
      SrcSpanAnnA
      (StmtLR
         (GhcPass 'Renamed)
         (GhcPass 'Renamed)
         (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))))
-> StmtLR
     (GhcPass 'Renamed)
     (GhcPass 'Renamed)
     (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))
-> GenLocated
     SrcSpanAnnA
     (StmtLR
        (GhcPass 'Renamed)
        (GhcPass 'Renamed)
        (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed))))
forall a b. (a -> b) -> a -> b
$ XLetStmt
  (GhcPass 'Renamed)
  (GhcPass 'Renamed)
  (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))
-> HsLocalBinds (GhcPass 'Renamed)
-> StmtLR
     (GhcPass 'Renamed)
     (GhcPass 'Renamed)
     (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))
forall idL idR body.
XLetStmt idL idR body
-> HsLocalBindsLR idL idR -> StmtLR idL idR body
LetStmt XLetStmt
  (GhcPass 'Renamed)
  (GhcPass 'Renamed)
  (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))
forall a. NoAnn a => a
noAnn (HsLocalBinds (GhcPass 'Renamed)
 -> StmtLR
      (GhcPass 'Renamed)
      (GhcPass 'Renamed)
      (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed))))
-> HsLocalBinds (GhcPass 'Renamed)
-> StmtLR
     (GhcPass 'Renamed)
     (GhcPass 'Renamed)
     (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))
forall a b. (a -> b) -> a -> b
$ XHsValBinds (GhcPass 'Renamed) (GhcPass 'Renamed)
-> HsValBindsLR (GhcPass 'Renamed) (GhcPass 'Renamed)
-> HsLocalBinds (GhcPass 'Renamed)
forall idL idR.
XHsValBinds idL idR
-> HsValBindsLR idL idR -> HsLocalBindsLR idL idR
HsValBinds XHsValBinds (GhcPass 'Renamed) (GhcPass 'Renamed)
forall a. NoAnn a => a
noAnn
                           (HsValBindsLR (GhcPass 'Renamed) (GhcPass 'Renamed)
 -> HsLocalBinds (GhcPass 'Renamed))
-> HsValBindsLR (GhcPass 'Renamed) (GhcPass 'Renamed)
-> HsLocalBinds (GhcPass 'Renamed)
forall a b. (a -> b) -> a -> b
$ XXValBindsLR (GhcPass 'Renamed) (GhcPass 'Renamed)
-> HsValBindsLR (GhcPass 'Renamed) (GhcPass 'Renamed)
forall idL idR. XXValBindsLR idL idR -> HsValBindsLR idL idR
XValBindsLR
                               ([(RecFlag, LHsBinds (GhcPass 'Renamed))]
-> [LSig (GhcPass 'Renamed)] -> NHsValBindsLR (GhcPass 'Renamed)
forall idL.
[(RecFlag, LHsBinds idL)]
-> [LSig (GhcPass 'Renamed)] -> NHsValBindsLR idL
NValBinds [(RecFlag
NonRecursive,[XRec
  (GhcPass 'Renamed) (HsBindLR (GhcPass 'Renamed) (GhcPass 'Renamed))
GenLocated
  SrcSpanAnnA (HsBindLR (GhcPass 'Renamed) (GhcPass 'Renamed))
the_bind])] [])

              -- [it <- e]
              bind_stmt = SrcSpanAnnA
-> StmtLR
     (GhcPass 'Renamed)
     (GhcPass 'Renamed)
     (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))
-> GenLocated
     SrcSpanAnnA
     (StmtLR
        (GhcPass 'Renamed)
        (GhcPass 'Renamed)
        (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed))))
forall l e. l -> e -> GenLocated l e
L SrcSpanAnnA
loc (StmtLR
   (GhcPass 'Renamed)
   (GhcPass 'Renamed)
   (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))
 -> GenLocated
      SrcSpanAnnA
      (StmtLR
         (GhcPass 'Renamed)
         (GhcPass 'Renamed)
         (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))))
-> StmtLR
     (GhcPass 'Renamed)
     (GhcPass 'Renamed)
     (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))
-> GenLocated
     SrcSpanAnnA
     (StmtLR
        (GhcPass 'Renamed)
        (GhcPass 'Renamed)
        (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed))))
forall a b. (a -> b) -> a -> b
$ XBindStmt
  (GhcPass 'Renamed)
  (GhcPass 'Renamed)
  (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))
-> LPat (GhcPass 'Renamed)
-> GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed))
-> StmtLR
     (GhcPass 'Renamed)
     (GhcPass 'Renamed)
     (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))
forall idL idR body.
XBindStmt idL idR body -> LPat idL -> body -> StmtLR idL idR body
BindStmt
                                       (XBindStmtRn
                                          { xbsrn_bindOp :: SyntaxExpr (GhcPass 'Renamed)
xbsrn_bindOp = Name -> SyntaxExprRn
mkRnSyntaxExpr Name
bindIOName
                                          , xbsrn_failOp :: FailOperator (GhcPass 'Renamed)
xbsrn_failOp = FailOperator (GhcPass 'Renamed)
Maybe SyntaxExprRn
forall a. Maybe a
Nothing
                                          })
                                       (SrcSpanAnnA
-> Pat (GhcPass 'Renamed)
-> GenLocated SrcSpanAnnA (Pat (GhcPass 'Renamed))
forall l e. l -> e -> GenLocated l e
L SrcSpanAnnA
loc (XVarPat (GhcPass 'Renamed)
-> LIdP (GhcPass 'Renamed) -> Pat (GhcPass 'Renamed)
forall p. XVarPat p -> LIdP p -> Pat p
VarPat XVarPat (GhcPass 'Renamed)
NoExtField
noExtField (SrcSpanAnnN -> Name -> GenLocated SrcSpanAnnN Name
forall l e. l -> e -> GenLocated l e
L SrcSpanAnnN
loc' Name
fresh_it)))
                                       (LHsExpr (GhcPass 'Renamed)
-> LHsExpr (GhcPass 'Renamed) -> LHsExpr (GhcPass 'Renamed)
forall (id :: Pass).
IsPass id =>
LHsExpr (GhcPass id)
-> LHsExpr (GhcPass id) -> LHsExpr (GhcPass id)
nlHsApp LHsExpr (GhcPass 'Renamed)
GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed))
ghciStep LHsExpr (GhcPass 'Renamed)
GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed))
rn_expr)

              -- [; print it]
              print_it  = SrcSpanAnnA
-> StmtLR
     (GhcPass 'Renamed)
     (GhcPass 'Renamed)
     (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))
-> GenLocated
     SrcSpanAnnA
     (StmtLR
        (GhcPass 'Renamed)
        (GhcPass 'Renamed)
        (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed))))
forall l e. l -> e -> GenLocated l e
L SrcSpanAnnA
loc (StmtLR
   (GhcPass 'Renamed)
   (GhcPass 'Renamed)
   (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))
 -> GenLocated
      SrcSpanAnnA
      (StmtLR
         (GhcPass 'Renamed)
         (GhcPass 'Renamed)
         (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))))
-> StmtLR
     (GhcPass 'Renamed)
     (GhcPass 'Renamed)
     (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))
-> GenLocated
     SrcSpanAnnA
     (StmtLR
        (GhcPass 'Renamed)
        (GhcPass 'Renamed)
        (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed))))
forall a b. (a -> b) -> a -> b
$ XBodyStmt
  (GhcPass 'Renamed)
  (GhcPass 'Renamed)
  (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))
-> GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed))
-> SyntaxExpr (GhcPass 'Renamed)
-> SyntaxExpr (GhcPass 'Renamed)
-> StmtLR
     (GhcPass 'Renamed)
     (GhcPass 'Renamed)
     (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))
forall idL idR body.
XBodyStmt idL idR body
-> body -> SyntaxExpr idR -> SyntaxExpr idR -> StmtLR idL idR body
BodyStmt XBodyStmt
  (GhcPass 'Renamed)
  (GhcPass 'Renamed)
  (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))
NoExtField
noExtField
                                           (LHsExpr (GhcPass 'Renamed)
-> LHsExpr (GhcPass 'Renamed) -> LHsExpr (GhcPass 'Renamed)
forall (id :: Pass).
IsPass id =>
LHsExpr (GhcPass id)
-> LHsExpr (GhcPass id) -> LHsExpr (GhcPass id)
nlHsApp (IdP (GhcPass 'Renamed) -> LHsExpr (GhcPass 'Renamed)
forall (p :: Pass) a.
IsSrcSpanAnn p a =>
IdP (GhcPass p) -> LHsExpr (GhcPass p)
nlHsVar IdP (GhcPass 'Renamed)
Name
interPrintName)
                                           (IdP (GhcPass 'Renamed) -> LHsExpr (GhcPass 'Renamed)
forall (p :: Pass) a.
IsSrcSpanAnn p a =>
IdP (GhcPass p) -> LHsExpr (GhcPass p)
nlHsVar IdP (GhcPass 'Renamed)
Name
fresh_it))
                                           (Name -> SyntaxExprRn
mkRnSyntaxExpr Name
thenIOName)
                                                  SyntaxExpr (GhcPass 'Renamed)
forall (p :: Pass). IsPass p => SyntaxExpr (GhcPass p)
noSyntaxExpr

              -- NewA
              no_it_a = SrcSpanAnnA
-> StmtLR
     (GhcPass 'Renamed)
     (GhcPass 'Renamed)
     (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))
-> GenLocated
     SrcSpanAnnA
     (StmtLR
        (GhcPass 'Renamed)
        (GhcPass 'Renamed)
        (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed))))
forall l e. l -> e -> GenLocated l e
L SrcSpanAnnA
loc (StmtLR
   (GhcPass 'Renamed)
   (GhcPass 'Renamed)
   (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))
 -> GenLocated
      SrcSpanAnnA
      (StmtLR
         (GhcPass 'Renamed)
         (GhcPass 'Renamed)
         (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))))
-> StmtLR
     (GhcPass 'Renamed)
     (GhcPass 'Renamed)
     (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))
-> GenLocated
     SrcSpanAnnA
     (StmtLR
        (GhcPass 'Renamed)
        (GhcPass 'Renamed)
        (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed))))
forall a b. (a -> b) -> a -> b
$ XBodyStmt
  (GhcPass 'Renamed)
  (GhcPass 'Renamed)
  (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))
-> GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed))
-> SyntaxExpr (GhcPass 'Renamed)
-> SyntaxExpr (GhcPass 'Renamed)
-> StmtLR
     (GhcPass 'Renamed)
     (GhcPass 'Renamed)
     (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))
forall idL idR body.
XBodyStmt idL idR body
-> body -> SyntaxExpr idR -> SyntaxExpr idR -> StmtLR idL idR body
BodyStmt XBodyStmt
  (GhcPass 'Renamed)
  (GhcPass 'Renamed)
  (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))
NoExtField
noExtField (IdP (GhcPass 'Renamed)
-> [LHsExpr (GhcPass 'Renamed)] -> LHsExpr (GhcPass 'Renamed)
forall (p :: Pass) a.
IsSrcSpanAnn p a =>
IdP (GhcPass p) -> [LHsExpr (GhcPass p)] -> LHsExpr (GhcPass p)
nlHsApps IdP (GhcPass 'Renamed)
Name
bindIOName
                                       [LHsExpr (GhcPass 'Renamed)
GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed))
rn_expr , IdP (GhcPass 'Renamed) -> LHsExpr (GhcPass 'Renamed)
forall (p :: Pass) a.
IsSrcSpanAnn p a =>
IdP (GhcPass p) -> LHsExpr (GhcPass p)
nlHsVar IdP (GhcPass 'Renamed)
Name
interPrintName])
                                       (Name -> SyntaxExprRn
mkRnSyntaxExpr Name
thenIOName)
                                       SyntaxExpr (GhcPass 'Renamed)
forall (p :: Pass). IsPass p => SyntaxExpr (GhcPass p)
noSyntaxExpr

              no_it_b = SrcSpanAnnA
-> StmtLR
     (GhcPass 'Renamed)
     (GhcPass 'Renamed)
     (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))
-> GenLocated
     SrcSpanAnnA
     (StmtLR
        (GhcPass 'Renamed)
        (GhcPass 'Renamed)
        (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed))))
forall l e. l -> e -> GenLocated l e
L SrcSpanAnnA
loc (StmtLR
   (GhcPass 'Renamed)
   (GhcPass 'Renamed)
   (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))
 -> GenLocated
      SrcSpanAnnA
      (StmtLR
         (GhcPass 'Renamed)
         (GhcPass 'Renamed)
         (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))))
-> StmtLR
     (GhcPass 'Renamed)
     (GhcPass 'Renamed)
     (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))
-> GenLocated
     SrcSpanAnnA
     (StmtLR
        (GhcPass 'Renamed)
        (GhcPass 'Renamed)
        (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed))))
forall a b. (a -> b) -> a -> b
$ XBodyStmt
  (GhcPass 'Renamed)
  (GhcPass 'Renamed)
  (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))
-> GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed))
-> SyntaxExpr (GhcPass 'Renamed)
-> SyntaxExpr (GhcPass 'Renamed)
-> StmtLR
     (GhcPass 'Renamed)
     (GhcPass 'Renamed)
     (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))
forall idL idR body.
XBodyStmt idL idR body
-> body -> SyntaxExpr idR -> SyntaxExpr idR -> StmtLR idL idR body
BodyStmt XBodyStmt
  (GhcPass 'Renamed)
  (GhcPass 'Renamed)
  (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))
NoExtField
noExtField (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed))
rn_expr)
                                       (Name -> SyntaxExprRn
mkRnSyntaxExpr Name
thenIOName)
                                       SyntaxExpr (GhcPass 'Renamed)
forall (p :: Pass). IsPass p => SyntaxExpr (GhcPass p)
noSyntaxExpr

              no_it_c = SrcSpanAnnA
-> StmtLR
     (GhcPass 'Renamed)
     (GhcPass 'Renamed)
     (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))
-> GenLocated
     SrcSpanAnnA
     (StmtLR
        (GhcPass 'Renamed)
        (GhcPass 'Renamed)
        (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed))))
forall l e. l -> e -> GenLocated l e
L SrcSpanAnnA
loc (StmtLR
   (GhcPass 'Renamed)
   (GhcPass 'Renamed)
   (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))
 -> GenLocated
      SrcSpanAnnA
      (StmtLR
         (GhcPass 'Renamed)
         (GhcPass 'Renamed)
         (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))))
-> StmtLR
     (GhcPass 'Renamed)
     (GhcPass 'Renamed)
     (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))
-> GenLocated
     SrcSpanAnnA
     (StmtLR
        (GhcPass 'Renamed)
        (GhcPass 'Renamed)
        (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed))))
forall a b. (a -> b) -> a -> b
$ XBodyStmt
  (GhcPass 'Renamed)
  (GhcPass 'Renamed)
  (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))
-> GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed))
-> SyntaxExpr (GhcPass 'Renamed)
-> SyntaxExpr (GhcPass 'Renamed)
-> StmtLR
     (GhcPass 'Renamed)
     (GhcPass 'Renamed)
     (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))
forall idL idR body.
XBodyStmt idL idR body
-> body -> SyntaxExpr idR -> SyntaxExpr idR -> StmtLR idL idR body
BodyStmt XBodyStmt
  (GhcPass 'Renamed)
  (GhcPass 'Renamed)
  (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))
NoExtField
noExtField
                                      (LHsExpr (GhcPass 'Renamed)
-> LHsExpr (GhcPass 'Renamed) -> LHsExpr (GhcPass 'Renamed)
forall (id :: Pass).
IsPass id =>
LHsExpr (GhcPass id)
-> LHsExpr (GhcPass id) -> LHsExpr (GhcPass id)
nlHsApp (IdP (GhcPass 'Renamed) -> LHsExpr (GhcPass 'Renamed)
forall (p :: Pass) a.
IsSrcSpanAnn p a =>
IdP (GhcPass p) -> LHsExpr (GhcPass p)
nlHsVar IdP (GhcPass 'Renamed)
Name
interPrintName) LHsExpr (GhcPass 'Renamed)
GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed))
rn_expr)
                                      (Name -> SyntaxExprRn
mkRnSyntaxExpr Name
thenIOName)
                                      SyntaxExpr (GhcPass 'Renamed)
forall (p :: Pass). IsPass p => SyntaxExpr (GhcPass p)
noSyntaxExpr

              -- See Note [GHCi Plans]

              it_plans =
                    -- Plan A
                    do { stuff@([it_id], _) <- [GhciLStmt (GhcPass 'Renamed)] -> Plan
tcGhciStmts [GhciLStmt (GhcPass 'Renamed)
GenLocated
  SrcSpanAnnA
  (StmtLR
     (GhcPass 'Renamed)
     (GhcPass 'Renamed)
     (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed))))
bind_stmt, GhciLStmt (GhcPass 'Renamed)
GenLocated
  SrcSpanAnnA
  (StmtLR
     (GhcPass 'Renamed)
     (GhcPass 'Renamed)
     (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed))))
print_it]
                       ; it_ty <- liftZonkM $ zonkTcType (idType it_id)
                       ; when (isUnitTy it_ty) failM
                       ; return stuff } TcM ([Id], GenLocated SrcSpanAnnA (HsExpr GhcTc))
-> [TcM ([Id], GenLocated SrcSpanAnnA (HsExpr GhcTc))]
-> NonEmpty (TcM ([Id], GenLocated SrcSpanAnnA (HsExpr GhcTc)))
forall a. a -> [a] -> NonEmpty a
:|

                        -- Plan B; a naked bind statement
                  [ [GhciLStmt (GhcPass 'Renamed)] -> Plan
tcGhciStmts [GhciLStmt (GhcPass 'Renamed)
GenLocated
  SrcSpanAnnA
  (StmtLR
     (GhcPass 'Renamed)
     (GhcPass 'Renamed)
     (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed))))
bind_stmt]

                        -- Plan C; check that the let-binding is typeable all by itself.
                        -- If not, fail; if so, try to print it.
                        -- The two-step process avoids getting two errors: one from
                        -- the expression itself, and one from the 'print it' part
                        -- This two-step story is very clunky, alas
                  , do { _ <- TcM ([Id], GenLocated SrcSpanAnnA (HsExpr GhcTc))
-> TcM ([Id], GenLocated SrcSpanAnnA (HsExpr GhcTc))
forall r. TcM r -> TcM r
checkNoErrs ([GhciLStmt (GhcPass 'Renamed)] -> Plan
tcGhciStmts [GhciLStmt (GhcPass 'Renamed)
GenLocated
  SrcSpanAnnA
  (StmtLR
     (GhcPass 'Renamed)
     (GhcPass 'Renamed)
     (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed))))
let_stmt])
                                --- checkNoErrs defeats the error recovery of let-bindings
                       ; tcGhciStmts [let_stmt, print_it] } ]

              -- Plans where we don't bind "it"
              no_it_plans =
                [GhciLStmt (GhcPass 'Renamed)] -> Plan
tcGhciStmts [GhciLStmt (GhcPass 'Renamed)
GenLocated
  SrcSpanAnnA
  (StmtLR
     (GhcPass 'Renamed)
     (GhcPass 'Renamed)
     (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed))))
no_it_a] TcM ([Id], GenLocated SrcSpanAnnA (HsExpr GhcTc))
-> [TcM ([Id], GenLocated SrcSpanAnnA (HsExpr GhcTc))]
-> NonEmpty (TcM ([Id], GenLocated SrcSpanAnnA (HsExpr GhcTc)))
forall a. a -> [a] -> NonEmpty a
:|
                [GhciLStmt (GhcPass 'Renamed)] -> Plan
tcGhciStmts [GhciLStmt (GhcPass 'Renamed)
GenLocated
  SrcSpanAnnA
  (StmtLR
     (GhcPass 'Renamed)
     (GhcPass 'Renamed)
     (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed))))
no_it_b] TcM ([Id], GenLocated SrcSpanAnnA (HsExpr GhcTc))
-> [TcM ([Id], GenLocated SrcSpanAnnA (HsExpr GhcTc))]
-> [TcM ([Id], GenLocated SrcSpanAnnA (HsExpr GhcTc))]
forall a. a -> [a] -> [a]
:
                [GhciLStmt (GhcPass 'Renamed)] -> Plan
tcGhciStmts [GhciLStmt (GhcPass 'Renamed)
GenLocated
  SrcSpanAnnA
  (StmtLR
     (GhcPass 'Renamed)
     (GhcPass 'Renamed)
     (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed))))
no_it_c] TcM ([Id], GenLocated SrcSpanAnnA (HsExpr GhcTc))
-> [TcM ([Id], GenLocated SrcSpanAnnA (HsExpr GhcTc))]
-> [TcM ([Id], GenLocated SrcSpanAnnA (HsExpr GhcTc))]
forall a. a -> [a] -> [a]
:
                []

        ; generate_it <- goptM Opt_NoIt

        -- We disable `-fdefer-type-errors` in GHCi for naked expressions.
        -- See Note [Deferred type errors in GHCi]

        -- NB: The flag `-fdefer-type-errors` implies `-fdefer-type-holes`
        -- and `-fdefer-out-of-scope-variables`. However the flag
        -- `-fno-defer-type-errors` doesn't imply `-fdefer-type-holes` and
        -- `-fno-defer-out-of-scope-variables`. Thus the later two flags
        -- also need to be unset here.
        ; plan <- unsetGOptM Opt_DeferTypeErrors $
                  unsetGOptM Opt_DeferTypedHoles $
                  unsetGOptM Opt_DeferOutOfScopeVariables $
                    runPlans $ if generate_it
                                 then no_it_plans
                                 else it_plans

        ; dumpOptTcRn Opt_D_dump_tc_ast "Typechecker AST" FormatHaskell
              (showAstData NoBlankSrcSpan NoBlankEpAnnotations plan)

        ; fix_env <- getFixityEnv
        ; return (plan, fix_env) }

{- Note [Deferred type errors in GHCi]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In GHCi, we ensure that type errors don't get deferred when type checking the
naked expressions. Deferring type errors here is unhelpful because the
expression gets evaluated right away anyway. It also would potentially emit
two redundant type-error warnings, one from each plan.

#14963 reveals another bug that when deferred type errors is enabled
in GHCi, any reference of imported/loaded variables (directly or indirectly)
in interactively issued naked expressions will cause ghc panic. See more
detailed discussion in #14963.

The interactively issued declarations, statements, as well as the modules
loaded into GHCi, are not affected. That means, for declaration, you could
have

    Prelude> :set -fdefer-type-errors
    Prelude> x :: IO (); x = putStrLn True
    <interactive>:14:26: warning: [-Wdeferred-type-errors]
        ? Couldn't match type ‘Bool’ with ‘[Char]’
          Expected type: String
            Actual type: Bool
        ? In the first argument of ‘putStrLn’, namely ‘True’
          In the expression: putStrLn True
          In an equation for ‘x’: x = putStrLn True

But for naked expressions, you will have

    Prelude> :set -fdefer-type-errors
    Prelude> putStrLn True
    <interactive>:2:10: error:
        ? Couldn't match type ‘Bool’ with ‘[Char]’
          Expected type: String
            Actual type: Bool
        ? In the first argument of ‘putStrLn’, namely ‘True’
          In the expression: putStrLn True
          In an equation for ‘it’: it = putStrLn True

    Prelude> let x = putStrLn True
    <interactive>:2:18: warning: [-Wdeferred-type-errors]
        ? Couldn't match type ‘Bool’ with ‘[Char]’
          Expected type: String
            Actual type: Bool
        ? In the first argument of ‘putStrLn’, namely ‘True’
          In the expression: putStrLn True
          In an equation for ‘x’: x = putStrLn True
-}

tcUserStmt rdr_stmt :: GhciLStmt GhcPs
rdr_stmt@(L SrcSpanAnnA
loc StmtLR GhcPs GhcPs (GenLocated SrcSpanAnnA (HsExpr GhcPs))
_)
  = do { (([rn_stmt], fix_env), fvs) <- TcM
  (([GenLocated
       SrcSpanAnnA
       (StmtLR
          (GhcPass 'Renamed)
          (GhcPass 'Renamed)
          (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed))))],
    FixityEnv),
   FreeVars)
-> TcM
     (([GenLocated
          SrcSpanAnnA
          (StmtLR
             (GhcPass 'Renamed)
             (GhcPass 'Renamed)
             (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed))))],
       FixityEnv),
      FreeVars)
forall r. TcM r -> TcM r
checkNoErrs (TcM
   (([GenLocated
        SrcSpanAnnA
        (StmtLR
           (GhcPass 'Renamed)
           (GhcPass 'Renamed)
           (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed))))],
     FixityEnv),
    FreeVars)
 -> TcM
      (([GenLocated
           SrcSpanAnnA
           (StmtLR
              (GhcPass 'Renamed)
              (GhcPass 'Renamed)
              (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed))))],
        FixityEnv),
       FreeVars))
-> TcM
     (([GenLocated
          SrcSpanAnnA
          (StmtLR
             (GhcPass 'Renamed)
             (GhcPass 'Renamed)
             (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed))))],
       FixityEnv),
      FreeVars)
-> TcM
     (([GenLocated
          SrcSpanAnnA
          (StmtLR
             (GhcPass 'Renamed)
             (GhcPass 'Renamed)
             (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed))))],
       FixityEnv),
      FreeVars)
forall a b. (a -> b) -> a -> b
$
           HsStmtContextRn
-> (HsExpr GhcPs -> RnM (HsExpr (GhcPass 'Renamed), FreeVars))
-> [LStmt GhcPs (GenLocated SrcSpanAnnA (HsExpr GhcPs))]
-> ([Name] -> IOEnv (Env TcGblEnv TcLclEnv) (FixityEnv, FreeVars))
-> IOEnv
     (Env TcGblEnv TcLclEnv)
     (([LStmt
          (GhcPass 'Renamed)
          (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))],
       FixityEnv),
      FreeVars)
forall (body :: * -> *) thing.
AnnoBody body =>
HsStmtContextRn
-> (body GhcPs -> RnM (body (GhcPass 'Renamed), FreeVars))
-> [LStmt GhcPs (LocatedA (body GhcPs))]
-> ([Name] -> RnM (thing, FreeVars))
-> RnM
     (([LStmt (GhcPass 'Renamed) (LocatedA (body (GhcPass 'Renamed)))],
       thing),
      FreeVars)
rnStmts (HsDoFlavour -> HsStmtContext (GenLocated SrcSpanAnnN Name)
forall fn. HsDoFlavour -> HsStmtContext fn
HsDoStmt HsDoFlavour
GhciStmtCtxt) HsExpr GhcPs -> RnM (HsExpr (GhcPass 'Renamed), FreeVars)
rnExpr [GhciLStmt GhcPs
LStmt GhcPs (GenLocated SrcSpanAnnA (HsExpr GhcPs))
rdr_stmt] (([Name] -> IOEnv (Env TcGblEnv TcLclEnv) (FixityEnv, FreeVars))
 -> IOEnv
      (Env TcGblEnv TcLclEnv)
      (([LStmt
           (GhcPass 'Renamed)
           (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))],
        FixityEnv),
       FreeVars))
-> ([Name] -> IOEnv (Env TcGblEnv TcLclEnv) (FixityEnv, FreeVars))
-> IOEnv
     (Env TcGblEnv TcLclEnv)
     (([LStmt
          (GhcPass 'Renamed)
          (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))],
       FixityEnv),
      FreeVars)
forall a b. (a -> b) -> a -> b
$ \[Name]
_ -> do
             fix_env <- TcRn FixityEnv
getFixityEnv
             return (fix_env, emptyFVs)
            -- Don't try to typecheck if the renamer fails!
       ; traceRn "tcRnStmt" (vcat [ppr rdr_stmt, ppr rn_stmt, ppr fvs])
       ; rnDump rn_stmt ;

       ; ghciStep <- getGhciStepIO
       ; let gi_stmt
               | (L SrcSpanAnnA
loc (BindStmt XBindStmt
  (GhcPass 'Renamed)
  (GhcPass 'Renamed)
  (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))
x LPat (GhcPass 'Renamed)
pat GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed))
expr)) <- GenLocated
  SrcSpanAnnA
  (StmtLR
     (GhcPass 'Renamed)
     (GhcPass 'Renamed)
     (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed))))
rn_stmt
                     = SrcSpanAnnA
-> StmtLR
     (GhcPass 'Renamed)
     (GhcPass 'Renamed)
     (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))
-> GenLocated
     SrcSpanAnnA
     (StmtLR
        (GhcPass 'Renamed)
        (GhcPass 'Renamed)
        (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed))))
forall l e. l -> e -> GenLocated l e
L SrcSpanAnnA
loc (StmtLR
   (GhcPass 'Renamed)
   (GhcPass 'Renamed)
   (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))
 -> GenLocated
      SrcSpanAnnA
      (StmtLR
         (GhcPass 'Renamed)
         (GhcPass 'Renamed)
         (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))))
-> StmtLR
     (GhcPass 'Renamed)
     (GhcPass 'Renamed)
     (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))
-> GenLocated
     SrcSpanAnnA
     (StmtLR
        (GhcPass 'Renamed)
        (GhcPass 'Renamed)
        (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed))))
forall a b. (a -> b) -> a -> b
$ XBindStmt
  (GhcPass 'Renamed)
  (GhcPass 'Renamed)
  (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))
-> LPat (GhcPass 'Renamed)
-> GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed))
-> StmtLR
     (GhcPass 'Renamed)
     (GhcPass 'Renamed)
     (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))
forall idL idR body.
XBindStmt idL idR body -> LPat idL -> body -> StmtLR idL idR body
BindStmt XBindStmt
  (GhcPass 'Renamed)
  (GhcPass 'Renamed)
  (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))
x LPat (GhcPass 'Renamed)
pat (LHsExpr (GhcPass 'Renamed)
-> LHsExpr (GhcPass 'Renamed) -> LHsExpr (GhcPass 'Renamed)
forall (id :: Pass).
IsPass id =>
LHsExpr (GhcPass id)
-> LHsExpr (GhcPass id) -> LHsExpr (GhcPass id)
nlHsApp LHsExpr (GhcPass 'Renamed)
GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed))
ghciStep LHsExpr (GhcPass 'Renamed)
GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed))
expr)
               | Bool
otherwise = GenLocated
  SrcSpanAnnA
  (StmtLR
     (GhcPass 'Renamed)
     (GhcPass 'Renamed)
     (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed))))
rn_stmt

       ; opt_pr_flag <- goptM Opt_PrintBindResult
       ; let print_result_plan
               | Bool
opt_pr_flag                         -- The flag says "print result"
               , [IdP (GhcPass 'Renamed)
v] <- CollectFlag (GhcPass 'Renamed)
-> LStmt
     (GhcPass 'Renamed)
     (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))
-> [IdP (GhcPass 'Renamed)]
forall (idL :: Pass) (idR :: Pass) body.
(IsPass idL, IsPass idR, CollectPass (GhcPass idL)) =>
CollectFlag (GhcPass idL)
-> LStmtLR (GhcPass idL) (GhcPass idR) body -> [IdP (GhcPass idL)]
collectLStmtBinders CollectFlag (GhcPass 'Renamed)
forall p. CollectFlag p
CollNoDictBinders LStmt
  (GhcPass 'Renamed)
  (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))
GenLocated
  SrcSpanAnnA
  (StmtLR
     (GhcPass 'Renamed)
     (GhcPass 'Renamed)
     (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed))))
gi_stmt  -- One binder
               = TcM ([Id], GenLocated SrcSpanAnnA (HsExpr GhcTc))
-> Maybe (TcM ([Id], GenLocated SrcSpanAnnA (HsExpr GhcTc)))
forall a. a -> Maybe a
Just (TcM ([Id], GenLocated SrcSpanAnnA (HsExpr GhcTc))
 -> Maybe (TcM ([Id], GenLocated SrcSpanAnnA (HsExpr GhcTc))))
-> TcM ([Id], GenLocated SrcSpanAnnA (HsExpr GhcTc))
-> Maybe (TcM ([Id], GenLocated SrcSpanAnnA (HsExpr GhcTc)))
forall a b. (a -> b) -> a -> b
$ GenLocated
  SrcSpanAnnA
  (StmtLR
     (GhcPass 'Renamed)
     (GhcPass 'Renamed)
     (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed))))
-> Name -> TcM ([Id], GenLocated SrcSpanAnnA (HsExpr GhcTc))
mk_print_result_plan GenLocated
  SrcSpanAnnA
  (StmtLR
     (GhcPass 'Renamed)
     (GhcPass 'Renamed)
     (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed))))
gi_stmt IdP (GhcPass 'Renamed)
Name
v
               | Bool
otherwise = Maybe (TcM ([Id], GenLocated SrcSpanAnnA (HsExpr GhcTc)))
forall a. Maybe a
Nothing

        -- The plans are:
        --      [stmt; print v]         if one binder and not v::()
        --      [stmt]                  otherwise
       ; plan <- runPlans $ maybe id (NE.<|) print_result_plan $ NE.singleton $ tcGhciStmts [gi_stmt]
       ; return (plan, fix_env) }
  where
    mk_print_result_plan :: GenLocated
  SrcSpanAnnA
  (StmtLR
     (GhcPass 'Renamed)
     (GhcPass 'Renamed)
     (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed))))
-> Name -> TcM ([Id], GenLocated SrcSpanAnnA (HsExpr GhcTc))
mk_print_result_plan GenLocated
  SrcSpanAnnA
  (StmtLR
     (GhcPass 'Renamed)
     (GhcPass 'Renamed)
     (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed))))
stmt Name
v
      = do { stuff@([v_id], _) <- [GhciLStmt (GhcPass 'Renamed)] -> Plan
tcGhciStmts [GhciLStmt (GhcPass 'Renamed)
GenLocated
  SrcSpanAnnA
  (StmtLR
     (GhcPass 'Renamed)
     (GhcPass 'Renamed)
     (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed))))
stmt, GhciLStmt (GhcPass 'Renamed)
GenLocated
  SrcSpanAnnA
  (StmtLR
     (GhcPass 'Renamed)
     (GhcPass 'Renamed)
     (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed))))
print_v]
           ; v_ty <- liftZonkM $ zonkTcType (idType v_id)
           ; when (isUnitTy v_ty || not (isTauTy v_ty)) failM
           ; return stuff }
      where
        print_v :: GenLocated
  SrcSpanAnnA
  (StmtLR
     (GhcPass 'Renamed)
     (GhcPass 'Renamed)
     (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed))))
print_v  = SrcSpanAnnA
-> StmtLR
     (GhcPass 'Renamed)
     (GhcPass 'Renamed)
     (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))
-> GenLocated
     SrcSpanAnnA
     (StmtLR
        (GhcPass 'Renamed)
        (GhcPass 'Renamed)
        (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed))))
forall l e. l -> e -> GenLocated l e
L SrcSpanAnnA
loc (StmtLR
   (GhcPass 'Renamed)
   (GhcPass 'Renamed)
   (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))
 -> GenLocated
      SrcSpanAnnA
      (StmtLR
         (GhcPass 'Renamed)
         (GhcPass 'Renamed)
         (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))))
-> StmtLR
     (GhcPass 'Renamed)
     (GhcPass 'Renamed)
     (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))
-> GenLocated
     SrcSpanAnnA
     (StmtLR
        (GhcPass 'Renamed)
        (GhcPass 'Renamed)
        (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed))))
forall a b. (a -> b) -> a -> b
$ XBodyStmt
  (GhcPass 'Renamed)
  (GhcPass 'Renamed)
  (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))
-> GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed))
-> SyntaxExpr (GhcPass 'Renamed)
-> SyntaxExpr (GhcPass 'Renamed)
-> StmtLR
     (GhcPass 'Renamed)
     (GhcPass 'Renamed)
     (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))
forall idL idR body.
XBodyStmt idL idR body
-> body -> SyntaxExpr idR -> SyntaxExpr idR -> StmtLR idL idR body
BodyStmt XBodyStmt
  (GhcPass 'Renamed)
  (GhcPass 'Renamed)
  (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))
NoExtField
noExtField (LHsExpr (GhcPass 'Renamed)
-> LHsExpr (GhcPass 'Renamed) -> LHsExpr (GhcPass 'Renamed)
forall (id :: Pass).
IsPass id =>
LHsExpr (GhcPass id)
-> LHsExpr (GhcPass id) -> LHsExpr (GhcPass id)
nlHsApp (IdP (GhcPass 'Renamed) -> LHsExpr (GhcPass 'Renamed)
forall (p :: Pass) a.
IsSrcSpanAnn p a =>
IdP (GhcPass p) -> LHsExpr (GhcPass p)
nlHsVar IdP (GhcPass 'Renamed)
Name
printName)
                                    (IdP (GhcPass 'Renamed) -> LHsExpr (GhcPass 'Renamed)
forall (p :: Pass) a.
IsSrcSpanAnn p a =>
IdP (GhcPass p) -> LHsExpr (GhcPass p)
nlHsVar IdP (GhcPass 'Renamed)
Name
v))
                                    (Name -> SyntaxExprRn
mkRnSyntaxExpr Name
thenIOName) SyntaxExpr (GhcPass 'Renamed)
forall (p :: Pass). IsPass p => SyntaxExpr (GhcPass p)
noSyntaxExpr

{-
Note [GHCi Plans]
~~~~~~~~~~~~~~~~~
When a user types an expression in the repl we try to print it in three different
ways. Also, depending on whether -fno-it is set, we bind a variable called `it`
which can be used to refer to the result of the expression subsequently in the repl.

The normal plans are :
  A. [it <- e; print e]     but not if it::()
  B. [it <- e]
  C. [let it = e; print it]

When -fno-it is set, the plans are:
  A. [e >>= print]
  B. [e]
  C. [let it = e in print it]

The reason for -fno-it is explained in #14336. `it` can lead to the repl
leaking memory as it is repeatedly queried.
-}

any_lifted :: Type
any_lifted :: Type
any_lifted = Type -> Type
anyTypeOfKind Type
liftedTypeKind

-- | Typecheck the statements given and then return the results of the
-- statement in the form 'IO [Any]'.
tcGhciStmts :: [GhciLStmt GhcRn] -> TcM PlanResult
tcGhciStmts :: [GhciLStmt (GhcPass 'Renamed)] -> Plan
tcGhciStmts [GhciLStmt (GhcPass 'Renamed)]
stmts
 = do { ioTyCon <- Name -> TcM TyCon
tcLookupTyCon Name
ioTyConName
      ; ret_id  <- tcLookupId returnIOName             -- return @ IO
      ; let ret_ty      = Type -> Type
mkListTy Type
any_lifted
            io_ret_ty   = TyCon -> [Type] -> Type
mkTyConApp TyCon
ioTyCon [Type
ret_ty]
            tc_io_stmts = HsStmtContextRn
-> TcStmtChecker HsExpr ExpType
-> [LStmt
      (GhcPass 'Renamed)
      (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))]
-> ExpType
-> (ExpType -> TcM [Id])
-> TcM
     ([LStmt GhcTc (GenLocated SrcSpanAnnA (HsExpr GhcTc))], [Id])
forall (body :: * -> *) rho_type thing.
AnnoBody body =>
HsStmtContextRn
-> TcStmtChecker body rho_type
-> [LStmt (GhcPass 'Renamed) (LocatedA (body (GhcPass 'Renamed)))]
-> rho_type
-> (rho_type -> TcM thing)
-> TcM ([LStmt GhcTc (LocatedA (body GhcTc))], thing)
tcStmtsAndThen (HsDoFlavour -> HsStmtContext (GenLocated SrcSpanAnnN Name)
forall fn. HsDoFlavour -> HsStmtContext fn
HsDoStmt HsDoFlavour
GhciStmtCtxt) HsStmtContextRn
-> StmtLR
     (GhcPass 'Renamed)
     (GhcPass 'Renamed)
     (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))
-> ExpType
-> (ExpType -> TcM thing)
-> TcM (Stmt GhcTc (GenLocated SrcSpanAnnA (HsExpr GhcTc)), thing)
TcStmtChecker HsExpr ExpType
tcDoStmt [GhciLStmt (GhcPass 'Renamed)]
[LStmt
   (GhcPass 'Renamed)
   (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))]
stmts
                                         (Type -> ExpType
mkCheckExpType Type
io_ret_ty)
            names = CollectFlag (GhcPass 'Renamed)
-> [LStmt
      (GhcPass 'Renamed)
      (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))]
-> [IdP (GhcPass 'Renamed)]
forall (idL :: Pass) (idR :: Pass) body.
(IsPass idL, IsPass idR, CollectPass (GhcPass idL)) =>
CollectFlag (GhcPass idL)
-> [LStmtLR (GhcPass idL) (GhcPass idR) body]
-> [IdP (GhcPass idL)]
collectLStmtsBinders CollectFlag (GhcPass 'Renamed)
forall p. CollectFlag p
CollNoDictBinders [GhciLStmt (GhcPass 'Renamed)]
[LStmt
   (GhcPass 'Renamed)
   (GenLocated SrcSpanAnnA (HsExpr (GhcPass 'Renamed)))]
stmts

        -- OK, we're ready to typecheck the stmts
      ; traceTc "GHC.Tc.Module.tcGhciStmts: tc stmts" empty
      ; ((tc_stmts, ids), lie) <- captureTopConstraints $
                                  tc_io_stmts $ \ ExpType
_ ->
                                  (Name -> TcM Id) -> [Name] -> TcM [Id]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
forall (m :: * -> *) a b. Monad m => (a -> m b) -> [a] -> m [b]
mapM Name -> TcM Id
tcLookupId [IdP (GhcPass 'Renamed)]
[Name]
names
                        -- Look up the names right in the middle,
                        -- where they will all be in scope

        -- Simplify the context
      ; traceTc "GHC.Tc.Module.tcGhciStmts: simplify ctxt" empty
      ; const_binds <- checkNoErrs (simplifyInteractive lie)
                -- checkNoErrs ensures that the plan fails if context redn fails


      ; traceTc "GHC.Tc.Module.tcGhciStmts: done" empty

      -- ret_expr is the expression
      --      returnIO @[Any] [unsafeCoerce# @Any x, ..,  unsafeCoerce# @Any z]
      --
      -- Despite the inconvenience of building the type applications etc,
      -- this *has* to be done in type-annotated post-typecheck form
      -- because we are going to return a list of *polymorphic* values
      -- coerced to type Any. If we built a *source* stmt
      --      return [coerce x, ..., coerce z]
      -- then the type checker would instantiate x..z, and we wouldn't
      -- get their *polymorphic* values.  (And we'd get ambiguity errs
      -- if they were overloaded, since they aren't applied to anything.)
      --
      -- We use Any rather than a dummy type such as () because of
      -- the rules of unsafeCoerce#; see Unsafe/Coerce.hs for the details.

      ; AnId unsafe_coerce_id <- tcLookupGlobal unsafeCoercePrimName
           -- We use unsafeCoerce# here because of (U11) in
           -- Note [Implementing unsafeCoerce] in base:Unsafe.Coerce

      ; let ret_expr = LHsExpr GhcTc -> LHsExpr GhcTc -> LHsExpr GhcTc
forall (id :: Pass).
IsPass id =>
LHsExpr (GhcPass id)
-> LHsExpr (GhcPass id) -> LHsExpr (GhcPass id)
nlHsApp (Id -> [Type] -> LHsExpr GhcTc
nlHsTyApp Id
ret_id [Type
ret_ty]) (LHsExpr GhcTc -> LHsExpr GhcTc) -> LHsExpr GhcTc -> LHsExpr GhcTc
forall a b. (a -> b) -> a -> b
$
                       HsExpr GhcTc -> GenLocated SrcSpanAnnA (HsExpr GhcTc)
forall e a. HasAnnotation e => a -> GenLocated e a
noLocA (HsExpr GhcTc -> GenLocated SrcSpanAnnA (HsExpr GhcTc))
-> HsExpr GhcTc -> GenLocated SrcSpanAnnA (HsExpr GhcTc)
forall a b. (a -> b) -> a -> b
$ XExplicitList GhcTc -> [LHsExpr GhcTc] -> HsExpr GhcTc
forall p. XExplicitList p -> [LHsExpr p] -> HsExpr p
ExplicitList XExplicitList GhcTc
Type
any_lifted ([LHsExpr GhcTc] -> HsExpr GhcTc)
-> [LHsExpr GhcTc] -> HsExpr GhcTc
forall a b. (a -> b) -> a -> b
$
                       (Id -> LHsExpr GhcTc) -> [Id] -> [LHsExpr GhcTc]
forall a b. (a -> b) -> [a] -> [b]
map Id -> LHsExpr GhcTc
mk_item [Id]
ids

            mk_item Id
id = Id
unsafe_coerce_id Id -> [Type] -> LHsExpr GhcTc
`nlHsTyApp` [ HasDebugCallStack => Type -> Type
Type -> Type
getRuntimeRep (Id -> Type
idType Id
id)
                                                      , HasDebugCallStack => Type -> Type
Type -> Type
getRuntimeRep Type
any_lifted
                                                      , Id -> Type
idType Id
id, Type
any_lifted]
                                          LHsExpr GhcTc -> LHsExpr GhcTc -> LHsExpr GhcTc
forall (id :: Pass).
IsPass id =>
LHsExpr (GhcPass id)
-> LHsExpr (GhcPass id) -> LHsExpr (GhcPass id)
`nlHsApp` IdP GhcTc -> LHsExpr GhcTc
forall (p :: Pass) a.
IsSrcSpanAnn p a =>
IdP (GhcPass p) -> LHsExpr (GhcPass p)
nlHsVar IdP GhcTc
Id
id
            stmts = [LStmt GhcTc (GenLocated SrcSpanAnnA (HsExpr GhcTc))]
[GenLocated
   SrcSpanAnnA (Stmt GhcTc (GenLocated SrcSpanAnnA (HsExpr GhcTc)))]
tc_stmts [GenLocated
   SrcSpanAnnA (Stmt GhcTc (GenLocated SrcSpanAnnA (HsExpr GhcTc)))]
-> [GenLocated
      SrcSpanAnnA (Stmt GhcTc (GenLocated SrcSpanAnnA (HsExpr GhcTc)))]
-> [GenLocated
      SrcSpanAnnA (Stmt GhcTc (GenLocated SrcSpanAnnA (HsExpr GhcTc)))]
forall a. [a] -> [a] -> [a]
++ [Stmt GhcTc (GenLocated SrcSpanAnnA (HsExpr GhcTc))
-> GenLocated
     SrcSpanAnnA (Stmt GhcTc (GenLocated SrcSpanAnnA (HsExpr GhcTc)))
forall e a. HasAnnotation e => a -> GenLocated e a
noLocA (GenLocated SrcSpanAnnA (HsExpr GhcTc)
-> Stmt GhcTc (GenLocated SrcSpanAnnA (HsExpr GhcTc))
forall (idR :: Pass) (bodyR :: * -> *) (idL :: Pass).
IsPass idR =>
LocatedA (bodyR (GhcPass idR))
-> StmtLR
     (GhcPass idL) (GhcPass idR) (LocatedA (bodyR (GhcPass idR)))
mkLastStmt LHsExpr GhcTc
GenLocated SrcSpanAnnA (HsExpr GhcTc)
ret_expr)]

      ; return (ids, mkHsDictLet (EvBinds const_binds) $
                     noLocA (HsDo io_ret_ty GhciStmtCtxt (noLocA stmts)))
    }

-- | Generate a typed ghciStepIO expression (ghciStep :: Ty a -> IO a)
getGhciStepIO :: TcM (LHsExpr GhcRn)
getGhciStepIO :: TcM (LHsExpr (GhcPass 'Renamed))
getGhciStepIO = do
    ghciTy <- TcRn Name
getGHCiMonad
    a_tv <- newName (mkTyVarOccFS (fsLit "a"))
    let ghciM   = LHsType (GhcPass 'Renamed)
-> LHsType (GhcPass 'Renamed) -> LHsType (GhcPass 'Renamed)
forall (p :: Pass).
LHsType (GhcPass p) -> LHsType (GhcPass p) -> LHsType (GhcPass p)
nlHsAppTy (PromotionFlag
-> IdP (GhcPass 'Renamed) -> LHsType (GhcPass 'Renamed)
forall (p :: Pass) a.
IsSrcSpanAnn p a =>
PromotionFlag -> IdP (GhcPass p) -> LHsType (GhcPass p)
nlHsTyVar PromotionFlag
NotPromoted IdP (GhcPass 'Renamed)
Name
ghciTy) (PromotionFlag
-> IdP (GhcPass 'Renamed) -> LHsType (GhcPass 'Renamed)
forall (p :: Pass) a.
IsSrcSpanAnn p a =>
PromotionFlag -> IdP (GhcPass p) -> LHsType (GhcPass p)
nlHsTyVar PromotionFlag
NotPromoted IdP (GhcPass 'Renamed)
Name
a_tv)
        ioM     = LHsType (GhcPass 'Renamed)
-> LHsType (GhcPass 'Renamed) -> LHsType (GhcPass 'Renamed)
forall (p :: Pass).
LHsType (GhcPass p) -> LHsType (GhcPass p) -> LHsType (GhcPass p)
nlHsAppTy (PromotionFlag
-> IdP (GhcPass 'Renamed) -> LHsType (GhcPass 'Renamed)
forall (p :: Pass) a.
IsSrcSpanAnn p a =>
PromotionFlag -> IdP (GhcPass p) -> LHsType (GhcPass p)
nlHsTyVar PromotionFlag
NotPromoted IdP (GhcPass 'Renamed)
Name
ioTyConName) (PromotionFlag
-> IdP (GhcPass 'Renamed) -> LHsType (GhcPass 'Renamed)
forall (p :: Pass) a.
IsSrcSpanAnn p a =>
PromotionFlag -> IdP (GhcPass p) -> LHsType (GhcPass p)
nlHsTyVar PromotionFlag
NotPromoted IdP (GhcPass 'Renamed)
Name
a_tv)

        step_ty :: LHsSigType GhcRn
        step_ty = HsSigType (GhcPass 'Renamed)
-> GenLocated SrcSpanAnnA (HsSigType (GhcPass 'Renamed))
forall e a. HasAnnotation e => a -> GenLocated e a
noLocA (HsSigType (GhcPass 'Renamed)
 -> GenLocated SrcSpanAnnA (HsSigType (GhcPass 'Renamed)))
-> HsSigType (GhcPass 'Renamed)
-> GenLocated SrcSpanAnnA (HsSigType (GhcPass 'Renamed))
forall a b. (a -> b) -> a -> b
$ HsSig
                     { sig_bndrs :: HsOuterSigTyVarBndrs (GhcPass 'Renamed)
sig_bndrs = HsOuterImplicit{hso_ximplicit :: XHsOuterImplicit (GhcPass 'Renamed)
hso_ximplicit = [Name
a_tv]}
                     , sig_ext :: XHsSig (GhcPass 'Renamed)
sig_ext = XHsSig (GhcPass 'Renamed)
NoExtField
noExtField
                     , sig_body :: LHsType (GhcPass 'Renamed)
sig_body = LHsType (GhcPass 'Renamed)
-> LHsType (GhcPass 'Renamed) -> LHsType (GhcPass 'Renamed)
forall (p :: Pass).
IsPass p =>
LHsType (GhcPass p) -> LHsType (GhcPass p) -> LHsType (GhcPass p)
nlHsFunTy LHsType (GhcPass 'Renamed)
ghciM LHsType (GhcPass 'Renamed)
ioM }

        stepTy :: LHsSigWcType GhcRn
        stepTy = GenLocated SrcSpanAnnA (HsSigType (GhcPass 'Renamed))
-> HsWildCardBndrs
     (GhcPass 'Renamed)
     (GenLocated SrcSpanAnnA (HsSigType (GhcPass 'Renamed)))
forall thing. thing -> HsWildCardBndrs (GhcPass 'Renamed) thing
mkEmptyWildCardBndrs LHsSigType (GhcPass 'Renamed)
GenLocated SrcSpanAnnA (HsSigType (GhcPass 'Renamed))
step_ty

    return (noLocA $ ExprWithTySig noExtField (nlHsVar ghciStepIoMName) stepTy)

isGHCiMonad :: HscEnv -> String -> IO (Messages TcRnMessage, Maybe Name)
isGHCiMonad :: HscEnv -> String -> IO (Messages TcRnMessage, Maybe Name)
isGHCiMonad HscEnv
hsc_env String
ty
  = HscEnv -> TcRn Name -> IO (Messages TcRnMessage, Maybe Name)
forall a. HscEnv -> TcRn a -> IO (Messages TcRnMessage, Maybe a)
runTcInteractive HscEnv
hsc_env (TcRn Name -> IO (Messages TcRnMessage, Maybe Name))
-> TcRn Name -> IO (Messages TcRnMessage, Maybe Name)
forall a b. (a -> b) -> a -> b
$ do
        rdrEnv <- TcRn GlobalRdrEnv
getGlobalRdrEnv
        let occIO = GlobalRdrEnv -> OccName -> Maybe [GlobalRdrElt]
forall a. OccEnv a -> OccName -> Maybe a
lookupOccEnv GlobalRdrEnv
rdrEnv (NameSpace -> String -> OccName
mkOccName NameSpace
tcName String
ty)
        case occIO of
            Just [GlobalRdrElt
n] -> do
                let name :: Name
name = GlobalRdrElt -> Name
forall info. GlobalRdrEltX info -> Name
greName GlobalRdrElt
n
                ghciClass <- Name -> TcM Class
tcLookupClass Name
ghciIoClassName
                userTyCon <- tcLookupTyCon name
                let userTy = TyCon -> [Type] -> Type
mkTyConApp TyCon
userTyCon []
                _ <- tcLookupInstance ghciClass [userTy]
                return name
            Maybe [GlobalRdrElt]
_ -> TcRnMessage -> TcRn Name
forall a. TcRnMessage -> TcM a
failWithTc (TcRnMessage -> TcRn Name) -> TcRnMessage -> TcRn Name
forall a b. (a -> b) -> a -> b
$ String -> Maybe [GlobalRdrElt] -> TcRnMessage
TcRnGhciMonadLookupFail String
ty Maybe [GlobalRdrElt]
occIO

-- | How should we infer a type? See Note [TcRnExprMode]
data TcRnExprMode = TM_Inst     -- ^ Instantiate inferred quantifiers only (:type)
                  | TM_Default  -- ^ Instantiate all quantifiers,
                                --   and do eager defaulting (:type +d)

-- | tcRnExpr just finds the type of an expression
--   for :type
tcRnExpr :: HscEnv
         -> TcRnExprMode
         -> LHsExpr GhcPs
         -> IO (Messages TcRnMessage, Maybe Type)
tcRnExpr :: HscEnv
-> TcRnExprMode
-> LHsExpr GhcPs
-> IO (Messages TcRnMessage, Maybe Type)
tcRnExpr HscEnv
hsc_env TcRnExprMode
mode LHsExpr GhcPs
rdr_expr
  = HscEnv -> TcM Type -> IO (Messages TcRnMessage, Maybe Type)
forall a. HscEnv -> TcRn a -> IO (Messages TcRnMessage, Maybe a)
runTcInteractive HscEnv
hsc_env (TcM Type -> IO (Messages TcRnMessage, Maybe Type))
-> TcM Type -> IO (Messages TcRnMessage, Maybe Type)
forall a b. (a -> b) -> a -> b
$
    do {

    (rn_expr, _fvs) <- LHsExpr GhcPs -> RnM (LHsExpr (GhcPass 'Renamed), FreeVars)
rnLExpr LHsExpr GhcPs
rdr_expr ;
    failIfErrsM ;

    -- Typecheck the expression
    ((tclvl, res_ty), lie)
          <- captureTopConstraints $
             pushTcLevelM          $
             tcInferSigma inst rn_expr ;

    -- Generalise
    uniq <- newUnique ;
    let { fresh_it = Unique -> SrcSpan -> Name
itName Unique
uniq (GenLocated SrcSpanAnnA (HsExpr GhcPs) -> SrcSpan
forall a e. HasLoc a => GenLocated a e -> SrcSpan
getLocA LHsExpr GhcPs
GenLocated SrcSpanAnnA (HsExpr GhcPs)
rdr_expr) } ;
    ((qtvs, dicts, _, _), residual)
         <- captureConstraints $
            simplifyInfer TopLevel tclvl infer_mode
                          []    {- No sig vars -}
                          [(fresh_it, res_ty)]
                          lie ;

    -- Ignore the dictionary bindings
    _ <- perhaps_disable_default_warnings $
         simplifyInteractive residual ;

    let { all_expr_ty = [Id] -> Type -> Type
mkInfForAllTys [Id]
qtvs (Type -> Type) -> Type -> Type
forall a b. (a -> b) -> a -> b
$
                        [Type] -> Type -> Type
HasDebugCallStack => [Type] -> Type -> Type
mkPhiTy ((Id -> Type) -> [Id] -> [Type]
forall a b. (a -> b) -> [a] -> [b]
map Id -> Type
idType [Id]
dicts) Type
res_ty } ;
    ty <- liftZonkM $ zonkTcType all_expr_ty ;

    -- See Note [Normalising the type in :type]
    fam_envs <- tcGetFamInstEnvs ;
    let { normalised_type = Reduction -> Type
reductionReducedType (Reduction -> Type) -> Reduction -> Type
forall a b. (a -> b) -> a -> b
$ FamInstEnvs -> Role -> Type -> Reduction
normaliseType FamInstEnvs
fam_envs Role
Nominal Type
ty
          -- normaliseType returns a coercion which we discard, so the Role is irrelevant.
        ; final_type = if Type -> Bool
isSigmaTy Type
res_ty then Type
ty else Type
normalised_type } ;
    return final_type }
  where
    -- Optionally instantiate the type of the expression
    -- See Note [TcRnExprMode]
    (Bool
inst, InferMode
infer_mode, TcRn (Bag EvBind) -> TcRn (Bag EvBind)
perhaps_disable_default_warnings) = case TcRnExprMode
mode of
      TcRnExprMode
TM_Inst    -> (Bool
False, InferMode
NoRestrictions,  TcRn (Bag EvBind) -> TcRn (Bag EvBind)
forall a. a -> a
id)
      TcRnExprMode
TM_Default -> (Bool
True,  InferMode
EagerDefaulting, WarningFlag -> TcRn (Bag EvBind) -> TcRn (Bag EvBind)
forall gbl lcl a.
WarningFlag -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
unsetWOptM WarningFlag
Opt_WarnTypeDefaults)

{- Note [Implementing :type]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider   :type const

We want    forall a b. a -> b -> a
and not    forall {a}{b}. a -> b -> a

The latter is what we'd get if we eagerly instantiated and then
re-generalised with Inferred binders.  It makes a difference, because
it tells us we where we can use Visible Type Application (VTA).

And also for   :type const @Int
we want        forall b. Int -> b -> Int
and not        forall {b}. Int -> b -> Int

Solution: use tcInferSigma, which in turn uses tcInferApp, which
has a special case for application chains.

Note [Normalising the type in :type]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In :t <expr> we usually normalise the type (to simplify type functions)
before displaying the result.  Reason (see #10321): otherwise we may show
types like
    <expr> :: Vec (1+2) Int
rather than the simpler
    <expr> :: Vec 3 Int
In GHC.Tc.Gen.Bind.mkInferredPolyId we normalise for a very similar reason.

However this normalisation is less helpful when <expr> is just
an identifier, whose user-written type happens to contain type-function
applications.  E.g. (#20974)
    test :: F [Monad, A, B] m => m ()
where F is a type family.  If we say `:t test`, we'd prefer to see
the type family un-expanded.

We adopt the following ad-hoc solution: if the type inferred for <expr>
(before generalisation, namely res_ty) is a SigmaType (i.e. is not
fully instantiated) then do not normalise; otherwise normalise.
This is not ideal; for example, suppose  x :: F Int.  Then
  :t x
would be normalised because `F Int` is not a SigmaType.  But
anything here is ad-hoc, and it's a user-sought improvement.
-}

--------------------------
tcRnImportDecls :: HscEnv
                -> [LImportDecl GhcPs]
                -> IO (Messages TcRnMessage, Maybe GlobalRdrEnv)
-- Find the new chunk of GlobalRdrEnv created by this list of import
-- decls.  In contract tcRnImports *extends* the TcGblEnv.
tcRnImportDecls :: HscEnv
-> [LImportDecl GhcPs]
-> IO (Messages TcRnMessage, Maybe GlobalRdrEnv)
tcRnImportDecls HscEnv
hsc_env [LImportDecl GhcPs]
import_decls
 =  HscEnv
-> TcRn GlobalRdrEnv
-> IO (Messages TcRnMessage, Maybe GlobalRdrEnv)
forall a. HscEnv -> TcRn a -> IO (Messages TcRnMessage, Maybe a)
runTcInteractive HscEnv
hsc_env (TcRn GlobalRdrEnv
 -> IO (Messages TcRnMessage, Maybe GlobalRdrEnv))
-> TcRn GlobalRdrEnv
-> IO (Messages TcRnMessage, Maybe GlobalRdrEnv)
forall a b. (a -> b) -> a -> b
$
    do { (_, gbl_env) <- (TcGblEnv -> TcGblEnv)
-> TcM ([NonEmpty ClassDefaults], TcGblEnv)
-> TcM ([NonEmpty ClassDefaults], TcGblEnv)
forall gbl lcl a.
(gbl -> gbl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
updGblEnv TcGblEnv -> TcGblEnv
zap_rdr_env (TcM ([NonEmpty ClassDefaults], TcGblEnv)
 -> TcM ([NonEmpty ClassDefaults], TcGblEnv))
-> TcM ([NonEmpty ClassDefaults], TcGblEnv)
-> TcM ([NonEmpty ClassDefaults], TcGblEnv)
forall a b. (a -> b) -> a -> b
$
                         HscEnv
-> [(LImportDecl GhcPs, SDoc)]
-> TcM ([NonEmpty ClassDefaults], TcGblEnv)
tcRnImports HscEnv
hsc_env ([(LImportDecl GhcPs, SDoc)]
 -> TcM ([NonEmpty ClassDefaults], TcGblEnv))
-> [(LImportDecl GhcPs, SDoc)]
-> TcM ([NonEmpty ClassDefaults], TcGblEnv)
forall a b. (a -> b) -> a -> b
$ (GenLocated SrcSpanAnnA (ImportDecl GhcPs)
 -> (LImportDecl GhcPs, SDoc))
-> [GenLocated SrcSpanAnnA (ImportDecl GhcPs)]
-> [(LImportDecl GhcPs, SDoc)]
forall a b. (a -> b) -> [a] -> [b]
map (,String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"is directly imported") [LImportDecl GhcPs]
[GenLocated SrcSpanAnnA (ImportDecl GhcPs)]
import_decls
       ; return (tcg_rdr_env gbl_env) }
  where
    zap_rdr_env :: TcGblEnv -> TcGblEnv
zap_rdr_env TcGblEnv
gbl_env = TcGblEnv
gbl_env { tcg_rdr_env = emptyGlobalRdrEnv }

-- tcRnType just finds the kind of a type
tcRnType :: HscEnv
         -> ZonkFlexi
         -> Bool        -- Normalise the returned type
         -> LHsType GhcPs
         -> IO (Messages TcRnMessage, Maybe (Type, Kind))
tcRnType :: HscEnv
-> ZonkFlexi
-> Bool
-> LHsType GhcPs
-> IO (Messages TcRnMessage, Maybe (Type, Type))
tcRnType HscEnv
hsc_env ZonkFlexi
flexi Bool
normalise LHsType GhcPs
rdr_type
  = HscEnv
-> TcM (Type, Type)
-> IO (Messages TcRnMessage, Maybe (Type, Type))
forall a. HscEnv -> TcRn a -> IO (Messages TcRnMessage, Maybe a)
runTcInteractive HscEnv
hsc_env (TcM (Type, Type) -> IO (Messages TcRnMessage, Maybe (Type, Type)))
-> TcM (Type, Type)
-> IO (Messages TcRnMessage, Maybe (Type, Type))
forall a b. (a -> b) -> a -> b
$
    Extension -> TcM (Type, Type) -> TcM (Type, Type)
forall gbl lcl a. Extension -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
setXOptM Extension
LangExt.PolyKinds (TcM (Type, Type) -> TcM (Type, Type))
-> TcM (Type, Type) -> TcM (Type, Type)
forall a b. (a -> b) -> a -> b
$   -- See Note [Kind-generalise in tcRnType]
    do { (HsWC { hswc_ext = wcs, hswc_body = rn_sig_type@(L _ (HsSig{sig_bndrs = outer_bndrs, sig_body = body })) }, _fvs)
                 -- we are using 'rnHsSigWcType' to bind the unbound type variables
                 -- and in combination with 'tcOuterTKBndrs' we are able to
                 -- implicitly quantify them as if the user wrote 'forall' by
                 -- hand (see #19217). This allows kind check to work in presence
                 -- of free type variables :
                 -- ghci> :k [a]
                 -- [a] :: *
               <- HsDocContext
-> LHsSigWcType GhcPs
-> RnM (LHsSigWcType (GhcPass 'Renamed), FreeVars)
rnHsSigWcType HsDocContext
GHCiCtx (LHsSigType GhcPs -> LHsSigWcType GhcPs
forall thing. thing -> HsWildCardBndrs GhcPs thing
mkHsWildCardBndrs (LHsSigType GhcPs -> LHsSigWcType GhcPs)
-> LHsSigType GhcPs -> LHsSigWcType GhcPs
forall a b. (a -> b) -> a -> b
$ HsSigType GhcPs -> GenLocated SrcSpanAnnA (HsSigType GhcPs)
forall e a. HasAnnotation e => a -> GenLocated e a
noLocA (LHsType GhcPs -> HsSigType GhcPs
mkHsImplicitSigType LHsType GhcPs
rdr_type))
                  -- The type can have wild cards, but no implicit
                  -- generalisation; e.g.   :kind (T _)
       ; failIfErrsM

        -- We follow Note [Recipe for checking a signature] in GHC.Tc.Gen.HsType here

        -- Now kind-check the type
        -- It can have any rank or kind
        -- First bring into scope any wildcards
       ; traceTc "tcRnType" (vcat [ppr wcs, ppr rn_sig_type])
       ; si <- mkSkolemInfo $ SigTypeSkol (GhciCtxt True)
       ; ((_, (ty, kind)), wanted)
               <- captureTopConstraints $
                  pushTcLevelM_         $
                  bindNamedWildCardBinders wcs $ \ [(Name, Id)]
wcs' ->
                  do { ((Name, Id) -> IOEnv (Env TcGblEnv TcLclEnv) ())
-> [(Name, Id)] -> IOEnv (Env TcGblEnv TcLclEnv) ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (Name, Id) -> IOEnv (Env TcGblEnv TcLclEnv) ()
emitNamedTypeHole [(Name, Id)]
wcs'
                     ; SkolemInfo
-> HsOuterSigTyVarBndrs (GhcPass 'Renamed)
-> TcM (Type, Type)
-> TcM (HsOuterTyVarBndrs Specificity GhcTc, (Type, Type))
forall flag a.
OutputableBndrFlag flag 'Renamed =>
SkolemInfo
-> HsOuterTyVarBndrs flag (GhcPass 'Renamed)
-> TcM a
-> TcM (HsOuterTyVarBndrs flag GhcTc, a)
tcOuterTKBndrs SkolemInfo
si HsOuterSigTyVarBndrs (GhcPass 'Renamed)
outer_bndrs (TcM (Type, Type)
 -> TcM (HsOuterTyVarBndrs Specificity GhcTc, (Type, Type)))
-> TcM (Type, Type)
-> TcM (HsOuterTyVarBndrs Specificity GhcTc, (Type, Type))
forall a b. (a -> b) -> a -> b
$ LHsType (GhcPass 'Renamed) -> TcM (Type, Type)
tcInferLHsTypeUnsaturated LHsType (GhcPass 'Renamed)
body }
       -- Since all the wanteds are equalities, the returned bindings will be empty
       ; empty_binds <- simplifyTop wanted
       ; massertPpr (isEmptyBag empty_binds) (ppr empty_binds)

       -- Do kind generalisation; see Note [Kind-generalise in tcRnType]
       ; kvs <- kindGeneralizeAll unkSkol kind

       ; ty  <- initZonkEnv flexi $ zonkTcTypeToTypeX ty

       -- Do validity checking on type
       ; checkValidType (GhciCtxt True) ty

       -- Optionally (:k vs :k!) normalise the type. Does two things:
       --   normaliseType: expand type-family applications
       --   expandTypeSynonyms: expand type synonyms (#18828)
       ; fam_envs <- tcGetFamInstEnvs
       ; let ty' | Bool
normalise = Type -> Type
expandTypeSynonyms (Type -> Type) -> Type -> Type
forall a b. (a -> b) -> a -> b
$ Reduction -> Type
reductionReducedType (Reduction -> Type) -> Reduction -> Type
forall a b. (a -> b) -> a -> b
$
                               FamInstEnvs -> Role -> Type -> Reduction
normaliseType FamInstEnvs
fam_envs Role
Nominal Type
ty
                 | Bool
otherwise = Type
ty

       ; traceTc "tcRnExpr" (debugPprType ty $$ debugPprType ty')
       ; return (ty', mkInfForAllTys kvs (typeKind ty')) }


{- Note [TcRnExprMode]
~~~~~~~~~~~~~~~~~~~~~~
How should we infer a type when a user asks for the type of an expression e
at the GHCi prompt? We offer 2 different possibilities, described below. Each
considers this example, with -fprint-explicit-foralls enabled.  See also
https://github.com/ghc-proposals/ghc-proposals/blob/master/proposals/0179-printing-foralls.rst

:type / TM_Inst

  In this mode, we report the type obtained by instantiating only the
  /inferred/ quantifiers of e's type, solving constraints, and
  re-generalising, as discussed in #11376.

  > :type reverse
  reverse :: forall a. [a] -> [a]

  -- foo :: forall a f b. (Show a, Num b, Foldable f) => a -> f b -> String
  > :type foo @Int
  forall f b. (Show Int, Num b, Foldable f) => Int -> f b -> String

  Note that Show Int is still reported, because the solver never got a chance
  to see it.

:type +d / TM_Default

  This mode is for the benefit of users who wish to see instantiations
  of generalized types, and in particular to instantiate Foldable and
  Traversable.  In this mode, all type variables (inferred or
  specified) are instantiated.  Because GHCi uses
  -XExtendedDefaultRules, this means that Foldable and Traversable are
  defaulted.

  > :type +d reverse
  reverse :: forall {a}. [a] -> [a]

  -- foo :: forall a f b. (Show a, Num b, Foldable f) => a -> f b -> String
  > :type +d foo @Int
  Int -> [Integer] -> String

  Note that this mode can sometimes lead to a type error, if a type variable is
  used with a defaultable class but cannot actually be defaulted:

  bar :: (Num a, Monoid a) => a -> a
  > :type +d bar
  ** error **

  The error arises because GHC tries to default a but cannot find a concrete
  type in the defaulting list that is both Num and Monoid. (If this list is
  modified to include an element that is both Num and Monoid, the defaulting
  would succeed, of course.)

  Note that the variables and constraints are reordered here, because this
  is possible during regeneralization. Also note that the variables are
  reported as Inferred instead of Specified.

Note [Kind-generalise in tcRnType]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We switch on PolyKinds when kind-checking a user type, so that we will
kind-generalise the type, even when PolyKinds is not otherwise on.
This gives the right default behaviour at the GHCi prompt, where if
you say ":k T", and T has a polymorphic kind, you'd like to see that
polymorphism. Of course.  If T isn't kind-polymorphic you won't get
anything unexpected, but the apparent *loss* of polymorphism, for
types that you know are polymorphic, is quite surprising.  See Trac
#7688 for a discussion.

Note that the goal is to generalise the *kind of the type*, not
the type itself! Example:
  ghci> data SameKind :: k -> k -> Type
  ghci> :k SameKind _

We want to get `k -> Type`, not `Any -> Type`, which is what we would
get without kind-generalisation. Note that `:k SameKind` is OK, as
GHC will not instantiate SameKind here, and so we see its full kind
of `forall k. k -> k -> Type`.

************************************************************************
*                                                                      *
                 tcRnDeclsi
*                                                                      *
************************************************************************

tcRnDeclsi exists to allow class, data, and other declarations in GHCi.
-}

tcRnDeclsi :: HscEnv
           -> [LHsDecl GhcPs]
           -> IO (Messages TcRnMessage, Maybe TcGblEnv)
tcRnDeclsi :: HscEnv
-> [LHsDecl GhcPs] -> IO (Messages TcRnMessage, Maybe TcGblEnv)
tcRnDeclsi HscEnv
hsc_env [LHsDecl GhcPs]
local_decls
  = HscEnv -> TcM TcGblEnv -> IO (Messages TcRnMessage, Maybe TcGblEnv)
forall a. HscEnv -> TcRn a -> IO (Messages TcRnMessage, Maybe a)
runTcInteractive HscEnv
hsc_env (TcM TcGblEnv -> IO (Messages TcRnMessage, Maybe TcGblEnv))
-> TcM TcGblEnv -> IO (Messages TcRnMessage, Maybe TcGblEnv)
forall a b. (a -> b) -> a -> b
$
    Bool
-> Maybe (GenLocated SrcSpanAnnLI [XRec GhcPs (IE GhcPs)])
-> [LHsDecl GhcPs]
-> TcM TcGblEnv
tcRnSrcDecls Bool
False Maybe (GenLocated SrcSpanAnnLI [XRec GhcPs (IE GhcPs)])
Maybe (GenLocated SrcSpanAnnLI [GenLocated SrcSpanAnnA (IE GhcPs)])
forall a. Maybe a
Nothing [LHsDecl GhcPs]
local_decls

externaliseAndTidyId :: Module -> Id -> TcM Id
externaliseAndTidyId :: Module -> Id -> TcM Id
externaliseAndTidyId Module
this_mod Id
id
  = do { name' <- Module -> Name -> TcRn Name
forall m n. Module -> Name -> TcRnIf m n Name
externaliseName Module
this_mod (Id -> Name
idName Id
id)
       ; return $ globaliseId id
                     `setIdName` name'
                     `setIdType` tidyTopType (idType id) }


{-
************************************************************************
*                                                                      *
        More GHCi stuff, to do with browsing and getting info
*                                                                      *
************************************************************************
-}

-- | ASSUMES that the module is either in the 'HomePackageTable' or is
-- a package module with an interface on disk.  If neither of these is
-- true, then the result will be an error indicating the interface
-- could not be found.
getModuleInterface :: HscEnv -> Module -> IO (Messages TcRnMessage, Maybe ModIface)
getModuleInterface :: HscEnv
-> Module
-> IO (Messages TcRnMessage, Maybe (ModIface_ 'ModIfaceFinal))
getModuleInterface HscEnv
hsc_env Module
mod
  = HscEnv
-> IOEnv (Env TcGblEnv TcLclEnv) (ModIface_ 'ModIfaceFinal)
-> IO (Messages TcRnMessage, Maybe (ModIface_ 'ModIfaceFinal))
forall a. HscEnv -> TcRn a -> IO (Messages TcRnMessage, Maybe a)
runTcInteractive HscEnv
hsc_env (IOEnv (Env TcGblEnv TcLclEnv) (ModIface_ 'ModIfaceFinal)
 -> IO (Messages TcRnMessage, Maybe (ModIface_ 'ModIfaceFinal)))
-> IOEnv (Env TcGblEnv TcLclEnv) (ModIface_ 'ModIfaceFinal)
-> IO (Messages TcRnMessage, Maybe (ModIface_ 'ModIfaceFinal))
forall a b. (a -> b) -> a -> b
$
    SDoc
-> Module
-> IOEnv (Env TcGblEnv TcLclEnv) (ModIface_ 'ModIfaceFinal)
loadModuleInterface (String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"getModuleInterface") Module
mod

tcRnLookupRdrName :: HscEnv -> LocatedN RdrName
                  -> IO (Messages TcRnMessage, Maybe [Name])
-- ^ Find all the Names that this RdrName could mean, in GHCi
tcRnLookupRdrName :: HscEnv
-> GenLocated SrcSpanAnnN RdrName
-> IO (Messages TcRnMessage, Maybe [Name])
tcRnLookupRdrName HscEnv
hsc_env (L SrcSpanAnnN
loc RdrName
rdr_name)
  = HscEnv -> TcRn [Name] -> IO (Messages TcRnMessage, Maybe [Name])
forall a. HscEnv -> TcRn a -> IO (Messages TcRnMessage, Maybe a)
runTcInteractive HscEnv
hsc_env (TcRn [Name] -> IO (Messages TcRnMessage, Maybe [Name]))
-> TcRn [Name] -> IO (Messages TcRnMessage, Maybe [Name])
forall a b. (a -> b) -> a -> b
$
    SrcSpanAnnN -> TcRn [Name] -> TcRn [Name]
forall ann a. EpAnn ann -> TcRn a -> TcRn a
setSrcSpanA SrcSpanAnnN
loc          (TcRn [Name] -> TcRn [Name]) -> TcRn [Name] -> TcRn [Name]
forall a b. (a -> b) -> a -> b
$
    do {   -- If the identifier is a constructor (begins with an
           -- upper-case letter), then we need to consider both
           -- constructor and type class identifiers.
         let rdr_names :: [RdrName]
rdr_names = RdrName -> [RdrName]
dataTcOccs RdrName
rdr_name
       ; names_s <- (RdrName -> TcRn [Name])
-> [RdrName] -> IOEnv (Env TcGblEnv TcLclEnv) [[Name]]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
forall (m :: * -> *) a b. Monad m => (a -> m b) -> [a] -> m [b]
mapM RdrName -> TcRn [Name]
lookupInfoOccRn [RdrName]
rdr_names
       ; let names = [[Name]] -> [Name]
forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat [[Name]]
names_s
       ; when (null names) (addErrTc $ mkTcRnNotInScope rdr_name NotInScope)
       ; return names }

tcRnLookupName :: HscEnv -> Name -> IO (Messages TcRnMessage, Maybe TyThing)
tcRnLookupName :: HscEnv -> Name -> IO (Messages TcRnMessage, Maybe TyThing)
tcRnLookupName HscEnv
hsc_env Name
name
  = HscEnv -> TcM TyThing -> IO (Messages TcRnMessage, Maybe TyThing)
forall a. HscEnv -> TcRn a -> IO (Messages TcRnMessage, Maybe a)
runTcInteractive HscEnv
hsc_env (TcM TyThing -> IO (Messages TcRnMessage, Maybe TyThing))
-> TcM TyThing -> IO (Messages TcRnMessage, Maybe TyThing)
forall a b. (a -> b) -> a -> b
$
    Name -> TcM TyThing
tcRnLookupName' Name
name

-- To look up a name we have to look in the local environment (tcl_lcl)
-- as well as the global environment, which is what tcLookup does.
-- But we also want a TyThing, so we have to convert:

tcRnLookupName' :: Name -> TcRn TyThing
tcRnLookupName' :: Name -> TcM TyThing
tcRnLookupName' Name
name = do
   tcthing <- Name -> TcM TcTyThing
tcLookup Name
name
   case tcthing of
     AGlobal TyThing
thing    -> TyThing -> TcM TyThing
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return TyThing
thing
     ATcId{tct_id :: TcTyThing -> Id
tct_id=Id
id} -> TyThing -> TcM TyThing
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Id -> TyThing
AnId Id
id)
     TcTyThing
_ -> String -> TcM TyThing
forall a. HasCallStack => String -> a
panic String
"tcRnLookupName'"

tcRnGetInfo :: HscEnv
            -> Name
            -> IO ( Messages TcRnMessage
                  , Maybe (TyThing, Fixity, [ClsInst], [FamInst], SDoc))

-- Used to implement :info in GHCi
--
-- Look up a RdrName and return all the TyThings it might be
-- A capitalised RdrName is given to us in the DataName namespace,
-- but we want to treat it as *both* a data constructor
--  *and* as a type or class constructor;
-- hence the call to dataTcOccs, and we return up to two results
tcRnGetInfo :: HscEnv
-> Name
-> IO
     (Messages TcRnMessage,
      Maybe (TyThing, Fixity, [ClsInst], [FamInst], SDoc))
tcRnGetInfo HscEnv
hsc_env Name
name
  = HscEnv
-> TcRn (TyThing, Fixity, [ClsInst], [FamInst], SDoc)
-> IO
     (Messages TcRnMessage,
      Maybe (TyThing, Fixity, [ClsInst], [FamInst], SDoc))
forall a. HscEnv -> TcRn a -> IO (Messages TcRnMessage, Maybe a)
runTcInteractive HscEnv
hsc_env (TcRn (TyThing, Fixity, [ClsInst], [FamInst], SDoc)
 -> IO
      (Messages TcRnMessage,
       Maybe (TyThing, Fixity, [ClsInst], [FamInst], SDoc)))
-> TcRn (TyThing, Fixity, [ClsInst], [FamInst], SDoc)
-> IO
     (Messages TcRnMessage,
      Maybe (TyThing, Fixity, [ClsInst], [FamInst], SDoc))
forall a b. (a -> b) -> a -> b
$
    do { HscEnv -> InteractiveContext -> IOEnv (Env TcGblEnv TcLclEnv) ()
loadUnqualIfaces HscEnv
hsc_env (HscEnv -> InteractiveContext
hsc_IC HscEnv
hsc_env)
           -- Load the interface for all unqualified types and classes
           -- That way we will find all the instance declarations
           -- (Packages have not orphan modules, and we assume that
           --  in the home package all relevant modules are loaded.)

       ; thing  <- Name -> TcM TyThing
tcRnLookupName' Name
name
       ; fixity <- lookupFixityRn name
       ; (cls_insts, fam_insts) <- lookupInsts thing
       ; let info = Name -> SDoc
lookupKnownNameInfo Name
name
       ; return (thing, fixity, cls_insts, fam_insts, info) }


-- Lookup all class and family instances for a type constructor.
--
-- This function filters all instances in the type environment, so there
-- is a lot of duplicated work if it is called many times in the same
-- type environment. If this becomes a problem, the NameEnv computed
-- in GHC.getNameToInstancesIndex could be cached in TcM and both functions
-- could be changed to consult that index.
lookupInsts :: TyThing -> TcM ([ClsInst],[FamInst])
lookupInsts :: TyThing -> TcM ([ClsInst], [FamInst])
lookupInsts (ATyCon TyCon
tc)
  = do  { InstEnvs { ie_global = pkg_ie, ie_local = home_ie, ie_visible = vis_mods } <- TcM InstEnvs
tcGetInstEnvs
        ; (pkg_fie, home_fie) <- tcGetFamInstEnvs
                -- Load all instances for all classes that are
                -- in the type environment (which are all the ones
                -- we've seen in any interface file so far)

          -- Return only the instances relevant to the given thing, i.e.
          -- the instances whose head contains the thing's name.
        ; let cls_insts =
                 [ ClsInst
ispec        -- Search all
                 | ClsInst
ispec <- InstEnv -> [ClsInst]
instEnvElts InstEnv
home_ie [ClsInst] -> [ClsInst] -> [ClsInst]
forall a. [a] -> [a] -> [a]
++ InstEnv -> [ClsInst]
instEnvElts InstEnv
pkg_ie
                 , VisibleOrphanModules -> ClsInst -> Bool
instIsVisible VisibleOrphanModules
vis_mods ClsInst
ispec
                 , Name
tc_name Name -> FreeVars -> Bool
`elemNameSet` ClsInst -> FreeVars
orphNamesOfClsInst ClsInst
ispec ]
        ; let fam_insts =
                 [ FamInst
fispec
                 | FamInst
fispec <- FamInstEnv -> [FamInst]
famInstEnvElts FamInstEnv
home_fie [FamInst] -> [FamInst] -> [FamInst]
forall a. [a] -> [a] -> [a]
++ FamInstEnv -> [FamInst]
famInstEnvElts FamInstEnv
pkg_fie
                 , Name
tc_name Name -> FreeVars -> Bool
`elemNameSet` FamInst -> FreeVars
orphNamesOfFamInst FamInst
fispec ]
        ; return (cls_insts, fam_insts) }
  where
    tc_name :: Name
tc_name     = TyCon -> Name
tyConName TyCon
tc

lookupInsts TyThing
_ = ([ClsInst], [FamInst]) -> TcM ([ClsInst], [FamInst])
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return ([],[])

loadUnqualIfaces :: HscEnv -> InteractiveContext -> TcM ()
-- Load the interface for everything that is in scope unqualified
-- This is so that we can accurately report the instances for
-- something
loadUnqualIfaces :: HscEnv -> InteractiveContext -> IOEnv (Env TcGblEnv TcLclEnv) ()
loadUnqualIfaces HscEnv
hsc_env InteractiveContext
ictxt
  = IfG () -> IOEnv (Env TcGblEnv TcLclEnv) ()
forall a. IfG a -> TcRn a
initIfaceTcRn (IfG () -> IOEnv (Env TcGblEnv TcLclEnv) ())
-> IfG () -> IOEnv (Env TcGblEnv TcLclEnv) ()
forall a b. (a -> b) -> a -> b
$
    (Module -> IOEnv (Env IfGblEnv ()) (ModIface_ 'ModIfaceFinal))
-> [Module] -> IfG ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (SDoc
-> Module -> IOEnv (Env IfGblEnv ()) (ModIface_ 'ModIfaceFinal)
forall lcl. SDoc -> Module -> IfM lcl (ModIface_ 'ModIfaceFinal)
loadSysInterface SDoc
doc) (VisibleOrphanModules -> [Module]
moduleSetElts ([Module] -> VisibleOrphanModules
mkModuleSet [Module]
unqual_mods))
  where
    home_unit :: HomeUnit
home_unit = HscEnv -> HomeUnit
hsc_home_unit HscEnv
hsc_env

    unqual_mods :: [Module]
unqual_mods = [ HasDebugCallStack => Name -> Module
Name -> Module
nameModule Name
name
                  | GlobalRdrElt
gre <- GlobalRdrEnv -> [GlobalRdrElt]
forall info. GlobalRdrEnvX info -> [GlobalRdrEltX info]
globalRdrEnvElts (InteractiveContext -> GlobalRdrEnv
icReaderEnv InteractiveContext
ictxt)
                  , let name :: Name
name = GlobalRdrElt -> Name
forall info. GlobalRdrEltX info -> Name
greName GlobalRdrElt
gre
                  , HomeUnit -> Name -> Bool
nameIsFromExternalPackage HomeUnit
home_unit Name
name
                  , OccName -> Bool
isTcOcc (Name -> OccName
nameOccName Name
name)   -- Types and classes only
                  , GlobalRdrElt -> Bool
forall info. GlobalRdrEltX info -> Bool
unQualOK GlobalRdrElt
gre ]               -- In scope unqualified
    doc :: SDoc
doc = String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"Need interface for module whose export(s) are in scope unqualified"



{-
************************************************************************
*                                                                      *
                Debugging output
      This is what happens when you do -ddump-types
*                                                                      *
************************************************************************
-}

-- | Dump, with a banner, if -ddump-rn
rnDump :: (Outputable a, Data a) => a -> TcRn ()
rnDump :: forall a.
(Outputable a, Data a) =>
a -> IOEnv (Env TcGblEnv TcLclEnv) ()
rnDump a
rn = DumpFlag
-> String -> DumpFormat -> SDoc -> IOEnv (Env TcGblEnv TcLclEnv) ()
dumpOptTcRn DumpFlag
Opt_D_dump_rn String
"Renamer" DumpFormat
FormatHaskell (a -> SDoc
forall a. Outputable a => a -> SDoc
ppr a
rn)

tcDump :: TcGblEnv -> TcRn ()
tcDump :: TcGblEnv -> IOEnv (Env TcGblEnv TcLclEnv) ()
tcDump TcGblEnv
env
 = do { unit_state <- HasDebugCallStack => HscEnv -> UnitState
HscEnv -> UnitState
hsc_units (HscEnv -> UnitState)
-> TcRnIf TcGblEnv TcLclEnv HscEnv
-> IOEnv (Env TcGblEnv TcLclEnv) UnitState
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> TcRnIf TcGblEnv TcLclEnv HscEnv
forall gbl lcl. TcRnIf gbl lcl HscEnv
getTopEnv ;
        logger <- getLogger ;

        -- Dump short output if -ddump-types or -ddump-tc
        when (logHasDumpFlag logger Opt_D_dump_types || logHasDumpFlag logger Opt_D_dump_tc)
          (dumpTcRn True Opt_D_dump_types
            "" FormatText (pprWithUnitState unit_state short_dump)) ;

        -- Dump bindings if -ddump-tc
        dumpOptTcRn Opt_D_dump_tc "Typechecker" FormatHaskell full_dump;

        -- Dump bindings as an hsSyn AST if -ddump-tc-ast
        dumpOptTcRn Opt_D_dump_tc_ast "Typechecker AST" FormatHaskell ast_dump
   }
  where
    short_dump :: SDoc
short_dump = TcGblEnv -> SDoc
pprTcGblEnv TcGblEnv
env
    full_dump :: SDoc
full_dump  = LHsBinds GhcTc -> SDoc
forall (idL :: Pass) (idR :: Pass).
(OutputableBndrId idL, OutputableBndrId idR) =>
LHsBindsLR (GhcPass idL) (GhcPass idR) -> SDoc
pprLHsBinds (TcGblEnv -> LHsBinds GhcTc
tcg_binds TcGblEnv
env)
        -- NB: foreign x-d's have undefined's in their types;
        --     hence can't show the tc_fords
    ast_dump :: SDoc
ast_dump = BlankSrcSpan
-> BlankEpAnnotations
-> [GenLocated SrcSpanAnnA (HsBindLR GhcTc GhcTc)]
-> SDoc
forall a. Data a => BlankSrcSpan -> BlankEpAnnotations -> a -> SDoc
showAstData BlankSrcSpan
NoBlankSrcSpan BlankEpAnnotations
NoBlankEpAnnotations (TcGblEnv -> LHsBinds GhcTc
tcg_binds TcGblEnv
env)

-- It's unpleasant having both pprModGuts and pprModDetails here
pprTcGblEnv :: TcGblEnv -> SDoc
pprTcGblEnv :: TcGblEnv -> SDoc
pprTcGblEnv (TcGblEnv { tcg_type_env :: TcGblEnv -> TypeEnv
tcg_type_env  = TypeEnv
type_env,
                        tcg_insts :: TcGblEnv -> [ClsInst]
tcg_insts     = [ClsInst]
insts,
                        tcg_fam_insts :: TcGblEnv -> [FamInst]
tcg_fam_insts = [FamInst]
fam_insts,
                        tcg_rules :: TcGblEnv -> [LRuleDecl GhcTc]
tcg_rules     = [LRuleDecl GhcTc]
rules,
                        tcg_imports :: TcGblEnv -> ImportAvails
tcg_imports   = ImportAvails
imports })
  = (Bool -> SDoc) -> SDoc
forall doc. IsOutput doc => (Bool -> doc) -> doc
getPprDebug ((Bool -> SDoc) -> SDoc) -> (Bool -> SDoc) -> SDoc
forall a b. (a -> b) -> a -> b
$ \Bool
debug ->
    [SDoc] -> SDoc
forall doc. IsDoc doc => [doc] -> doc
vcat [ Bool -> TypeEnv -> SDoc
ppr_types Bool
debug TypeEnv
type_env
         , Bool -> [FamInst] -> TypeEnv -> SDoc
ppr_tycons Bool
debug [FamInst]
fam_insts TypeEnv
type_env
         , Bool -> TypeEnv -> SDoc
ppr_datacons Bool
debug TypeEnv
type_env
         , TypeEnv -> SDoc
ppr_patsyns TypeEnv
type_env
         , [ClsInst] -> SDoc
ppr_insts [ClsInst]
insts
         , [FamInst] -> SDoc
ppr_fam_insts [FamInst]
fam_insts
         , [LRuleDecl GhcTc] -> SDoc
ppr_rules [LRuleDecl GhcTc]
rules
         , String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"Dependent modules:" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+>
                ([(InstalledModule, ModuleNameWithIsBoot)] -> SDoc
forall a. Outputable a => a -> SDoc
ppr ([(InstalledModule, ModuleNameWithIsBoot)] -> SDoc)
-> (InstalledModuleEnv ModuleNameWithIsBoot
    -> [(InstalledModule, ModuleNameWithIsBoot)])
-> InstalledModuleEnv ModuleNameWithIsBoot
-> SDoc
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [(InstalledModule, ModuleNameWithIsBoot)]
-> [(InstalledModule, ModuleNameWithIsBoot)]
forall a. Ord a => [a] -> [a]
sort ([(InstalledModule, ModuleNameWithIsBoot)]
 -> [(InstalledModule, ModuleNameWithIsBoot)])
-> (InstalledModuleEnv ModuleNameWithIsBoot
    -> [(InstalledModule, ModuleNameWithIsBoot)])
-> InstalledModuleEnv ModuleNameWithIsBoot
-> [(InstalledModule, ModuleNameWithIsBoot)]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. InstalledModuleEnv ModuleNameWithIsBoot
-> [(InstalledModule, ModuleNameWithIsBoot)]
forall a. InstalledModuleEnv a -> [(InstalledModule, a)]
installedModuleEnvElts (InstalledModuleEnv ModuleNameWithIsBoot -> SDoc)
-> InstalledModuleEnv ModuleNameWithIsBoot -> SDoc
forall a b. (a -> b) -> a -> b
$ ImportAvails -> InstalledModuleEnv ModuleNameWithIsBoot
imp_direct_dep_mods ImportAvails
imports)
         , String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"Dependent packages:" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+>
                [UnitId] -> SDoc
forall a. Outputable a => a -> SDoc
ppr (Set UnitId -> [UnitId]
forall a. Set a -> [a]
S.toList (Set UnitId -> [UnitId]) -> Set UnitId -> [UnitId]
forall a b. (a -> b) -> a -> b
$ ImportAvails -> Set UnitId
imp_dep_direct_pkgs ImportAvails
imports)]
                -- The use of sort is just to reduce unnecessary
                -- wobbling in testsuite output

ppr_rules :: [LRuleDecl GhcTc] -> SDoc
ppr_rules :: [LRuleDecl GhcTc] -> SDoc
ppr_rules [LRuleDecl GhcTc]
rules
  = Bool -> SDoc -> SDoc
forall doc. IsOutput doc => Bool -> doc -> doc
ppUnless ([GenLocated SrcSpanAnnA (RuleDecl GhcTc)] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [LRuleDecl GhcTc]
[GenLocated SrcSpanAnnA (RuleDecl GhcTc)]
rules) (SDoc -> SDoc) -> SDoc -> SDoc
forall a b. (a -> b) -> a -> b
$
    SDoc -> Arity -> SDoc -> SDoc
hang (String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"RULES")
       Arity
2 ([SDoc] -> SDoc
forall doc. IsDoc doc => [doc] -> doc
vcat ((GenLocated SrcSpanAnnA (RuleDecl GhcTc) -> SDoc)
-> [GenLocated SrcSpanAnnA (RuleDecl GhcTc)] -> [SDoc]
forall a b. (a -> b) -> [a] -> [b]
map GenLocated SrcSpanAnnA (RuleDecl GhcTc) -> SDoc
forall a. Outputable a => a -> SDoc
ppr [LRuleDecl GhcTc]
[GenLocated SrcSpanAnnA (RuleDecl GhcTc)]
rules))

ppr_types :: Bool -> TypeEnv -> SDoc
ppr_types :: Bool -> TypeEnv -> SDoc
ppr_types Bool
debug TypeEnv
type_env
  = String -> (Id -> SDoc) -> [Id] -> SDoc
forall a. String -> (a -> SDoc) -> [a] -> SDoc
ppr_things String
"TYPE SIGNATURES" Id -> SDoc
ppr_sig
             ((Id -> Id -> Ordering) -> [Id] -> [Id]
forall a. (a -> a -> Ordering) -> [a] -> [a]
sortBy ((Id -> OccName) -> Id -> Id -> Ordering
forall a b. Ord a => (b -> a) -> b -> b -> Ordering
comparing Id -> OccName
forall a. NamedThing a => a -> OccName
getOccName) [Id]
ids)
  where
    ids :: [Id]
ids = [Id
id | Id
id <- TypeEnv -> [Id]
typeEnvIds TypeEnv
type_env, Id -> Bool
want_sig Id
id]
    want_sig :: Id -> Bool
want_sig Id
id
      | Bool
debug     = Bool
True
      | Bool
otherwise = Id -> Bool
forall x. NamedThing x => x -> Bool
hasTopUserName Id
id
                    Bool -> Bool -> Bool
&& case Id -> IdDetails
idDetails Id
id of
                         IdDetails
VanillaId              -> Bool
True
                         WorkerLikeId {}        -> Bool
True
                         RecSelId {}            -> Bool
True
                         ClassOpId {}           -> Bool
True
                         FCallId {}             -> Bool
True
                         IdDetails
_                      -> Bool
False
             -- Data cons (workers and wrappers), pattern synonyms,
             -- etc are suppressed (unless -dppr-debug),
             -- because they appear elsewhere

    ppr_sig :: Id -> SDoc
ppr_sig Id
id = SDoc -> Arity -> SDoc -> SDoc
hang (Id -> SDoc
forall a. OutputableBndr a => a -> SDoc
pprPrefixOcc Id
id SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> SDoc
dcolon) Arity
2 (Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr (Type -> Type
tidyTopType (Id -> Type
idType Id
id)))

ppr_tycons :: Bool -> [FamInst] -> TypeEnv -> SDoc
ppr_tycons :: Bool -> [FamInst] -> TypeEnv -> SDoc
ppr_tycons Bool
debug [FamInst]
fam_insts TypeEnv
type_env
  = [SDoc] -> SDoc
forall doc. IsDoc doc => [doc] -> doc
vcat [ String -> (TyCon -> SDoc) -> [TyCon] -> SDoc
forall a. String -> (a -> SDoc) -> [a] -> SDoc
ppr_things String
"TYPE CONSTRUCTORS" TyCon -> SDoc
ppr_tc [TyCon]
tycons
         , String -> (CoAxiom Branched -> SDoc) -> [CoAxiom Branched] -> SDoc
forall a. String -> (a -> SDoc) -> [a] -> SDoc
ppr_things String
"COERCION AXIOMS" CoAxiom Branched -> SDoc
forall {br :: BranchFlag}. CoAxiom br -> SDoc
ppr_ax
                      (TypeEnv -> [CoAxiom Branched]
typeEnvCoAxioms TypeEnv
type_env) ]
  where
    fi_tycons :: [TyCon]
fi_tycons = [FamInst] -> [TyCon]
famInstsRepTyCons [FamInst]
fam_insts

    tycons :: [TyCon]
tycons = (TyCon -> TyCon -> Ordering) -> [TyCon] -> [TyCon]
forall a. (a -> a -> Ordering) -> [a] -> [a]
sortBy ((TyCon -> OccName) -> TyCon -> TyCon -> Ordering
forall a b. Ord a => (b -> a) -> b -> b -> Ordering
comparing TyCon -> OccName
forall a. NamedThing a => a -> OccName
getOccName) ([TyCon] -> [TyCon]) -> [TyCon] -> [TyCon]
forall a b. (a -> b) -> a -> b
$
             [TyCon
tycon | TyCon
tycon <- TypeEnv -> [TyCon]
typeEnvTyCons TypeEnv
type_env
                    , TyCon -> Bool
want_tycon TyCon
tycon]
             -- Sort by OccName to reduce unnecessary changes
    want_tycon :: TyCon -> Bool
want_tycon TyCon
tycon | Bool
debug      = Bool
True
                     | Bool
otherwise  = Name -> Bool
isExternalName (TyCon -> Name
tyConName TyCon
tycon) Bool -> Bool -> Bool
&&
                                    Bool -> Bool
not (TyCon
tycon TyCon -> [TyCon] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [TyCon]
fi_tycons)
    ppr_tc :: TyCon -> SDoc
ppr_tc TyCon
tc
       = [SDoc] -> SDoc
forall doc. IsDoc doc => [doc] -> doc
vcat [ SDoc -> Arity -> SDoc -> SDoc
hang (TyConFlavour TyCon -> SDoc
forall a. Outputable a => a -> SDoc
ppr (TyCon -> TyConFlavour TyCon
tyConFlavour TyCon
tc) SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> Name -> SDoc
forall a. OutputableBndr a => a -> SDoc
pprPrefixOcc (TyCon -> Name
tyConName TyCon
tc)
                      SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc
braces (Arity -> SDoc
forall a. Outputable a => a -> SDoc
ppr (TyCon -> Arity
tyConArity TyCon
tc)) SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> SDoc
dcolon)
                   Arity
2 (Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr (Type -> Type
tidyTopType (TyCon -> Type
tyConKind TyCon
tc)))
              , Arity -> SDoc -> SDoc
nest Arity
2 (SDoc -> SDoc) -> SDoc -> SDoc
forall a b. (a -> b) -> a -> b
$
                Bool -> SDoc -> SDoc
forall doc. IsOutput doc => Bool -> doc -> doc
ppWhen Bool
show_roles (SDoc -> SDoc) -> SDoc -> SDoc
forall a b. (a -> b) -> a -> b
$
                String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"roles" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> ([SDoc] -> SDoc
forall doc. IsLine doc => [doc] -> doc
sep ((Role -> SDoc) -> [Role] -> [SDoc]
forall a b. (a -> b) -> [a] -> [b]
map Role -> SDoc
forall a. Outputable a => a -> SDoc
ppr [Role]
roles)) ]
       where
         show_roles :: Bool
show_roles = Bool
debug Bool -> Bool -> Bool
|| Bool -> Bool
not ((Role -> Bool) -> [Role] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all (Role -> Role -> Bool
forall a. Eq a => a -> a -> Bool
== Role
boring_role) [Role]
roles)
         roles :: [Role]
roles = TyCon -> [Role]
tyConRoles TyCon
tc
         boring_role :: Role
boring_role | TyCon -> Bool
isClassTyCon TyCon
tc = Role
Nominal
                     | Bool
otherwise       = Role
Representational
            -- Matches the choice in GHC.Iface.Syntax, calls to pprRoles

    ppr_ax :: CoAxiom br -> SDoc
ppr_ax CoAxiom br
ax = IfaceDecl -> SDoc
forall a. Outputable a => a -> SDoc
ppr (CoAxiom br -> IfaceDecl
forall (br :: BranchFlag). CoAxiom br -> IfaceDecl
coAxiomToIfaceDecl CoAxiom br
ax)
      -- We go via IfaceDecl rather than using pprCoAxiom
      -- This way we get the full axiom (both LHS and RHS) with
      -- wildcard binders tidied to _1, _2, etc.

ppr_datacons :: Bool -> TypeEnv -> SDoc
ppr_datacons :: Bool -> TypeEnv -> SDoc
ppr_datacons Bool
debug TypeEnv
type_env
  = String -> (DataCon -> SDoc) -> [DataCon] -> SDoc
forall a. String -> (a -> SDoc) -> [a] -> SDoc
ppr_things String
"DATA CONSTRUCTORS" DataCon -> SDoc
ppr_dc [DataCon]
wanted_dcs
      -- The filter gets rid of class data constructors
  where
    ppr_dc :: DataCon -> SDoc
ppr_dc DataCon
dc = (SDocContext -> Bool) -> (Bool -> SDoc) -> SDoc
forall a. (SDocContext -> a) -> (a -> SDoc) -> SDoc
sdocOption SDocContext -> Bool
sdocLinearTypes (\Bool
show_linear_types ->
                DataCon -> SDoc
forall a. Outputable a => a -> SDoc
ppr DataCon
dc SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> SDoc
dcolon SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr (Bool -> DataCon -> Type
dataConDisplayType Bool
show_linear_types DataCon
dc))
    all_dcs :: [DataCon]
all_dcs    = TypeEnv -> [DataCon]
typeEnvDataCons TypeEnv
type_env
    wanted_dcs :: [DataCon]
wanted_dcs | Bool
debug     = [DataCon]
all_dcs
               | Bool
otherwise = (DataCon -> Bool) -> [DataCon] -> [DataCon]
forall a. (a -> Bool) -> [a] -> [a]
filterOut DataCon -> Bool
is_cls_dc [DataCon]
all_dcs
    is_cls_dc :: DataCon -> Bool
is_cls_dc DataCon
dc = TyCon -> Bool
isClassTyCon (DataCon -> TyCon
dataConTyCon DataCon
dc)

ppr_patsyns :: TypeEnv -> SDoc
ppr_patsyns :: TypeEnv -> SDoc
ppr_patsyns TypeEnv
type_env
  = String -> (PatSyn -> SDoc) -> [PatSyn] -> SDoc
forall a. String -> (a -> SDoc) -> [a] -> SDoc
ppr_things String
"PATTERN SYNONYMS" PatSyn -> SDoc
ppr_ps
               (TypeEnv -> [PatSyn]
typeEnvPatSyns TypeEnv
type_env)
  where
    ppr_ps :: PatSyn -> SDoc
ppr_ps PatSyn
ps = PatSyn -> SDoc
forall a. OutputableBndr a => a -> SDoc
pprPrefixOcc PatSyn
ps SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> SDoc
dcolon SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> PatSyn -> SDoc
pprPatSynType PatSyn
ps

ppr_insts :: [ClsInst] -> SDoc
ppr_insts :: [ClsInst] -> SDoc
ppr_insts [ClsInst]
ispecs
  = String -> (ClsInst -> SDoc) -> [ClsInst] -> SDoc
forall a. String -> (a -> SDoc) -> [a] -> SDoc
ppr_things String
"CLASS INSTANCES" ClsInst -> SDoc
pprInstance [ClsInst]
ispecs

ppr_fam_insts :: [FamInst] -> SDoc
ppr_fam_insts :: [FamInst] -> SDoc
ppr_fam_insts [FamInst]
fam_insts
  = String -> (FamInst -> SDoc) -> [FamInst] -> SDoc
forall a. String -> (a -> SDoc) -> [a] -> SDoc
ppr_things String
"FAMILY INSTANCES" FamInst -> SDoc
pprFamInst [FamInst]
fam_insts

ppr_things :: String -> (a -> SDoc) -> [a] -> SDoc
ppr_things :: forall a. String -> (a -> SDoc) -> [a] -> SDoc
ppr_things String
herald a -> SDoc
ppr_one [a]
things
  | [a] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [a]
things = SDoc
forall doc. IsOutput doc => doc
empty
  | Bool
otherwise   = String -> SDoc
forall doc. IsLine doc => String -> doc
text String
herald SDoc -> SDoc -> SDoc
forall doc. IsDoc doc => doc -> doc -> doc
$$ Arity -> SDoc -> SDoc
nest Arity
2 ([SDoc] -> SDoc
forall doc. IsDoc doc => [doc] -> doc
vcat ((a -> SDoc) -> [a] -> [SDoc]
forall a b. (a -> b) -> [a] -> [b]
map a -> SDoc
ppr_one [a]
things))

hasTopUserName :: NamedThing x => x -> Bool
-- A top-level thing whose name is not "derived"
-- Thus excluding things like $tcX, from Typeable boilerplate
-- and C:Coll from class-dictionary data constructors
hasTopUserName :: forall x. NamedThing x => x -> Bool
hasTopUserName x
x
  = Name -> Bool
isExternalName Name
name Bool -> Bool -> Bool
&& Bool -> Bool
not (OccName -> Bool
isDerivedOccName (Name -> OccName
nameOccName Name
name))
  where
    name :: Name
name = x -> Name
forall a. NamedThing a => a -> Name
getName x
x

{-
********************************************************************************

Type Checker Plugins

********************************************************************************
-}

withTcPlugins :: HscEnv -> TcM a -> TcM a
withTcPlugins :: forall a. HscEnv -> TcM a -> TcM a
withTcPlugins HscEnv
hsc_env TcM a
m =
    case [Maybe TcPlugin] -> [TcPlugin]
forall a. [Maybe a] -> [a]
catMaybes ([Maybe TcPlugin] -> [TcPlugin]) -> [Maybe TcPlugin] -> [TcPlugin]
forall a b. (a -> b) -> a -> b
$ Plugins
-> (Plugin -> [String] -> Maybe TcPlugin) -> [Maybe TcPlugin]
forall a. Plugins -> (Plugin -> [String] -> a) -> [a]
mapPlugins (HscEnv -> Plugins
hsc_plugins HscEnv
hsc_env) Plugin -> [String] -> Maybe TcPlugin
tcPlugin of
       []      -> TcM a
m  -- Common fast case
       [TcPlugin]
plugins -> do
                (solvers, rewriters, stops) <-
                  [(TcPluginSolver, UniqFM TyCon TcPluginRewriter, TcPluginM ())]
-> ([TcPluginSolver], [UniqFM TyCon TcPluginRewriter],
    [TcPluginM ()])
forall a b c. [(a, b, c)] -> ([a], [b], [c])
unzip3 ([(TcPluginSolver, UniqFM TyCon TcPluginRewriter, TcPluginM ())]
 -> ([TcPluginSolver], [UniqFM TyCon TcPluginRewriter],
     [TcPluginM ()]))
-> IOEnv
     (Env TcGblEnv TcLclEnv)
     [(TcPluginSolver, UniqFM TyCon TcPluginRewriter, TcPluginM ())]
-> IOEnv
     (Env TcGblEnv TcLclEnv)
     ([TcPluginSolver], [UniqFM TyCon TcPluginRewriter], [TcPluginM ()])
forall a b.
(a -> b)
-> IOEnv (Env TcGblEnv TcLclEnv) a
-> IOEnv (Env TcGblEnv TcLclEnv) b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
`fmap` (TcPlugin
 -> IOEnv
      (Env TcGblEnv TcLclEnv)
      (TcPluginSolver, UniqFM TyCon TcPluginRewriter, TcPluginM ()))
-> [TcPlugin]
-> IOEnv
     (Env TcGblEnv TcLclEnv)
     [(TcPluginSolver, UniqFM TyCon TcPluginRewriter, TcPluginM ())]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
forall (m :: * -> *) a b. Monad m => (a -> m b) -> [a] -> m [b]
mapM TcPlugin
-> IOEnv
     (Env TcGblEnv TcLclEnv)
     (TcPluginSolver, UniqFM TyCon TcPluginRewriter, TcPluginM ())
start_plugin [TcPlugin]
plugins
                let
                  rewritersUniqFM :: UniqFM TyCon [TcPluginRewriter]
                  !rewritersUniqFM = [UniqFM TyCon TcPluginRewriter] -> UniqFM TyCon [TcPluginRewriter]
forall {k} (key :: k) elt. [UniqFM key elt] -> UniqFM key [elt]
sequenceUFMList [UniqFM TyCon TcPluginRewriter]
rewriters
                -- The following ensures that tcPluginStop is called even if a type
                -- error occurs during compilation (Fix of #10078)
                eitherRes <- tryM $
                  updGblEnv (\TcGblEnv
e -> TcGblEnv
e { tcg_tc_plugin_solvers   = solvers
                                     , tcg_tc_plugin_rewriters = rewritersUniqFM }) m
                mapM_ runTcPluginM stops
                case eitherRes of
                  Left IOEnvFailure
_ -> TcM a
forall env a. IOEnv env a
failM
                  Right a
res -> a -> TcM a
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return a
res
  where
  start_plugin :: TcPlugin
-> IOEnv
     (Env TcGblEnv TcLclEnv)
     (TcPluginSolver, UniqFM TyCon TcPluginRewriter, TcPluginM ())
start_plugin (TcPlugin TcPluginM s
start s -> TcPluginSolver
solve s -> UniqFM TyCon TcPluginRewriter
rewrite s -> TcPluginM ()
stop) =
    do s <- TcPluginM s -> TcM s
forall a. TcPluginM a -> TcM a
runTcPluginM TcPluginM s
start
       return (solve s, rewrite s, stop s)

withDefaultingPlugins :: HscEnv -> TcM a -> TcM a
withDefaultingPlugins :: forall a. HscEnv -> TcM a -> TcM a
withDefaultingPlugins HscEnv
hsc_env TcM a
m =
  do case [Maybe DefaultingPlugin] -> [DefaultingPlugin]
forall a. [Maybe a] -> [a]
catMaybes ([Maybe DefaultingPlugin] -> [DefaultingPlugin])
-> [Maybe DefaultingPlugin] -> [DefaultingPlugin]
forall a b. (a -> b) -> a -> b
$ Plugins
-> (Plugin -> [String] -> Maybe DefaultingPlugin)
-> [Maybe DefaultingPlugin]
forall a. Plugins -> (Plugin -> [String] -> a) -> [a]
mapPlugins (HscEnv -> Plugins
hsc_plugins HscEnv
hsc_env) Plugin -> [String] -> Maybe DefaultingPlugin
defaultingPlugin of
       [] -> TcM a
m  -- Common fast case
       [DefaultingPlugin]
plugins  -> do (plugins,stops) <- (DefaultingPlugin
 -> IOEnv (Env TcGblEnv TcLclEnv) (FillDefaulting, TcPluginM ()))
-> [DefaultingPlugin]
-> IOEnv (Env TcGblEnv TcLclEnv) ([FillDefaulting], [TcPluginM ()])
forall (m :: * -> *) a b c.
Applicative m =>
(a -> m (b, c)) -> [a] -> m ([b], [c])
mapAndUnzipM DefaultingPlugin
-> IOEnv (Env TcGblEnv TcLclEnv) (FillDefaulting, TcPluginM ())
start_plugin [DefaultingPlugin]
plugins
                      -- This ensures that dePluginStop is called even if a type
                      -- error occurs during compilation
                      eitherRes <- tryM $ do
                        updGblEnv (\TcGblEnv
e -> TcGblEnv
e { tcg_defaulting_plugins = plugins }) m
                      mapM_ runTcPluginM stops
                      case eitherRes of
                        Left IOEnvFailure
_ -> TcM a
forall env a. IOEnv env a
failM
                        Right a
res -> a -> TcM a
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return a
res
  where
  start_plugin :: DefaultingPlugin
-> IOEnv (Env TcGblEnv TcLclEnv) (FillDefaulting, TcPluginM ())
start_plugin (DefaultingPlugin TcPluginM s
start s -> FillDefaulting
fill s -> TcPluginM ()
stop) =
    do s <- TcPluginM s -> TcM s
forall a. TcPluginM a -> TcM a
runTcPluginM TcPluginM s
start
       return (fill s, stop s)

withHoleFitPlugins :: HscEnv -> TcM a -> TcM a
withHoleFitPlugins :: forall a. HscEnv -> TcM a -> TcM a
withHoleFitPlugins HscEnv
hsc_env TcM a
m =
  case [Maybe HoleFitPluginR] -> [HoleFitPluginR]
forall a. [Maybe a] -> [a]
catMaybes ([Maybe HoleFitPluginR] -> [HoleFitPluginR])
-> [Maybe HoleFitPluginR] -> [HoleFitPluginR]
forall a b. (a -> b) -> a -> b
$ Plugins
-> (Plugin -> [String] -> Maybe HoleFitPluginR)
-> [Maybe HoleFitPluginR]
forall a. Plugins -> (Plugin -> [String] -> a) -> [a]
mapPlugins (HscEnv -> Plugins
hsc_plugins HscEnv
hsc_env) Plugin -> [String] -> Maybe HoleFitPluginR
holeFitPlugin of
    [] -> TcM a
m  -- Common fast case
    [HoleFitPluginR]
plugins -> do (plugins,stops) <- (HoleFitPluginR
 -> IOEnv
      (Env TcGblEnv TcLclEnv)
      (HoleFitPlugin, IOEnv (Env TcGblEnv TcLclEnv) ()))
-> [HoleFitPluginR]
-> IOEnv
     (Env TcGblEnv TcLclEnv)
     ([HoleFitPlugin], [IOEnv (Env TcGblEnv TcLclEnv) ()])
forall (m :: * -> *) a b c.
Applicative m =>
(a -> m (b, c)) -> [a] -> m ([b], [c])
mapAndUnzipM HoleFitPluginR
-> IOEnv
     (Env TcGblEnv TcLclEnv)
     (HoleFitPlugin, IOEnv (Env TcGblEnv TcLclEnv) ())
start_plugin [HoleFitPluginR]
plugins
                  -- This ensures that hfPluginStop is called even if a type
                  -- error occurs during compilation.
                  eitherRes <- tryM $
                    updGblEnv (\TcGblEnv
e -> TcGblEnv
e { tcg_hf_plugins = plugins }) m
                  sequence_ stops
                  case eitherRes of
                    Left IOEnvFailure
_ -> TcM a
forall env a. IOEnv env a
failM
                    Right a
res -> a -> TcM a
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return a
res
  where
    start_plugin :: HoleFitPluginR
-> IOEnv
     (Env TcGblEnv TcLclEnv)
     (HoleFitPlugin, IOEnv (Env TcGblEnv TcLclEnv) ())
start_plugin (HoleFitPluginR TcM (TcRef s)
init TcRef s -> HoleFitPlugin
plugin TcRef s -> IOEnv (Env TcGblEnv TcLclEnv) ()
stop) =
      do ref <- TcM (TcRef s)
init
         return (plugin ref, stop ref)


runRenamerPlugin :: TcGblEnv
                 -> HsGroup GhcRn
                 -> TcM (TcGblEnv, HsGroup GhcRn)
runRenamerPlugin :: TcGblEnv
-> HsGroup (GhcPass 'Renamed)
-> TcM (TcGblEnv, HsGroup (GhcPass 'Renamed))
runRenamerPlugin TcGblEnv
gbl_env HsGroup (GhcPass 'Renamed)
hs_group = do
    hsc_env <- TcRnIf TcGblEnv TcLclEnv HscEnv
forall gbl lcl. TcRnIf gbl lcl HscEnv
getTopEnv
    withPlugins (hsc_plugins hsc_env)
      (\Plugin
p [String]
opts (TcGblEnv
e, HsGroup (GhcPass 'Renamed)
g) -> ( DynFlags -> IOEnv (Env TcGblEnv TcLclEnv) ()
mark_plugin_unsafe (HscEnv -> DynFlags
hsc_dflags HscEnv
hsc_env)
                            IOEnv (Env TcGblEnv TcLclEnv) ()
-> TcM (TcGblEnv, HsGroup (GhcPass 'Renamed))
-> TcM (TcGblEnv, HsGroup (GhcPass 'Renamed))
forall a b.
IOEnv (Env TcGblEnv TcLclEnv) a
-> IOEnv (Env TcGblEnv TcLclEnv) b
-> IOEnv (Env TcGblEnv TcLclEnv) b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> Plugin
-> [String]
-> TcGblEnv
-> HsGroup (GhcPass 'Renamed)
-> TcM (TcGblEnv, HsGroup (GhcPass 'Renamed))
renamedResultAction Plugin
p [String]
opts TcGblEnv
e HsGroup (GhcPass 'Renamed)
g))
      (gbl_env, hs_group)


-- XXX: should this really be a Maybe X?  Check under which circumstances this
-- can become a Nothing and decide whether this should instead throw an
-- exception/signal an error.
type RenamedStuff =
        (Maybe (HsGroup GhcRn, [LImportDecl GhcRn], Maybe [(LIE GhcRn, Avails)],
                Maybe (LHsDoc GhcRn), Maybe (XRec GhcRn ModuleName)))

-- | Extract the renamed information from TcGblEnv.
getRenamedStuff :: TcGblEnv -> RenamedStuff
getRenamedStuff :: TcGblEnv -> RenamedStuff
getRenamedStuff TcGblEnv
tc_result
  = (HsGroup (GhcPass 'Renamed)
 -> (HsGroup (GhcPass 'Renamed),
     [GenLocated SrcSpanAnnA (ImportDecl (GhcPass 'Renamed))],
     Maybe
       [(GenLocated SrcSpanAnnA (IE (GhcPass 'Renamed)), [AvailInfo])],
     Maybe (GenLocated SrcSpan (HsDoc (GhcPass 'Renamed))),
     Maybe (GenLocated SrcSpanAnnA ModuleName)))
-> Maybe (HsGroup (GhcPass 'Renamed))
-> Maybe
     (HsGroup (GhcPass 'Renamed),
      [GenLocated SrcSpanAnnA (ImportDecl (GhcPass 'Renamed))],
      Maybe
        [(GenLocated SrcSpanAnnA (IE (GhcPass 'Renamed)), [AvailInfo])],
      Maybe (GenLocated SrcSpan (HsDoc (GhcPass 'Renamed))),
      Maybe (GenLocated SrcSpanAnnA ModuleName))
forall a b. (a -> b) -> Maybe a -> Maybe b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (\HsGroup (GhcPass 'Renamed)
decls -> ( HsGroup (GhcPass 'Renamed)
decls, TcGblEnv -> [LImportDecl (GhcPass 'Renamed)]
tcg_rn_imports TcGblEnv
tc_result
                    , TcGblEnv -> Maybe [(LIE (GhcPass 'Renamed), [AvailInfo])]
tcg_rn_exports TcGblEnv
tc_result, Maybe (GenLocated SrcSpan (HsDoc (GhcPass 'Renamed)))
doc_hdr, Maybe (XRec (GhcPass 'Renamed) ModuleName)
Maybe (GenLocated SrcSpanAnnA ModuleName)
name_hdr ))
         (TcGblEnv -> Maybe (HsGroup (GhcPass 'Renamed))
tcg_rn_decls TcGblEnv
tc_result)
  where (Maybe (GenLocated SrcSpan (HsDoc (GhcPass 'Renamed)))
doc_hdr, Maybe (XRec (GhcPass 'Renamed) ModuleName)
name_hdr) = TcGblEnv
-> (Maybe (GenLocated SrcSpan (HsDoc (GhcPass 'Renamed))),
    Maybe (XRec (GhcPass 'Renamed) ModuleName))
tcg_hdr_info TcGblEnv
tc_result

runTypecheckerPlugin :: ModSummary -> TcGblEnv -> TcM TcGblEnv
runTypecheckerPlugin :: ModSummary -> TcGblEnv -> TcM TcGblEnv
runTypecheckerPlugin ModSummary
sum TcGblEnv
gbl_env = do
    hsc_env <- TcRnIf TcGblEnv TcLclEnv HscEnv
forall gbl lcl. TcRnIf gbl lcl HscEnv
getTopEnv
    withPlugins (hsc_plugins hsc_env)
      (\Plugin
p [String]
opts TcGblEnv
env -> DynFlags -> IOEnv (Env TcGblEnv TcLclEnv) ()
mark_plugin_unsafe (HscEnv -> DynFlags
hsc_dflags HscEnv
hsc_env)
                        IOEnv (Env TcGblEnv TcLclEnv) () -> TcM TcGblEnv -> TcM TcGblEnv
forall a b.
IOEnv (Env TcGblEnv TcLclEnv) a
-> IOEnv (Env TcGblEnv TcLclEnv) b
-> IOEnv (Env TcGblEnv TcLclEnv) b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> Plugin -> [String] -> ModSummary -> TcGblEnv -> TcM TcGblEnv
typeCheckResultAction Plugin
p [String]
opts ModSummary
sum TcGblEnv
env)
      gbl_env

mark_plugin_unsafe :: DynFlags -> TcM ()
mark_plugin_unsafe :: DynFlags -> IOEnv (Env TcGblEnv TcLclEnv) ()
mark_plugin_unsafe DynFlags
dflags = Bool
-> IOEnv (Env TcGblEnv TcLclEnv) ()
-> IOEnv (Env TcGblEnv TcLclEnv) ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (GeneralFlag -> DynFlags -> Bool
gopt GeneralFlag
Opt_PluginTrustworthy DynFlags
dflags) (IOEnv (Env TcGblEnv TcLclEnv) ()
 -> IOEnv (Env TcGblEnv TcLclEnv) ())
-> IOEnv (Env TcGblEnv TcLclEnv) ()
-> IOEnv (Env TcGblEnv TcLclEnv) ()
forall a b. (a -> b) -> a -> b
$
  Messages TcRnMessage -> IOEnv (Env TcGblEnv TcLclEnv) ()
recordUnsafeInfer Messages TcRnMessage
pluginUnsafe
  where
    !diag_opts :: DiagOpts
diag_opts = DynFlags -> DiagOpts
initDiagOpts DynFlags
dflags
    pluginUnsafe :: Messages TcRnMessage
pluginUnsafe =
      MsgEnvelope TcRnMessage -> Messages TcRnMessage
forall e. MsgEnvelope e -> Messages e
singleMessage (MsgEnvelope TcRnMessage -> Messages TcRnMessage)
-> MsgEnvelope TcRnMessage -> Messages TcRnMessage
forall a b. (a -> b) -> a -> b
$
      DiagOpts -> SrcSpan -> TcRnMessage -> MsgEnvelope TcRnMessage
forall e. Diagnostic e => DiagOpts -> SrcSpan -> e -> MsgEnvelope e
mkPlainMsgEnvelope DiagOpts
diag_opts SrcSpan
noSrcSpan TcRnMessage
TcRnUnsafeDueToPlugin


-- Note [Typechecking default declarations]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Typechecking default declarations requires careful placement:
--
-- 1. We must check them after types (tcTyAndClassDecls) because they can refer
-- to them. E.g.
--
--    data T = MkT ...
--    default(Int, T, Integer)
--
--    -- or even (tested by T11974b and T2245)
--    default(Int, T, Integer)
--    data T = MkT ...
--
-- 2. We must check them before typechecking deriving clauses (tcInstDeclsDeriv)
-- otherwise we may lookup default default types (Integer, Double) while checking
-- deriving clauses, ignoring the default declaration.
--
-- Before this careful placement (#24566), compiling the following example
-- (T24566) with "-ddump-if-trace -ddump-tc-trace" showed a call to
-- `applyDefaultingRules` with default types set to "(Integer,Double)":
--
--     module M where
--
--     import GHC.Classes
--     default ()
--
--     data Foo a = Nothing | Just a
--       deriving (Eq, Ord)
--
-- This was an issue while building modules like M in the ghc-internal package
-- because they would spuriously fail to build if the module defining Integer
-- (ghc-bignum:GHC.Num.Integer) wasn't compiled yet and its interface not to be
-- found. The implicit dependency between M and GHC.Num.Integer isn't known to
-- the build system.
-- In addition, trying to explicitly avoid the implicit dependency with `default
-- ()` didn't work, except if *standalone* deriving was used, which was an
-- inconsistent behavior.