-- (c) The University of Glasgow 2006
{-# LANGUAGE CPP, FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}  -- instance MonadThings is necessarily an
                                       -- orphan
{-# LANGUAGE UndecidableInstances #-} -- Wrinkle in Note [Trees That Grow]
                                      -- in module GHC.Hs.Extension
{-# LANGUAGE TypeFamilies #-}

module GHC.Tc.Utils.Env(
        TyThing(..), TcTyThing(..), TcId,

        -- Instance environment, and InstInfo type
        InstInfo(..), iDFunId, pprInstInfoDetails,
        simpleInstInfoClsTy, simpleInstInfoTy, simpleInstInfoTyCon,
        InstBindings(..),

        -- Global environment
        tcExtendGlobalEnv, tcExtendTyConEnv,
        tcExtendGlobalEnvImplicit, setGlobalTypeEnv,
        tcExtendGlobalValEnv,
        tcLookupLocatedGlobal, tcLookupGlobal, tcLookupGlobalOnly,
        tcLookupTyCon, tcLookupClass,
        tcLookupDataCon, tcLookupPatSyn, tcLookupConLike,
        tcLookupLocatedGlobalId, tcLookupLocatedTyCon,
        tcLookupLocatedClass, tcLookupAxiom,
        lookupGlobal, ioLookupDataCon,
        addTypecheckedBinds,

        -- Local environment
        tcExtendKindEnv, tcExtendKindEnvList,
        tcExtendTyVarEnv, tcExtendNameTyVarEnv,
        tcExtendLetEnv, tcExtendSigIds, tcExtendRecIds,
        tcExtendIdEnv, tcExtendIdEnv1, tcExtendIdEnv2,
        tcExtendBinderStack, tcExtendLocalTypeEnv,
        isTypeClosedLetBndr,
        tcCheckUsage,

        tcLookup, tcLookupLocated, tcLookupLocalIds,
        tcLookupId, tcLookupIdMaybe, tcLookupTyVar,
        tcLookupTcTyCon,
        tcLookupLcl_maybe,
        getInLocalScope,
        wrongThingErr, pprBinders,

        tcAddDataFamConPlaceholders, tcAddPatSynPlaceholders,
        getTypeSigNames,
        tcExtendRecEnv,         -- For knot-tying

        -- Tidying
        tcInitTidyEnv, tcInitOpenTidyEnv,

        -- Instances
        tcLookupInstance, tcGetInstEnvs,

        -- Rules
        tcExtendRules,

        -- Defaults
        tcGetDefaultTys,

        -- Template Haskell stuff
        checkWellStaged, tcMetaTy, thLevel,
        topIdLvl, isBrackStage,

        -- New Ids
        newDFunName, newFamInstTyConName,
        newFamInstAxiomName,
        mkStableIdFromString, mkStableIdFromName,
        mkWrapperName
  ) where

#include "HsVersions.h"

import GHC.Prelude

import GHC.Hs
import GHC.Iface.Env
import GHC.Tc.Utils.Monad
import GHC.Tc.Utils.TcMType
import GHC.Tc.Utils.TcType
import GHC.Core.UsageEnv
import GHC.Tc.Types.Evidence (HsWrapper, idHsWrapper)
import {-# SOURCE #-} GHC.Tc.Utils.Unify ( tcSubMult )
import GHC.Tc.Types.Origin ( CtOrigin(UsageEnvironmentOf) )
import GHC.Iface.Load
import GHC.Builtin.Names
import GHC.Builtin.Types
import GHC.Types.Id
import GHC.Types.Var
import GHC.Types.Name.Reader
import GHC.Core.InstEnv
import GHC.Core.DataCon ( DataCon )
import GHC.Core.PatSyn  ( PatSyn )
import GHC.Core.ConLike
import GHC.Core.TyCon
import GHC.Core.Type
import GHC.Core.Coercion.Axiom

import GHC.Core.Class
import GHC.Types.Name
import GHC.Types.Name.Set
import GHC.Types.Name.Env
import GHC.Types.Var.Env
import GHC.Driver.Types
import GHC.Driver.Session
import GHC.Types.SrcLoc
import GHC.Types.Basic hiding( SuccessFlag(..) )
import GHC.Unit.Module
import GHC.Utils.Outputable
import GHC.Utils.Encoding
import GHC.Data.FastString
import GHC.Data.Bag
import GHC.Data.List.SetOps
import GHC.Utils.Error
import GHC.Data.Maybe( MaybeErr(..), orElse )
import qualified GHC.LanguageExtensions as LangExt
import GHC.Utils.Misc ( HasDebugCallStack )

import Data.IORef
import Data.List (intercalate)
import Control.Monad

{- *********************************************************************
*                                                                      *
            An IO interface to looking up globals
*                                                                      *
********************************************************************* -}

lookupGlobal :: HscEnv -> Name -> IO TyThing
-- A variant of lookupGlobal_maybe for the clients which are not
-- interested in recovering from lookup failure and accept panic.
lookupGlobal :: HscEnv -> Name -> IO TyThing
lookupGlobal HscEnv
hsc_env Name
name
  = do  {
          MaybeErr MsgDoc TyThing
mb_thing <- HscEnv -> Name -> IO (MaybeErr MsgDoc TyThing)
lookupGlobal_maybe HscEnv
hsc_env Name
name
        ; case MaybeErr MsgDoc TyThing
mb_thing of
            Succeeded TyThing
thing -> TyThing -> IO TyThing
forall (m :: * -> *) a. Monad m => a -> m a
return TyThing
thing
            Failed MsgDoc
msg      -> String -> MsgDoc -> IO TyThing
forall a. HasCallStack => String -> MsgDoc -> a
pprPanic String
"lookupGlobal" MsgDoc
msg
        }

lookupGlobal_maybe :: HscEnv -> Name -> IO (MaybeErr MsgDoc TyThing)
-- This may look up an Id that one has previously looked up.
-- If so, we are going to read its interface file, and add its bindings
-- to the ExternalPackageTable.
lookupGlobal_maybe :: HscEnv -> Name -> IO (MaybeErr MsgDoc TyThing)
lookupGlobal_maybe HscEnv
hsc_env Name
name
  = do  {    -- Try local envt
          let mod :: Module
mod = InteractiveContext -> Module
icInteractiveModule (HscEnv -> InteractiveContext
hsc_IC HscEnv
hsc_env)
              dflags :: DynFlags
dflags = HscEnv -> DynFlags
hsc_dflags HscEnv
hsc_env
              tcg_semantic_mod :: Module
tcg_semantic_mod = DynFlags -> Module -> Module
canonicalizeModuleIfHome DynFlags
dflags Module
mod

        ; if Module -> Name -> Bool
nameIsLocalOrFrom Module
tcg_semantic_mod Name
name
              then (MaybeErr MsgDoc TyThing -> IO (MaybeErr MsgDoc TyThing)
forall (m :: * -> *) a. Monad m => a -> m a
return
                (MsgDoc -> MaybeErr MsgDoc TyThing
forall err val. err -> MaybeErr err val
Failed (String -> MsgDoc
text String
"Can't find local name: " MsgDoc -> MsgDoc -> MsgDoc
<+> Name -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr Name
name)))
                  -- Internal names can happen in GHCi
              else
           -- Try home package table and external package table
          HscEnv -> Name -> IO (MaybeErr MsgDoc TyThing)
lookupImported_maybe HscEnv
hsc_env Name
name
        }

lookupImported_maybe :: HscEnv -> Name -> IO (MaybeErr MsgDoc TyThing)
-- Returns (Failed err) if we can't find the interface file for the thing
lookupImported_maybe :: HscEnv -> Name -> IO (MaybeErr MsgDoc TyThing)
lookupImported_maybe HscEnv
hsc_env Name
name
  = do  { Maybe TyThing
mb_thing <- HscEnv -> Name -> IO (Maybe TyThing)
lookupTypeHscEnv HscEnv
hsc_env Name
name
        ; case Maybe TyThing
mb_thing of
            Just TyThing
thing -> MaybeErr MsgDoc TyThing -> IO (MaybeErr MsgDoc TyThing)
forall (m :: * -> *) a. Monad m => a -> m a
return (TyThing -> MaybeErr MsgDoc TyThing
forall err val. val -> MaybeErr err val
Succeeded TyThing
thing)
            Maybe TyThing
Nothing    -> HscEnv -> Name -> IO (MaybeErr MsgDoc TyThing)
importDecl_maybe HscEnv
hsc_env Name
name
            }

importDecl_maybe :: HscEnv -> Name -> IO (MaybeErr MsgDoc TyThing)
importDecl_maybe :: HscEnv -> Name -> IO (MaybeErr MsgDoc TyThing)
importDecl_maybe HscEnv
hsc_env Name
name
  | Just TyThing
thing <- Name -> Maybe TyThing
wiredInNameTyThing_maybe Name
name
  = do  { Bool -> IO () -> IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (TyThing -> Bool
needWiredInHomeIface TyThing
thing)
               (HscEnv -> IfG () -> IO ()
forall a. HscEnv -> IfG a -> IO a
initIfaceLoad HscEnv
hsc_env (Name -> IfG ()
forall lcl. Name -> IfM lcl ()
loadWiredInHomeIface Name
name))
                -- See Note [Loading instances for wired-in things]
        ; MaybeErr MsgDoc TyThing -> IO (MaybeErr MsgDoc TyThing)
forall (m :: * -> *) a. Monad m => a -> m a
return (TyThing -> MaybeErr MsgDoc TyThing
forall err val. val -> MaybeErr err val
Succeeded TyThing
thing) }
  | Bool
otherwise
  = HscEnv
-> IfG (MaybeErr MsgDoc TyThing) -> IO (MaybeErr MsgDoc TyThing)
forall a. HscEnv -> IfG a -> IO a
initIfaceLoad HscEnv
hsc_env (Name -> IfG (MaybeErr MsgDoc TyThing)
forall lcl. Name -> IfM lcl (MaybeErr MsgDoc TyThing)
importDecl Name
name)

ioLookupDataCon :: HscEnv -> Name -> IO DataCon
ioLookupDataCon :: HscEnv -> Name -> IO DataCon
ioLookupDataCon HscEnv
hsc_env Name
name = do
  MaybeErr MsgDoc DataCon
mb_thing <- HscEnv -> Name -> IO (MaybeErr MsgDoc DataCon)
ioLookupDataCon_maybe HscEnv
hsc_env Name
name
  case MaybeErr MsgDoc DataCon
mb_thing of
    Succeeded DataCon
thing -> DataCon -> IO DataCon
forall (m :: * -> *) a. Monad m => a -> m a
return DataCon
thing
    Failed MsgDoc
msg      -> String -> MsgDoc -> IO DataCon
forall a. HasCallStack => String -> MsgDoc -> a
pprPanic String
"lookupDataConIO" MsgDoc
msg

ioLookupDataCon_maybe :: HscEnv -> Name -> IO (MaybeErr MsgDoc DataCon)
ioLookupDataCon_maybe :: HscEnv -> Name -> IO (MaybeErr MsgDoc DataCon)
ioLookupDataCon_maybe HscEnv
hsc_env Name
name = do
    TyThing
thing <- HscEnv -> Name -> IO TyThing
lookupGlobal HscEnv
hsc_env Name
name
    MaybeErr MsgDoc DataCon -> IO (MaybeErr MsgDoc DataCon)
forall (m :: * -> *) a. Monad m => a -> m a
return (MaybeErr MsgDoc DataCon -> IO (MaybeErr MsgDoc DataCon))
-> MaybeErr MsgDoc DataCon -> IO (MaybeErr MsgDoc DataCon)
forall a b. (a -> b) -> a -> b
$ case TyThing
thing of
        AConLike (RealDataCon DataCon
con) -> DataCon -> MaybeErr MsgDoc DataCon
forall err val. val -> MaybeErr err val
Succeeded DataCon
con
        TyThing
_                          -> MsgDoc -> MaybeErr MsgDoc DataCon
forall err val. err -> MaybeErr err val
Failed (MsgDoc -> MaybeErr MsgDoc DataCon)
-> MsgDoc -> MaybeErr MsgDoc DataCon
forall a b. (a -> b) -> a -> b
$
          TcTyThing -> MsgDoc
pprTcTyThingCategory (TyThing -> TcTyThing
AGlobal TyThing
thing) MsgDoc -> MsgDoc -> MsgDoc
<+> MsgDoc -> MsgDoc
quotes (Name -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr Name
name) MsgDoc -> MsgDoc -> MsgDoc
<+>
                String -> MsgDoc
text String
"used as a data constructor"

addTypecheckedBinds :: TcGblEnv -> [LHsBinds GhcTc] -> TcGblEnv
addTypecheckedBinds :: TcGblEnv -> [LHsBinds GhcTc] -> TcGblEnv
addTypecheckedBinds TcGblEnv
tcg_env [LHsBinds GhcTc]
binds
  | HscSource -> Bool
isHsBootOrSig (TcGblEnv -> HscSource
tcg_src TcGblEnv
tcg_env) = TcGblEnv
tcg_env
    -- Do not add the code for record-selector bindings
    -- when compiling hs-boot files
  | Bool
otherwise = TcGblEnv
tcg_env { tcg_binds :: LHsBinds GhcTc
tcg_binds = (LHsBinds GhcTc -> LHsBinds GhcTc -> LHsBinds GhcTc)
-> LHsBinds GhcTc -> [LHsBinds GhcTc] -> LHsBinds GhcTc
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr LHsBinds GhcTc -> LHsBinds GhcTc -> LHsBinds GhcTc
forall a. Bag a -> Bag a -> Bag a
unionBags
                                            (TcGblEnv -> LHsBinds GhcTc
tcg_binds TcGblEnv
tcg_env)
                                            [LHsBinds GhcTc]
binds }

{-
************************************************************************
*                                                                      *
*                      tcLookupGlobal                                  *
*                                                                      *
************************************************************************

Using the Located versions (eg. tcLookupLocatedGlobal) is preferred,
unless you know that the SrcSpan in the monad is already set to the
span of the Name.
-}


tcLookupLocatedGlobal :: Located Name -> TcM TyThing
-- c.f. GHC.IfaceToCore.tcIfaceGlobal
tcLookupLocatedGlobal :: Located Name -> TcM TyThing
tcLookupLocatedGlobal Located Name
name
  = (Name -> TcM TyThing) -> Located Name -> TcM TyThing
forall a b. (a -> TcM b) -> Located a -> TcM b
addLocM Name -> TcM TyThing
tcLookupGlobal Located Name
name

tcLookupGlobal :: Name -> TcM TyThing
-- The Name is almost always an ExternalName, but not always
-- In GHCi, we may make command-line bindings (ghci> let x = True)
-- that bind a GlobalId, but with an InternalName
tcLookupGlobal :: Name -> TcM TyThing
tcLookupGlobal Name
name
  = do  {    -- Try local envt
          TcGblEnv
env <- TcRnIf TcGblEnv TcLclEnv TcGblEnv
forall gbl lcl. TcRnIf gbl lcl gbl
getGblEnv
        ; case NameEnv TyThing -> Name -> Maybe TyThing
forall a. NameEnv a -> Name -> Maybe a
lookupNameEnv (TcGblEnv -> NameEnv TyThing
tcg_type_env TcGblEnv
env) Name
name of {
                Just TyThing
thing -> TyThing -> TcM TyThing
forall (m :: * -> *) a. Monad m => a -> m a
return TyThing
thing ;
                Maybe TyThing
Nothing    ->

                -- Should it have been in the local envt?
                -- (NB: use semantic mod here, since names never use
                -- identity module, see Note [Identity versus semantic module].)
          if Module -> Name -> Bool
nameIsLocalOrFrom (TcGblEnv -> Module
tcg_semantic_mod TcGblEnv
env) Name
name
          then Name -> TcM TyThing
notFound Name
name  -- Internal names can happen in GHCi
          else

           -- Try home package table and external package table
    do  { MaybeErr MsgDoc TyThing
mb_thing <- Name -> TcM (MaybeErr MsgDoc TyThing)
tcLookupImported_maybe Name
name
        ; case MaybeErr MsgDoc TyThing
mb_thing of
            Succeeded TyThing
thing -> TyThing -> TcM TyThing
forall (m :: * -> *) a. Monad m => a -> m a
return TyThing
thing
            Failed MsgDoc
msg      -> MsgDoc -> TcM TyThing
forall a. MsgDoc -> TcM a
failWithTc MsgDoc
msg
        }}}

-- Look up only in this module's global env't. Don't look in imports, etc.
-- Panic if it's not there.
tcLookupGlobalOnly :: Name -> TcM TyThing
tcLookupGlobalOnly :: Name -> TcM TyThing
tcLookupGlobalOnly Name
name
  = do { TcGblEnv
env <- TcRnIf TcGblEnv TcLclEnv TcGblEnv
forall gbl lcl. TcRnIf gbl lcl gbl
getGblEnv
       ; TyThing -> TcM TyThing
forall (m :: * -> *) a. Monad m => a -> m a
return (TyThing -> TcM TyThing) -> TyThing -> TcM TyThing
forall a b. (a -> b) -> a -> b
$ case NameEnv TyThing -> Name -> Maybe TyThing
forall a. NameEnv a -> Name -> Maybe a
lookupNameEnv (TcGblEnv -> NameEnv TyThing
tcg_type_env TcGblEnv
env) Name
name of
                    Just TyThing
thing -> TyThing
thing
                    Maybe TyThing
Nothing    -> String -> MsgDoc -> TyThing
forall a. HasCallStack => String -> MsgDoc -> a
pprPanic String
"tcLookupGlobalOnly" (Name -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr Name
name) }

tcLookupDataCon :: Name -> TcM DataCon
tcLookupDataCon :: Name -> TcM DataCon
tcLookupDataCon Name
name = do
    TyThing
thing <- Name -> TcM TyThing
tcLookupGlobal Name
name
    case TyThing
thing of
        AConLike (RealDataCon DataCon
con) -> DataCon -> TcM DataCon
forall (m :: * -> *) a. Monad m => a -> m a
return DataCon
con
        TyThing
_                          -> String -> TcTyThing -> Name -> TcM DataCon
forall a. String -> TcTyThing -> Name -> TcM a
wrongThingErr String
"data constructor" (TyThing -> TcTyThing
AGlobal TyThing
thing) Name
name

tcLookupPatSyn :: Name -> TcM PatSyn
tcLookupPatSyn :: Name -> TcM PatSyn
tcLookupPatSyn Name
name = do
    TyThing
thing <- Name -> TcM TyThing
tcLookupGlobal Name
name
    case TyThing
thing of
        AConLike (PatSynCon PatSyn
ps) -> PatSyn -> TcM PatSyn
forall (m :: * -> *) a. Monad m => a -> m a
return PatSyn
ps
        TyThing
_                       -> String -> TcTyThing -> Name -> TcM PatSyn
forall a. String -> TcTyThing -> Name -> TcM a
wrongThingErr String
"pattern synonym" (TyThing -> TcTyThing
AGlobal TyThing
thing) Name
name

tcLookupConLike :: Name -> TcM ConLike
tcLookupConLike :: Name -> TcM ConLike
tcLookupConLike Name
name = do
    TyThing
thing <- Name -> TcM TyThing
tcLookupGlobal Name
name
    case TyThing
thing of
        AConLike ConLike
cl -> ConLike -> TcM ConLike
forall (m :: * -> *) a. Monad m => a -> m a
return ConLike
cl
        TyThing
_           -> String -> TcTyThing -> Name -> TcM ConLike
forall a. String -> TcTyThing -> Name -> TcM a
wrongThingErr String
"constructor-like thing" (TyThing -> TcTyThing
AGlobal TyThing
thing) Name
name

tcLookupClass :: Name -> TcM Class
tcLookupClass :: Name -> TcM Class
tcLookupClass Name
name = do
    TyThing
thing <- Name -> TcM TyThing
tcLookupGlobal Name
name
    case TyThing
thing of
        ATyCon TyCon
tc | Just Class
cls <- TyCon -> Maybe Class
tyConClass_maybe TyCon
tc -> Class -> TcM Class
forall (m :: * -> *) a. Monad m => a -> m a
return Class
cls
        TyThing
_                                           -> String -> TcTyThing -> Name -> TcM Class
forall a. String -> TcTyThing -> Name -> TcM a
wrongThingErr String
"class" (TyThing -> TcTyThing
AGlobal TyThing
thing) Name
name

tcLookupTyCon :: Name -> TcM TyCon
tcLookupTyCon :: Name -> TcM TyCon
tcLookupTyCon Name
name = do
    TyThing
thing <- Name -> TcM TyThing
tcLookupGlobal Name
name
    case TyThing
thing of
        ATyCon TyCon
tc -> TyCon -> TcM TyCon
forall (m :: * -> *) a. Monad m => a -> m a
return TyCon
tc
        TyThing
_         -> String -> TcTyThing -> Name -> TcM TyCon
forall a. String -> TcTyThing -> Name -> TcM a
wrongThingErr String
"type constructor" (TyThing -> TcTyThing
AGlobal TyThing
thing) Name
name

tcLookupAxiom :: Name -> TcM (CoAxiom Branched)
tcLookupAxiom :: Name -> TcM (CoAxiom Branched)
tcLookupAxiom Name
name = do
    TyThing
thing <- Name -> TcM TyThing
tcLookupGlobal Name
name
    case TyThing
thing of
        ACoAxiom CoAxiom Branched
ax -> CoAxiom Branched -> TcM (CoAxiom Branched)
forall (m :: * -> *) a. Monad m => a -> m a
return CoAxiom Branched
ax
        TyThing
_           -> String -> TcTyThing -> Name -> TcM (CoAxiom Branched)
forall a. String -> TcTyThing -> Name -> TcM a
wrongThingErr String
"axiom" (TyThing -> TcTyThing
AGlobal TyThing
thing) Name
name

tcLookupLocatedGlobalId :: Located Name -> TcM Id
tcLookupLocatedGlobalId :: Located Name -> TcM Id
tcLookupLocatedGlobalId = (Name -> TcM Id) -> Located Name -> TcM Id
forall a b. (a -> TcM b) -> Located a -> TcM b
addLocM Name -> TcM Id
tcLookupId

tcLookupLocatedClass :: Located Name -> TcM Class
tcLookupLocatedClass :: Located Name -> TcM Class
tcLookupLocatedClass = (Name -> TcM Class) -> Located Name -> TcM Class
forall a b. (a -> TcM b) -> Located a -> TcM b
addLocM Name -> TcM Class
tcLookupClass

tcLookupLocatedTyCon :: Located Name -> TcM TyCon
tcLookupLocatedTyCon :: Located Name -> TcM TyCon
tcLookupLocatedTyCon = (Name -> TcM TyCon) -> Located Name -> TcM TyCon
forall a b. (a -> TcM b) -> Located a -> TcM b
addLocM Name -> TcM TyCon
tcLookupTyCon

-- Find the instance that exactly matches a type class application.  The class arguments must be precisely
-- the same as in the instance declaration (modulo renaming & casts).
--
tcLookupInstance :: Class -> [Type] -> TcM ClsInst
tcLookupInstance :: Class -> [Type] -> TcM ClsInst
tcLookupInstance Class
cls [Type]
tys
  = do { InstEnvs
instEnv <- TcM InstEnvs
tcGetInstEnvs
       ; case InstEnvs -> Class -> [Type] -> Either MsgDoc (ClsInst, [Type])
lookupUniqueInstEnv InstEnvs
instEnv Class
cls [Type]
tys of
           Left MsgDoc
err             -> MsgDoc -> TcM ClsInst
forall a. MsgDoc -> TcM a
failWithTc (MsgDoc -> TcM ClsInst) -> MsgDoc -> TcM ClsInst
forall a b. (a -> b) -> a -> b
$ String -> MsgDoc
text String
"Couldn't match instance:" MsgDoc -> MsgDoc -> MsgDoc
<+> MsgDoc
err
           Right (ClsInst
inst, [Type]
tys)
             | [Type] -> Bool
uniqueTyVars [Type]
tys -> ClsInst -> TcM ClsInst
forall (m :: * -> *) a. Monad m => a -> m a
return ClsInst
inst
             | Bool
otherwise        -> MsgDoc -> TcM ClsInst
forall a. MsgDoc -> TcM a
failWithTc MsgDoc
errNotExact
       }
  where
    errNotExact :: MsgDoc
errNotExact = String -> MsgDoc
text String
"Not an exact match (i.e., some variables get instantiated)"

    uniqueTyVars :: [Type] -> Bool
uniqueTyVars [Type]
tys = (Type -> Bool) -> [Type] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all Type -> Bool
isTyVarTy [Type]
tys
                    Bool -> Bool -> Bool
&& [Id] -> Bool
forall a. Eq a => [a] -> Bool
hasNoDups ((Type -> Id) -> [Type] -> [Id]
forall a b. (a -> b) -> [a] -> [b]
map (String -> Type -> Id
getTyVar String
"tcLookupInstance") [Type]
tys)

tcGetInstEnvs :: TcM InstEnvs
-- Gets both the external-package inst-env
-- and the home-pkg inst env (includes module being compiled)
tcGetInstEnvs :: TcM InstEnvs
tcGetInstEnvs = do { ExternalPackageState
eps <- TcRnIf TcGblEnv TcLclEnv ExternalPackageState
forall gbl lcl. TcRnIf gbl lcl ExternalPackageState
getEps
                   ; TcGblEnv
env <- TcRnIf TcGblEnv TcLclEnv TcGblEnv
forall gbl lcl. TcRnIf gbl lcl gbl
getGblEnv
                   ; InstEnvs -> TcM InstEnvs
forall (m :: * -> *) a. Monad m => a -> m a
return (InstEnvs :: InstEnv -> InstEnv -> VisibleOrphanModules -> InstEnvs
InstEnvs { ie_global :: InstEnv
ie_global  = ExternalPackageState -> InstEnv
eps_inst_env ExternalPackageState
eps
                                      , ie_local :: InstEnv
ie_local   = TcGblEnv -> InstEnv
tcg_inst_env TcGblEnv
env
                                      , ie_visible :: VisibleOrphanModules
ie_visible = TcGblEnv -> VisibleOrphanModules
tcVisibleOrphanMods TcGblEnv
env }) }

instance MonadThings (IOEnv (Env TcGblEnv TcLclEnv)) where
    lookupThing :: Name -> TcM TyThing
lookupThing = Name -> TcM TyThing
tcLookupGlobal

{-
************************************************************************
*                                                                      *
                Extending the global environment
*                                                                      *
************************************************************************
-}

setGlobalTypeEnv :: TcGblEnv -> TypeEnv -> TcM TcGblEnv
-- Use this to update the global type env
-- It updates both  * the normal tcg_type_env field
--                  * the tcg_type_env_var field seen by interface files
setGlobalTypeEnv :: TcGblEnv -> NameEnv TyThing -> TcRnIf TcGblEnv TcLclEnv TcGblEnv
setGlobalTypeEnv TcGblEnv
tcg_env NameEnv TyThing
new_type_env
  = do  {     -- Sync the type-envt variable seen by interface files
           IORef (NameEnv TyThing)
-> NameEnv TyThing -> IOEnv (Env TcGblEnv TcLclEnv) ()
forall a env. IORef a -> a -> IOEnv env ()
writeMutVar (TcGblEnv -> IORef (NameEnv TyThing)
tcg_type_env_var TcGblEnv
tcg_env) NameEnv TyThing
new_type_env
         ; TcGblEnv -> TcRnIf TcGblEnv TcLclEnv TcGblEnv
forall (m :: * -> *) a. Monad m => a -> m a
return (TcGblEnv
tcg_env { tcg_type_env :: NameEnv TyThing
tcg_type_env = NameEnv TyThing
new_type_env }) }


tcExtendGlobalEnvImplicit :: [TyThing] -> TcM r -> TcM r
  -- Just extend the global environment with some TyThings
  -- Do not extend tcg_tcs, tcg_patsyns etc
tcExtendGlobalEnvImplicit :: forall r. [TyThing] -> TcM r -> TcM r
tcExtendGlobalEnvImplicit [TyThing]
things TcM r
thing_inside
   = do { TcGblEnv
tcg_env <- TcRnIf TcGblEnv TcLclEnv TcGblEnv
forall gbl lcl. TcRnIf gbl lcl gbl
getGblEnv
        ; let ge' :: NameEnv TyThing
ge'  = NameEnv TyThing -> [TyThing] -> NameEnv TyThing
extendTypeEnvList (TcGblEnv -> NameEnv TyThing
tcg_type_env TcGblEnv
tcg_env) [TyThing]
things
        ; TcGblEnv
tcg_env' <- TcGblEnv -> NameEnv TyThing -> TcRnIf TcGblEnv TcLclEnv TcGblEnv
setGlobalTypeEnv TcGblEnv
tcg_env NameEnv TyThing
ge'
        ; TcGblEnv -> TcM r -> TcM r
forall gbl lcl a. gbl -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
setGblEnv TcGblEnv
tcg_env' TcM r
thing_inside }

tcExtendGlobalEnv :: [TyThing] -> TcM r -> TcM r
  -- Given a mixture of Ids, TyCons, Classes, all defined in the
  -- module being compiled, extend the global environment
tcExtendGlobalEnv :: forall r. [TyThing] -> TcM r -> TcM r
tcExtendGlobalEnv [TyThing]
things TcM r
thing_inside
  = do { TcGblEnv
env <- TcRnIf TcGblEnv TcLclEnv TcGblEnv
forall gbl lcl. TcRnIf gbl lcl gbl
getGblEnv
       ; let env' :: TcGblEnv
env' = TcGblEnv
env { tcg_tcs :: [TyCon]
tcg_tcs = [TyCon
tc | ATyCon TyCon
tc <- [TyThing]
things] [TyCon] -> [TyCon] -> [TyCon]
forall a. [a] -> [a] -> [a]
++ TcGblEnv -> [TyCon]
tcg_tcs TcGblEnv
env,
                          tcg_patsyns :: [PatSyn]
tcg_patsyns = [PatSyn
ps | AConLike (PatSynCon PatSyn
ps) <- [TyThing]
things] [PatSyn] -> [PatSyn] -> [PatSyn]
forall a. [a] -> [a] -> [a]
++ TcGblEnv -> [PatSyn]
tcg_patsyns TcGblEnv
env }
       ; TcGblEnv -> TcM r -> TcM r
forall gbl lcl a. gbl -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
setGblEnv TcGblEnv
env' (TcM r -> TcM r) -> TcM r -> TcM r
forall a b. (a -> b) -> a -> b
$
            [TyThing] -> TcM r -> TcM r
forall r. [TyThing] -> TcM r -> TcM r
tcExtendGlobalEnvImplicit [TyThing]
things TcM r
thing_inside
       }

tcExtendTyConEnv :: [TyCon] -> TcM r -> TcM r
  -- Given a mixture of Ids, TyCons, Classes, all defined in the
  -- module being compiled, extend the global environment
tcExtendTyConEnv :: forall r. [TyCon] -> TcM r -> TcM r
tcExtendTyConEnv [TyCon]
tycons TcM r
thing_inside
  = do { TcGblEnv
env <- TcRnIf TcGblEnv TcLclEnv TcGblEnv
forall gbl lcl. TcRnIf gbl lcl gbl
getGblEnv
       ; let env' :: TcGblEnv
env' = TcGblEnv
env { tcg_tcs :: [TyCon]
tcg_tcs = [TyCon]
tycons [TyCon] -> [TyCon] -> [TyCon]
forall a. [a] -> [a] -> [a]
++ TcGblEnv -> [TyCon]
tcg_tcs TcGblEnv
env }
       ; TcGblEnv -> TcM r -> TcM r
forall gbl lcl a. gbl -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
setGblEnv TcGblEnv
env' (TcM r -> TcM r) -> TcM r -> TcM r
forall a b. (a -> b) -> a -> b
$
         [TyThing] -> TcM r -> TcM r
forall r. [TyThing] -> TcM r -> TcM r
tcExtendGlobalEnvImplicit ((TyCon -> TyThing) -> [TyCon] -> [TyThing]
forall a b. (a -> b) -> [a] -> [b]
map TyCon -> TyThing
ATyCon [TyCon]
tycons) TcM r
thing_inside
       }

tcExtendGlobalValEnv :: [Id] -> TcM a -> TcM a
  -- Same deal as tcExtendGlobalEnv, but for Ids
tcExtendGlobalValEnv :: forall a. [Id] -> TcM a -> TcM a
tcExtendGlobalValEnv [Id]
ids TcM a
thing_inside
  = [TyThing] -> TcM a -> TcM a
forall r. [TyThing] -> TcM r -> TcM r
tcExtendGlobalEnvImplicit [Id -> TyThing
AnId Id
id | Id
id <- [Id]
ids] TcM a
thing_inside

tcExtendRecEnv :: [(Name,TyThing)] -> TcM r -> TcM r
-- Extend the global environments for the type/class knot tying game
-- Just like tcExtendGlobalEnv, except the argument is a list of pairs
tcExtendRecEnv :: forall r. [(Name, TyThing)] -> TcM r -> TcM r
tcExtendRecEnv [(Name, TyThing)]
gbl_stuff TcM r
thing_inside
 = do  { TcGblEnv
tcg_env <- TcRnIf TcGblEnv TcLclEnv TcGblEnv
forall gbl lcl. TcRnIf gbl lcl gbl
getGblEnv
       ; let ge' :: NameEnv TyThing
ge'      = NameEnv TyThing -> [(Name, TyThing)] -> NameEnv TyThing
forall a. NameEnv a -> [(Name, a)] -> NameEnv a
extendNameEnvList (TcGblEnv -> NameEnv TyThing
tcg_type_env TcGblEnv
tcg_env) [(Name, TyThing)]
gbl_stuff
             tcg_env' :: TcGblEnv
tcg_env' = TcGblEnv
tcg_env { tcg_type_env :: NameEnv TyThing
tcg_type_env = NameEnv TyThing
ge' }
         -- No need for setGlobalTypeEnv (which side-effects the
         -- tcg_type_env_var); tcExtendRecEnv is used just
         -- when kind-check a group of type/class decls. It would
         -- in any case be wrong for an interface-file decl to end up
         -- with a TcTyCon in it!
       ; TcGblEnv -> TcM r -> TcM r
forall gbl lcl a. gbl -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
setGblEnv TcGblEnv
tcg_env' TcM r
thing_inside }

{-
************************************************************************
*                                                                      *
\subsection{The local environment}
*                                                                      *
************************************************************************
-}

tcLookupLocated :: Located Name -> TcM TcTyThing
tcLookupLocated :: Located Name -> TcM TcTyThing
tcLookupLocated = (Name -> TcM TcTyThing) -> Located Name -> TcM TcTyThing
forall a b. (a -> TcM b) -> Located a -> TcM b
addLocM Name -> TcM TcTyThing
tcLookup

tcLookupLcl_maybe :: Name -> TcM (Maybe TcTyThing)
tcLookupLcl_maybe :: Name -> TcM (Maybe TcTyThing)
tcLookupLcl_maybe Name
name
  = do { TcTypeEnv
local_env <- TcM TcTypeEnv
getLclTypeEnv
       ; Maybe TcTyThing -> TcM (Maybe TcTyThing)
forall (m :: * -> *) a. Monad m => a -> m a
return (TcTypeEnv -> Name -> Maybe TcTyThing
forall a. NameEnv a -> Name -> Maybe a
lookupNameEnv TcTypeEnv
local_env Name
name) }

tcLookup :: Name -> TcM TcTyThing
tcLookup :: Name -> TcM TcTyThing
tcLookup Name
name = do
    TcTypeEnv
local_env <- TcM TcTypeEnv
getLclTypeEnv
    case TcTypeEnv -> Name -> Maybe TcTyThing
forall a. NameEnv a -> Name -> Maybe a
lookupNameEnv TcTypeEnv
local_env Name
name of
        Just TcTyThing
thing -> TcTyThing -> TcM TcTyThing
forall (m :: * -> *) a. Monad m => a -> m a
return TcTyThing
thing
        Maybe TcTyThing
Nothing    -> (TyThing -> TcTyThing
AGlobal (TyThing -> TcTyThing) -> TcM TyThing -> TcM TcTyThing
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Name -> TcM TyThing
tcLookupGlobal Name
name)

tcLookupTyVar :: Name -> TcM TcTyVar
tcLookupTyVar :: Name -> TcM Id
tcLookupTyVar Name
name
  = do { TcTyThing
thing <- Name -> TcM TcTyThing
tcLookup Name
name
       ; case TcTyThing
thing of
           ATyVar Name
_ Id
tv -> Id -> TcM Id
forall (m :: * -> *) a. Monad m => a -> m a
return Id
tv
           TcTyThing
_           -> String -> MsgDoc -> TcM Id
forall a. HasCallStack => String -> MsgDoc -> a
pprPanic String
"tcLookupTyVar" (Name -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr Name
name) }

tcLookupId :: Name -> TcM Id
-- Used when we aren't interested in the binding level, nor refinement.
-- The "no refinement" part means that we return the un-refined Id regardless
--
-- The Id is never a DataCon. (Why does that matter? see GHC.Tc.Gen.Expr.tcId)
tcLookupId :: Name -> TcM Id
tcLookupId Name
name = do
    Maybe Id
thing <- Name -> TcM (Maybe Id)
tcLookupIdMaybe Name
name
    case Maybe Id
thing of
        Just Id
id -> Id -> TcM Id
forall (m :: * -> *) a. Monad m => a -> m a
return Id
id
        Maybe Id
_       -> String -> MsgDoc -> TcM Id
forall a. HasCallStack => String -> MsgDoc -> a
pprPanic String
"tcLookupId" (Name -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr Name
name)

tcLookupIdMaybe :: Name -> TcM (Maybe Id)
tcLookupIdMaybe :: Name -> TcM (Maybe Id)
tcLookupIdMaybe Name
name
  = do { TcTyThing
thing <- Name -> TcM TcTyThing
tcLookup Name
name
       ; case TcTyThing
thing of
           ATcId { tct_id :: TcTyThing -> Id
tct_id = Id
id} -> Maybe Id -> TcM (Maybe Id)
forall (m :: * -> *) a. Monad m => a -> m a
return (Maybe Id -> TcM (Maybe Id)) -> Maybe Id -> TcM (Maybe Id)
forall a b. (a -> b) -> a -> b
$ Id -> Maybe Id
forall a. a -> Maybe a
Just Id
id
           AGlobal (AnId Id
id)    -> Maybe Id -> TcM (Maybe Id)
forall (m :: * -> *) a. Monad m => a -> m a
return (Maybe Id -> TcM (Maybe Id)) -> Maybe Id -> TcM (Maybe Id)
forall a b. (a -> b) -> a -> b
$ Id -> Maybe Id
forall a. a -> Maybe a
Just Id
id
           TcTyThing
_                    -> Maybe Id -> TcM (Maybe Id)
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe Id
forall a. Maybe a
Nothing }

tcLookupLocalIds :: [Name] -> TcM [TcId]
-- We expect the variables to all be bound, and all at
-- the same level as the lookup.  Only used in one place...
tcLookupLocalIds :: [Name] -> TcM [Id]
tcLookupLocalIds [Name]
ns
  = do { TcLclEnv
env <- TcRnIf TcGblEnv TcLclEnv TcLclEnv
forall gbl lcl. TcRnIf gbl lcl lcl
getLclEnv
       ; [Id] -> TcM [Id]
forall (m :: * -> *) a. Monad m => a -> m a
return ((Name -> Id) -> [Name] -> [Id]
forall a b. (a -> b) -> [a] -> [b]
map (TcTypeEnv -> Name -> Id
lookup (TcLclEnv -> TcTypeEnv
tcl_env TcLclEnv
env)) [Name]
ns) }
  where
    lookup :: TcTypeEnv -> Name -> Id
lookup TcTypeEnv
lenv Name
name
        = case TcTypeEnv -> Name -> Maybe TcTyThing
forall a. NameEnv a -> Name -> Maybe a
lookupNameEnv TcTypeEnv
lenv Name
name of
                Just (ATcId { tct_id :: TcTyThing -> Id
tct_id = Id
id }) ->  Id
id
                Maybe TcTyThing
_ -> String -> MsgDoc -> Id
forall a. HasCallStack => String -> MsgDoc -> a
pprPanic String
"tcLookupLocalIds" (Name -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr Name
name)

-- inferInitialKind has made a suitably-shaped kind for the type or class
-- Look it up in the local environment. This is used only for tycons
-- that we're currently type-checking, so we're sure to find a TcTyCon.
tcLookupTcTyCon :: HasDebugCallStack => Name -> TcM TcTyCon
tcLookupTcTyCon :: HasDebugCallStack => Name -> TcM TyCon
tcLookupTcTyCon Name
name = do
    TcTyThing
thing <- Name -> TcM TcTyThing
tcLookup Name
name
    case TcTyThing
thing of
        ATcTyCon TyCon
tc -> TyCon -> TcM TyCon
forall (m :: * -> *) a. Monad m => a -> m a
return TyCon
tc
        TcTyThing
_           -> String -> MsgDoc -> TcM TyCon
forall a. HasCallStack => String -> MsgDoc -> a
pprPanic String
"tcLookupTcTyCon" (Name -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr Name
name)

getInLocalScope :: TcM (Name -> Bool)
getInLocalScope :: TcM (Name -> Bool)
getInLocalScope = do { TcTypeEnv
lcl_env <- TcM TcTypeEnv
getLclTypeEnv
                     ; (Name -> Bool) -> TcM (Name -> Bool)
forall (m :: * -> *) a. Monad m => a -> m a
return (Name -> TcTypeEnv -> Bool
forall a. Name -> NameEnv a -> Bool
`elemNameEnv` TcTypeEnv
lcl_env) }

tcExtendKindEnvList :: [(Name, TcTyThing)] -> TcM r -> TcM r
-- Used only during kind checking, for TcThings that are
--      ATcTyCon or APromotionErr
-- No need to update the global tyvars, or tcl_th_bndrs, or tcl_rdr
tcExtendKindEnvList :: forall r. [(Name, TcTyThing)] -> TcM r -> TcM r
tcExtendKindEnvList [(Name, TcTyThing)]
things TcM r
thing_inside
  = do { String -> MsgDoc -> IOEnv (Env TcGblEnv TcLclEnv) ()
traceTc String
"tcExtendKindEnvList" ([(Name, TcTyThing)] -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr [(Name, TcTyThing)]
things)
       ; (TcLclEnv -> TcLclEnv) -> TcM r -> TcM r
forall lcl gbl a.
(lcl -> lcl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
updLclEnv TcLclEnv -> TcLclEnv
upd_env TcM r
thing_inside }
  where
    upd_env :: TcLclEnv -> TcLclEnv
upd_env TcLclEnv
env = TcLclEnv
env { tcl_env :: TcTypeEnv
tcl_env = TcTypeEnv -> [(Name, TcTyThing)] -> TcTypeEnv
forall a. NameEnv a -> [(Name, a)] -> NameEnv a
extendNameEnvList (TcLclEnv -> TcTypeEnv
tcl_env TcLclEnv
env) [(Name, TcTyThing)]
things }

tcExtendKindEnv :: NameEnv TcTyThing -> TcM r -> TcM r
-- A variant of tcExtendKindEvnList
tcExtendKindEnv :: forall r. TcTypeEnv -> TcM r -> TcM r
tcExtendKindEnv TcTypeEnv
extra_env TcM r
thing_inside
  = do { String -> MsgDoc -> IOEnv (Env TcGblEnv TcLclEnv) ()
traceTc String
"tcExtendKindEnv" (TcTypeEnv -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr TcTypeEnv
extra_env)
       ; (TcLclEnv -> TcLclEnv) -> TcM r -> TcM r
forall lcl gbl a.
(lcl -> lcl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
updLclEnv TcLclEnv -> TcLclEnv
upd_env TcM r
thing_inside }
  where
    upd_env :: TcLclEnv -> TcLclEnv
upd_env TcLclEnv
env = TcLclEnv
env { tcl_env :: TcTypeEnv
tcl_env = TcLclEnv -> TcTypeEnv
tcl_env TcLclEnv
env TcTypeEnv -> TcTypeEnv -> TcTypeEnv
forall a. NameEnv a -> NameEnv a -> NameEnv a
`plusNameEnv` TcTypeEnv
extra_env }

-----------------------
-- Scoped type and kind variables
tcExtendTyVarEnv :: [TyVar] -> TcM r -> TcM r
tcExtendTyVarEnv :: forall a. [Id] -> TcM a -> TcM a
tcExtendTyVarEnv [Id]
tvs TcM r
thing_inside
  = [(Name, Id)] -> TcM r -> TcM r
forall r. [(Name, Id)] -> TcM r -> TcM r
tcExtendNameTyVarEnv ([Id] -> [(Name, Id)]
mkTyVarNamePairs [Id]
tvs) TcM r
thing_inside

tcExtendNameTyVarEnv :: [(Name,TcTyVar)] -> TcM r -> TcM r
tcExtendNameTyVarEnv :: forall r. [(Name, Id)] -> TcM r -> TcM r
tcExtendNameTyVarEnv [(Name, Id)]
binds TcM r
thing_inside
  -- this should be used only for explicitly mentioned scoped variables.
  -- thus, no coercion variables
  = do { TopLevelFlag -> [(Name, TcTyThing)] -> TcM r -> TcM r
forall a. TopLevelFlag -> [(Name, TcTyThing)] -> TcM a -> TcM a
tc_extend_local_env TopLevelFlag
NotTopLevel
                    [(Name
name, Name -> Id -> TcTyThing
ATyVar Name
name Id
tv) | (Name
name, Id
tv) <- [(Name, Id)]
binds] (TcM r -> TcM r) -> TcM r -> TcM r
forall a b. (a -> b) -> a -> b
$
         [TcBinder] -> TcM r -> TcM r
forall a. [TcBinder] -> TcM a -> TcM a
tcExtendBinderStack [TcBinder]
tv_binds (TcM r -> TcM r) -> TcM r -> TcM r
forall a b. (a -> b) -> a -> b
$
         TcM r
thing_inside }
  where
    tv_binds :: [TcBinder]
    tv_binds :: [TcBinder]
tv_binds = [Name -> Id -> TcBinder
TcTvBndr Name
name Id
tv | (Name
name,Id
tv) <- [(Name, Id)]
binds]

isTypeClosedLetBndr :: Id -> Bool
-- See Note [Bindings with closed types] in GHC.Tc.Types
isTypeClosedLetBndr :: Id -> Bool
isTypeClosedLetBndr = Type -> Bool
noFreeVarsOfType (Type -> Bool) -> (Id -> Type) -> Id -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Id -> Type
idType

tcExtendRecIds :: [(Name, TcId)] -> TcM a -> TcM a
-- Used for binding the recursive uses of Ids in a binding
-- both top-level value bindings and nested let/where-bindings
-- Does not extend the TcBinderStack
tcExtendRecIds :: forall r. [(Name, Id)] -> TcM r -> TcM r
tcExtendRecIds [(Name, Id)]
pairs TcM a
thing_inside
  = TopLevelFlag -> [(Name, TcTyThing)] -> TcM a -> TcM a
forall a. TopLevelFlag -> [(Name, TcTyThing)] -> TcM a -> TcM a
tc_extend_local_env TopLevelFlag
NotTopLevel
          [ (Name
name, ATcId :: Id -> IdBindingInfo -> TcTyThing
ATcId { tct_id :: Id
tct_id   = Id
let_id
                         , tct_info :: IdBindingInfo
tct_info = RhsNames -> Bool -> IdBindingInfo
NonClosedLet RhsNames
emptyNameSet Bool
False })
          | (Name
name, Id
let_id) <- [(Name, Id)]
pairs ] (TcM a -> TcM a) -> TcM a -> TcM a
forall a b. (a -> b) -> a -> b
$
    TcM a
thing_inside

tcExtendSigIds :: TopLevelFlag -> [TcId] -> TcM a -> TcM a
-- Used for binding the Ids that have a complete user type signature
-- Does not extend the TcBinderStack
tcExtendSigIds :: forall a. TopLevelFlag -> [Id] -> TcM a -> TcM a
tcExtendSigIds TopLevelFlag
top_lvl [Id]
sig_ids TcM a
thing_inside
  = TopLevelFlag -> [(Name, TcTyThing)] -> TcM a -> TcM a
forall a. TopLevelFlag -> [(Name, TcTyThing)] -> TcM a -> TcM a
tc_extend_local_env TopLevelFlag
top_lvl
          [ (Id -> Name
idName Id
id, ATcId :: Id -> IdBindingInfo -> TcTyThing
ATcId { tct_id :: Id
tct_id   = Id
id
                              , tct_info :: IdBindingInfo
tct_info = IdBindingInfo
info })
          | Id
id <- [Id]
sig_ids
          , let closed :: Bool
closed = Id -> Bool
isTypeClosedLetBndr Id
id
                info :: IdBindingInfo
info   = RhsNames -> Bool -> IdBindingInfo
NonClosedLet RhsNames
emptyNameSet Bool
closed ]
     TcM a
thing_inside


tcExtendLetEnv :: TopLevelFlag -> TcSigFun -> IsGroupClosed
                  -> [TcId] -> TcM a -> TcM a
-- Used for both top-level value bindings and nested let/where-bindings
-- Adds to the TcBinderStack too
tcExtendLetEnv :: forall a.
TopLevelFlag -> TcSigFun -> IsGroupClosed -> [Id] -> TcM a -> TcM a
tcExtendLetEnv TopLevelFlag
top_lvl TcSigFun
sig_fn (IsGroupClosed NameEnv RhsNames
fvs Bool
fv_type_closed)
               [Id]
ids TcM a
thing_inside
  = [TcBinder] -> TcM a -> TcM a
forall a. [TcBinder] -> TcM a -> TcM a
tcExtendBinderStack [Id -> TopLevelFlag -> TcBinder
TcIdBndr Id
id TopLevelFlag
top_lvl | Id
id <- [Id]
ids] (TcM a -> TcM a) -> TcM a -> TcM a
forall a b. (a -> b) -> a -> b
$
    TopLevelFlag -> [(Name, TcTyThing)] -> TcM a -> TcM a
forall a. TopLevelFlag -> [(Name, TcTyThing)] -> TcM a -> TcM a
tc_extend_local_env TopLevelFlag
top_lvl
          [ (Id -> Name
idName Id
id, ATcId :: Id -> IdBindingInfo -> TcTyThing
ATcId { tct_id :: Id
tct_id   = Id
id
                              , tct_info :: IdBindingInfo
tct_info = Id -> IdBindingInfo
mk_tct_info Id
id })
          | Id
id <- [Id]
ids ]
    TcM a
thing_inside
  where
    mk_tct_info :: Id -> IdBindingInfo
mk_tct_info Id
id
      | Bool
type_closed Bool -> Bool -> Bool
&& RhsNames -> Bool
isEmptyNameSet RhsNames
rhs_fvs = IdBindingInfo
ClosedLet
      | Bool
otherwise                             = RhsNames -> Bool -> IdBindingInfo
NonClosedLet RhsNames
rhs_fvs Bool
type_closed
      where
        name :: Name
name        = Id -> Name
idName Id
id
        rhs_fvs :: RhsNames
rhs_fvs     = NameEnv RhsNames -> Name -> Maybe RhsNames
forall a. NameEnv a -> Name -> Maybe a
lookupNameEnv NameEnv RhsNames
fvs Name
name Maybe RhsNames -> RhsNames -> RhsNames
forall a. Maybe a -> a -> a
`orElse` RhsNames
emptyNameSet
        type_closed :: Bool
type_closed = Id -> Bool
isTypeClosedLetBndr Id
id Bool -> Bool -> Bool
&&
                      (Bool
fv_type_closed Bool -> Bool -> Bool
|| TcSigFun -> Name -> Bool
hasCompleteSig TcSigFun
sig_fn Name
name)

tcExtendIdEnv :: [TcId] -> TcM a -> TcM a
-- For lambda-bound and case-bound Ids
-- Extends the TcBinderStack as well
tcExtendIdEnv :: forall a. [Id] -> TcM a -> TcM a
tcExtendIdEnv [Id]
ids TcM a
thing_inside
  = [(Name, Id)] -> TcM a -> TcM a
forall r. [(Name, Id)] -> TcM r -> TcM r
tcExtendIdEnv2 [(Id -> Name
idName Id
id, Id
id) | Id
id <- [Id]
ids] TcM a
thing_inside

tcExtendIdEnv1 :: Name -> TcId -> TcM a -> TcM a
-- Exactly like tcExtendIdEnv2, but for a single (name,id) pair
tcExtendIdEnv1 :: forall a. Name -> Id -> TcM a -> TcM a
tcExtendIdEnv1 Name
name Id
id TcM a
thing_inside
  = [(Name, Id)] -> TcM a -> TcM a
forall r. [(Name, Id)] -> TcM r -> TcM r
tcExtendIdEnv2 [(Name
name,Id
id)] TcM a
thing_inside

tcExtendIdEnv2 :: [(Name,TcId)] -> TcM a -> TcM a
tcExtendIdEnv2 :: forall r. [(Name, Id)] -> TcM r -> TcM r
tcExtendIdEnv2 [(Name, Id)]
names_w_ids TcM a
thing_inside
  = [TcBinder] -> TcM a -> TcM a
forall a. [TcBinder] -> TcM a -> TcM a
tcExtendBinderStack [ Id -> TopLevelFlag -> TcBinder
TcIdBndr Id
mono_id TopLevelFlag
NotTopLevel
                        | (Name
_,Id
mono_id) <- [(Name, Id)]
names_w_ids ] (TcM a -> TcM a) -> TcM a -> TcM a
forall a b. (a -> b) -> a -> b
$
    TopLevelFlag -> [(Name, TcTyThing)] -> TcM a -> TcM a
forall a. TopLevelFlag -> [(Name, TcTyThing)] -> TcM a -> TcM a
tc_extend_local_env TopLevelFlag
NotTopLevel
            [ (Name
name, ATcId :: Id -> IdBindingInfo -> TcTyThing
ATcId { tct_id :: Id
tct_id = Id
id
                           , tct_info :: IdBindingInfo
tct_info    = IdBindingInfo
NotLetBound })
            | (Name
name,Id
id) <- [(Name, Id)]
names_w_ids]
    TcM a
thing_inside

tc_extend_local_env :: TopLevelFlag -> [(Name, TcTyThing)] -> TcM a -> TcM a
tc_extend_local_env :: forall a. TopLevelFlag -> [(Name, TcTyThing)] -> TcM a -> TcM a
tc_extend_local_env TopLevelFlag
top_lvl [(Name, TcTyThing)]
extra_env TcM a
thing_inside
-- Precondition: the argument list extra_env has TcTyThings
--               that ATcId or ATyVar, but nothing else
--
-- Invariant: the ATcIds are fully zonked. Reasons:
--      (a) The kinds of the forall'd type variables are defaulted
--          (see Kind.defaultKind, done in skolemiseQuantifiedTyVar)
--      (b) There are no via-Indirect occurrences of the bound variables
--          in the types, because instantiation does not look through such things
--      (c) The call to tyCoVarsOfTypes is ok without looking through refs

-- The second argument of type TyVarSet is a set of type variables
-- that are bound together with extra_env and should not be regarded
-- as free in the types of extra_env.
  = do  { String -> MsgDoc -> IOEnv (Env TcGblEnv TcLclEnv) ()
traceTc String
"tc_extend_local_env" ([(Name, TcTyThing)] -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr [(Name, TcTyThing)]
extra_env)
        ; ThStage
stage <- TcM ThStage
getStage
        ; env0 :: TcLclEnv
env0@(TcLclEnv { tcl_rdr :: TcLclEnv -> LocalRdrEnv
tcl_rdr      = LocalRdrEnv
rdr_env
                         , tcl_th_bndrs :: TcLclEnv -> ThBindEnv
tcl_th_bndrs = ThBindEnv
th_bndrs
                         , tcl_env :: TcLclEnv -> TcTypeEnv
tcl_env      = TcTypeEnv
lcl_type_env }) <- TcRnIf TcGblEnv TcLclEnv TcLclEnv
forall gbl lcl. TcRnIf gbl lcl lcl
getLclEnv

        ; let thlvl :: (TopLevelFlag, ThLevel)
thlvl = (TopLevelFlag
top_lvl, ThStage -> ThLevel
thLevel ThStage
stage)

              env1 :: TcLclEnv
env1 = TcLclEnv
env0 { tcl_rdr :: LocalRdrEnv
tcl_rdr = LocalRdrEnv -> [Name] -> LocalRdrEnv
extendLocalRdrEnvList LocalRdrEnv
rdr_env
                                      [ Name
n | (Name
n, TcTyThing
_) <- [(Name, TcTyThing)]
extra_env, Name -> Bool
isInternalName Name
n ]
                                      -- The LocalRdrEnv contains only non-top-level names
                                      -- (GlobalRdrEnv handles the top level)

                         , tcl_th_bndrs :: ThBindEnv
tcl_th_bndrs = ThBindEnv -> [(Name, (TopLevelFlag, ThLevel))] -> ThBindEnv
forall a. NameEnv a -> [(Name, a)] -> NameEnv a
extendNameEnvList ThBindEnv
th_bndrs
                                          [(Name
n, (TopLevelFlag, ThLevel)
thlvl) | (Name
n, ATcId {}) <- [(Name, TcTyThing)]
extra_env]
                                          -- We only track Ids in tcl_th_bndrs

                         , tcl_env :: TcTypeEnv
tcl_env = TcTypeEnv -> [(Name, TcTyThing)] -> TcTypeEnv
forall a. NameEnv a -> [(Name, a)] -> NameEnv a
extendNameEnvList TcTypeEnv
lcl_type_env [(Name, TcTyThing)]
extra_env }

              -- tcl_rdr and tcl_th_bndrs: extend the local LocalRdrEnv and
              -- Template Haskell staging env simultaneously. Reason for extending
              -- LocalRdrEnv: after running a TH splice we need to do renaming.

        ; TcLclEnv -> TcM a -> TcM a
forall lcl' gbl a lcl.
lcl' -> TcRnIf gbl lcl' a -> TcRnIf gbl lcl a
setLclEnv TcLclEnv
env1 TcM a
thing_inside }

tcExtendLocalTypeEnv :: TcLclEnv -> [(Name, TcTyThing)] -> TcLclEnv
tcExtendLocalTypeEnv :: TcLclEnv -> [(Name, TcTyThing)] -> TcLclEnv
tcExtendLocalTypeEnv lcl_env :: TcLclEnv
lcl_env@(TcLclEnv { tcl_env :: TcLclEnv -> TcTypeEnv
tcl_env = TcTypeEnv
lcl_type_env }) [(Name, TcTyThing)]
tc_ty_things
  = TcLclEnv
lcl_env { tcl_env :: TcTypeEnv
tcl_env = TcTypeEnv -> [(Name, TcTyThing)] -> TcTypeEnv
forall a. NameEnv a -> [(Name, a)] -> NameEnv a
extendNameEnvList TcTypeEnv
lcl_type_env [(Name, TcTyThing)]
tc_ty_things }

-- | @tcCheckUsage name mult thing_inside@ runs @thing_inside@, checks that the
-- usage of @name@ is a submultiplicity of @mult@, and removes @name@ from the
-- usage environment. See also Note [Wrapper returned from tcSubMult] in
-- GHC.Tc.Utils.Unify, which applies to the wrapper returned from this function.
tcCheckUsage :: Name -> Mult -> TcM a -> TcM (a, HsWrapper)
tcCheckUsage :: forall a. Name -> Type -> TcM a -> TcM (a, HsWrapper)
tcCheckUsage Name
name Type
id_mult TcM a
thing_inside
  = do { (UsageEnv
local_usage, a
result) <- TcM a -> TcM (UsageEnv, a)
forall a. TcM a -> TcM (UsageEnv, a)
tcCollectingUsage TcM a
thing_inside
       ; HsWrapper
wrapper <- UsageEnv -> TcM HsWrapper
check_then_add_usage UsageEnv
local_usage
       ; (a, HsWrapper) -> TcM (a, HsWrapper)
forall (m :: * -> *) a. Monad m => a -> m a
return (a
result, HsWrapper
wrapper) }
    where
    check_then_add_usage :: UsageEnv -> TcM HsWrapper
    -- Checks that the usage of the newly introduced binder is compatible with
    -- its multiplicity, and combines the usage of non-new binders to |uenv|
    check_then_add_usage :: UsageEnv -> TcM HsWrapper
check_then_add_usage UsageEnv
uenv
      = do { let actual_u :: Usage
actual_u = UsageEnv -> Name -> Usage
forall n. NamedThing n => UsageEnv -> n -> Usage
lookupUE UsageEnv
uenv Name
name
           ; String -> MsgDoc -> IOEnv (Env TcGblEnv TcLclEnv) ()
traceTc String
"check_then_add_usage" (Type -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr Type
id_mult MsgDoc -> MsgDoc -> MsgDoc
$$ Usage -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr Usage
actual_u)
           ; HsWrapper
wrapper <- case Usage
actual_u of
               Usage
Bottom -> HsWrapper -> TcM HsWrapper
forall (m :: * -> *) a. Monad m => a -> m a
return HsWrapper
idHsWrapper
               Usage
Zero     -> CtOrigin -> Type -> Type -> TcM HsWrapper
tcSubMult (Name -> CtOrigin
UsageEnvironmentOf Name
name) Type
Many Type
id_mult
               MUsage Type
m -> do { Type
m <- Type -> IOEnv (Env TcGblEnv TcLclEnv) Type
promote_mult Type
m
                              ; CtOrigin -> Type -> Type -> TcM HsWrapper
tcSubMult (Name -> CtOrigin
UsageEnvironmentOf Name
name) Type
m Type
id_mult }
           ; UsageEnv -> IOEnv (Env TcGblEnv TcLclEnv) ()
tcEmitBindingUsage (UsageEnv -> Name -> UsageEnv
forall n. NamedThing n => UsageEnv -> n -> UsageEnv
deleteUE UsageEnv
uenv Name
name)
           ; HsWrapper -> TcM HsWrapper
forall (m :: * -> *) a. Monad m => a -> m a
return HsWrapper
wrapper }

    -- This is gross. The problem is in test case typecheck/should_compile/T18998:
    --   f :: a %1-> Id n a -> Id n a
    --   f x (MkId _) = MkId x
    -- where MkId is a GADT constructor. Multiplicity polymorphism of constructors
    -- invents a new multiplicity variable p[2] for the application MkId x. This
    -- variable is at level 2, bumped because of the GADT pattern-match (MkId _).
    -- We eventually unify the variable with One, due to the call to tcSubMult in
    -- tcCheckUsage. But by then, we're at TcLevel 1, and so the level-check
    -- fails.
    --
    -- What to do? If we did inference "for real", the sub-multiplicity constraint
    -- would end up in the implication of the GADT pattern-match, and all would
    -- be well. But we don't have a real sub-multiplicity constraint to put in
    -- the implication. (Multiplicity inference works outside the usual generate-
    -- constraints-and-solve scheme.) Here, where the multiplicity arrives, we
    -- must promote all multiplicity variables to reflect this outer TcLevel.
    -- It's reminiscent of floating a constraint, really, so promotion is
    -- appropriate. The promoteTcType function works only on types of kind TYPE rr,
    -- so we can't use it here. Thus, this dirtiness.
    --
    -- It works nicely in practice.
    --
    -- We use a set to avoid calling promoteMetaTyVarTo twice on the same
    -- metavariable. This happened in #19400.
    promote_mult :: Type -> IOEnv (Env TcGblEnv TcLclEnv) Type
promote_mult Type
m = do { TyCoVarSet
fvs <- TyCoVarSet -> TcM TyCoVarSet
zonkTyCoVarsAndFV (Type -> TyCoVarSet
tyCoVarsOfType Type
m)
                        ; Bool
any_promoted <- TyCoVarSet -> TcM Bool
promoteTyVarSet TyCoVarSet
fvs
                        ; if Bool
any_promoted then Type -> IOEnv (Env TcGblEnv TcLclEnv) Type
zonkTcType Type
m else Type -> IOEnv (Env TcGblEnv TcLclEnv) Type
forall (m :: * -> *) a. Monad m => a -> m a
return Type
m
                        }

{- *********************************************************************
*                                                                      *
             The TcBinderStack
*                                                                      *
********************************************************************* -}

tcExtendBinderStack :: [TcBinder] -> TcM a -> TcM a
tcExtendBinderStack :: forall a. [TcBinder] -> TcM a -> TcM a
tcExtendBinderStack [TcBinder]
bndrs TcM a
thing_inside
  = do { String -> MsgDoc -> IOEnv (Env TcGblEnv TcLclEnv) ()
traceTc String
"tcExtendBinderStack" ([TcBinder] -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr [TcBinder]
bndrs)
       ; (TcLclEnv -> TcLclEnv) -> TcM a -> TcM a
forall lcl gbl a.
(lcl -> lcl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
updLclEnv (\TcLclEnv
env -> TcLclEnv
env { tcl_bndrs :: [TcBinder]
tcl_bndrs = [TcBinder]
bndrs [TcBinder] -> [TcBinder] -> [TcBinder]
forall a. [a] -> [a] -> [a]
++ TcLclEnv -> [TcBinder]
tcl_bndrs TcLclEnv
env })
                   TcM a
thing_inside }

tcInitTidyEnv :: TcM TidyEnv
-- We initialise the "tidy-env", used for tidying types before printing,
-- by building a reverse map from the in-scope type variables to the
-- OccName that the programmer originally used for them
tcInitTidyEnv :: TcM TidyEnv
tcInitTidyEnv
  = do  { TcLclEnv
lcl_env <- TcRnIf TcGblEnv TcLclEnv TcLclEnv
forall gbl lcl. TcRnIf gbl lcl lcl
getLclEnv
        ; TidyEnv -> [TcBinder] -> TcM TidyEnv
go TidyEnv
emptyTidyEnv (TcLclEnv -> [TcBinder]
tcl_bndrs TcLclEnv
lcl_env) }
  where
    go :: TidyEnv -> [TcBinder] -> TcM TidyEnv
go (TidyOccEnv
env, VarEnv Id
subst) []
      = TidyEnv -> TcM TidyEnv
forall (m :: * -> *) a. Monad m => a -> m a
return (TidyOccEnv
env, VarEnv Id
subst)
    go (TidyOccEnv
env, VarEnv Id
subst) (TcBinder
b : [TcBinder]
bs)
      | TcTvBndr Name
name Id
tyvar <- TcBinder
b
       = do { let (TidyOccEnv
env', OccName
occ') = TidyOccEnv -> OccName -> (TidyOccEnv, OccName)
tidyOccName TidyOccEnv
env (Name -> OccName
nameOccName Name
name)
                  name' :: Name
name'  = Name -> OccName -> Name
tidyNameOcc Name
name OccName
occ'
                  tyvar1 :: Id
tyvar1 = Id -> Name -> Id
setTyVarName Id
tyvar Name
name'
            ; Id
tyvar2 <- HasDebugCallStack => Id -> TcM Id
Id -> TcM Id
zonkTcTyVarToTyVar Id
tyvar1
              -- Be sure to zonk here!  Tidying applies to zonked
              -- types, so if we don't zonk we may create an
              -- ill-kinded type (#14175)
            ; TidyEnv -> [TcBinder] -> TcM TidyEnv
go (TidyOccEnv
env', VarEnv Id -> Id -> Id -> VarEnv Id
forall a. VarEnv a -> Id -> a -> VarEnv a
extendVarEnv VarEnv Id
subst Id
tyvar Id
tyvar2) [TcBinder]
bs }
      | Bool
otherwise
      = TidyEnv -> [TcBinder] -> TcM TidyEnv
go (TidyOccEnv
env, VarEnv Id
subst) [TcBinder]
bs

-- | Get a 'TidyEnv' that includes mappings for all vars free in the given
-- type. Useful when tidying open types.
tcInitOpenTidyEnv :: [TyCoVar] -> TcM TidyEnv
tcInitOpenTidyEnv :: [Id] -> TcM TidyEnv
tcInitOpenTidyEnv [Id]
tvs
  = do { TidyEnv
env1 <- TcM TidyEnv
tcInitTidyEnv
       ; let env2 :: TidyEnv
env2 = TidyEnv -> [Id] -> TidyEnv
tidyFreeTyCoVars TidyEnv
env1 [Id]
tvs
       ; TidyEnv -> TcM TidyEnv
forall (m :: * -> *) a. Monad m => a -> m a
return TidyEnv
env2 }



{- *********************************************************************
*                                                                      *
             Adding placeholders
*                                                                      *
********************************************************************* -}

tcAddDataFamConPlaceholders :: [LInstDecl GhcRn] -> TcM a -> TcM a
-- See Note [AFamDataCon: not promoting data family constructors]
tcAddDataFamConPlaceholders :: forall a. [LInstDecl GhcRn] -> TcM a -> TcM a
tcAddDataFamConPlaceholders [LInstDecl GhcRn]
inst_decls TcM a
thing_inside
  = [(Name, TcTyThing)] -> TcM a -> TcM a
forall r. [(Name, TcTyThing)] -> TcM r -> TcM r
tcExtendKindEnvList [ (Name
con, PromotionErr -> TcTyThing
APromotionErr PromotionErr
FamDataConPE)
                        | LInstDecl GhcRn
lid <- [LInstDecl GhcRn]
inst_decls, Name
con <- LInstDecl GhcRn -> [Name]
get_cons LInstDecl GhcRn
lid ]
      TcM a
thing_inside
      -- Note [AFamDataCon: not promoting data family constructors]
  where
    -- get_cons extracts the *constructor* bindings of the declaration
    get_cons :: LInstDecl GhcRn -> [Name]
    get_cons :: LInstDecl GhcRn -> [Name]
get_cons (L SrcSpan
_ (TyFamInstD {}))                     = []
    get_cons (L SrcSpan
_ (DataFamInstD { dfid_inst :: forall pass. InstDecl pass -> DataFamInstDecl pass
dfid_inst = DataFamInstDecl GhcRn
fid }))  = DataFamInstDecl GhcRn -> [Name]
get_fi_cons DataFamInstDecl GhcRn
fid
    get_cons (L SrcSpan
_ (ClsInstD { cid_inst :: forall pass. InstDecl pass -> ClsInstDecl pass
cid_inst = ClsInstDecl { cid_datafam_insts :: forall pass. ClsInstDecl pass -> [LDataFamInstDecl pass]
cid_datafam_insts = [LDataFamInstDecl GhcRn]
fids } }))
      = (LDataFamInstDecl GhcRn -> [Name])
-> [LDataFamInstDecl GhcRn] -> [Name]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap (DataFamInstDecl GhcRn -> [Name]
get_fi_cons (DataFamInstDecl GhcRn -> [Name])
-> (LDataFamInstDecl GhcRn -> DataFamInstDecl GhcRn)
-> LDataFamInstDecl GhcRn
-> [Name]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. LDataFamInstDecl GhcRn -> DataFamInstDecl GhcRn
forall l e. GenLocated l e -> e
unLoc) [LDataFamInstDecl GhcRn]
fids

    get_fi_cons :: DataFamInstDecl GhcRn -> [Name]
    get_fi_cons :: DataFamInstDecl GhcRn -> [Name]
get_fi_cons (DataFamInstDecl { dfid_eqn :: forall pass.
DataFamInstDecl pass -> FamInstEqn pass (HsDataDefn pass)
dfid_eqn = HsIB { hsib_body :: forall pass thing. HsImplicitBndrs pass thing -> thing
hsib_body =
                  FamEqn { feqn_rhs :: forall pass rhs. FamEqn pass rhs -> rhs
feqn_rhs = HsDataDefn { dd_cons :: forall pass. HsDataDefn pass -> [LConDecl pass]
dd_cons = [LConDecl GhcRn]
cons } }}})
      = (Located Name -> Name) -> [Located Name] -> [Name]
forall a b. (a -> b) -> [a] -> [b]
map Located Name -> Name
forall l e. GenLocated l e -> e
unLoc ([Located Name] -> [Name]) -> [Located Name] -> [Name]
forall a b. (a -> b) -> a -> b
$ (LConDecl GhcRn -> [Located Name])
-> [LConDecl GhcRn] -> [Located Name]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap (ConDecl GhcRn -> [Located Name]
getConNames (ConDecl GhcRn -> [Located Name])
-> (LConDecl GhcRn -> ConDecl GhcRn)
-> LConDecl GhcRn
-> [Located Name]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. LConDecl GhcRn -> ConDecl GhcRn
forall l e. GenLocated l e -> e
unLoc) [LConDecl GhcRn]
cons


tcAddPatSynPlaceholders :: [PatSynBind GhcRn GhcRn] -> TcM a -> TcM a
-- See Note [Don't promote pattern synonyms]
tcAddPatSynPlaceholders :: forall a. [PatSynBind GhcRn GhcRn] -> TcM a -> TcM a
tcAddPatSynPlaceholders [PatSynBind GhcRn GhcRn]
pat_syns TcM a
thing_inside
  = [(Name, TcTyThing)] -> TcM a -> TcM a
forall r. [(Name, TcTyThing)] -> TcM r -> TcM r
tcExtendKindEnvList [ (Name
IdP GhcRn
name, PromotionErr -> TcTyThing
APromotionErr PromotionErr
PatSynPE)
                        | PSB{ psb_id :: forall idL idR. PatSynBind idL idR -> Located (IdP idL)
psb_id = L SrcSpan
_ IdP GhcRn
name } <- [PatSynBind GhcRn GhcRn]
pat_syns ]
       TcM a
thing_inside

getTypeSigNames :: [LSig GhcRn] -> NameSet
-- Get the names that have a user type sig
getTypeSigNames :: [LSig GhcRn] -> RhsNames
getTypeSigNames [LSig GhcRn]
sigs
  = (LSig GhcRn -> RhsNames -> RhsNames)
-> RhsNames -> [LSig GhcRn] -> RhsNames
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr LSig GhcRn -> RhsNames -> RhsNames
get_type_sig RhsNames
emptyNameSet [LSig GhcRn]
sigs
  where
    get_type_sig :: LSig GhcRn -> NameSet -> NameSet
    get_type_sig :: LSig GhcRn -> RhsNames -> RhsNames
get_type_sig LSig GhcRn
sig RhsNames
ns =
      case LSig GhcRn
sig of
        L SrcSpan
_ (TypeSig XTypeSig GhcRn
_ [GenLocated SrcSpan (IdP GhcRn)]
names LHsSigWcType GhcRn
_) -> RhsNames -> [Name] -> RhsNames
extendNameSetList RhsNames
ns ((Located Name -> Name) -> [Located Name] -> [Name]
forall a b. (a -> b) -> [a] -> [b]
map Located Name -> Name
forall l e. GenLocated l e -> e
unLoc [Located Name]
[GenLocated SrcSpan (IdP GhcRn)]
names)
        L SrcSpan
_ (PatSynSig XPatSynSig GhcRn
_ [GenLocated SrcSpan (IdP GhcRn)]
names LHsSigType GhcRn
_) -> RhsNames -> [Name] -> RhsNames
extendNameSetList RhsNames
ns ((Located Name -> Name) -> [Located Name] -> [Name]
forall a b. (a -> b) -> [a] -> [b]
map Located Name -> Name
forall l e. GenLocated l e -> e
unLoc [Located Name]
[GenLocated SrcSpan (IdP GhcRn)]
names)
        LSig GhcRn
_ -> RhsNames
ns


{- Note [AFamDataCon: not promoting data family constructors]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
  data family T a
  data instance T Int = MkT
  data Proxy (a :: k)
  data S = MkS (Proxy 'MkT)

Is it ok to use the promoted data family instance constructor 'MkT' in
the data declaration for S (where both declarations live in the same module)?
No, we don't allow this. It *might* make sense, but at least it would mean that
we'd have to interleave typechecking instances and data types, whereas at
present we do data types *then* instances.

So to check for this we put in the TcLclEnv a binding for all the family
constructors, bound to AFamDataCon, so that if we trip over 'MkT' when
type checking 'S' we'll produce a decent error message.

#12088 describes this limitation. Of course, when MkT and S live in
different modules then all is well.

Note [Don't promote pattern synonyms]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We never promote pattern synonyms.

Consider this (#11265):
  pattern A = True
  instance Eq A
We want a civilised error message from the occurrence of 'A'
in the instance, yet 'A' really has not yet been type checked.

Similarly (#9161)
  {-# LANGUAGE PatternSynonyms, DataKinds #-}
  pattern A = ()
  b :: A
  b = undefined
Here, the type signature for b mentions A.  But A is a pattern
synonym, which is typechecked as part of a group of bindings (for very
good reasons; a view pattern in the RHS may mention a value binding).
It is entirely reasonable to reject this, but to do so we need A to be
in the kind environment when kind-checking the signature for B.

Hence tcAddPatSynPlaceholers adds a binding
    A -> APromotionErr PatSynPE
to the environment. Then GHC.Tc.Gen.HsType.tcTyVar will find A in the kind
environment, and will give a 'wrongThingErr' as a result.  But the
lookup of A won't fail.


************************************************************************
*                                                                      *
\subsection{Rules}
*                                                                      *
************************************************************************
-}

tcExtendRules :: [LRuleDecl GhcTc] -> TcM a -> TcM a
        -- Just pop the new rules into the EPS and envt resp
        -- All the rules come from an interface file, not source
        -- Nevertheless, some may be for this module, if we read
        -- its interface instead of its source code
tcExtendRules :: forall a. [LRuleDecl GhcTc] -> TcM a -> TcM a
tcExtendRules [LRuleDecl GhcTc]
lcl_rules TcM a
thing_inside
 = do { TcGblEnv
env <- TcRnIf TcGblEnv TcLclEnv TcGblEnv
forall gbl lcl. TcRnIf gbl lcl gbl
getGblEnv
      ; let
          env' :: TcGblEnv
env' = TcGblEnv
env { tcg_rules :: [LRuleDecl GhcTc]
tcg_rules = [LRuleDecl GhcTc]
lcl_rules [LRuleDecl GhcTc] -> [LRuleDecl GhcTc] -> [LRuleDecl GhcTc]
forall a. [a] -> [a] -> [a]
++ TcGblEnv -> [LRuleDecl GhcTc]
tcg_rules TcGblEnv
env }
      ; TcGblEnv -> TcM a -> TcM a
forall gbl lcl a. gbl -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
setGblEnv TcGblEnv
env' TcM a
thing_inside }

{-
************************************************************************
*                                                                      *
                Meta level
*                                                                      *
************************************************************************
-}

checkWellStaged :: SDoc         -- What the stage check is for
                -> ThLevel      -- Binding level (increases inside brackets)
                -> ThLevel      -- Use stage
                -> TcM ()       -- Fail if badly staged, adding an error
checkWellStaged :: MsgDoc -> ThLevel -> ThLevel -> IOEnv (Env TcGblEnv TcLclEnv) ()
checkWellStaged MsgDoc
pp_thing ThLevel
bind_lvl ThLevel
use_lvl
  | ThLevel
use_lvl ThLevel -> ThLevel -> Bool
forall a. Ord a => a -> a -> Bool
>= ThLevel
bind_lvl         -- OK! Used later than bound
  = () -> IOEnv (Env TcGblEnv TcLclEnv) ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()                   -- E.g.  \x -> [| $(f x) |]

  | ThLevel
bind_lvl ThLevel -> ThLevel -> Bool
forall a. Eq a => a -> a -> Bool
== ThLevel
outerLevel      -- GHC restriction on top level splices
  = MsgDoc -> IOEnv (Env TcGblEnv TcLclEnv) ()
forall a. MsgDoc -> TcM a
stageRestrictionError MsgDoc
pp_thing

  | Bool
otherwise                   -- Badly staged
  = MsgDoc -> IOEnv (Env TcGblEnv TcLclEnv) ()
forall a. MsgDoc -> TcM a
failWithTc (MsgDoc -> IOEnv (Env TcGblEnv TcLclEnv) ())
-> MsgDoc -> IOEnv (Env TcGblEnv TcLclEnv) ()
forall a b. (a -> b) -> a -> b
$                -- E.g.  \x -> $(f x)
    String -> MsgDoc
text String
"Stage error:" MsgDoc -> MsgDoc -> MsgDoc
<+> MsgDoc
pp_thing MsgDoc -> MsgDoc -> MsgDoc
<+>
        [MsgDoc] -> MsgDoc
hsep   [String -> MsgDoc
text String
"is bound at stage" MsgDoc -> MsgDoc -> MsgDoc
<+> ThLevel -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr ThLevel
bind_lvl,
                String -> MsgDoc
text String
"but used at stage" MsgDoc -> MsgDoc -> MsgDoc
<+> ThLevel -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr ThLevel
use_lvl]

stageRestrictionError :: SDoc -> TcM a
stageRestrictionError :: forall a. MsgDoc -> TcM a
stageRestrictionError MsgDoc
pp_thing
  = MsgDoc -> TcM a
forall a. MsgDoc -> TcM a
failWithTc (MsgDoc -> TcM a) -> MsgDoc -> TcM a
forall a b. (a -> b) -> a -> b
$
    [MsgDoc] -> MsgDoc
sep [ String -> MsgDoc
text String
"GHC stage restriction:"
        , ThLevel -> MsgDoc -> MsgDoc
nest ThLevel
2 ([MsgDoc] -> MsgDoc
vcat [ MsgDoc
pp_thing MsgDoc -> MsgDoc -> MsgDoc
<+> String -> MsgDoc
text String
"is used in a top-level splice, quasi-quote, or annotation,"
                       , String -> MsgDoc
text String
"and must be imported, not defined locally"])]

topIdLvl :: Id -> ThLevel
-- Globals may either be imported, or may be from an earlier "chunk"
-- (separated by declaration splices) of this module.  The former
--  *can* be used inside a top-level splice, but the latter cannot.
-- Hence we give the former impLevel, but the latter topLevel
-- E.g. this is bad:
--      x = [| foo |]
--      $( f x )
-- By the time we are processing the $(f x), the binding for "x"
-- will be in the global env, not the local one.
topIdLvl :: Id -> ThLevel
topIdLvl Id
id | Id -> Bool
isLocalId Id
id = ThLevel
outerLevel
            | Bool
otherwise    = ThLevel
impLevel

tcMetaTy :: Name -> TcM Type
-- Given the name of a Template Haskell data type,
-- return the type
-- E.g. given the name "Expr" return the type "Expr"
tcMetaTy :: Name -> IOEnv (Env TcGblEnv TcLclEnv) Type
tcMetaTy Name
tc_name = do
    TyCon
t <- Name -> TcM TyCon
tcLookupTyCon Name
tc_name
    Type -> IOEnv (Env TcGblEnv TcLclEnv) Type
forall (m :: * -> *) a. Monad m => a -> m a
return (TyCon -> Type
mkTyConTy TyCon
t)

isBrackStage :: ThStage -> Bool
isBrackStage :: ThStage -> Bool
isBrackStage (Brack {}) = Bool
True
isBrackStage ThStage
_other     = Bool
False

{-
************************************************************************
*                                                                      *
                 getDefaultTys
*                                                                      *
************************************************************************
-}

tcGetDefaultTys :: TcM ([Type], -- Default types
                        (Bool,  -- True <=> Use overloaded strings
                         Bool)) -- True <=> Use extended defaulting rules
tcGetDefaultTys :: TcM ([Type], (Bool, Bool))
tcGetDefaultTys
  = do  { DynFlags
dflags <- IOEnv (Env TcGblEnv TcLclEnv) DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags
        ; let ovl_strings :: Bool
ovl_strings = Extension -> DynFlags -> Bool
xopt Extension
LangExt.OverloadedStrings DynFlags
dflags
              extended_defaults :: Bool
extended_defaults = Extension -> DynFlags -> Bool
xopt Extension
LangExt.ExtendedDefaultRules DynFlags
dflags
                                        -- See also #1974
              flags :: (Bool, Bool)
flags = (Bool
ovl_strings, Bool
extended_defaults)

        ; Maybe [Type]
mb_defaults <- TcRn (Maybe [Type])
getDeclaredDefaultTys
        ; case Maybe [Type]
mb_defaults of {
           Just [Type]
tys -> ([Type], (Bool, Bool)) -> TcM ([Type], (Bool, Bool))
forall (m :: * -> *) a. Monad m => a -> m a
return ([Type]
tys, (Bool, Bool)
flags) ;
                                -- User-supplied defaults
           Maybe [Type]
Nothing  -> do

        -- No use-supplied default
        -- Use [Integer, Double], plus modifications
        { Type
integer_ty <- Name -> IOEnv (Env TcGblEnv TcLclEnv) Type
tcMetaTy Name
integerTyConName
        ; Type
list_ty <- Name -> IOEnv (Env TcGblEnv TcLclEnv) Type
tcMetaTy Name
listTyConName
        ; TyCon -> IOEnv (Env TcGblEnv TcLclEnv) ()
checkWiredInTyCon TyCon
doubleTyCon
        ; let deflt_tys :: [Type]
deflt_tys = Bool -> [Type] -> [Type]
forall {a}. Bool -> [a] -> [a]
opt_deflt Bool
extended_defaults [Type
unitTy, Type
list_ty]
                          -- Note [Extended defaults]
                          [Type] -> [Type] -> [Type]
forall a. [a] -> [a] -> [a]
++ [Type
integer_ty, Type
doubleTy]
                          [Type] -> [Type] -> [Type]
forall a. [a] -> [a] -> [a]
++ Bool -> [Type] -> [Type]
forall {a}. Bool -> [a] -> [a]
opt_deflt Bool
ovl_strings [Type
stringTy]
        ; ([Type], (Bool, Bool)) -> TcM ([Type], (Bool, Bool))
forall (m :: * -> *) a. Monad m => a -> m a
return ([Type]
deflt_tys, (Bool, Bool)
flags) } } }
  where
    opt_deflt :: Bool -> [a] -> [a]
opt_deflt Bool
True  [a]
xs = [a]
xs
    opt_deflt Bool
False [a]
_  = []

{-
Note [Extended defaults]
~~~~~~~~~~~~~~~~~~~~~
In interactive mode (or with -XExtendedDefaultRules) we add () as the first type we
try when defaulting.  This has very little real impact, except in the following case.
Consider:
        Text.Printf.printf "hello"
This has type (forall a. IO a); it prints "hello", and returns 'undefined'.  We don't
want the GHCi repl loop to try to print that 'undefined'.  The neatest thing is to
default the 'a' to (), rather than to Integer (which is what would otherwise happen;
and then GHCi doesn't attempt to print the ().  So in interactive mode, we add
() to the list of defaulting types.  See #1200.

Additionally, the list type [] is added as a default specialization for
Traversable and Foldable. As such the default default list now has types of
varying kinds, e.g. ([] :: * -> *)  and (Integer :: *).

************************************************************************
*                                                                      *
\subsection{The InstInfo type}
*                                                                      *
************************************************************************

The InstInfo type summarises the information in an instance declaration

    instance c => k (t tvs) where b

It is used just for *local* instance decls (not ones from interface files).
But local instance decls includes
        - derived ones
        - generic ones
as well as explicit user written ones.
-}

data InstInfo a
  = InstInfo
      { forall a. InstInfo a -> ClsInst
iSpec   :: ClsInst          -- Includes the dfun id
      , forall a. InstInfo a -> InstBindings a
iBinds  :: InstBindings a
      }

iDFunId :: InstInfo a -> DFunId
iDFunId :: forall a. InstInfo a -> Id
iDFunId InstInfo a
info = ClsInst -> Id
instanceDFunId (InstInfo a -> ClsInst
forall a. InstInfo a -> ClsInst
iSpec InstInfo a
info)

data InstBindings a
  = InstBindings
      { forall a. InstBindings a -> [Name]
ib_tyvars  :: [Name]   -- Names of the tyvars from the instance head
                               -- that are lexically in scope in the bindings
                               -- Must correspond 1-1 with the forall'd tyvars
                               -- of the dfun Id.  When typechecking, we are
                               -- going to extend the typechecker's envt with
                               --     ib_tyvars -> dfun_forall_tyvars

      , forall a. InstBindings a -> LHsBinds a
ib_binds   :: LHsBinds a    -- Bindings for the instance methods

      , forall a. InstBindings a -> [LSig a]
ib_pragmas :: [LSig a]      -- User pragmas recorded for generating
                                    -- specialised instances

      , forall a. InstBindings a -> [Extension]
ib_extensions :: [LangExt.Extension] -- Any extra extensions that should
                                             -- be enabled when type-checking
                                             -- this instance; needed for
                                             -- GeneralizedNewtypeDeriving

      , forall a. InstBindings a -> Bool
ib_derived :: Bool
           -- True <=> This code was generated by GHC from a deriving clause
           --          or standalone deriving declaration
           --          Used only to improve error messages
      }

instance (OutputableBndrId a)
       => Outputable (InstInfo (GhcPass a)) where
    ppr :: InstInfo (GhcPass a) -> MsgDoc
ppr = InstInfo (GhcPass a) -> MsgDoc
forall (a :: Pass).
OutputableBndrId a =>
InstInfo (GhcPass a) -> MsgDoc
pprInstInfoDetails

pprInstInfoDetails :: (OutputableBndrId a)
                   => InstInfo (GhcPass a) -> SDoc
pprInstInfoDetails :: forall (a :: Pass).
OutputableBndrId a =>
InstInfo (GhcPass a) -> MsgDoc
pprInstInfoDetails InstInfo (GhcPass a)
info
   = MsgDoc -> ThLevel -> MsgDoc -> MsgDoc
hang (ClsInst -> MsgDoc
pprInstanceHdr (InstInfo (GhcPass a) -> ClsInst
forall a. InstInfo a -> ClsInst
iSpec InstInfo (GhcPass a)
info) MsgDoc -> MsgDoc -> MsgDoc
<+> String -> MsgDoc
text String
"where")
        ThLevel
2 (InstBindings (GhcPass a) -> MsgDoc
forall {id2 :: Pass}.
(OutputableBndr (IdGhcP id2),
 OutputableBndr (IdGhcP (NoGhcTcPass id2)), IsPass id2) =>
InstBindings (GhcPass id2) -> MsgDoc
details (InstInfo (GhcPass a) -> InstBindings (GhcPass a)
forall a. InstInfo a -> InstBindings a
iBinds InstInfo (GhcPass a)
info))
  where
    details :: InstBindings (GhcPass id2) -> MsgDoc
details (InstBindings { ib_pragmas :: forall a. InstBindings a -> [LSig a]
ib_pragmas = [LSig (GhcPass id2)]
p, ib_binds :: forall a. InstBindings a -> LHsBinds a
ib_binds = LHsBinds (GhcPass id2)
b }) =
      [MsgDoc] -> MsgDoc
pprDeclList (LHsBinds (GhcPass id2) -> [LSig (GhcPass id2)] -> [MsgDoc]
forall (idL :: Pass) (idR :: Pass) (id2 :: Pass).
(OutputableBndrId idL, OutputableBndrId idR,
 OutputableBndrId id2) =>
LHsBindsLR (GhcPass idL) (GhcPass idR)
-> [LSig (GhcPass id2)] -> [MsgDoc]
pprLHsBindsForUser LHsBinds (GhcPass id2)
b [LSig (GhcPass id2)]
p)

simpleInstInfoClsTy :: InstInfo a -> (Class, Type)
simpleInstInfoClsTy :: forall a. InstInfo a -> (Class, Type)
simpleInstInfoClsTy InstInfo a
info = case ClsInst -> ([Id], Class, [Type])
instanceHead (InstInfo a -> ClsInst
forall a. InstInfo a -> ClsInst
iSpec InstInfo a
info) of
                           ([Id]
_, Class
cls, [Type
ty]) -> (Class
cls, Type
ty)
                           ([Id], Class, [Type])
_ -> String -> (Class, Type)
forall a. String -> a
panic String
"simpleInstInfoClsTy"

simpleInstInfoTy :: InstInfo a -> Type
simpleInstInfoTy :: forall a. InstInfo a -> Type
simpleInstInfoTy InstInfo a
info = (Class, Type) -> Type
forall a b. (a, b) -> b
snd (InstInfo a -> (Class, Type)
forall a. InstInfo a -> (Class, Type)
simpleInstInfoClsTy InstInfo a
info)

simpleInstInfoTyCon :: InstInfo a -> TyCon
  -- Gets the type constructor for a simple instance declaration,
  -- i.e. one of the form       instance (...) => C (T a b c) where ...
simpleInstInfoTyCon :: forall a. InstInfo a -> TyCon
simpleInstInfoTyCon InstInfo a
inst = Type -> TyCon
tcTyConAppTyCon (InstInfo a -> Type
forall a. InstInfo a -> Type
simpleInstInfoTy InstInfo a
inst)

-- | Make a name for the dict fun for an instance decl.  It's an *external*
-- name, like other top-level names, and hence must be made with
-- newGlobalBinder.
newDFunName :: Class -> [Type] -> SrcSpan -> TcM Name
newDFunName :: Class -> [Type] -> SrcSpan -> TcM Name
newDFunName Class
clas [Type]
tys SrcSpan
loc
  = do  { Bool
is_boot <- TcM Bool
tcIsHsBootOrSig
        ; Module
mod     <- IOEnv (Env TcGblEnv TcLclEnv) Module
forall (m :: * -> *). HasModule m => m Module
getModule
        ; let info_string :: String
info_string = OccName -> String
occNameString (Class -> OccName
forall a. NamedThing a => a -> OccName
getOccName Class
clas) String -> String -> String
forall a. [a] -> [a] -> [a]
++
                            (Type -> String) -> [Type] -> String
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap (OccName -> String
occNameString(OccName -> String) -> (Type -> OccName) -> Type -> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
.Type -> OccName
getDFunTyKey) [Type]
tys
        ; OccName
dfun_occ <- (OccSet -> OccName) -> TcM OccName
chooseUniqueOccTc (String -> Bool -> OccSet -> OccName
mkDFunOcc String
info_string Bool
is_boot)
        ; Module -> OccName -> SrcSpan -> TcM Name
forall a b. Module -> OccName -> SrcSpan -> TcRnIf a b Name
newGlobalBinder Module
mod OccName
dfun_occ SrcSpan
loc }

newFamInstTyConName :: Located Name -> [Type] -> TcM Name
newFamInstTyConName :: Located Name -> [Type] -> TcM Name
newFamInstTyConName (L SrcSpan
loc Name
name) [Type]
tys = (OccName -> OccName) -> SrcSpan -> Name -> [[Type]] -> TcM Name
mk_fam_inst_name OccName -> OccName
forall a. a -> a
id SrcSpan
loc Name
name [[Type]
tys]

newFamInstAxiomName :: Located Name -> [[Type]] -> TcM Name
newFamInstAxiomName :: Located Name -> [[Type]] -> TcM Name
newFamInstAxiomName (L SrcSpan
loc Name
name) [[Type]]
branches
  = (OccName -> OccName) -> SrcSpan -> Name -> [[Type]] -> TcM Name
mk_fam_inst_name OccName -> OccName
mkInstTyCoOcc SrcSpan
loc Name
name [[Type]]
branches

mk_fam_inst_name :: (OccName -> OccName) -> SrcSpan -> Name -> [[Type]] -> TcM Name
mk_fam_inst_name :: (OccName -> OccName) -> SrcSpan -> Name -> [[Type]] -> TcM Name
mk_fam_inst_name OccName -> OccName
adaptOcc SrcSpan
loc Name
tc_name [[Type]]
tyss
  = do  { Module
mod   <- IOEnv (Env TcGblEnv TcLclEnv) Module
forall (m :: * -> *). HasModule m => m Module
getModule
        ; let info_string :: String
info_string = OccName -> String
occNameString (Name -> OccName
forall a. NamedThing a => a -> OccName
getOccName Name
tc_name) String -> String -> String
forall a. [a] -> [a] -> [a]
++
                            String -> [String] -> String
forall a. [a] -> [[a]] -> [a]
intercalate String
"|" [String]
ty_strings
        ; OccName
occ   <- (OccSet -> OccName) -> TcM OccName
chooseUniqueOccTc (String -> OccSet -> OccName
mkInstTyTcOcc String
info_string)
        ; Module -> OccName -> SrcSpan -> TcM Name
forall a b. Module -> OccName -> SrcSpan -> TcRnIf a b Name
newGlobalBinder Module
mod (OccName -> OccName
adaptOcc OccName
occ) SrcSpan
loc }
  where
    ty_strings :: [String]
ty_strings = ([Type] -> String) -> [[Type]] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map ((Type -> String) -> [Type] -> String
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap (OccName -> String
occNameString (OccName -> String) -> (Type -> OccName) -> Type -> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Type -> OccName
getDFunTyKey)) [[Type]]
tyss

{-
Stable names used for foreign exports and annotations.
For stable names, the name must be unique (see #1533).  If the
same thing has several stable Ids based on it, the
top-level bindings generated must not have the same name.
Hence we create an External name (doesn't change), and we
append a Unique to the string right here.
-}

mkStableIdFromString :: String -> Type -> SrcSpan -> (OccName -> OccName) -> TcM TcId
mkStableIdFromString :: String -> Type -> SrcSpan -> (OccName -> OccName) -> TcM Id
mkStableIdFromString String
str Type
sig_ty SrcSpan
loc OccName -> OccName
occ_wrapper = do
    Unique
uniq <- TcRnIf TcGblEnv TcLclEnv Unique
forall gbl lcl. TcRnIf gbl lcl Unique
newUnique
    Module
mod <- IOEnv (Env TcGblEnv TcLclEnv) Module
forall (m :: * -> *). HasModule m => m Module
getModule
    FastString
name <- String -> String -> IOEnv (Env TcGblEnv TcLclEnv) FastString
forall (m :: * -> *).
(MonadIO m, HasDynFlags m, HasModule m) =>
String -> String -> m FastString
mkWrapperName String
"stable" String
str
    let occ :: OccName
occ = FastString -> OccName
mkVarOccFS FastString
name :: OccName
        gnm :: Name
gnm = Unique -> Module -> OccName -> SrcSpan -> Name
mkExternalName Unique
uniq Module
mod (OccName -> OccName
occ_wrapper OccName
occ) SrcSpan
loc :: Name
        id :: Id
id  = Name -> Type -> Id
mkExportedVanillaId Name
gnm Type
sig_ty :: Id
    Id -> TcM Id
forall (m :: * -> *) a. Monad m => a -> m a
return Id
id

mkStableIdFromName :: Name -> Type -> SrcSpan -> (OccName -> OccName) -> TcM TcId
mkStableIdFromName :: Name -> Type -> SrcSpan -> (OccName -> OccName) -> TcM Id
mkStableIdFromName Name
nm = String -> Type -> SrcSpan -> (OccName -> OccName) -> TcM Id
mkStableIdFromString (Name -> String
forall a. NamedThing a => a -> String
getOccString Name
nm)

mkWrapperName :: (MonadIO m, HasDynFlags m, HasModule m)
              => String -> String -> m FastString
mkWrapperName :: forall (m :: * -> *).
(MonadIO m, HasDynFlags m, HasModule m) =>
String -> String -> m FastString
mkWrapperName String
what String
nameBase
    = do DynFlags
dflags <- m DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags
         Module
thisMod <- m Module
forall (m :: * -> *). HasModule m => m Module
getModule
         let -- Note [Generating fresh names for ccall wrapper]
             wrapperRef :: IORef (ModuleEnv ThLevel)
wrapperRef = DynFlags -> IORef (ModuleEnv ThLevel)
nextWrapperNum DynFlags
dflags
             pkg :: String
pkg = Unit -> String
unitString  (Module -> Unit
forall unit. GenModule unit -> unit
moduleUnit Module
thisMod)
             mod :: String
mod = ModuleName -> String
moduleNameString (Module -> ModuleName
forall unit. GenModule unit -> ModuleName
moduleName      Module
thisMod)
         ThLevel
wrapperNum <- IO ThLevel -> m ThLevel
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO ThLevel -> m ThLevel) -> IO ThLevel -> m ThLevel
forall a b. (a -> b) -> a -> b
$ IORef (ModuleEnv ThLevel)
-> (ModuleEnv ThLevel -> (ModuleEnv ThLevel, ThLevel))
-> IO ThLevel
forall a b. IORef a -> (a -> (a, b)) -> IO b
atomicModifyIORef' IORef (ModuleEnv ThLevel)
wrapperRef ((ModuleEnv ThLevel -> (ModuleEnv ThLevel, ThLevel)) -> IO ThLevel)
-> (ModuleEnv ThLevel -> (ModuleEnv ThLevel, ThLevel))
-> IO ThLevel
forall a b. (a -> b) -> a -> b
$ \ModuleEnv ThLevel
mod_env ->
             let num :: ThLevel
num = ModuleEnv ThLevel -> ThLevel -> Module -> ThLevel
forall a. ModuleEnv a -> a -> Module -> a
lookupWithDefaultModuleEnv ModuleEnv ThLevel
mod_env ThLevel
0 Module
thisMod
                 mod_env' :: ModuleEnv ThLevel
mod_env' = ModuleEnv ThLevel -> Module -> ThLevel -> ModuleEnv ThLevel
forall a. ModuleEnv a -> Module -> a -> ModuleEnv a
extendModuleEnv ModuleEnv ThLevel
mod_env Module
thisMod (ThLevel
numThLevel -> ThLevel -> ThLevel
forall a. Num a => a -> a -> a
+ThLevel
1)
             in (ModuleEnv ThLevel
mod_env', ThLevel
num)
         let components :: [String]
components = [String
what, ThLevel -> String
forall a. Show a => a -> String
show ThLevel
wrapperNum, String
pkg, String
mod, String
nameBase]
         FastString -> m FastString
forall (m :: * -> *) a. Monad m => a -> m a
return (FastString -> m FastString) -> FastString -> m FastString
forall a b. (a -> b) -> a -> b
$ String -> FastString
mkFastString (String -> FastString) -> String -> FastString
forall a b. (a -> b) -> a -> b
$ String -> String
zEncodeString (String -> String) -> String -> String
forall a b. (a -> b) -> a -> b
$ String -> [String] -> String
forall a. [a] -> [[a]] -> [a]
intercalate String
":" [String]
components

{-
Note [Generating fresh names for FFI wrappers]

We used to use a unique, rather than nextWrapperNum, to distinguish
between FFI wrapper functions. However, the wrapper names that we
generate are external names. This means that if a call to them ends up
in an unfolding, then we can't alpha-rename them, and thus if the
unique randomly changes from one compile to another then we get a
spurious ABI change (#4012).

The wrapper counter has to be per-module, not global, so that the number we end
up using is not dependent on the modules compiled before the current one.
-}

{-
************************************************************************
*                                                                      *
\subsection{Errors}
*                                                                      *
************************************************************************
-}

pprBinders :: [Name] -> SDoc
-- Used in error messages
-- Use quotes for a single one; they look a bit "busy" for several
pprBinders :: [Name] -> MsgDoc
pprBinders [Name
bndr] = MsgDoc -> MsgDoc
quotes (Name -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr Name
bndr)
pprBinders [Name]
bndrs  = (Name -> MsgDoc) -> [Name] -> MsgDoc
forall a. (a -> MsgDoc) -> [a] -> MsgDoc
pprWithCommas Name -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr [Name]
bndrs

notFound :: Name -> TcM TyThing
notFound :: Name -> TcM TyThing
notFound Name
name
  = do { TcLclEnv
lcl_env <- TcRnIf TcGblEnv TcLclEnv TcLclEnv
forall gbl lcl. TcRnIf gbl lcl lcl
getLclEnv
       ; let stage :: ThStage
stage = TcLclEnv -> ThStage
tcl_th_ctxt TcLclEnv
lcl_env
       ; case ThStage
stage of   -- See Note [Out of scope might be a staging error]
           Splice {}
             | Name -> Bool
isUnboundName Name
name -> TcM TyThing
forall env a. IOEnv env a
failM  -- If the name really isn't in scope
                                            -- don't report it again (#11941)
             | Bool
otherwise -> MsgDoc -> TcM TyThing
forall a. MsgDoc -> TcM a
stageRestrictionError (MsgDoc -> MsgDoc
quotes (Name -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr Name
name))
           ThStage
_ -> MsgDoc -> TcM TyThing
forall a. MsgDoc -> TcM a
failWithTc (MsgDoc -> TcM TyThing) -> MsgDoc -> TcM TyThing
forall a b. (a -> b) -> a -> b
$
                [MsgDoc] -> MsgDoc
vcat[String -> MsgDoc
text String
"GHC internal error:" MsgDoc -> MsgDoc -> MsgDoc
<+> MsgDoc -> MsgDoc
quotes (Name -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr Name
name) MsgDoc -> MsgDoc -> MsgDoc
<+>
                     String -> MsgDoc
text String
"is not in scope during type checking, but it passed the renamer",
                     String -> MsgDoc
text String
"tcl_env of environment:" MsgDoc -> MsgDoc -> MsgDoc
<+> TcTypeEnv -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr (TcLclEnv -> TcTypeEnv
tcl_env TcLclEnv
lcl_env)]
                       -- Take care: printing the whole gbl env can
                       -- cause an infinite loop, in the case where we
                       -- are in the middle of a recursive TyCon/Class group;
                       -- so let's just not print it!  Getting a loop here is
                       -- very unhelpful, because it hides one compiler bug with another
       }

wrongThingErr :: String -> TcTyThing -> Name -> TcM a
-- It's important that this only calls pprTcTyThingCategory, which in
-- turn does not look at the details of the TcTyThing.
-- See Note [Placeholder PatSyn kinds] in GHC.Tc.Gen.Bind
wrongThingErr :: forall a. String -> TcTyThing -> Name -> TcM a
wrongThingErr String
expected TcTyThing
thing Name
name
  = MsgDoc -> TcM a
forall a. MsgDoc -> TcM a
failWithTc (TcTyThing -> MsgDoc
pprTcTyThingCategory TcTyThing
thing MsgDoc -> MsgDoc -> MsgDoc
<+> MsgDoc -> MsgDoc
quotes (Name -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr Name
name) MsgDoc -> MsgDoc -> MsgDoc
<+>
                String -> MsgDoc
text String
"used as a" MsgDoc -> MsgDoc -> MsgDoc
<+> String -> MsgDoc
text String
expected)

{- Note [Out of scope might be a staging error]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
  x = 3
  data T = MkT $(foo x)

where 'foo' is imported from somewhere.

This is really a staging error, because we can't run code involving 'x'.
But in fact the type checker processes types first, so 'x' won't even be
in the type envt when we look for it in $(foo x).  So inside splices we
report something missing from the type env as a staging error.
See #5752 and #5795.
-}