{-# LANGUAGE LambdaCase      #-}
{-# LANGUAGE MultiWayIf      #-}
{-# LANGUAGE RecursiveDo     #-}
{-# LANGUAGE TupleSections   #-}

{-# OPTIONS_GHC -Wno-incomplete-record-updates #-}
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998

-}

-- | Monadic type operations
--
-- This module contains monadic operations over types that contain mutable type
-- variables.
module GHC.Tc.Utils.TcMType (
  TcTyVar, TcKind, TcType, TcTauType, TcThetaType, TcTyVarSet,

  --------------------------------
  -- Creating new mutable type variables
  newFlexiTyVar,
  newNamedFlexiTyVar,
  newFlexiTyVarTy,              -- Kind -> TcM TcType
  newFlexiTyVarTys,             -- Int -> Kind -> TcM [TcType]
  newOpenFlexiTyVar, newOpenFlexiTyVarTy, newOpenTypeKind,
  newOpenFlexiFRRTyVar, newOpenFlexiFRRTyVarTy,
  newOpenBoxedTypeKind,
  newMetaKindVar, newMetaKindVars,
  newMetaTyVarTyAtLevel, newConcreteTyVarTyAtLevel, substConcreteTvOrigin,
  newAnonMetaTyVar, newConcreteTyVar,
  cloneMetaTyVar, cloneMetaTyVarWithInfo,
  newCycleBreakerTyVar,

  newMultiplicityVar,
  readMetaTyVar, writeMetaTyVar, writeMetaTyVarRef,
  newTauTvDetailsAtLevel, newMetaDetails, newMetaTyVarName,
  isFilledMetaTyVar_maybe, isFilledMetaTyVar, isUnfilledMetaTyVar,

  --------------------------------
  -- Creating new evidence variables
  newEvVar, newEvVars, newDict,
  newWantedWithLoc, newWanted, newWanteds, cloneWanted, cloneWC, cloneWantedCtEv,
  emitWanted, emitWantedEq, emitWantedEvVar, emitWantedEvVars,
  emitWantedEqs,
  newTcEvBinds, newNoTcEvBinds, addTcEvBind,
  emitNewExprHole,

  newCoercionHole, newCoercionHoleO, newVanillaCoercionHole,
  fillCoercionHole, isFilledCoercionHole,
  unpackCoercionHole, unpackCoercionHole_maybe,
  checkCoercionHole,

  newImplication,

  --------------------------------
  -- Instantiation
  newMetaTyVars, newMetaTyVarX, newMetaTyVarsX, newMetaTyVarBndrsX,
  newMetaTyVarTyVarX,
  newTyVarTyVar, cloneTyVarTyVar,
  newConcreteTyVarX,
  newPatTyVar, newSkolemTyVar, newWildCardX,

  --------------------------------
  -- Expected types
  ExpType(..), ExpSigmaType, ExpRhoType,
  mkCheckExpType, newInferExpType, newInferExpTypeFRR,
  tcInfer, tcInferFRR,
  readExpType, readExpType_maybe, readScaledExpType,
  expTypeToType, scaledExpTypeToType,
  checkingExpType_maybe, checkingExpType,
  inferResultToType, ensureMonoType, promoteTcType,

  --------------------------------
  -- Multiplicity usage environment
  tcCheckUsage,

  ---------------------------------
  -- Promotion, defaulting, skolemisation
  defaultTyVar, promoteMetaTyVarTo, promoteTyVarSet,
  quantifyTyVars, isQuantifiableTv,
  zonkAndSkolemise, skolemiseQuantifiedTyVar,
  doNotQuantifyTyVars,

  candidateQTyVarsOfType,  candidateQTyVarsOfKind,
  candidateQTyVarsOfTypes, candidateQTyVarsOfKinds,
  candidateQTyVarsWithBinders,
  CandidatesQTvs(..), delCandidates,
  candidateKindVars, partitionCandidates,

  ------------------------------
  -- Representation polymorphism
  checkTypeHasFixedRuntimeRep,

  -- * Other HsSyn functions
  mkHsDictLet, mkHsApp,
  mkHsAppTy, mkHsCaseAlt,
  tcShortCutLit, shortCutLit, hsOverLitName,
  conLikeResTy
  ) where

import GHC.Prelude

import GHC.Hs
import GHC.Platform

import GHC.Driver.DynFlags
import qualified GHC.LanguageExtensions as LangExt

import {-# SOURCE #-} GHC.Tc.Utils.Unify( unifyInvisibleType, tcSubMult )
import GHC.Tc.Types.Origin
import GHC.Tc.Types.Constraint
import GHC.Tc.Types.Evidence
import GHC.Tc.Utils.Monad        -- TcType, amongst others
import GHC.Tc.Utils.TcType
import GHC.Tc.Errors.Types
import GHC.Tc.Zonk.Type
import GHC.Tc.Zonk.TcType

import GHC.Builtin.Names

import GHC.Core.ConLike
import GHC.Core.DataCon
import GHC.Core.TyCo.Rep
import GHC.Core.TyCo.Ppr
import GHC.Core.Type
import GHC.Core.TyCon
import GHC.Core.Coercion
import GHC.Core.Class
import GHC.Core.Predicate
import GHC.Core.UsageEnv

import GHC.Types.Var
import GHC.Types.Id as Id
import GHC.Types.Name
import GHC.Types.SourceText
import GHC.Types.Var.Set

import GHC.Builtin.Types
import GHC.Types.Var.Env
import GHC.Types.Unique.Set
import GHC.Types.Basic ( TypeOrKind(..)
                       , NonStandardDefaultingStrategy(..)
                       , DefaultingStrategy(..), defaultNonStandardTyVars )

import GHC.Data.FastString
import GHC.Data.Bag

import GHC.Utils.Misc
import GHC.Utils.Outputable
import GHC.Utils.Panic
import GHC.Utils.Constants (debugIsOn)

import Control.Monad
import Data.IORef
import GHC.Data.Maybe
import qualified Data.Semigroup as Semi
import GHC.Types.Name.Reader

{-
************************************************************************
*                                                                      *
        Kind variables
*                                                                      *
************************************************************************
-}

newMetaKindVar :: TcM TcKind
newMetaKindVar :: TcM TcType
newMetaKindVar
  = do { details <- MetaInfo -> TcM TcTyVarDetails
newMetaDetails MetaInfo
TauTv
       ; name    <- newMetaTyVarName (fsLit "k")
                    -- All MetaKindVars are called "k"
                    -- They may be jiggled by tidying
       ; let kv = Name -> TcType -> TcTyVarDetails -> TcTyVar
mkTcTyVar Name
name TcType
liftedTypeKind TcTyVarDetails
details
       ; traceTc "newMetaKindVar" (ppr kv)
       ; return (mkTyVarTy kv) }

newMetaKindVars :: Int -> TcM [TcKind]
newMetaKindVars :: Int -> TcM [TcType]
newMetaKindVars Int
n = Int -> TcM TcType -> TcM [TcType]
forall (m :: * -> *) a. Applicative m => Int -> m a -> m [a]
replicateM Int
n TcM TcType
newMetaKindVar

{-
************************************************************************
*                                                                      *
     Evidence variables; range over constraints we can abstract over
*                                                                      *
************************************************************************
-}

newEvVars :: TcThetaType -> TcM [EvVar]
newEvVars :: [TcType] -> TcM [TcTyVar]
newEvVars [TcType]
theta = (TcType -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar)
-> [TcType] -> TcM [TcTyVar]
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 TcType -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
forall gbl lcl. TcType -> TcRnIf gbl lcl TcTyVar
newEvVar [TcType]
theta

--------------

newEvVar :: TcPredType -> TcRnIf gbl lcl EvVar
-- Creates new *rigid* variables for predicates
newEvVar :: forall gbl lcl. TcType -> TcRnIf gbl lcl TcTyVar
newEvVar TcType
ty = do { name <- OccName -> TcRnIf gbl lcl Name
forall gbl lcl. OccName -> TcRnIf gbl lcl Name
newSysName (TcType -> OccName
predTypeOccName TcType
ty)
                 ; return (mkLocalIdOrCoVar name ManyTy ty) }

-- | Create a new Wanted constraint with the given 'CtLoc'.
newWantedWithLoc :: CtLoc -> PredType -> TcM CtEvidence
newWantedWithLoc :: CtLoc -> TcType -> TcM CtEvidence
newWantedWithLoc CtLoc
loc TcType
pty
  = do dst <- case TcType -> Pred
classifyPredType TcType
pty of
                EqPred {} -> CoercionHole -> TcEvDest
HoleDest  (CoercionHole -> TcEvDest)
-> IOEnv (Env TcGblEnv TcLclEnv) CoercionHole
-> IOEnv (Env TcGblEnv TcLclEnv) TcEvDest
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> CtLoc -> TcType -> IOEnv (Env TcGblEnv TcLclEnv) CoercionHole
newCoercionHole CtLoc
loc TcType
pty
                Pred
_         -> TcTyVar -> TcEvDest
EvVarDest (TcTyVar -> TcEvDest)
-> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
-> IOEnv (Env TcGblEnv TcLclEnv) TcEvDest
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> TcType -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
forall gbl lcl. TcType -> TcRnIf gbl lcl TcTyVar
newEvVar TcType
pty
       return $ CtWanted { ctev_dest      = dst
                         , ctev_pred      = pty
                         , ctev_loc       = loc
                         , ctev_rewriters = emptyRewriterSet }

-- | Create a new Wanted constraint with the given 'CtOrigin', and
-- location information taken from the 'TcM' environment.
newWanted :: CtOrigin -> Maybe TypeOrKind -> PredType -> TcM CtEvidence
-- Deals with both equality and non-equality predicates
newWanted :: CtOrigin -> Maybe TypeOrKind -> TcType -> TcM CtEvidence
newWanted CtOrigin
orig Maybe TypeOrKind
t_or_k TcType
pty
  = do loc <- CtOrigin -> Maybe TypeOrKind -> TcM CtLoc
getCtLocM CtOrigin
orig Maybe TypeOrKind
t_or_k
       newWantedWithLoc loc pty

-- | Create new Wanted constraints with the given 'CtOrigin',
-- and location information taken from the 'TcM' environment.
newWanteds :: CtOrigin -> ThetaType -> TcM [CtEvidence]
newWanteds :: CtOrigin -> [TcType] -> TcM [CtEvidence]
newWanteds CtOrigin
orig = (TcType -> TcM CtEvidence) -> [TcType] -> TcM [CtEvidence]
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 (CtOrigin -> Maybe TypeOrKind -> TcType -> TcM CtEvidence
newWanted CtOrigin
orig Maybe TypeOrKind
forall a. Maybe a
Nothing)

----------------------------------------------
-- Cloning constraints
----------------------------------------------

cloneWantedCtEv :: CtEvidence -> TcM CtEvidence
cloneWantedCtEv :: CtEvidence -> TcM CtEvidence
cloneWantedCtEv ctev :: CtEvidence
ctev@(CtWanted { ctev_pred :: CtEvidence -> TcType
ctev_pred = TcType
pty, ctev_dest :: CtEvidence -> TcEvDest
ctev_dest = HoleDest CoercionHole
_, ctev_loc :: CtEvidence -> CtLoc
ctev_loc = CtLoc
loc })
  | TcType -> Bool
isEqPrimPred TcType
pty
  = do { co_hole <- CtLoc -> TcType -> IOEnv (Env TcGblEnv TcLclEnv) CoercionHole
newCoercionHole CtLoc
loc TcType
pty
       ; return (ctev { ctev_dest = HoleDest co_hole }) }
  | Bool
otherwise
  = String -> SDoc -> TcM CtEvidence
forall a. HasCallStack => String -> SDoc -> a
pprPanic String
"cloneWantedCtEv" (TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
pty)
cloneWantedCtEv CtEvidence
ctev = CtEvidence -> TcM CtEvidence
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return CtEvidence
ctev

cloneWanted :: Ct -> TcM Ct
cloneWanted :: Ct -> TcM Ct
cloneWanted Ct
ct = CtEvidence -> Ct
mkNonCanonical (CtEvidence -> Ct) -> TcM CtEvidence -> TcM Ct
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> CtEvidence -> TcM CtEvidence
cloneWantedCtEv (Ct -> CtEvidence
ctEvidence Ct
ct)

cloneWC :: WantedConstraints -> TcM WantedConstraints
-- Clone all the evidence bindings in
--   a) the ic_bind field of any implications
--   b) the CoercionHoles of any wanted constraints
-- so that solving the WantedConstraints will not have any visible side
-- effect, /except/ from causing unifications
cloneWC :: WantedConstraints -> TcM WantedConstraints
cloneWC wc :: WantedConstraints
wc@(WC { wc_simple :: WantedConstraints -> Cts
wc_simple = Cts
simples, wc_impl :: WantedConstraints -> Bag Implication
wc_impl = Bag Implication
implics })
  = do { simples' <- (Ct -> TcM Ct) -> Cts -> IOEnv (Env TcGblEnv TcLclEnv) Cts
forall (m :: * -> *) a b.
Monad m =>
(a -> m b) -> Bag a -> m (Bag b)
mapBagM Ct -> TcM Ct
cloneWanted Cts
simples
       ; implics' <- mapBagM cloneImplication implics
       ; return (wc { wc_simple = simples', wc_impl = implics' }) }

cloneImplication :: Implication -> TcM Implication
cloneImplication :: Implication -> IOEnv (Env TcGblEnv TcLclEnv) Implication
cloneImplication implic :: Implication
implic@(Implic { ic_binds :: Implication -> EvBindsVar
ic_binds = EvBindsVar
binds, ic_wanted :: Implication -> WantedConstraints
ic_wanted = WantedConstraints
inner_wanted })
  = do { binds'        <- EvBindsVar -> TcM EvBindsVar
cloneEvBindsVar EvBindsVar
binds
       ; inner_wanted' <- cloneWC inner_wanted
       ; return (implic { ic_binds = binds', ic_wanted = inner_wanted' }) }

----------------------------------------------
-- Emitting constraints
----------------------------------------------

-- | Emits a new Wanted. Deals with both equalities and non-equalities.
emitWanted :: CtOrigin -> TcPredType -> TcM EvTerm
emitWanted :: CtOrigin -> TcType -> TcM EvTerm
emitWanted CtOrigin
origin TcType
pty
  = do { ev <- CtOrigin -> Maybe TypeOrKind -> TcType -> TcM CtEvidence
newWanted CtOrigin
origin Maybe TypeOrKind
forall a. Maybe a
Nothing TcType
pty
       ; emitSimple $ mkNonCanonical ev
       ; return $ ctEvTerm ev }

emitWantedEqs :: CtOrigin -> [(TcType,TcType)] -> TcM ()
-- Emit some new wanted nominal equalities
emitWantedEqs :: CtOrigin -> [(TcType, TcType)] -> TcRn ()
emitWantedEqs CtOrigin
origin [(TcType, TcType)]
pairs
  | [(TcType, TcType)] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [(TcType, TcType)]
pairs
  = () -> TcRn ()
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return ()
  | Bool
otherwise
  = ((TcType, TcType) -> IOEnv (Env TcGblEnv TcLclEnv) Coercion)
-> [(TcType, TcType)] -> TcRn ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ ((TcType -> TcType -> IOEnv (Env TcGblEnv TcLclEnv) Coercion)
-> (TcType, TcType) -> IOEnv (Env TcGblEnv TcLclEnv) Coercion
forall a b c. (a -> b -> c) -> (a, b) -> c
uncurry (CtOrigin
-> TypeOrKind
-> Role
-> TcType
-> TcType
-> IOEnv (Env TcGblEnv TcLclEnv) Coercion
emitWantedEq CtOrigin
origin TypeOrKind
TypeLevel Role
Nominal)) [(TcType, TcType)]
pairs

-- | Emits a new equality constraint
emitWantedEq :: CtOrigin -> TypeOrKind -> Role -> TcType -> TcType -> TcM Coercion
emitWantedEq :: CtOrigin
-> TypeOrKind
-> Role
-> TcType
-> TcType
-> IOEnv (Env TcGblEnv TcLclEnv) Coercion
emitWantedEq CtOrigin
origin TypeOrKind
t_or_k Role
role TcType
ty1 TcType
ty2
  = do { hole <- CtOrigin -> TcType -> IOEnv (Env TcGblEnv TcLclEnv) CoercionHole
newCoercionHoleO CtOrigin
origin TcType
pty
       ; loc  <- getCtLocM origin (Just t_or_k)
       ; emitSimple $ mkNonCanonical $
         CtWanted { ctev_pred      = pty
                  , ctev_dest      = HoleDest hole
                  , ctev_loc       = loc
                  , ctev_rewriters = emptyRewriterSet }
       ; return (HoleCo hole) }
  where
    pty :: TcType
pty = Role -> TcType -> TcType -> TcType
mkPrimEqPredRole Role
role TcType
ty1 TcType
ty2

-- | Creates a new EvVar and immediately emits it as a Wanted.
-- No equality predicates here.
emitWantedEvVar :: CtOrigin -> TcPredType -> TcM EvVar
emitWantedEvVar :: CtOrigin -> TcType -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
emitWantedEvVar CtOrigin
origin TcType
ty
  = do { new_cv <- TcType -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
forall gbl lcl. TcType -> TcRnIf gbl lcl TcTyVar
newEvVar TcType
ty
       ; loc <- getCtLocM origin Nothing
       ; let ctev = CtWanted { ctev_pred :: TcType
ctev_pred      = TcType
ty
                             , ctev_dest :: TcEvDest
ctev_dest      = TcTyVar -> TcEvDest
EvVarDest TcTyVar
new_cv
                             , ctev_loc :: CtLoc
ctev_loc       = CtLoc
loc
                             , ctev_rewriters :: RewriterSet
ctev_rewriters = RewriterSet
emptyRewriterSet }
       ; emitSimple $ mkNonCanonical ctev
       ; return new_cv }

emitWantedEvVars :: CtOrigin -> [TcPredType] -> TcM [EvVar]
emitWantedEvVars :: CtOrigin -> [TcType] -> TcM [TcTyVar]
emitWantedEvVars CtOrigin
orig = (TcType -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar)
-> [TcType] -> TcM [TcTyVar]
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 (CtOrigin -> TcType -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
emitWantedEvVar CtOrigin
orig)

-- | Emit a new wanted expression hole
emitNewExprHole :: RdrName         -- of the hole
                -> Type -> TcM HoleExprRef
emitNewExprHole :: RdrName -> TcType -> TcM HoleExprRef
emitNewExprHole RdrName
occ TcType
ty
  = do { u <- TcRnIf TcGblEnv TcLclEnv Unique
forall gbl lcl. TcRnIf gbl lcl Unique
newUnique
       ; ref <- newTcRef (pprPanic "unfilled unbound-variable evidence" (ppr u))
       ; let her = TcRef EvTerm -> TcType -> Unique -> HoleExprRef
HER TcRef EvTerm
ref TcType
ty Unique
u

       ; loc <- getCtLocM (ExprHoleOrigin (Just occ)) (Just TypeLevel)

       ; let hole = Hole { hole_sort :: HoleSort
hole_sort = HoleExprRef -> HoleSort
ExprHole HoleExprRef
her
                         , hole_occ :: RdrName
hole_occ  = RdrName
occ
                         , hole_ty :: TcType
hole_ty   = TcType
ty
                         , hole_loc :: CtLoc
hole_loc  = CtLoc
loc }
       ; emitHole hole
       ; return her }

newDict :: Class -> [TcType] -> TcM DictId
newDict :: Class -> [TcType] -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
newDict Class
cls [TcType]
tys
  = do { name <- OccName -> TcM Name
forall gbl lcl. OccName -> TcRnIf gbl lcl Name
newSysName (OccName -> OccName
mkDictOcc (Class -> OccName
forall a. NamedThing a => a -> OccName
getOccName Class
cls))
       ; return (mkLocalId name ManyTy (mkClassPred cls tys)) }

predTypeOccName :: PredType -> OccName
predTypeOccName :: TcType -> OccName
predTypeOccName TcType
ty = case TcType -> Pred
classifyPredType TcType
ty of
    ClassPred Class
cls [TcType]
_ -> OccName -> OccName
mkDictOcc (Class -> OccName
forall a. NamedThing a => a -> OccName
getOccName Class
cls)
    EqPred {}       -> FastString -> OccName
mkVarOccFS (String -> FastString
fsLit String
"co")
    IrredPred {}    -> FastString -> OccName
mkVarOccFS (String -> FastString
fsLit String
"irred")
    ForAllPred {}   -> FastString -> OccName
mkVarOccFS (String -> FastString
fsLit String
"df")

-- | Create a new 'Implication' with as many sensible defaults for its fields
-- as possible. Note that the 'ic_tclvl', 'ic_binds', and 'ic_info' fields do
-- /not/ have sensible defaults, so they are initialized with lazy thunks that
-- will 'panic' if forced, so one should take care to initialize these fields
-- after creation.
--
-- This is monadic to look up the 'TcLclEnv', which is used to initialize
-- 'ic_env', and to set the -Winaccessible-code flag. See
-- Note [Avoid -Winaccessible-code when deriving] in "GHC.Tc.TyCl.Instance".
newImplication :: TcM Implication
newImplication :: IOEnv (Env TcGblEnv TcLclEnv) Implication
newImplication
  = do env <- TcRnIf TcGblEnv TcLclEnv TcLclEnv
forall gbl lcl. TcRnIf gbl lcl lcl
getLclEnv
       warn_inaccessible <- woptM Opt_WarnInaccessibleCode
       let in_gen_code = TcLclEnv -> Bool
lclEnvInGeneratedCode TcLclEnv
env
       return $
         (implicationPrototype (mkCtLocEnv env))
           { ic_warn_inaccessible = warn_inaccessible && not in_gen_code }

{-
************************************************************************
*                                                                      *
        Coercion holes
*                                                                      *
************************************************************************
-}

newVanillaCoercionHole :: TcPredType -> TcM CoercionHole
newVanillaCoercionHole :: TcType -> IOEnv (Env TcGblEnv TcLclEnv) CoercionHole
newVanillaCoercionHole = Bool -> TcType -> IOEnv (Env TcGblEnv TcLclEnv) CoercionHole
new_coercion_hole Bool
False

newCoercionHole :: CtLoc -> TcPredType -> TcM CoercionHole
newCoercionHole :: CtLoc -> TcType -> IOEnv (Env TcGblEnv TcLclEnv) CoercionHole
newCoercionHole CtLoc
loc = CtOrigin -> TcType -> IOEnv (Env TcGblEnv TcLclEnv) CoercionHole
newCoercionHoleO (CtLoc -> CtOrigin
ctLocOrigin CtLoc
loc)

newCoercionHoleO :: CtOrigin -> TcPredType -> TcM CoercionHole
newCoercionHoleO :: CtOrigin -> TcType -> IOEnv (Env TcGblEnv TcLclEnv) CoercionHole
newCoercionHoleO (KindEqOrigin {}) TcType
pty = Bool -> TcType -> IOEnv (Env TcGblEnv TcLclEnv) CoercionHole
new_coercion_hole Bool
True TcType
pty
newCoercionHoleO CtOrigin
_ TcType
pty                 = Bool -> TcType -> IOEnv (Env TcGblEnv TcLclEnv) CoercionHole
new_coercion_hole Bool
False TcType
pty

new_coercion_hole :: Bool -> TcPredType -> TcM CoercionHole
new_coercion_hole :: Bool -> TcType -> IOEnv (Env TcGblEnv TcLclEnv) CoercionHole
new_coercion_hole Bool
hetero_kind TcType
pred_ty
  = do { co_var <- TcType -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
forall gbl lcl. TcType -> TcRnIf gbl lcl TcTyVar
newEvVar TcType
pred_ty
       ; traceTc "New coercion hole:" (ppr co_var <+> dcolon <+> ppr pred_ty)
       ; ref <- newMutVar Nothing
       ; return $ CoercionHole { ch_co_var = co_var, ch_ref = ref
                               , ch_hetero_kind = hetero_kind } }

-- | Put a value in a coercion hole
fillCoercionHole :: CoercionHole -> Coercion -> TcM ()
fillCoercionHole :: CoercionHole -> Coercion -> TcRn ()
fillCoercionHole (CoercionHole { ch_ref :: CoercionHole -> IORef (Maybe Coercion)
ch_ref = IORef (Maybe Coercion)
ref, ch_co_var :: CoercionHole -> TcTyVar
ch_co_var = TcTyVar
cv }) Coercion
co = do
  Bool -> TcRn () -> TcRn ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when Bool
debugIsOn (TcRn () -> TcRn ()) -> TcRn () -> TcRn ()
forall a b. (a -> b) -> a -> b
$ do
    cts <- IORef (Maybe Coercion)
-> IOEnv (Env TcGblEnv TcLclEnv) (Maybe Coercion)
forall (m :: * -> *) a. MonadIO m => TcRef a -> m a
readTcRef IORef (Maybe Coercion)
ref
    whenIsJust cts $ \Coercion
old_co ->
      String -> SDoc -> TcRn ()
forall a. HasCallStack => String -> SDoc -> a
pprPanic String
"Filling a filled coercion hole" (TcTyVar -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcTyVar
cv SDoc -> SDoc -> SDoc
forall doc. IsDoc doc => doc -> doc -> doc
$$ Coercion -> SDoc
forall a. Outputable a => a -> SDoc
ppr Coercion
co SDoc -> SDoc -> SDoc
forall doc. IsDoc doc => doc -> doc -> doc
$$ Coercion -> SDoc
forall a. Outputable a => a -> SDoc
ppr Coercion
old_co)
  String -> SDoc -> TcRn ()
traceTc String
"Filling coercion hole" (TcTyVar -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcTyVar
cv SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> String -> SDoc
forall doc. IsLine doc => String -> doc
text String
":=" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> Coercion -> SDoc
forall a. Outputable a => a -> SDoc
ppr Coercion
co)
  IORef (Maybe Coercion) -> Maybe Coercion -> TcRn ()
forall (m :: * -> *) a. MonadIO m => TcRef a -> a -> m ()
writeTcRef IORef (Maybe Coercion)
ref (Coercion -> Maybe Coercion
forall a. a -> Maybe a
Just Coercion
co)


{- **********************************************************************
*
                      ExpType functions
*
********************************************************************** -}

{- Note [ExpType]
~~~~~~~~~~~~~~~~~
An ExpType is used as the "expected type" when type-checking an expression.
An ExpType can hold a "hole" that can be filled in by the type-checker.
This allows us to have one tcExpr that works in both checking mode and
synthesis mode (that is, bidirectional type-checking). Previously, this
was achieved by using ordinary unification variables, but we don't need
or want that generality. (For example, #11397 was caused by doing the
wrong thing with unification variables.) Instead, we observe that these
holes should

1. never be nested
2. never appear as the type of a variable
3. be used linearly (never be duplicated)

By defining ExpType, separately from Type, we can achieve goals 1 and 2
statically.

See also [wiki:typechecking]

Note [TcLevel of ExpType]
~~~~~~~~~~~~~~~~~~~~~~~~~
Consider

  data G a where
    MkG :: G Bool

  foo MkG = True

This is a classic untouchable-variable / ambiguous GADT return type
scenario. But, with ExpTypes, we'll be inferring the type of the RHS.
We thus must track a TcLevel in an Inferring ExpType. If we try to
fill the ExpType and find that the TcLevels don't work out, we fill
the ExpType with a tau-tv at the low TcLevel, hopefully to be worked
out later by some means -- see fillInferResult, and Note [fillInferResult]

This behaviour triggered in test gadt/gadt-escape1.

Note [FixedRuntimeRep context in ExpType]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Sometimes, we want to be sure that we fill an ExpType with a type
that has a syntactically fixed RuntimeRep (in the sense of
Note [Fixed RuntimeRep] in GHC.Tc.Utils.Concrete).

Example:

  pattern S a = (a :: (T :: TYPE R))

We have to infer a type for `a` which has a syntactically fixed RuntimeRep.
When it comes time to filling in the inferred type, we do the appropriate
representation-polymorphism check, much like we do a level check
as explained in Note [TcLevel of ExpType].

See test case T21325.
-}

-- actual data definition is in GHC.Tc.Utils.TcType

newInferExpType :: TcM ExpType
newInferExpType :: TcM ExpType
newInferExpType = Maybe FixedRuntimeRepContext -> TcM ExpType
new_inferExpType Maybe FixedRuntimeRepContext
forall a. Maybe a
Nothing

newInferExpTypeFRR :: FixedRuntimeRepContext -> TcM ExpTypeFRR
newInferExpTypeFRR :: FixedRuntimeRepContext -> TcM ExpType
newInferExpTypeFRR FixedRuntimeRepContext
frr_orig
  = do { th_stage <- TcM ThStage
getStage
       ; if
          -- See [Wrinkle: Typed Template Haskell]
          -- in Note [hasFixedRuntimeRep] in GHC.Tc.Utils.Concrete.
          | Brack _ (TcPending {}) <- th_stage
          -> new_inferExpType Nothing

          | otherwise
          -> new_inferExpType (Just frr_orig) }

new_inferExpType :: Maybe FixedRuntimeRepContext -> TcM ExpType
new_inferExpType :: Maybe FixedRuntimeRepContext -> TcM ExpType
new_inferExpType Maybe FixedRuntimeRepContext
mb_frr_orig
  = do { u <- TcRnIf TcGblEnv TcLclEnv Unique
forall gbl lcl. TcRnIf gbl lcl Unique
newUnique
       ; tclvl <- getTcLevel
       ; traceTc "newInferExpType" (ppr u <+> ppr tclvl)
       ; ref <- newMutVar Nothing
       ; return (Infer (IR { ir_uniq = u, ir_lvl = tclvl
                           , ir_ref = ref
                           , ir_frr = mb_frr_orig })) }

-- | Extract a type out of an ExpType, if one exists. But one should always
-- exist. Unless you're quite sure you know what you're doing.
readExpType_maybe :: MonadIO m => ExpType -> m (Maybe TcType)
readExpType_maybe :: forall (m :: * -> *). MonadIO m => ExpType -> m (Maybe TcType)
readExpType_maybe (Check TcType
ty)                   = Maybe TcType -> m (Maybe TcType)
forall a. a -> m a
forall (m :: * -> *) a. Monad m => a -> m a
return (TcType -> Maybe TcType
forall a. a -> Maybe a
Just TcType
ty)
readExpType_maybe (Infer (IR { ir_ref :: InferResult -> IORef (Maybe TcType)
ir_ref = IORef (Maybe TcType)
ref})) = IO (Maybe TcType) -> m (Maybe TcType)
forall a. IO a -> m a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO (Maybe TcType) -> m (Maybe TcType))
-> IO (Maybe TcType) -> m (Maybe TcType)
forall a b. (a -> b) -> a -> b
$ IORef (Maybe TcType) -> IO (Maybe TcType)
forall a. IORef a -> IO a
readIORef IORef (Maybe TcType)
ref
{-# INLINEABLE readExpType_maybe #-}

-- | Same as readExpType, but for Scaled ExpTypes
readScaledExpType :: MonadIO m => Scaled ExpType -> m (Scaled Type)
readScaledExpType :: forall (m :: * -> *).
MonadIO m =>
Scaled ExpType -> m (Scaled TcType)
readScaledExpType (Scaled TcType
m ExpType
exp_ty)
  = do { ty <- ExpType -> m TcType
forall (m :: * -> *). MonadIO m => ExpType -> m TcType
readExpType ExpType
exp_ty
       ; return (Scaled m ty) }
{-# INLINEABLE readScaledExpType  #-}

-- | Extract a type out of an ExpType. Otherwise, panics.
readExpType :: MonadIO m => ExpType -> m TcType
readExpType :: forall (m :: * -> *). MonadIO m => ExpType -> m TcType
readExpType ExpType
exp_ty
  = do { mb_ty <- ExpType -> m (Maybe TcType)
forall (m :: * -> *). MonadIO m => ExpType -> m (Maybe TcType)
readExpType_maybe ExpType
exp_ty
       ; case mb_ty of
           Just TcType
ty -> TcType -> m TcType
forall a. a -> m a
forall (m :: * -> *) a. Monad m => a -> m a
return TcType
ty
           Maybe TcType
Nothing -> String -> SDoc -> m TcType
forall a. HasCallStack => String -> SDoc -> a
pprPanic String
"Unknown expected type" (ExpType -> SDoc
forall a. Outputable a => a -> SDoc
ppr ExpType
exp_ty) }
{-# INLINEABLE readExpType  #-}

scaledExpTypeToType :: Scaled ExpType -> TcM (Scaled TcType)
scaledExpTypeToType :: Scaled ExpType -> TcM (Scaled TcType)
scaledExpTypeToType (Scaled TcType
m ExpType
exp_ty)
  = do { ty <- ExpType -> TcM TcType
expTypeToType ExpType
exp_ty
       ; return (Scaled m ty) }

-- | Extracts the expected type if there is one, or generates a new
-- TauTv if there isn't.
expTypeToType :: ExpType -> TcM TcType
expTypeToType :: ExpType -> TcM TcType
expTypeToType (Check TcType
ty)      = TcType -> TcM TcType
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return TcType
ty
expTypeToType (Infer InferResult
inf_res) = InferResult -> TcM TcType
inferResultToType InferResult
inf_res

inferResultToType :: InferResult -> TcM Type
inferResultToType :: InferResult -> TcM TcType
inferResultToType (IR { ir_uniq :: InferResult -> Unique
ir_uniq = Unique
u, ir_lvl :: InferResult -> TcLevel
ir_lvl = TcLevel
tc_lvl
                      , ir_ref :: InferResult -> IORef (Maybe TcType)
ir_ref = IORef (Maybe TcType)
ref
                      , ir_frr :: InferResult -> Maybe FixedRuntimeRepContext
ir_frr = Maybe FixedRuntimeRepContext
mb_frr })
  = do { mb_inferred_ty <- IORef (Maybe TcType)
-> IOEnv (Env TcGblEnv TcLclEnv) (Maybe TcType)
forall (m :: * -> *) a. MonadIO m => TcRef a -> m a
readTcRef IORef (Maybe TcType)
ref
       ; tau <- case mb_inferred_ty of
            Just TcType
ty -> do { TcType -> TcRn ()
ensureMonoType TcType
ty
                            -- See Note [inferResultToType]
                          ; TcType -> TcM TcType
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return TcType
ty }
            Maybe TcType
Nothing -> do { tau <- TcM TcType
new_meta
                          ; writeMutVar ref (Just tau)
                          ; return tau }
       ; traceTc "Forcing ExpType to be monomorphic:"
                 (ppr u <+> text ":=" <+> ppr tau)
       ; return tau }
  where
    -- See Note [TcLevel of ExpType]
    new_meta :: TcM TcType
new_meta = case Maybe FixedRuntimeRepContext
mb_frr of
      Maybe FixedRuntimeRepContext
Nothing  ->  do { rr  <- TcLevel -> TcType -> TcM TcType
newMetaTyVarTyAtLevel TcLevel
tc_lvl TcType
runtimeRepTy
                      ; newMetaTyVarTyAtLevel tc_lvl (mkTYPEapp rr) }
      Just FixedRuntimeRepContext
frr -> mdo { rr  <- newConcreteTyVarTyAtLevel conc_orig tc_lvl runtimeRepTy
                      ; tau <- newMetaTyVarTyAtLevel tc_lvl (mkTYPEapp rr)
                      ; let conc_orig = FixedRuntimeRepOrigin -> ConcreteTvOrigin
ConcreteFRR (FixedRuntimeRepOrigin -> ConcreteTvOrigin)
-> FixedRuntimeRepOrigin -> ConcreteTvOrigin
forall a b. (a -> b) -> a -> b
$ TcType -> FixedRuntimeRepContext -> FixedRuntimeRepOrigin
FixedRuntimeRepOrigin TcType
tau FixedRuntimeRepContext
frr
                      ; return tau }

{- Note [inferResultToType]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
expTypeToType and inferResultType convert an InferResult to a monotype.
It must be a monotype because if the InferResult isn't already filled in,
we fill it in with a unification variable (hence monotype).  So to preserve
order-independence we check for mono-type-ness even if it *is* filled in
already.

See also Note [TcLevel of ExpType] above, and
Note [fillInferResult] in GHC.Tc.Utils.Unify.
-}

-- | Infer a type using a fresh ExpType
-- See also Note [ExpType] in "GHC.Tc.Utils.TcMType"
--
-- Use 'tcInferFRR' if you require the type to have a fixed
-- runtime representation.
tcInfer :: (ExpSigmaType -> TcM a) -> TcM (a, TcSigmaType)
tcInfer :: forall a. (ExpType -> TcM a) -> TcM (a, TcType)
tcInfer = Maybe FixedRuntimeRepContext
-> (ExpType -> TcM a) -> TcM (a, TcType)
forall a.
Maybe FixedRuntimeRepContext
-> (ExpType -> TcM a) -> TcM (a, TcType)
tc_infer Maybe FixedRuntimeRepContext
forall a. Maybe a
Nothing

-- | Like 'tcInfer', except it ensures that the resulting type
-- has a syntactically fixed RuntimeRep as per Note [Fixed RuntimeRep] in
-- GHC.Tc.Utils.Concrete.
tcInferFRR :: FixedRuntimeRepContext -> (ExpSigmaTypeFRR -> TcM a) -> TcM (a, TcSigmaTypeFRR)
tcInferFRR :: forall a.
FixedRuntimeRepContext -> (ExpType -> TcM a) -> TcM (a, TcType)
tcInferFRR FixedRuntimeRepContext
frr_orig = Maybe FixedRuntimeRepContext
-> (ExpType -> TcM a) -> TcM (a, TcType)
forall a.
Maybe FixedRuntimeRepContext
-> (ExpType -> TcM a) -> TcM (a, TcType)
tc_infer (FixedRuntimeRepContext -> Maybe FixedRuntimeRepContext
forall a. a -> Maybe a
Just FixedRuntimeRepContext
frr_orig)

tc_infer :: Maybe FixedRuntimeRepContext -> (ExpSigmaType -> TcM a) -> TcM (a, TcSigmaType)
tc_infer :: forall a.
Maybe FixedRuntimeRepContext
-> (ExpType -> TcM a) -> TcM (a, TcType)
tc_infer Maybe FixedRuntimeRepContext
mb_frr ExpType -> TcM a
tc_check
  = do { res_ty <- Maybe FixedRuntimeRepContext -> TcM ExpType
new_inferExpType Maybe FixedRuntimeRepContext
mb_frr
       ; result <- tc_check res_ty
       ; res_ty <- readExpType res_ty
       ; return (result, res_ty) }

{- *********************************************************************
*                                                                      *
              Promoting types
*                                                                      *
********************************************************************* -}

ensureMonoType :: TcType -> TcM ()
-- Assuming that the argument type is of kind (TYPE r),
-- ensure that it is a /monotype/
-- If it is not a monotype we can see right away (since unification
-- variables and type-function applications stand for monotypes), but
-- we emit a Wanted equality just to delay the error message until later
ensureMonoType :: TcType -> TcRn ()
ensureMonoType TcType
res_ty
  | TcType -> Bool
isTauTy TcType
res_ty   -- isTauTy doesn't need zonking or anything
  = () -> TcRn ()
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return ()
  | Bool
otherwise
  = do { mono_ty <- TcM TcType
newOpenFlexiTyVarTy
       ; _co <- unifyInvisibleType res_ty mono_ty
       ; return () }

promoteTcType :: TcLevel -> TcType -> TcM (TcCoercionN, TcType)
-- See Note [Promoting a type]
-- See also Note [fillInferResult]
-- promoteTcType level ty = (co, ty')
--   * Returns ty'  whose max level is just 'level'
--             and  whose kind is ~# to the kind of 'ty'
--             and  whose kind has form TYPE rr
--   * and co :: ty ~ ty'
--   * and emits constraints to justify the coercion
--
-- NB: we expect that 'ty' has already kind (TYPE rr) for
--     some rr::RuntimeRep.  It is, after all, the type of a term.
promoteTcType :: TcLevel -> TcType -> TcM (Coercion, TcType)
promoteTcType TcLevel
dest_lvl TcType
ty
  = do { cur_lvl <- TcM TcLevel
getTcLevel
       ; if (cur_lvl `sameDepthAs` dest_lvl)
         then return (mkNomReflCo ty, ty)
         else promote_it }
  where
    promote_it :: TcM (TcCoercion, TcType)
    promote_it :: TcM (Coercion, TcType)
promote_it  -- Emit a constraint  (alpha :: TYPE rr) ~ ty
                -- where alpha and rr are fresh and from level dest_lvl
      = do { rr      <- TcLevel -> TcType -> TcM TcType
newMetaTyVarTyAtLevel TcLevel
dest_lvl TcType
runtimeRepTy
           ; prom_ty <- newMetaTyVarTyAtLevel dest_lvl (mkTYPEapp rr)
           ; co <- unifyInvisibleType ty prom_ty
           ; return (co, prom_ty) }

{- Note [Promoting a type]
~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider (#12427)

  data T where
    MkT :: (Int -> Int) -> a -> T

  h y = case y of MkT v w -> v

We'll infer the RHS type with an expected type ExpType of
  (IR { ir_lvl = l, ir_ref = ref, ... )
where 'l' is the TcLevel of the RHS of 'h'.  Then the MkT pattern
match will increase the level, so we'll end up in tcSubType, trying to
unify the type of v,
  v :: Int -> Int
with the expected type.  But this attempt takes place at level (l+1),
rightly so, since v's type could have mentioned existential variables,
(like w's does) and we want to catch that.

So we
  - create a new meta-var alpha[l+1]
  - fill in the InferRes ref cell 'ref' with alpha
  - emit an equality constraint, thus
        [W] alpha[l+1] ~ (Int -> Int)

That constraint will float outwards, as it should, unless v's
type mentions a skolem-captured variable.

This approach fails if v has a higher rank type; see
Note [Promotion and higher rank types]


Note [Promotion and higher rank types]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If v had a higher-rank type, say v :: (forall a. a->a) -> Int,
then we'd emit an equality
        [W] alpha[l+1] ~ ((forall a. a->a) -> Int)
which will sadly fail because we can't unify a unification variable
with a polytype.  But there is nothing really wrong with the program
here.

We could just about solve this by "promote the type" of v, to expose
its polymorphic "shape" while still leaving constraints that will
prevent existential escape.  But we must be careful!  Exposing
the "shape" of the type is precisely what we must NOT do under
a GADT pattern match!  So in this case we might promote the type
to
        (forall a. a->a) -> alpha[l+1]
and emit the constraint
        [W] alpha[l+1] ~ Int
Now the promoted type can fill the ref cell, while the emitted
equality can float or not, according to the usual rules.

But that's not quite right!  We are exposing the arrow! We could
deal with that too:
        (forall a. mu[l+1] a a) -> alpha[l+1]
with constraints
        [W] alpha[l+1] ~ Int
        [W] mu[l+1] ~ (->)
Here we abstract over the '->' inside the forall, in case that
is subject to an equality constraint from a GADT match.

Note that we kept the outer (->) because that's part of
the polymorphic "shape".  And because of impredicativity,
GADT matches can't give equalities that affect polymorphic
shape.

This reasoning just seems too complicated, so I decided not
to do it.  These higher-rank notes are just here to record
the thinking.
-}


{- *********************************************************************
*                                                                      *
        MetaTvs (meta type variables; mutable)
*                                                                      *
********************************************************************* -}

{- Note [TyVarTv]
~~~~~~~~~~~~~~~~~
A TyVarTv can unify with type *variables* only, including other TyVarTvs and
skolems.  They are used in two places:

1. In kind signatures, see GHC.Tc.TyCl
      Note [Inferring kinds for type declarations]
   and Note [Using TyVarTvs for kind-checking GADTs]

2. In partial type signatures.  See GHC.Tc.Types
   Note [Quantified variables in partial type signatures]

Sometimes, they can unify with type variables that the user would
rather keep distinct; see #11203 for an example.  So, any client of
this function needs to either allow the TyVarTvs to unify with each
other or check that they don't. In the case of (1) the check is done
in GHC.Tc.TyCl.swizzleTcTyConBndrs.  In case of (2) it's done by
findDupTyVarTvs in GHC.Tc.Gen.Bind.chooseInferredQuantifiers.

Historical note: Before #15050 this (under the name SigTv) was also
used for ScopedTypeVariables in patterns, to make sure these type
variables only refer to other type variables, but this restriction was
dropped, and ScopedTypeVariables can now refer to full types (GHC
Proposal 29).
-}

newMetaTyVarName :: FastString -> TcM Name
-- Makes a /System/ Name, which is eagerly eliminated by
-- the unifier; see GHC.Tc.Utils.Unify.nicer_to_update_tv1, and
-- GHC.Tc.Solver.Equality.canEqTyVarTyVar (nicer_to_update_tv2)
newMetaTyVarName :: FastString -> TcM Name
newMetaTyVarName FastString
str
  = OccName -> TcM Name
forall gbl lcl. OccName -> TcRnIf gbl lcl Name
newSysName (FastString -> OccName
mkTyVarOccFS FastString
str)

cloneMetaTyVarName :: Name -> TcM Name
cloneMetaTyVarName :: Name -> TcM Name
cloneMetaTyVarName Name
name
  = OccName -> TcM Name
forall gbl lcl. OccName -> TcRnIf gbl lcl Name
newSysName (Name -> OccName
nameOccName Name
name)
         -- See Note [Name of an instantiated type variable]

{- Note [Name of an instantiated type variable]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
At the moment we give a unification variable a System Name, which
influences the way it is tidied; see TypeRep.tidyTyVarBndr.
-}

metaInfoToTyVarName :: MetaInfo -> FastString
metaInfoToTyVarName :: MetaInfo -> FastString
metaInfoToTyVarName  MetaInfo
meta_info =
  case MetaInfo
meta_info of
       MetaInfo
TauTv          -> String -> FastString
fsLit String
"t"
       MetaInfo
TyVarTv        -> String -> FastString
fsLit String
"a"
       MetaInfo
RuntimeUnkTv   -> String -> FastString
fsLit String
"r"
       MetaInfo
CycleBreakerTv -> String -> FastString
fsLit String
"b"
       ConcreteTv {}  -> String -> FastString
fsLit String
"c"

newAnonMetaTyVar :: MetaInfo -> Kind -> TcM TcTyVar
newAnonMetaTyVar :: MetaInfo -> TcType -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
newAnonMetaTyVar MetaInfo
mi = FastString
-> MetaInfo -> TcType -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
newNamedAnonMetaTyVar (MetaInfo -> FastString
metaInfoToTyVarName MetaInfo
mi) MetaInfo
mi

newNamedAnonMetaTyVar :: FastString -> MetaInfo -> Kind -> TcM TcTyVar
-- Make a new meta tyvar out of thin air
newNamedAnonMetaTyVar :: FastString
-> MetaInfo -> TcType -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
newNamedAnonMetaTyVar FastString
tyvar_name MetaInfo
meta_info TcType
kind

  = do  { name    <- FastString -> TcM Name
newMetaTyVarName FastString
tyvar_name
        ; details <- newMetaDetails meta_info
        ; let tyvar = Name -> TcType -> TcTyVarDetails -> TcTyVar
mkTcTyVar Name
name TcType
kind TcTyVarDetails
details
        ; traceTc "newAnonMetaTyVar" (ppr tyvar)
        ; return tyvar }

-- makes a new skolem tv
newSkolemTyVar :: SkolemInfo -> Name -> Kind -> TcM TcTyVar
newSkolemTyVar :: SkolemInfo
-> Name -> TcType -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
newSkolemTyVar SkolemInfo
skol_info Name
name TcType
kind
  = do { lvl <- TcM TcLevel
getTcLevel
       ; return (mkTcTyVar name kind (SkolemTv skol_info lvl False)) }

newTyVarTyVar :: Name -> Kind -> TcM TcTyVar
-- See Note [TyVarTv]
-- Does not clone a fresh unique
newTyVarTyVar :: Name -> TcType -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
newTyVarTyVar Name
name TcType
kind
  = do { details <- MetaInfo -> TcM TcTyVarDetails
newMetaDetails MetaInfo
TyVarTv
       ; let tyvar = Name -> TcType -> TcTyVarDetails -> TcTyVar
mkTcTyVar Name
name TcType
kind TcTyVarDetails
details
       ; traceTc "newTyVarTyVar" (ppr tyvar)
       ; return tyvar }

cloneTyVarTyVar :: Name -> Kind -> TcM TcTyVar
-- See Note [TyVarTv]
-- Clones a fresh unique
cloneTyVarTyVar :: Name -> TcType -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
cloneTyVarTyVar Name
name TcType
kind
  = do { details <- MetaInfo -> TcM TcTyVarDetails
newMetaDetails MetaInfo
TyVarTv
       ; uniq <- newUnique
       ; let name' = Name
name Name -> Unique -> Name
`setNameUnique` Unique
uniq
             tyvar = Name -> TcType -> TcTyVarDetails -> TcTyVar
mkTcTyVar Name
name' TcType
kind TcTyVarDetails
details
         -- Don't use cloneMetaTyVar, which makes a SystemName
         -- We want to keep the original more user-friendly Name
         -- In practical terms that means that in error messages,
         -- when the Name is tidied we get 'a' rather than 'a0'
       ; traceTc "cloneTyVarTyVar" (ppr tyvar)
       ; return tyvar }

-- | Create a new metavariable, of the given kind, which can only be unified
-- with a concrete type.
--
-- Invariant: the kind must be concrete, as per Note [ConcreteTv].
-- This is checked with an assertion.
newConcreteTyVar :: HasDebugCallStack => ConcreteTvOrigin
                 -> FastString -> TcKind -> TcM TcTyVar
newConcreteTyVar :: HasDebugCallStack =>
ConcreteTvOrigin
-> FastString -> TcType -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
newConcreteTyVar ConcreteTvOrigin
reason FastString
fs TcType
kind
  = Bool
-> SDoc
-> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
-> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
forall a. HasCallStack => Bool -> SDoc -> a -> a
assertPpr (TcType -> Bool
isConcreteType TcType
kind) SDoc
assert_msg (IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
 -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar)
-> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
-> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
forall a b. (a -> b) -> a -> b
$
  do { th_stage <- TcM ThStage
getStage
     ; if
        -- See [Wrinkle: Typed Template Haskell]
        -- in Note [hasFixedRuntimeRep] in GHC.Tc.Utils.Concrete.
        | Brack _ (TcPending {}) <- th_stage
        -> newNamedAnonMetaTyVar fs TauTv kind

        | otherwise
        -> newNamedAnonMetaTyVar fs (ConcreteTv reason) kind }
  where
    assert_msg :: SDoc
assert_msg = String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"newConcreteTyVar: non-concrete kind" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
kind

newPatTyVar :: Name -> Kind -> TcM TcTyVar
newPatTyVar :: Name -> TcType -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
newPatTyVar Name
name TcType
kind
  = do { details <- MetaInfo -> TcM TcTyVarDetails
newMetaDetails MetaInfo
TauTv
       ; uniq <- newUnique
       ; let name' = Name
name Name -> Unique -> Name
`setNameUnique` Unique
uniq
             tyvar = Name -> TcType -> TcTyVarDetails -> TcTyVar
mkTcTyVar Name
name' TcType
kind TcTyVarDetails
details
         -- Don't use cloneMetaTyVar;
         -- same reasoning as in newTyVarTyVar
       ; traceTc "newPatTyVar" (ppr tyvar)
       ; return tyvar }

cloneAnonMetaTyVar :: MetaInfo -> TyVar -> TcKind -> TcM TcTyVar
-- Make a fresh MetaTyVar, basing the name
-- on that of the supplied TyVar
cloneAnonMetaTyVar :: MetaInfo
-> TcTyVar -> TcType -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
cloneAnonMetaTyVar MetaInfo
info TcTyVar
tv TcType
kind
  = do  { details <- MetaInfo -> TcM TcTyVarDetails
newMetaDetails MetaInfo
info
        ; name    <- cloneMetaTyVarName (tyVarName tv)
        ; let tyvar = Name -> TcType -> TcTyVarDetails -> TcTyVar
mkTcTyVar Name
name TcType
kind TcTyVarDetails
details
        ; traceTc "cloneAnonMetaTyVar" (ppr tyvar <+> dcolon <+> ppr (tyVarKind tyvar))
        ; return tyvar }

-- Make a new CycleBreakerTv. See Note [Type equality cycles]
-- in GHC.Tc.Solver.Equality
newCycleBreakerTyVar :: TcKind -> TcM TcTyVar
newCycleBreakerTyVar :: TcType -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
newCycleBreakerTyVar TcType
kind
  = do { details <- MetaInfo -> TcM TcTyVarDetails
newMetaDetails MetaInfo
CycleBreakerTv
       ; name <- newMetaTyVarName (fsLit "cbv")
       ; return (mkTcTyVar name kind details) }

newMetaDetails :: MetaInfo -> TcM TcTyVarDetails
newMetaDetails :: MetaInfo -> TcM TcTyVarDetails
newMetaDetails MetaInfo
info
  = do { ref <- MetaDetails -> IOEnv (Env TcGblEnv TcLclEnv) (IORef MetaDetails)
forall a env. a -> IOEnv env (IORef a)
newMutVar MetaDetails
Flexi
       ; tclvl <- getTcLevel
       ; return (MetaTv { mtv_info = info
                        , mtv_ref = ref
                        , mtv_tclvl = tclvl }) }

newTauTvDetailsAtLevel :: TcLevel -> TcM TcTyVarDetails
newTauTvDetailsAtLevel :: TcLevel -> TcM TcTyVarDetails
newTauTvDetailsAtLevel TcLevel
tclvl
  = do { ref <- MetaDetails -> IOEnv (Env TcGblEnv TcLclEnv) (IORef MetaDetails)
forall a env. a -> IOEnv env (IORef a)
newMutVar MetaDetails
Flexi
       ; return (MetaTv { mtv_info  = TauTv
                        , mtv_ref   = ref
                        , mtv_tclvl = tclvl }) }

newConcreteTvDetailsAtLevel :: ConcreteTvOrigin -> TcLevel -> TcM TcTyVarDetails
newConcreteTvDetailsAtLevel :: ConcreteTvOrigin -> TcLevel -> TcM TcTyVarDetails
newConcreteTvDetailsAtLevel ConcreteTvOrigin
conc_orig TcLevel
tclvl
  = do { ref <- MetaDetails -> IOEnv (Env TcGblEnv TcLclEnv) (IORef MetaDetails)
forall a env. a -> IOEnv env (IORef a)
newMutVar MetaDetails
Flexi
       ; return (MetaTv { mtv_info  = ConcreteTv conc_orig
                        , mtv_ref   = ref
                        , mtv_tclvl = tclvl }) }

cloneMetaTyVar :: TcTyVar -> TcM TcTyVar
cloneMetaTyVar :: TcTyVar -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
cloneMetaTyVar TcTyVar
tv
  = Bool
-> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
-> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
forall a. HasCallStack => Bool -> a -> a
assert (TcTyVar -> Bool
isTcTyVar TcTyVar
tv) (IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
 -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar)
-> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
-> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
forall a b. (a -> b) -> a -> b
$
    do  { ref  <- MetaDetails -> IOEnv (Env TcGblEnv TcLclEnv) (IORef MetaDetails)
forall a env. a -> IOEnv env (IORef a)
newMutVar MetaDetails
Flexi
        ; name' <- cloneMetaTyVarName (tyVarName tv)
        ; let details' = case TcTyVar -> TcTyVarDetails
tcTyVarDetails TcTyVar
tv of
                           details :: TcTyVarDetails
details@(MetaTv {}) -> TcTyVarDetails
details { mtv_ref = ref }
                           TcTyVarDetails
_ -> String -> SDoc -> TcTyVarDetails
forall a. HasCallStack => String -> SDoc -> a
pprPanic String
"cloneMetaTyVar" (TcTyVar -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcTyVar
tv)
              tyvar = Name -> TcType -> TcTyVarDetails -> TcTyVar
mkTcTyVar Name
name' (TcTyVar -> TcType
tyVarKind TcTyVar
tv) TcTyVarDetails
details'
        ; traceTc "cloneMetaTyVar" (ppr tyvar)
        ; return tyvar }

cloneMetaTyVarWithInfo :: MetaInfo -> TcLevel -> TcTyVar -> TcM TcTyVar
cloneMetaTyVarWithInfo :: MetaInfo
-> TcLevel -> TcTyVar -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
cloneMetaTyVarWithInfo MetaInfo
info TcLevel
tc_lvl TcTyVar
tv
  = Bool
-> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
-> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
forall a. HasCallStack => Bool -> a -> a
assert (TcTyVar -> Bool
isTcTyVar TcTyVar
tv) (IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
 -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar)
-> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
-> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
forall a b. (a -> b) -> a -> b
$
    do  { ref  <- MetaDetails -> IOEnv (Env TcGblEnv TcLclEnv) (IORef MetaDetails)
forall a env. a -> IOEnv env (IORef a)
newMutVar MetaDetails
Flexi
        ; name' <- cloneMetaTyVarName (tyVarName tv)
        ; let details = MetaTv { mtv_info :: MetaInfo
mtv_info  = MetaInfo
info
                               , mtv_ref :: IORef MetaDetails
mtv_ref   = IORef MetaDetails
ref
                               , mtv_tclvl :: TcLevel
mtv_tclvl = TcLevel
tc_lvl }
              tyvar = Name -> TcType -> TcTyVarDetails -> TcTyVar
mkTcTyVar Name
name' (TcTyVar -> TcType
tyVarKind TcTyVar
tv) TcTyVarDetails
details
        ; traceTc "cloneMetaTyVarWithInfo" (ppr tyvar)
        ; return tyvar }

-- Works for both type and kind variables
readMetaTyVar :: MonadIO m => TyVar -> m MetaDetails
readMetaTyVar :: forall (m :: * -> *). MonadIO m => TcTyVar -> m MetaDetails
readMetaTyVar TcTyVar
tyvar = Bool -> SDoc -> m MetaDetails -> m MetaDetails
forall a. HasCallStack => Bool -> SDoc -> a -> a
assertPpr (TcTyVar -> Bool
isMetaTyVar TcTyVar
tyvar) (TcTyVar -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcTyVar
tyvar) (m MetaDetails -> m MetaDetails) -> m MetaDetails -> m MetaDetails
forall a b. (a -> b) -> a -> b
$
                      IO MetaDetails -> m MetaDetails
forall a. IO a -> m a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO MetaDetails -> m MetaDetails)
-> IO MetaDetails -> m MetaDetails
forall a b. (a -> b) -> a -> b
$ IORef MetaDetails -> IO MetaDetails
forall a. IORef a -> IO a
readIORef (TcTyVar -> IORef MetaDetails
metaTyVarRef TcTyVar
tyvar)
{-# SPECIALISE readMetaTyVar :: TyVar -> TcM MetaDetails #-}
{-# SPECIALISE readMetaTyVar :: TyVar -> ZonkM MetaDetails #-}

isFilledMetaTyVar_maybe :: TcTyVar -> TcM (Maybe Type)
isFilledMetaTyVar_maybe :: TcTyVar -> IOEnv (Env TcGblEnv TcLclEnv) (Maybe TcType)
isFilledMetaTyVar_maybe TcTyVar
tv
-- TODO: This should be an assertion that tv is definitely a TcTyVar but it fails
-- at the moment (Jan 22)
 | TcTyVar -> Bool
isTcTyVar TcTyVar
tv
 , MetaTv { mtv_ref :: TcTyVarDetails -> IORef MetaDetails
mtv_ref = IORef MetaDetails
ref } <- TcTyVar -> TcTyVarDetails
tcTyVarDetails TcTyVar
tv
 = do { cts <- IORef MetaDetails -> IOEnv (Env TcGblEnv TcLclEnv) MetaDetails
forall (m :: * -> *) a. MonadIO m => TcRef a -> m a
readTcRef IORef MetaDetails
ref
      ; case cts of
          Indirect TcType
ty -> Maybe TcType -> IOEnv (Env TcGblEnv TcLclEnv) (Maybe TcType)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (TcType -> Maybe TcType
forall a. a -> Maybe a
Just TcType
ty)
          MetaDetails
Flexi       -> Maybe TcType -> IOEnv (Env TcGblEnv TcLclEnv) (Maybe TcType)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe TcType
forall a. Maybe a
Nothing }
 | Bool
otherwise
 = Maybe TcType -> IOEnv (Env TcGblEnv TcLclEnv) (Maybe TcType)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe TcType
forall a. Maybe a
Nothing

isFilledMetaTyVar :: TyVar -> TcM Bool
-- True of a filled-in (Indirect) meta type variable
isFilledMetaTyVar :: TcTyVar -> TcRnIf TcGblEnv TcLclEnv Bool
isFilledMetaTyVar TcTyVar
tv = Maybe TcType -> Bool
forall a. Maybe a -> Bool
isJust (Maybe TcType -> Bool)
-> IOEnv (Env TcGblEnv TcLclEnv) (Maybe TcType)
-> TcRnIf TcGblEnv TcLclEnv Bool
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> TcTyVar -> IOEnv (Env TcGblEnv TcLclEnv) (Maybe TcType)
isFilledMetaTyVar_maybe TcTyVar
tv

isUnfilledMetaTyVar :: TyVar -> TcM Bool
-- True of a un-filled-in (Flexi) meta type variable
-- NB: Not the opposite of isFilledMetaTyVar
isUnfilledMetaTyVar :: TcTyVar -> TcRnIf TcGblEnv TcLclEnv Bool
isUnfilledMetaTyVar TcTyVar
tv
  | MetaTv { mtv_ref :: TcTyVarDetails -> IORef MetaDetails
mtv_ref = IORef MetaDetails
ref } <- TcTyVar -> TcTyVarDetails
tcTyVarDetails TcTyVar
tv
  = do  { details <- IORef MetaDetails -> IOEnv (Env TcGblEnv TcLclEnv) MetaDetails
forall a env. IORef a -> IOEnv env a
readMutVar IORef MetaDetails
ref
        ; return (isFlexi details) }
  | Bool
otherwise = Bool -> TcRnIf TcGblEnv TcLclEnv Bool
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
False

{-
************************************************************************
*                                                                      *
        MetaTvs: TauTvs
*                                                                      *
************************************************************************

Note [Never need to instantiate coercion variables]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
With coercion variables sloshing around in types, it might seem that we
sometimes need to instantiate coercion variables. This would be problematic,
because coercion variables inhabit unboxed equality (~#), and the constraint
solver thinks in terms only of boxed equality (~). The solution is that
we never need to instantiate coercion variables in the first place.

The tyvars that we need to instantiate come from the types of functions,
data constructors, and patterns. These will never be quantified over
coercion variables, except for the special case of the promoted Eq#. But,
that can't ever appear in user code, so we're safe!
-}


newMultiplicityVar :: TcM TcType
newMultiplicityVar :: TcM TcType
newMultiplicityVar = TcType -> TcM TcType
newFlexiTyVarTy TcType
multiplicityTy

newFlexiTyVar :: Kind -> TcM TcTyVar
newFlexiTyVar :: TcType -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
newFlexiTyVar TcType
kind = MetaInfo -> TcType -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
newAnonMetaTyVar MetaInfo
TauTv TcType
kind

-- | Create a new flexi ty var with a specific name
newNamedFlexiTyVar :: FastString -> Kind -> TcM TcTyVar
newNamedFlexiTyVar :: FastString -> TcType -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
newNamedFlexiTyVar FastString
fs TcType
kind = FastString
-> MetaInfo -> TcType -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
newNamedAnonMetaTyVar FastString
fs MetaInfo
TauTv TcType
kind

newFlexiTyVarTy :: Kind -> TcM TcType
newFlexiTyVarTy :: TcType -> TcM TcType
newFlexiTyVarTy TcType
kind = do
    tc_tyvar <- TcType -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
newFlexiTyVar TcType
kind
    return (mkTyVarTy tc_tyvar)

newFlexiTyVarTys :: Int -> Kind -> TcM [TcType]
newFlexiTyVarTys :: Int -> TcType -> TcM [TcType]
newFlexiTyVarTys Int
n TcType
kind = Int -> TcM TcType -> TcM [TcType]
forall (m :: * -> *) a. Applicative m => Int -> m a -> m [a]
replicateM Int
n (TcType -> TcM TcType
newFlexiTyVarTy TcType
kind)

newOpenTypeKind :: TcM TcKind
newOpenTypeKind :: TcM TcType
newOpenTypeKind
  = do { rr <- TcType -> TcM TcType
newFlexiTyVarTy TcType
runtimeRepTy
       ; return (mkTYPEapp rr) }

-- | Create a tyvar that can be a lifted or unlifted type.
-- Returns @alpha :: TYPE kappa@, where both @alpha@ and @kappa@ are fresh.
--
-- Note: you should use 'newOpenFlexiFRRTyVarTy' if you also need to ensure
-- that the representation is concrete, in the sense of Note [Concrete types]
-- in GHC.Tc.Utils.Concrete.
newOpenFlexiTyVarTy :: TcM TcType
newOpenFlexiTyVarTy :: TcM TcType
newOpenFlexiTyVarTy
  = do { tv <- IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
newOpenFlexiTyVar
       ; return (mkTyVarTy tv) }

newOpenFlexiTyVar :: TcM TcTyVar
newOpenFlexiTyVar :: IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
newOpenFlexiTyVar
  = do { kind <- TcM TcType
newOpenTypeKind
       ; newFlexiTyVar kind }

-- | Like 'newOpenFlexiTyVar', but ensures the type variable has a
-- syntactically fixed RuntimeRep in the sense of Note [Fixed RuntimeRep]
-- in GHC.Tc.Utils.Concrete.
newOpenFlexiFRRTyVar :: FixedRuntimeRepContext -> TcM TcTyVar
newOpenFlexiFRRTyVar :: FixedRuntimeRepContext -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
newOpenFlexiFRRTyVar FixedRuntimeRepContext
frr_ctxt
  = do { th_stage <- TcM ThStage
getStage
       ; case th_stage of
          { Brack ThStage
_ (TcPending {}) -- See [Wrinkle: Typed Template Haskell]
              -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
newOpenFlexiTyVar -- in Note [hasFixedRuntimeRep] in GHC.Tc.Utils.Concrete.
          ; ThStage
_ ->
   mdo { let conc_orig = FixedRuntimeRepOrigin -> ConcreteTvOrigin
ConcreteFRR (FixedRuntimeRepOrigin -> ConcreteTvOrigin)
-> FixedRuntimeRepOrigin -> ConcreteTvOrigin
forall a b. (a -> b) -> a -> b
$
                          FixedRuntimeRepOrigin
                            { frr_context :: FixedRuntimeRepContext
frr_context = FixedRuntimeRepContext
frr_ctxt
                            , frr_type :: TcType
frr_type    = TcTyVar -> TcType
mkTyVarTy TcTyVar
tv }
        ; rr <- mkTyVarTy <$> newConcreteTyVar conc_orig (fsLit "cx") runtimeRepTy
        ; tv <- newFlexiTyVar (mkTYPEapp rr)
        ; return tv } } }

-- | See 'newOpenFlexiFRRTyVar'.
newOpenFlexiFRRTyVarTy :: FixedRuntimeRepContext -> TcM TcType
newOpenFlexiFRRTyVarTy :: FixedRuntimeRepContext -> TcM TcType
newOpenFlexiFRRTyVarTy FixedRuntimeRepContext
frr_ctxt
  = do { tv <- FixedRuntimeRepContext -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
newOpenFlexiFRRTyVar FixedRuntimeRepContext
frr_ctxt
       ; return (mkTyVarTy tv) }

newOpenBoxedTypeKind :: TcM TcKind
newOpenBoxedTypeKind :: TcM TcType
newOpenBoxedTypeKind
  = do { lev <- TcType -> TcM TcType
newFlexiTyVarTy (TyCon -> TcType
mkTyConTy TyCon
levityTyCon)
       ; let rr = TyCon -> [TcType] -> TcType
mkTyConApp TyCon
boxedRepDataConTyCon [TcType
lev]
       ; return (mkTYPEapp rr) }

newMetaTyVars :: [TyVar] -> TcM (Subst, [TcTyVar])
-- Instantiate with META type variables
-- Note that this works for a sequence of kind, type, and coercion variables
-- variables.  Eg    [ (k:*), (a:k->k) ]
--             Gives [ (k7:*), (a8:k7->k7) ]
newMetaTyVars :: [TcTyVar] -> TcM (Subst, [TcTyVar])
newMetaTyVars = Subst -> [TcTyVar] -> TcM (Subst, [TcTyVar])
newMetaTyVarsX Subst
emptySubst
    -- emptySubst has an empty in-scope set, but that's fine here
    -- Since the tyvars are freshly made, they cannot possibly be
    -- captured by any existing for-alls.

newMetaTyVarsX :: Subst -> [TyVar] -> TcM (Subst, [TcTyVar])
-- Just like newMetaTyVars, but start with an existing substitution.
newMetaTyVarsX :: Subst -> [TcTyVar] -> TcM (Subst, [TcTyVar])
newMetaTyVarsX Subst
subst = (Subst
 -> TcTyVar -> IOEnv (Env TcGblEnv TcLclEnv) (Subst, TcTyVar))
-> Subst -> [TcTyVar] -> TcM (Subst, [TcTyVar])
forall (m :: * -> *) (t :: * -> *) acc x y.
(Monad m, Traversable t) =>
(acc -> x -> m (acc, y)) -> acc -> t x -> m (acc, t y)
mapAccumLM Subst -> TcTyVar -> IOEnv (Env TcGblEnv TcLclEnv) (Subst, TcTyVar)
newMetaTyVarX Subst
subst

newMetaTyVarBndrsX :: Subst -> [VarBndr TyVar vis] -> TcM (Subst, [VarBndr TcTyVar vis])
newMetaTyVarBndrsX :: forall vis.
Subst
-> [VarBndr TcTyVar vis] -> TcM (Subst, [VarBndr TcTyVar vis])
newMetaTyVarBndrsX Subst
subst [VarBndr TcTyVar vis]
bndrs = do
  (subst, bndrs') <- Subst -> [TcTyVar] -> TcM (Subst, [TcTyVar])
newMetaTyVarsX Subst
subst ([VarBndr TcTyVar vis] -> [TcTyVar]
forall tv argf. [VarBndr tv argf] -> [tv]
binderVars [VarBndr TcTyVar vis]
bndrs)
  pure (subst, zipWith mkForAllTyBinder flags bndrs')
  where
    flags :: [vis]
flags = [VarBndr TcTyVar vis] -> [vis]
forall tv argf. [VarBndr tv argf] -> [argf]
binderFlags [VarBndr TcTyVar vis]
bndrs

newMetaTyVarX :: Subst -> TyVar -> TcM (Subst, TcTyVar)
-- Make a new unification variable tyvar whose Name and Kind come from
-- an existing TyVar. We substitute kind variables in the kind.
newMetaTyVarX :: Subst -> TcTyVar -> IOEnv (Env TcGblEnv TcLclEnv) (Subst, TcTyVar)
newMetaTyVarX = MetaInfo
-> Subst
-> TcTyVar
-> IOEnv (Env TcGblEnv TcLclEnv) (Subst, TcTyVar)
new_meta_tv_x MetaInfo
TauTv

-- | Like 'newMetaTyVarX', but for concrete type variables.
newConcreteTyVarX :: ConcreteTvOrigin -> Subst -> TyVar -> TcM (Subst, TcTyVar)
newConcreteTyVarX :: ConcreteTvOrigin
-> Subst
-> TcTyVar
-> IOEnv (Env TcGblEnv TcLclEnv) (Subst, TcTyVar)
newConcreteTyVarX ConcreteTvOrigin
conc Subst
subst TcTyVar
tv
  = do { th_stage <- TcM ThStage
getStage
       ; if
          -- See [Wrinkle: Typed Template Haskell]
          -- in Note [hasFixedRuntimeRep] in GHC.Tc.Utils.Concrete.
          | Brack _ (TcPending {}) <- th_stage
          -> new_meta_tv_x TauTv subst tv
          | otherwise
          -> new_meta_tv_x (ConcreteTv conc) subst tv }

newMetaTyVarTyVarX :: Subst -> TyVar -> TcM (Subst, TcTyVar)
-- Just like newMetaTyVarX, but make a TyVarTv
newMetaTyVarTyVarX :: Subst -> TcTyVar -> IOEnv (Env TcGblEnv TcLclEnv) (Subst, TcTyVar)
newMetaTyVarTyVarX Subst
subst TcTyVar
tv = MetaInfo
-> Subst
-> TcTyVar
-> IOEnv (Env TcGblEnv TcLclEnv) (Subst, TcTyVar)
new_meta_tv_x MetaInfo
TyVarTv Subst
subst TcTyVar
tv

newWildCardX :: Subst -> TyVar -> TcM (Subst, TcTyVar)
newWildCardX :: Subst -> TcTyVar -> IOEnv (Env TcGblEnv TcLclEnv) (Subst, TcTyVar)
newWildCardX Subst
subst TcTyVar
tv
  = do { new_tv <- MetaInfo -> TcType -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
newAnonMetaTyVar MetaInfo
TauTv (HasDebugCallStack => Subst -> TcType -> TcType
Subst -> TcType -> TcType
substTy Subst
subst (TcTyVar -> TcType
tyVarKind TcTyVar
tv))
       ; return (extendTvSubstWithClone subst tv new_tv, new_tv) }

new_meta_tv_x :: MetaInfo -> Subst -> TyVar -> TcM (Subst, TcTyVar)
new_meta_tv_x :: MetaInfo
-> Subst
-> TcTyVar
-> IOEnv (Env TcGblEnv TcLclEnv) (Subst, TcTyVar)
new_meta_tv_x MetaInfo
info Subst
subst TcTyVar
tv
  = do  { new_tv <- MetaInfo
-> TcTyVar -> TcType -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
cloneAnonMetaTyVar MetaInfo
info TcTyVar
tv TcType
substd_kind
        ; let subst1 = Subst -> TcTyVar -> TcTyVar -> Subst
extendTvSubstWithClone Subst
subst TcTyVar
tv TcTyVar
new_tv
        ; return (subst1, new_tv) }
  where
    substd_kind :: TcType
substd_kind = HasDebugCallStack => Subst -> TcType -> TcType
Subst -> TcType -> TcType
substTy Subst
subst (TcTyVar -> TcType
tyVarKind TcTyVar
tv)

newMetaTyVarTyAtLevel :: TcLevel -> TcKind -> TcM TcType
newMetaTyVarTyAtLevel :: TcLevel -> TcType -> TcM TcType
newMetaTyVarTyAtLevel TcLevel
tc_lvl TcType
kind
  = do  { details <- TcLevel -> TcM TcTyVarDetails
newTauTvDetailsAtLevel TcLevel
tc_lvl
        ; name    <- newMetaTyVarName (fsLit "p")
        ; return (mkTyVarTy (mkTcTyVar name kind details)) }

newConcreteTyVarTyAtLevel :: ConcreteTvOrigin -> TcLevel -> TcKind -> TcM TcType
newConcreteTyVarTyAtLevel :: ConcreteTvOrigin -> TcLevel -> TcType -> TcM TcType
newConcreteTyVarTyAtLevel ConcreteTvOrigin
conc_orig TcLevel
tc_lvl TcType
kind
  = do  { details <- ConcreteTvOrigin -> TcLevel -> TcM TcTyVarDetails
newConcreteTvDetailsAtLevel ConcreteTvOrigin
conc_orig TcLevel
tc_lvl
        ; name    <- newMetaTyVarName (fsLit "c")
        ; return (mkTyVarTy (mkTcTyVar name kind details)) }

{- Note [substConcreteTvOrigin]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
To report helpful representation-polymorphism errors to the users, we want to
indicate which type caused the error, instead of simply printing kinds.
For example, in

  coerce :: forall {r} (a :: TYPE r) (b :: TYPE r). Coercible a b => a -> b

  bad :: forall {s} (z :: TYPE s). z -> z
  bad = coerce

we want the error message to say (with additional debug info on type variables
for clarity of this explanation):

  The first argument of 'coerce' does not have a fixed runtime representation.
  Its type is:
    a0[tau] :: TYPE r0[conc]
  Could not unify s[sk] with r0[conc] because the former is not a concrete
  RuntimeRep.

This is more informative than just saying that we could not unify s[sk] with
r0[conc]; it's helpful to users to phrase it in terms of types rather than kinds
whenever possible (especially as the kind variables often have inferred Specificity).

To achieve this, we store the type on which the representation-polymorphism
check is being performed, in the field frr_type of FixedRuntimeRepOrigin.
This is all described in Note [Reporting representation-polymorphism errors] in
GHC.Tc.Types.Origin.

However, we have to be careful in the example above, in which we are
instantiating a built-in representation-polymorphic 'Id'. As described in the
Note [Representation-polymorphism checking built-ins] in GHC.Tc.Gen.Head, in such
cases we end up storing types appearing in the original type of the primop,
which means for the situation above with 'coerce' we end up with a ConcreteTvOrigin
which includes type variables bound in the original type of 'coerce':

  FixedRuntimeRepOrigin
    { frr_type = a[tv] :: TYPE r[tv]
    , frr_context = "first argument of coerce" }

When we instantiate 'coerce' in the previous example, we obtain a substitution

  [ r[tv] |-> r0[conc], a |-> a0 :: TYPE r0[conc] ]

which we need to apply to the 'frr_type' field in order for the type variables
in the error message to match up.
This is done by the call to 'substConcreteTvOrigin' in 'instantiateSigma'.

Wrinkle [Extending the substitution]

  In certain cases, we need to extend the substitution we get from 'instantiateSigma'.
  For example, suppose we have:

    bad2 :: forall {s} (z :: TYPE s). z -> z
    bad2 = coerce @z

  Then 'instantiateSigma' will only instantiate the inferred type variable 'r'
  of 'coerce', as it needs to leave 'a' un-instantiated so that the visible
  type application '@z' makes sense. In this case, we end up with a substitution

    subst:                   [ r[tv] |-> r0[conc] ]
    body_ty:                forall (a :: TYPE r[tv]) (b :: TYPE r[tv]). ...
    substTy subst body_ty:  forall (a' :: TYPE r0[conc]) (b' :: TYPE r0[conc]). ...

  Now, we still want a substitution that maps (a :: TYPE r[tv]) to
  (a' :: TYPE r0[conc]) in order to apply it to the 'frr_type', so that we don't
  mention the un-substed (a :: TYPE r[tv]) in the error message.
  To achieve this, we extend the substitution with the outermost quantified type
  variables in the leftover (partially-instantiated) type using 'substTyVarBndrs'
  to get the full substitution which we use in 'substConcreteTvOrigin'.
-}

substConcreteTvOrigin :: Subst -> Type -> ConcreteTvOrigin -> ConcreteTvOrigin
substConcreteTvOrigin :: Subst -> TcType -> ConcreteTvOrigin -> ConcreteTvOrigin
substConcreteTvOrigin Subst
subst TcType
body_ty (ConcreteFRR FixedRuntimeRepOrigin
frr_orig)
  -- See Note [substConcreteTvOrigin], Wrinkle [Extending the substitution]
  -- for the justification of this extra complication.
  = let subst' :: Subst
subst' = case TcType -> ([TcTyVar], TcType)
splitForAllTyCoVars TcType
body_ty of
                   ([], TcType
_) -> Subst
subst
                   ([TcTyVar]
bndrs, TcType
_) -> (Subst, [TcTyVar]) -> Subst
forall a b. (a, b) -> a
fst ((Subst, [TcTyVar]) -> Subst) -> (Subst, [TcTyVar]) -> Subst
forall a b. (a -> b) -> a -> b
$ HasDebugCallStack => Subst -> [TcTyVar] -> (Subst, [TcTyVar])
Subst -> [TcTyVar] -> (Subst, [TcTyVar])
substTyVarBndrs Subst
subst [TcTyVar]
bndrs
    in FixedRuntimeRepOrigin -> ConcreteTvOrigin
ConcreteFRR (FixedRuntimeRepOrigin -> ConcreteTvOrigin)
-> FixedRuntimeRepOrigin -> ConcreteTvOrigin
forall a b. (a -> b) -> a -> b
$ Subst -> FixedRuntimeRepOrigin -> FixedRuntimeRepOrigin
substFRROrigin Subst
subst' FixedRuntimeRepOrigin
frr_orig

substFRROrigin :: Subst -> FixedRuntimeRepOrigin -> FixedRuntimeRepOrigin
substFRROrigin :: Subst -> FixedRuntimeRepOrigin -> FixedRuntimeRepOrigin
substFRROrigin Subst
subst orig :: FixedRuntimeRepOrigin
orig@(FixedRuntimeRepOrigin { frr_type :: FixedRuntimeRepOrigin -> TcType
frr_type = TcType
ty })
  = FixedRuntimeRepOrigin
orig { frr_type = substTy subst ty }

{- *********************************************************************
*                                                                      *
          Finding variables to quantify over
*                                                                      *
********************************************************************* -}

{- Note [Dependent type variables]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In Haskell type inference we quantify over type variables; but we only
quantify over /kind/ variables when -XPolyKinds is on.  Without -XPolyKinds
we default the kind variables to *.

So, to support this defaulting, and only for that reason, when
collecting the free vars of a type (in candidateQTyVarsOfType and friends),
prior to quantifying, we must keep the type and kind variables separate.

But what does that mean in a system where kind variables /are/ type
variables? It's a fairly arbitrary distinction based on how the
variables appear:

  - "Kind variables" appear in the kind of some other free variable
    or in the kind of a locally quantified type variable
    (forall (a :: kappa). ...) or in the kind of a coercion
    (a |> (co :: kappa1 ~ kappa2)).

     These are the ones we default to * if -XPolyKinds is off

  - "Type variables" are all free vars that are not kind variables

E.g.  In the type    T k (a::k)
      'k' is a kind variable, because it occurs in the kind of 'a',
          even though it also appears at "top level" of the type
      'a' is a type variable, because it doesn't

We gather these variables using a CandidatesQTvs record:
  DV { dv_kvs: Variables free in the kind of a free type variable
               or of a forall-bound type variable
     , dv_tvs: Variables syntactically free in the type }

So:  dv_kvs            are the kind variables of the type
     (dv_tvs - dv_kvs) are the type variable of the type

Note that

* A variable can occur in both.
      T k (x::k)    The first occurrence of k makes it
                    show up in dv_tvs, the second in dv_kvs

* We include any coercion variables in the "dependent",
  "kind-variable" set because we never quantify over them.

* The "kind variables" might depend on each other; e.g
     (k1 :: k2), (k2 :: *)
  The "type variables" do not depend on each other; if
  one did, it'd be classified as a kind variable!

Note [CandidatesQTvs determinism and order]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Determinism: when we quantify over type variables we decide the
  order in which they appear in the final type. Because the order of
  type variables in the type can end up in the interface file and
  affects some optimizations like worker-wrapper, we want this order to
  be deterministic.

  To achieve that we use deterministic sets of variables that can be
  converted to lists in a deterministic order. For more information
  about deterministic sets see Note [Deterministic UniqFM] in GHC.Types.Unique.DFM.

* Order: as well as being deterministic, we use an
  accumulating-parameter style for candidateQTyVarsOfType so that we
  add variables one at a time, left to right.  That means we tend to
  produce the variables in left-to-right order.  This is just to make
  it bit more predictable for the programmer.

Note [Naughty quantification candidates]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider (#14880, dependent/should_compile/T14880-2), suppose
we are trying to generalise this type:

  forall arg. ... (alpha[tau]:arg) ...

We have a metavariable alpha whose kind mentions a skolem variable
bound inside the very type we are generalising.
This can arise while type-checking a user-written type signature
(see the test case for the full code).

We cannot generalise over alpha!  That would produce a type like
  forall {a :: arg}. forall arg. ...blah...
The fact that alpha's kind mentions arg renders it completely
ineligible for generalisation.

However, we are not going to learn any new constraints on alpha,
because its kind isn't even in scope in the outer context (but see Wrinkle).
So alpha is entirely unconstrained.

What then should we do with alpha?  During generalization, every
metavariable is either (A) promoted, (B) generalized, or (C) zapped
(according to Note [Recipe for checking a signature] in GHC.Tc.Gen.HsType).

 * We can't generalise it.
 * We can't promote it, because its kind prevents that
 * We can't simply leave it be, because this type is about to
   go into the typing environment (as the type of some let-bound
   variable, say), and then chaos erupts when we try to instantiate.

Previously, we zapped it to Any. This worked, but it had the unfortunate
effect of causing Any sometimes to appear in error messages. If this
kind of signature happens, the user probably has made a mistake -- no
one really wants Any in their types. So we now error. This must be
a hard error (failure in the monad) to avoid other messages from mentioning
Any.

We do this eager erroring in candidateQTyVars, which always precedes
generalisation, because at that moment we have a clear picture of what
skolems are in scope within the type itself (e.g. that 'forall arg').

This change is inspired by and described in Section 7.2 of "Kind Inference
for Datatypes", POPL'20.

NB: this is all rather similar to, but sadly not the same as
    Note [Error on unconstrained meta-variables]

Wrinkle:

We must make absolutely sure that alpha indeed is not from an outer
context. (Otherwise, we might indeed learn more information about it.)
This can be done easily: we just check alpha's TcLevel.  That level
must be strictly greater than the ambient TcLevel in order to treat it
as naughty. We say "strictly greater than" because the call to
candidateQTyVars is made outside the bumped TcLevel, as stated in the
comment to candidateQTyVarsOfType. The level check is done in go_tv in
collect_cand_qtvs. Skipping this check caused #16517.

-}

data CandidatesQTvs
  -- See Note [Dependent type variables]
  -- See Note [CandidatesQTvs determinism and order]
  --
  -- Invariants:
  --   * All variables are fully zonked, including their kinds
  --   * All variables are at a level greater than the ambient level
  --     See Note [Use level numbers for quantification]
  --
  -- This *can* contain skolems. For example, in `data X k :: k -> Type`
  -- we need to know that the k is a dependent variable. This is done
  -- by collecting the candidates in the kind after skolemising. It also
  -- comes up when generalizing a associated type instance, where instance
  -- variables are skolems. (Recall that associated type instances are generalized
  -- independently from their enclosing class instance, and the associated
  -- type instance may be generalized by more, fewer, or different variables
  -- than the class instance.)
  --
  = DV { CandidatesQTvs -> DTyVarSet
dv_kvs :: DTyVarSet    -- "kind" metavariables (dependent)
       , CandidatesQTvs -> DTyVarSet
dv_tvs :: DTyVarSet    -- "type" metavariables (non-dependent)
         -- A variable may appear in both sets
         -- E.g.   T k (x::k)    The first occurrence of k makes it
         --                      show up in dv_tvs, the second in dv_kvs
         -- See Note [Dependent type variables]

       , CandidatesQTvs -> CoVarSet
dv_cvs :: CoVarSet
         -- These are covars. Included only so that we don't repeatedly
         -- look at covars' kinds in accumulator. Not used by quantifyTyVars.
    }

instance Semi.Semigroup CandidatesQTvs where
   (DV { dv_kvs :: CandidatesQTvs -> DTyVarSet
dv_kvs = DTyVarSet
kv1, dv_tvs :: CandidatesQTvs -> DTyVarSet
dv_tvs = DTyVarSet
tv1, dv_cvs :: CandidatesQTvs -> CoVarSet
dv_cvs = CoVarSet
cv1 })
     <> :: CandidatesQTvs -> CandidatesQTvs -> CandidatesQTvs
<> (DV { dv_kvs :: CandidatesQTvs -> DTyVarSet
dv_kvs = DTyVarSet
kv2, dv_tvs :: CandidatesQTvs -> DTyVarSet
dv_tvs = DTyVarSet
tv2, dv_cvs :: CandidatesQTvs -> CoVarSet
dv_cvs = CoVarSet
cv2 })
          = DV { dv_kvs :: DTyVarSet
dv_kvs = DTyVarSet
kv1 DTyVarSet -> DTyVarSet -> DTyVarSet
`unionDVarSet` DTyVarSet
kv2
               , dv_tvs :: DTyVarSet
dv_tvs = DTyVarSet
tv1 DTyVarSet -> DTyVarSet -> DTyVarSet
`unionDVarSet` DTyVarSet
tv2
               , dv_cvs :: CoVarSet
dv_cvs = CoVarSet
cv1 CoVarSet -> CoVarSet -> CoVarSet
`unionVarSet` CoVarSet
cv2 }

instance Monoid CandidatesQTvs where
   mempty :: CandidatesQTvs
mempty = DV { dv_kvs :: DTyVarSet
dv_kvs = DTyVarSet
emptyDVarSet, dv_tvs :: DTyVarSet
dv_tvs = DTyVarSet
emptyDVarSet, dv_cvs :: CoVarSet
dv_cvs = CoVarSet
emptyVarSet }
   mappend :: CandidatesQTvs -> CandidatesQTvs -> CandidatesQTvs
mappend = CandidatesQTvs -> CandidatesQTvs -> CandidatesQTvs
forall a. Semigroup a => a -> a -> a
(Semi.<>)

instance Outputable CandidatesQTvs where
  ppr :: CandidatesQTvs -> SDoc
ppr (DV {dv_kvs :: CandidatesQTvs -> DTyVarSet
dv_kvs = DTyVarSet
kvs, dv_tvs :: CandidatesQTvs -> DTyVarSet
dv_tvs = DTyVarSet
tvs, dv_cvs :: CandidatesQTvs -> CoVarSet
dv_cvs = CoVarSet
cvs })
    = String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"DV" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc
braces ((SDoc -> SDoc) -> [SDoc] -> SDoc
forall a. (a -> SDoc) -> [a] -> SDoc
pprWithCommas SDoc -> SDoc
forall a. a -> a
id [ String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"dv_kvs =" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> DTyVarSet -> SDoc
forall a. Outputable a => a -> SDoc
ppr DTyVarSet
kvs
                                             , String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"dv_tvs =" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> DTyVarSet -> SDoc
forall a. Outputable a => a -> SDoc
ppr DTyVarSet
tvs
                                             , String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"dv_cvs =" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> CoVarSet -> SDoc
forall a. Outputable a => a -> SDoc
ppr CoVarSet
cvs ])

isEmptyCandidates :: CandidatesQTvs -> Bool
isEmptyCandidates :: CandidatesQTvs -> Bool
isEmptyCandidates (DV { dv_kvs :: CandidatesQTvs -> DTyVarSet
dv_kvs = DTyVarSet
kvs, dv_tvs :: CandidatesQTvs -> DTyVarSet
dv_tvs = DTyVarSet
tvs })
  = DTyVarSet -> Bool
isEmptyDVarSet DTyVarSet
kvs Bool -> Bool -> Bool
&& DTyVarSet -> Bool
isEmptyDVarSet DTyVarSet
tvs

-- | Extract out the kind vars (in order) and type vars (in order) from
-- a 'CandidatesQTvs'. The lists are guaranteed to be distinct. Keeping
-- the lists separate is important only in the -XNoPolyKinds case.
candidateVars :: CandidatesQTvs -> ([TcTyVar], [TcTyVar])
candidateVars :: CandidatesQTvs -> ([TcTyVar], [TcTyVar])
candidateVars (DV { dv_kvs :: CandidatesQTvs -> DTyVarSet
dv_kvs = DTyVarSet
dep_kv_set, dv_tvs :: CandidatesQTvs -> DTyVarSet
dv_tvs = DTyVarSet
nondep_tkv_set })
  = ([TcTyVar]
dep_kvs, [TcTyVar]
nondep_tvs)
  where
    dep_kvs :: [TcTyVar]
dep_kvs = [TcTyVar] -> [TcTyVar]
scopedSort ([TcTyVar] -> [TcTyVar]) -> [TcTyVar] -> [TcTyVar]
forall a b. (a -> b) -> a -> b
$ DTyVarSet -> [TcTyVar]
dVarSetElems DTyVarSet
dep_kv_set
      -- scopedSort: put the kind variables into
      --    well-scoped order.
      --    E.g.  [k, (a::k)] not the other way round

    nondep_tvs :: [TcTyVar]
nondep_tvs = DTyVarSet -> [TcTyVar]
dVarSetElems (DTyVarSet
nondep_tkv_set DTyVarSet -> DTyVarSet -> DTyVarSet
`minusDVarSet` DTyVarSet
dep_kv_set)
      -- See Note [Dependent type variables]
      -- The `minus` dep_tkvs removes any kind-level vars
      --    e.g. T k (a::k)   Since k appear in a kind it'll
      --    be in dv_kvs, and is dependent. So remove it from
      --    dv_tvs which will also contain k
      -- NB kinds of tvs are already zonked

candidateKindVars :: CandidatesQTvs -> TyVarSet
candidateKindVars :: CandidatesQTvs -> CoVarSet
candidateKindVars CandidatesQTvs
dvs = DTyVarSet -> CoVarSet
dVarSetToVarSet (CandidatesQTvs -> DTyVarSet
dv_kvs CandidatesQTvs
dvs)

delCandidates :: CandidatesQTvs -> [Var] -> CandidatesQTvs
delCandidates :: CandidatesQTvs -> [TcTyVar] -> CandidatesQTvs
delCandidates (DV { dv_kvs :: CandidatesQTvs -> DTyVarSet
dv_kvs = DTyVarSet
kvs, dv_tvs :: CandidatesQTvs -> DTyVarSet
dv_tvs = DTyVarSet
tvs, dv_cvs :: CandidatesQTvs -> CoVarSet
dv_cvs = CoVarSet
cvs }) [TcTyVar]
vars
  = DV { dv_kvs :: DTyVarSet
dv_kvs = DTyVarSet
kvs DTyVarSet -> [TcTyVar] -> DTyVarSet
`delDVarSetList` [TcTyVar]
vars
       , dv_tvs :: DTyVarSet
dv_tvs = DTyVarSet
tvs DTyVarSet -> [TcTyVar] -> DTyVarSet
`delDVarSetList` [TcTyVar]
vars
       , dv_cvs :: CoVarSet
dv_cvs = CoVarSet
cvs CoVarSet -> [TcTyVar] -> CoVarSet
`delVarSetList`  [TcTyVar]
vars }

partitionCandidates :: CandidatesQTvs -> (TyVar -> Bool) -> (TyVarSet, CandidatesQTvs)
-- The selected TyVars are returned as a non-deterministic TyVarSet
partitionCandidates :: CandidatesQTvs -> (TcTyVar -> Bool) -> (CoVarSet, CandidatesQTvs)
partitionCandidates dvs :: CandidatesQTvs
dvs@(DV { dv_kvs :: CandidatesQTvs -> DTyVarSet
dv_kvs = DTyVarSet
kvs, dv_tvs :: CandidatesQTvs -> DTyVarSet
dv_tvs = DTyVarSet
tvs }) TcTyVar -> Bool
pred
  = (CoVarSet
extracted, CandidatesQTvs
dvs { dv_kvs = rest_kvs, dv_tvs = rest_tvs })
  where
    (DTyVarSet
extracted_kvs, DTyVarSet
rest_kvs) = (TcTyVar -> Bool) -> DTyVarSet -> (DTyVarSet, DTyVarSet)
partitionDVarSet TcTyVar -> Bool
pred DTyVarSet
kvs
    (DTyVarSet
extracted_tvs, DTyVarSet
rest_tvs) = (TcTyVar -> Bool) -> DTyVarSet -> (DTyVarSet, DTyVarSet)
partitionDVarSet TcTyVar -> Bool
pred DTyVarSet
tvs
    extracted :: CoVarSet
extracted = DTyVarSet -> CoVarSet
dVarSetToVarSet DTyVarSet
extracted_kvs CoVarSet -> CoVarSet -> CoVarSet
`unionVarSet` DTyVarSet -> CoVarSet
dVarSetToVarSet DTyVarSet
extracted_tvs

candidateQTyVarsWithBinders :: [TyVar] -> Type -> TcM CandidatesQTvs
-- (candidateQTyVarsWithBinders tvs ty) returns the candidateQTyVars
-- of (forall tvs. ty), but do not treat 'tvs' as bound for the purpose
-- of Note [Naughty quantification candidates].  Why?
-- Because we are going to scoped-sort the quantified variables
-- in among the tvs
candidateQTyVarsWithBinders :: [TcTyVar] -> TcType -> TcM CandidatesQTvs
candidateQTyVarsWithBinders [TcTyVar]
bound_tvs TcType
ty
  = do { kvs     <- [TcType] -> TcM CandidatesQTvs
candidateQTyVarsOfKinds ((TcTyVar -> TcType) -> [TcTyVar] -> [TcType]
forall a b. (a -> b) -> [a] -> [b]
map TcTyVar -> TcType
tyVarKind [TcTyVar]
bound_tvs)
       ; cur_lvl <- getTcLevel
       ; all_tvs <- collect_cand_qtvs ty False cur_lvl emptyVarSet kvs ty
       ; return (all_tvs `delCandidates` bound_tvs) }

-- | Gathers free variables to use as quantification candidates (in
-- 'quantifyTyVars'). This might output the same var
-- in both sets, if it's used in both a type and a kind.
-- The variables to quantify must have a TcLevel strictly greater than
-- the ambient level. (See Wrinkle in Note [Naughty quantification candidates])
-- See Note [CandidatesQTvs determinism and order]
-- See Note [Dependent type variables]
candidateQTyVarsOfType :: TcType       -- not necessarily zonked
                       -> TcM CandidatesQTvs
candidateQTyVarsOfType :: TcType -> TcM CandidatesQTvs
candidateQTyVarsOfType TcType
ty
  = do { cur_lvl <- TcM TcLevel
getTcLevel
       ; collect_cand_qtvs ty False cur_lvl emptyVarSet mempty ty }

-- | Like 'candidateQTyVarsOfType', but over a list of types
-- The variables to quantify must have a TcLevel strictly greater than
-- the ambient level. (See Wrinkle in Note [Naughty quantification candidates])
candidateQTyVarsOfTypes :: [Type] -> TcM CandidatesQTvs
candidateQTyVarsOfTypes :: [TcType] -> TcM CandidatesQTvs
candidateQTyVarsOfTypes [TcType]
tys
  = do { cur_lvl <- TcM TcLevel
getTcLevel
       ; foldlM (\CandidatesQTvs
acc TcType
ty -> TcType
-> Bool
-> TcLevel
-> CoVarSet
-> CandidatesQTvs
-> TcType
-> TcM CandidatesQTvs
collect_cand_qtvs TcType
ty Bool
False TcLevel
cur_lvl CoVarSet
emptyVarSet CandidatesQTvs
acc TcType
ty)
                mempty tys }

-- | Like 'candidateQTyVarsOfType', but consider every free variable
-- to be dependent. This is appropriate when generalizing a *kind*,
-- instead of a type. (That way, -XNoPolyKinds will default the variables
-- to Type.)
candidateQTyVarsOfKind :: TcKind       -- Not necessarily zonked
                       -> TcM CandidatesQTvs
candidateQTyVarsOfKind :: TcType -> TcM CandidatesQTvs
candidateQTyVarsOfKind TcType
ty
  = do { cur_lvl <- TcM TcLevel
getTcLevel
       ; collect_cand_qtvs ty True cur_lvl emptyVarSet mempty ty }

candidateQTyVarsOfKinds :: [TcKind]    -- Not necessarily zonked
                       -> TcM CandidatesQTvs
candidateQTyVarsOfKinds :: [TcType] -> TcM CandidatesQTvs
candidateQTyVarsOfKinds [TcType]
tys
  = do { cur_lvl <- TcM TcLevel
getTcLevel
       ; foldM (\CandidatesQTvs
acc TcType
ty -> TcType
-> Bool
-> TcLevel
-> CoVarSet
-> CandidatesQTvs
-> TcType
-> TcM CandidatesQTvs
collect_cand_qtvs TcType
ty Bool
True TcLevel
cur_lvl CoVarSet
emptyVarSet CandidatesQTvs
acc TcType
ty)
               mempty tys }

collect_cand_qtvs
  :: TcType          -- Original type that we started recurring into; for errors
  -> Bool            -- True <=> consider every fv in Type to be dependent
  -> TcLevel         -- Current TcLevel; collect only tyvars whose level is greater
  -> VarSet          -- Bound variables (locals only)
  -> CandidatesQTvs  -- Accumulating parameter
  -> Type            -- Not necessarily zonked
  -> TcM CandidatesQTvs

-- Key points:
--   * Looks through meta-tyvars as it goes;
--     no need to zonk in advance
--
--   * Needs to be monadic anyway, because it handles naughty
--     quantification; see Note [Naughty quantification candidates]
--
--   * Returns fully-zonked CandidateQTvs, including their kinds
--     so that subsequent dependency analysis (to build a well
--     scoped telescope) works correctly

collect_cand_qtvs :: TcType
-> Bool
-> TcLevel
-> CoVarSet
-> CandidatesQTvs
-> TcType
-> TcM CandidatesQTvs
collect_cand_qtvs TcType
orig_ty Bool
is_dep TcLevel
cur_lvl CoVarSet
bound CandidatesQTvs
dvs TcType
ty
  = CandidatesQTvs -> TcType -> TcM CandidatesQTvs
go CandidatesQTvs
dvs TcType
ty
  where
    is_bound :: TcTyVar -> Bool
is_bound TcTyVar
tv = TcTyVar
tv TcTyVar -> CoVarSet -> Bool
`elemVarSet` CoVarSet
bound

    -----------------
    go :: CandidatesQTvs -> TcType -> TcM CandidatesQTvs
    -- Uses accumulating-parameter style
    go :: CandidatesQTvs -> TcType -> TcM CandidatesQTvs
go CandidatesQTvs
dv (AppTy TcType
t1 TcType
t2)       = (CandidatesQTvs -> TcType -> TcM CandidatesQTvs)
-> CandidatesQTvs -> [TcType] -> TcM CandidatesQTvs
forall (t :: * -> *) (m :: * -> *) b a.
(Foldable t, Monad m) =>
(b -> a -> m b) -> b -> t a -> m b
foldlM CandidatesQTvs -> TcType -> TcM CandidatesQTvs
go CandidatesQTvs
dv [TcType
t1, TcType
t2]
    go CandidatesQTvs
dv (TyConApp TyCon
tc [TcType]
tys)   = CandidatesQTvs -> [TyConBinder] -> [TcType] -> TcM CandidatesQTvs
go_tc_args CandidatesQTvs
dv (TyCon -> [TyConBinder]
tyConBinders TyCon
tc) [TcType]
tys
    go CandidatesQTvs
dv (FunTy FunTyFlag
_ TcType
w TcType
arg TcType
res) = (CandidatesQTvs -> TcType -> TcM CandidatesQTvs)
-> CandidatesQTvs -> [TcType] -> TcM CandidatesQTvs
forall (t :: * -> *) (m :: * -> *) b a.
(Foldable t, Monad m) =>
(b -> a -> m b) -> b -> t a -> m b
foldlM CandidatesQTvs -> TcType -> TcM CandidatesQTvs
go CandidatesQTvs
dv [TcType
w, TcType
arg, TcType
res]
    go CandidatesQTvs
dv (LitTy {})          = CandidatesQTvs -> TcM CandidatesQTvs
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return CandidatesQTvs
dv
    go CandidatesQTvs
dv (CastTy TcType
ty Coercion
co)      = do { dv1 <- CandidatesQTvs -> TcType -> TcM CandidatesQTvs
go CandidatesQTvs
dv TcType
ty
                                   ; collect_cand_qtvs_co orig_ty cur_lvl bound dv1 co }
    go CandidatesQTvs
dv (CoercionTy Coercion
co)     = TcType
-> TcLevel
-> CoVarSet
-> CandidatesQTvs
-> Coercion
-> TcM CandidatesQTvs
collect_cand_qtvs_co TcType
orig_ty TcLevel
cur_lvl CoVarSet
bound CandidatesQTvs
dv Coercion
co

    go CandidatesQTvs
dv (TyVarTy TcTyVar
tv)
      | TcTyVar -> Bool
is_bound TcTyVar
tv = CandidatesQTvs -> TcM CandidatesQTvs
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return CandidatesQTvs
dv
      | Bool
otherwise   = do { m_contents <- TcTyVar -> IOEnv (Env TcGblEnv TcLclEnv) (Maybe TcType)
isFilledMetaTyVar_maybe TcTyVar
tv
                         ; case m_contents of
                             Just TcType
ind_ty -> CandidatesQTvs -> TcType -> TcM CandidatesQTvs
go CandidatesQTvs
dv TcType
ind_ty
                             Maybe TcType
Nothing     -> CandidatesQTvs -> TcTyVar -> TcM CandidatesQTvs
go_tv CandidatesQTvs
dv TcTyVar
tv }

    go CandidatesQTvs
dv (ForAllTy (Bndr TcTyVar
tv ForAllTyFlag
_) TcType
ty)
      = do { dv1 <- TcType
-> Bool
-> TcLevel
-> CoVarSet
-> CandidatesQTvs
-> TcType
-> TcM CandidatesQTvs
collect_cand_qtvs TcType
orig_ty Bool
True TcLevel
cur_lvl CoVarSet
bound CandidatesQTvs
dv (TcTyVar -> TcType
tyVarKind TcTyVar
tv)
           ; collect_cand_qtvs orig_ty is_dep cur_lvl (bound `extendVarSet` tv) dv1 ty }

      -- This makes sure that we default e.g. the alpha in Proxy alpha (Any alpha).
      -- Tested in polykinds/NestedProxies.
      -- We just might get this wrong in AppTy, but I don't think that's possible
      -- with -XNoPolyKinds. And fixing it would be non-performant, as we'd need
      -- to look at kinds.
    go_tc_args :: CandidatesQTvs -> [TyConBinder] -> [TcType] -> TcM CandidatesQTvs
go_tc_args CandidatesQTvs
dv (TyConBinder
tc_bndr:[TyConBinder]
tc_bndrs) (TcType
ty:[TcType]
tys)
      = do { dv1 <- TcType
-> Bool
-> TcLevel
-> CoVarSet
-> CandidatesQTvs
-> TcType
-> TcM CandidatesQTvs
collect_cand_qtvs TcType
orig_ty (Bool
is_dep Bool -> Bool -> Bool
|| TyConBinder -> Bool
isNamedTyConBinder TyConBinder
tc_bndr)
                                      TcLevel
cur_lvl CoVarSet
bound CandidatesQTvs
dv TcType
ty
           ; go_tc_args dv1 tc_bndrs tys }
    go_tc_args CandidatesQTvs
dv [TyConBinder]
_bndrs [TcType]
tys  -- _bndrs might be non-empty: undersaturation
                              -- tys might be non-empty: oversaturation
                              -- either way, the foldlM is correct
      = (CandidatesQTvs -> TcType -> TcM CandidatesQTvs)
-> CandidatesQTvs -> [TcType] -> TcM CandidatesQTvs
forall (t :: * -> *) (m :: * -> *) b a.
(Foldable t, Monad m) =>
(b -> a -> m b) -> b -> t a -> m b
foldlM CandidatesQTvs -> TcType -> TcM CandidatesQTvs
go CandidatesQTvs
dv [TcType]
tys

    -----------------
    go_tv :: CandidatesQTvs -> TcTyVar -> TcM CandidatesQTvs
go_tv dv :: CandidatesQTvs
dv@(DV { dv_kvs :: CandidatesQTvs -> DTyVarSet
dv_kvs = DTyVarSet
kvs, dv_tvs :: CandidatesQTvs -> DTyVarSet
dv_tvs = DTyVarSet
tvs }) TcTyVar
tv
      | TcTyVar -> TcLevel
tcTyVarLevel TcTyVar
tv TcLevel -> TcLevel -> Bool
forall a. Ord a => a -> a -> Bool
<= TcLevel
cur_lvl
      = CandidatesQTvs -> TcM CandidatesQTvs
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return CandidatesQTvs
dv   -- This variable is from an outer context; skip
                    -- See Note [Use level numbers for quantification]

      | case TcTyVar -> TcTyVarDetails
tcTyVarDetails TcTyVar
tv of
          SkolemTv SkolemInfo
_ TcLevel
lvl Bool
_ -> TcLevel
lvl TcLevel -> TcLevel -> Bool
forall a. Ord a => a -> a -> Bool
> TcLevel -> TcLevel
pushTcLevel TcLevel
cur_lvl
          TcTyVarDetails
_                -> Bool
False
      = CandidatesQTvs -> TcM CandidatesQTvs
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return CandidatesQTvs
dv  -- Skip inner skolems
        -- This only happens for erroneous program with bad telescopes
        -- e.g. BadTelescope2:  forall a k (b :: k). SameKind a b
        --      We have (a::k), and at the outer we don't want to quantify
        --      over the already-quantified skolem k.
        -- (Apparently we /do/ want to quantify over skolems whose level sk_lvl is
        -- sk_lvl > cur_lvl; you get lots of failures otherwise. A battle for another day.)

      | TcTyVar
tv TcTyVar -> DTyVarSet -> Bool
`elemDVarSet` DTyVarSet
kvs
      = CandidatesQTvs -> TcM CandidatesQTvs
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return CandidatesQTvs
dv  -- We have met this tyvar already

      | Bool -> Bool
not Bool
is_dep
      , TcTyVar
tv TcTyVar -> DTyVarSet -> Bool
`elemDVarSet` DTyVarSet
tvs
      = CandidatesQTvs -> TcM CandidatesQTvs
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return CandidatesQTvs
dv  -- We have met this tyvar already

      | Bool
otherwise
      = do { tv_kind <- ZonkM TcType -> TcM TcType
forall a. ZonkM a -> TcM a
liftZonkM (ZonkM TcType -> TcM TcType) -> ZonkM TcType -> TcM TcType
forall a b. (a -> b) -> a -> b
$ TcType -> ZonkM TcType
zonkTcType (TcTyVar -> TcType
tyVarKind TcTyVar
tv)
                 -- This zonk is annoying, but it is necessary, both to
                 -- ensure that the collected candidates have zonked kinds
                 -- (#15795) and to make the naughty check
                 -- (which comes next) works correctly

           ; let tv_kind_vars = TcType -> CoVarSet
tyCoVarsOfType TcType
tv_kind
           ; if | intersectsVarSet bound tv_kind_vars
                   -- the tyvar must not be from an outer context, but we have
                   -- already checked for this.
                   -- See Note [Naughty quantification candidates]
                -> do { traceTc "Naughty quantifier" $
                          vcat [ ppr tv <+> dcolon <+> ppr tv_kind
                               , text "bound:" <+> pprTyVars (nonDetEltsUniqSet bound)
                               , text "fvs:" <+> pprTyVars (nonDetEltsUniqSet tv_kind_vars) ]

                      ; let escapees = CoVarSet -> CoVarSet -> CoVarSet
intersectVarSet CoVarSet
bound CoVarSet
tv_kind_vars
                      ; naughtyQuantification orig_ty tv escapees }

                |  otherwise
                -> do { let tv' = TcTyVar
tv TcTyVar -> TcType -> TcTyVar
`setTyVarKind` TcType
tv_kind
                            dv' | Bool
is_dep    = CandidatesQTvs
dv { dv_kvs = kvs `extendDVarSet` tv' }
                                | Bool
otherwise = CandidatesQTvs
dv { dv_tvs = tvs `extendDVarSet` tv' }
                                -- See Note [Order of accumulation]

                        -- See Note [Recurring into kinds for candidateQTyVars]
                      ; collect_cand_qtvs orig_ty True cur_lvl bound dv' tv_kind } }

collect_cand_qtvs_co :: TcType -- original type at top of recursion; for errors
                     -> TcLevel
                     -> VarSet -- bound variables
                     -> CandidatesQTvs -> Coercion
                     -> TcM CandidatesQTvs
collect_cand_qtvs_co :: TcType
-> TcLevel
-> CoVarSet
-> CandidatesQTvs
-> Coercion
-> TcM CandidatesQTvs
collect_cand_qtvs_co TcType
orig_ty TcLevel
cur_lvl CoVarSet
bound = CandidatesQTvs -> Coercion -> TcM CandidatesQTvs
go_co
  where
    go_co :: CandidatesQTvs -> Coercion -> TcM CandidatesQTvs
go_co CandidatesQTvs
dv (Refl TcType
ty)               = TcType
-> Bool
-> TcLevel
-> CoVarSet
-> CandidatesQTvs
-> TcType
-> TcM CandidatesQTvs
collect_cand_qtvs TcType
orig_ty Bool
True TcLevel
cur_lvl CoVarSet
bound CandidatesQTvs
dv TcType
ty
    go_co CandidatesQTvs
dv (GRefl Role
_ TcType
ty MCoercionN
mco)        = do { dv1 <- TcType
-> Bool
-> TcLevel
-> CoVarSet
-> CandidatesQTvs
-> TcType
-> TcM CandidatesQTvs
collect_cand_qtvs TcType
orig_ty Bool
True TcLevel
cur_lvl CoVarSet
bound CandidatesQTvs
dv TcType
ty
                                          ; go_mco dv1 mco }
    go_co CandidatesQTvs
dv (TyConAppCo Role
_ TyCon
_ [Coercion]
cos)    = (CandidatesQTvs -> Coercion -> TcM CandidatesQTvs)
-> CandidatesQTvs -> [Coercion] -> TcM CandidatesQTvs
forall (t :: * -> *) (m :: * -> *) b a.
(Foldable t, Monad m) =>
(b -> a -> m b) -> b -> t a -> m b
foldlM CandidatesQTvs -> Coercion -> TcM CandidatesQTvs
go_co CandidatesQTvs
dv [Coercion]
cos
    go_co CandidatesQTvs
dv (AppCo Coercion
co1 Coercion
co2)         = (CandidatesQTvs -> Coercion -> TcM CandidatesQTvs)
-> CandidatesQTvs -> [Coercion] -> TcM CandidatesQTvs
forall (t :: * -> *) (m :: * -> *) b a.
(Foldable t, Monad m) =>
(b -> a -> m b) -> b -> t a -> m b
foldlM CandidatesQTvs -> Coercion -> TcM CandidatesQTvs
go_co CandidatesQTvs
dv [Coercion
co1, Coercion
co2]
    go_co CandidatesQTvs
dv (FunCo Role
_ FunTyFlag
_ FunTyFlag
_ Coercion
w Coercion
co1 Coercion
co2) = (CandidatesQTvs -> Coercion -> TcM CandidatesQTvs)
-> CandidatesQTvs -> [Coercion] -> TcM CandidatesQTvs
forall (t :: * -> *) (m :: * -> *) b a.
(Foldable t, Monad m) =>
(b -> a -> m b) -> b -> t a -> m b
foldlM CandidatesQTvs -> Coercion -> TcM CandidatesQTvs
go_co CandidatesQTvs
dv [Coercion
w, Coercion
co1, Coercion
co2]
    go_co CandidatesQTvs
dv (AxiomInstCo CoAxiom Branched
_ Int
_ [Coercion]
cos)   = (CandidatesQTvs -> Coercion -> TcM CandidatesQTvs)
-> CandidatesQTvs -> [Coercion] -> TcM CandidatesQTvs
forall (t :: * -> *) (m :: * -> *) b a.
(Foldable t, Monad m) =>
(b -> a -> m b) -> b -> t a -> m b
foldlM CandidatesQTvs -> Coercion -> TcM CandidatesQTvs
go_co CandidatesQTvs
dv [Coercion]
cos
    go_co CandidatesQTvs
dv (AxiomRuleCo CoAxiomRule
_ [Coercion]
cos)     = (CandidatesQTvs -> Coercion -> TcM CandidatesQTvs)
-> CandidatesQTvs -> [Coercion] -> TcM CandidatesQTvs
forall (t :: * -> *) (m :: * -> *) b a.
(Foldable t, Monad m) =>
(b -> a -> m b) -> b -> t a -> m b
foldlM CandidatesQTvs -> Coercion -> TcM CandidatesQTvs
go_co CandidatesQTvs
dv [Coercion]
cos
    go_co CandidatesQTvs
dv (UnivCo UnivCoProvenance
prov Role
_ TcType
t1 TcType
t2)   = do { dv1 <- CandidatesQTvs -> UnivCoProvenance -> TcM CandidatesQTvs
go_prov CandidatesQTvs
dv UnivCoProvenance
prov
                                          ; dv2 <- collect_cand_qtvs orig_ty True cur_lvl bound dv1 t1
                                          ; collect_cand_qtvs orig_ty True cur_lvl bound dv2 t2 }
    go_co CandidatesQTvs
dv (SymCo Coercion
co)              = CandidatesQTvs -> Coercion -> TcM CandidatesQTvs
go_co CandidatesQTvs
dv Coercion
co
    go_co CandidatesQTvs
dv (TransCo Coercion
co1 Coercion
co2)       = (CandidatesQTvs -> Coercion -> TcM CandidatesQTvs)
-> CandidatesQTvs -> [Coercion] -> TcM CandidatesQTvs
forall (t :: * -> *) (m :: * -> *) b a.
(Foldable t, Monad m) =>
(b -> a -> m b) -> b -> t a -> m b
foldlM CandidatesQTvs -> Coercion -> TcM CandidatesQTvs
go_co CandidatesQTvs
dv [Coercion
co1, Coercion
co2]
    go_co CandidatesQTvs
dv (SelCo CoSel
_ Coercion
co)            = CandidatesQTvs -> Coercion -> TcM CandidatesQTvs
go_co CandidatesQTvs
dv Coercion
co
    go_co CandidatesQTvs
dv (LRCo LeftOrRight
_ Coercion
co)             = CandidatesQTvs -> Coercion -> TcM CandidatesQTvs
go_co CandidatesQTvs
dv Coercion
co
    go_co CandidatesQTvs
dv (InstCo Coercion
co1 Coercion
co2)        = (CandidatesQTvs -> Coercion -> TcM CandidatesQTvs)
-> CandidatesQTvs -> [Coercion] -> TcM CandidatesQTvs
forall (t :: * -> *) (m :: * -> *) b a.
(Foldable t, Monad m) =>
(b -> a -> m b) -> b -> t a -> m b
foldlM CandidatesQTvs -> Coercion -> TcM CandidatesQTvs
go_co CandidatesQTvs
dv [Coercion
co1, Coercion
co2]
    go_co CandidatesQTvs
dv (KindCo Coercion
co)             = CandidatesQTvs -> Coercion -> TcM CandidatesQTvs
go_co CandidatesQTvs
dv Coercion
co
    go_co CandidatesQTvs
dv (SubCo Coercion
co)              = CandidatesQTvs -> Coercion -> TcM CandidatesQTvs
go_co CandidatesQTvs
dv Coercion
co

    go_co CandidatesQTvs
dv (HoleCo CoercionHole
hole)
      = do m_co <- CoercionHole -> IOEnv (Env TcGblEnv TcLclEnv) (Maybe Coercion)
unpackCoercionHole_maybe CoercionHole
hole
           case m_co of
             Just Coercion
co -> CandidatesQTvs -> Coercion -> TcM CandidatesQTvs
go_co CandidatesQTvs
dv Coercion
co
             Maybe Coercion
Nothing -> CandidatesQTvs -> TcTyVar -> TcM CandidatesQTvs
go_cv CandidatesQTvs
dv (CoercionHole -> TcTyVar
coHoleCoVar CoercionHole
hole)

    go_co CandidatesQTvs
dv (CoVarCo TcTyVar
cv) = CandidatesQTvs -> TcTyVar -> TcM CandidatesQTvs
go_cv CandidatesQTvs
dv TcTyVar
cv

    go_co CandidatesQTvs
dv (ForAllCo { fco_tcv :: Coercion -> TcTyVar
fco_tcv = TcTyVar
tcv, fco_kind :: Coercion -> Coercion
fco_kind = Coercion
kind_co, fco_body :: Coercion -> Coercion
fco_body = Coercion
co })
      = do { dv1 <- CandidatesQTvs -> Coercion -> TcM CandidatesQTvs
go_co CandidatesQTvs
dv Coercion
kind_co
           ; collect_cand_qtvs_co orig_ty cur_lvl (bound `extendVarSet` tcv) dv1 co }

    go_mco :: CandidatesQTvs -> MCoercionN -> TcM CandidatesQTvs
go_mco CandidatesQTvs
dv MCoercionN
MRefl    = CandidatesQTvs -> TcM CandidatesQTvs
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return CandidatesQTvs
dv
    go_mco CandidatesQTvs
dv (MCo Coercion
co) = CandidatesQTvs -> Coercion -> TcM CandidatesQTvs
go_co CandidatesQTvs
dv Coercion
co

    go_prov :: CandidatesQTvs -> UnivCoProvenance -> TcM CandidatesQTvs
go_prov CandidatesQTvs
dv (PhantomProv Coercion
co)    = CandidatesQTvs -> Coercion -> TcM CandidatesQTvs
go_co CandidatesQTvs
dv Coercion
co
    go_prov CandidatesQTvs
dv (ProofIrrelProv Coercion
co) = CandidatesQTvs -> Coercion -> TcM CandidatesQTvs
go_co CandidatesQTvs
dv Coercion
co
    go_prov CandidatesQTvs
dv (PluginProv String
_)      = CandidatesQTvs -> TcM CandidatesQTvs
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return CandidatesQTvs
dv

    go_cv :: CandidatesQTvs -> CoVar -> TcM CandidatesQTvs
    go_cv :: CandidatesQTvs -> TcTyVar -> TcM CandidatesQTvs
go_cv dv :: CandidatesQTvs
dv@(DV { dv_cvs :: CandidatesQTvs -> CoVarSet
dv_cvs = CoVarSet
cvs }) TcTyVar
cv
      | TcTyVar -> Bool
is_bound TcTyVar
cv         = CandidatesQTvs -> TcM CandidatesQTvs
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return CandidatesQTvs
dv
      | TcTyVar
cv TcTyVar -> CoVarSet -> Bool
`elemVarSet` CoVarSet
cvs = CandidatesQTvs -> TcM CandidatesQTvs
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return CandidatesQTvs
dv

        -- See Note [Recurring into kinds for candidateQTyVars]
      | Bool
otherwise           = TcType
-> Bool
-> TcLevel
-> CoVarSet
-> CandidatesQTvs
-> TcType
-> TcM CandidatesQTvs
collect_cand_qtvs TcType
orig_ty Bool
True TcLevel
cur_lvl CoVarSet
bound
                                    (CandidatesQTvs
dv { dv_cvs = cvs `extendVarSet` cv })
                                    (TcTyVar -> TcType
idType TcTyVar
cv)

    is_bound :: TcTyVar -> Bool
is_bound TcTyVar
tv = TcTyVar
tv TcTyVar -> CoVarSet -> Bool
`elemVarSet` CoVarSet
bound

{- Note [Order of accumulation]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
You might be tempted (like I was) to use unitDVarSet and mappend
rather than extendDVarSet.  However, the union algorithm for
deterministic sets depends on (roughly) the size of the sets. The
elements from the smaller set end up to the right of the elements from
the larger one. When sets are equal, the left-hand argument to
`mappend` goes to the right of the right-hand argument.

In our case, if we use unitDVarSet and mappend, we learn that the free
variables of (a -> b -> c -> d) are [b, a, c, d], and we then quantify
over them in that order. (The a comes after the b because we union the
singleton sets as ({a} `mappend` {b}), producing {b, a}. Thereafter,
the size criterion works to our advantage.) This is just annoying to
users, so I use `extendDVarSet`, which unambiguously puts the new
element to the right.

Note that the unitDVarSet/mappend implementation would not be wrong
against any specification -- just suboptimal and confounding to users.

Note [Recurring into kinds for candidateQTyVars]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
First, read Note [Closing over free variable kinds] in GHC.Core.TyCo.FVs, paying
attention to the end of the Note about using an empty bound set when
traversing a variable's kind.

That Note concludes with the recommendation that we empty out the bound
set when recurring into the kind of a type variable. Yet, we do not do
this here. I have two tasks in order to convince you that this code is
right. First, I must show why it is safe to ignore the reasoning in that
Note. Then, I must show why is is necessary to contradict the reasoning in
that Note.

Why it is safe: There can be no
shadowing in the candidateQ... functions: they work on the output of
type inference, which is seeded by the renamer and its insistence to
use different Uniques for different variables. (In contrast, the Core
functions work on the output of optimizations, which may introduce
shadowing.) Without shadowing, the problem studied by
Note [Closing over free variable kinds] in GHC.Core.TyCo.FVs cannot happen.

Why it is necessary:
Wiping the bound set would be just plain wrong here. Consider

  forall k1 k2 (a :: k1). Proxy k2 (a |> (hole :: k1 ~# k2))

We really don't want to think k1 and k2 are free here. (It's true that we'll
never be able to fill in `hole`, but we don't want to go off the rails just
because we have an insoluble coercion hole.) So: why is it wrong to wipe
the bound variables here but right in Core? Because the final statement
in Note [Closing over free variable kinds] in GHC.Core.TyCo.FVs is wrong: not
every variable is either free or bound. A variable can be a hole, too!
The reasoning in that Note then breaks down.

And the reasoning applies just as well to free non-hole variables, so we
retain the bound set always.

-}

{- *********************************************************************
*                                                                      *
             Quantification
*                                                                      *
************************************************************************

Note [quantifyTyVars]
~~~~~~~~~~~~~~~~~~~~~
quantifyTyVars is given the free vars of a type that we
are about to wrap in a forall.

It takes these free type/kind variables (partitioned into dependent and
non-dependent variables) skolemises metavariables with a TcLevel greater
than the ambient level (see Note [Use level numbers for quantification]).

* This function distinguishes between dependent and non-dependent
  variables only to keep correct defaulting behavior with -XNoPolyKinds.
  With -XPolyKinds, it treats both classes of variables identically.

* quantifyTyVars never quantifies over
    - a coercion variable (or any tv mentioned in the kind of a covar)
    - a runtime-rep variable

Note [Use level numbers for quantification]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The level numbers assigned to metavariables are very useful. Not only
do they track touchability (Note [TcLevel invariants] in GHC.Tc.Utils.TcType),
but they also allow us to determine which variables to
generalise. The rule is this:

  When generalising, quantify only metavariables with a TcLevel greater
  than the ambient level.

This works because we bump the level every time we go inside a new
source-level construct. In a traditional generalisation algorithm, we
would gather all free variables that aren't free in an environment.
However, if a variable is in that environment, it will always have a lower
TcLevel: it came from an outer scope. So we can replace the "free in
environment" check with a level-number check.

Here is an example:

  f x = x + (z True)
    where
      z y = x * x

We start by saying (x :: alpha[1]). When inferring the type of z, we'll
quickly discover that z :: alpha[1]. But it would be disastrous to
generalise over alpha in the type of z. So we need to know that alpha
comes from an outer environment. By contrast, the type of y is beta[2],
and we are free to generalise over it. What's the difference between
alpha[1] and beta[2]? Their levels. beta[2] has the right TcLevel for
generalisation, and so we generalise it. alpha[1] does not, and so
we leave it alone.

Note that not *every* variable with a higher level will get
generalised, either due to the monomorphism restriction or other
quirks. See, for example, the code in GHC.Tc.Solver.decidePromotedTyVars
and in GHC.Tc.Gen.HsType.kindGeneralizeSome, both of which exclude
certain otherwise-eligible variables from being generalised.

Using level numbers for quantification is implemented in the candidateQTyVars...
functions, by adding only those variables with a level strictly higher than
the ambient level to the set of candidates.

Note [quantifyTyVars determinism]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The results of quantifyTyVars are wrapped in a forall and can end up in the
interface file. One such example is inferred type signatures. They also affect
the results of optimizations, for example worker-wrapper. This means that to
get deterministic builds quantifyTyVars needs to be deterministic.

To achieve this CandidatesQTvs is backed by deterministic sets which allows them
to be later converted to a list in a deterministic order.

For more information about deterministic sets see
Note [Deterministic UniqFM] in GHC.Types.Unique.DFM.
-}

quantifyTyVars :: SkolemInfo
               -> NonStandardDefaultingStrategy
               -> CandidatesQTvs   -- See Note [Dependent type variables]
                                   -- Already zonked
               -> TcM [TcTyVar]
-- See Note [quantifyTyVars]
-- Can be given a mixture of TcTyVars and TyVars, in the case of
--   associated type declarations. Also accepts covars, but *never* returns any.
-- According to Note [Use level numbers for quantification] and the
-- invariants on CandidateQTvs, we do not have to filter out variables
-- free in the environment here. Just quantify unconditionally, subject
-- to the restrictions in Note [quantifyTyVars].
quantifyTyVars :: SkolemInfo
-> NonStandardDefaultingStrategy -> CandidatesQTvs -> TcM [TcTyVar]
quantifyTyVars SkolemInfo
skol_info NonStandardDefaultingStrategy
ns_strat CandidatesQTvs
dvs
       -- short-circuit common case
  | CandidatesQTvs -> Bool
isEmptyCandidates CandidatesQTvs
dvs
  = do { String -> SDoc -> TcRn ()
traceTc String
"quantifyTyVars has nothing to quantify" SDoc
forall doc. IsOutput doc => doc
empty
       ; [TcTyVar] -> TcM [TcTyVar]
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return [] }

  | Bool
otherwise
  = do { String -> SDoc -> TcRn ()
traceTc String
"quantifyTyVars {"
           ( [SDoc] -> SDoc
forall doc. IsDoc doc => [doc] -> doc
vcat [ String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"ns_strat =" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> NonStandardDefaultingStrategy -> SDoc
forall a. Outputable a => a -> SDoc
ppr NonStandardDefaultingStrategy
ns_strat
                  , String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"dvs =" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> CandidatesQTvs -> SDoc
forall a. Outputable a => a -> SDoc
ppr CandidatesQTvs
dvs ])

       ; undefaulted <- NonStandardDefaultingStrategy -> CandidatesQTvs -> TcM [TcTyVar]
defaultTyVars NonStandardDefaultingStrategy
ns_strat CandidatesQTvs
dvs
       ; final_qtvs  <- liftZonkM $ mapMaybeM zonk_quant undefaulted

       ; traceTc "quantifyTyVars }"
           (vcat [ text "undefaulted:" <+> pprTyVars undefaulted
                 , text "final_qtvs:"  <+> pprTyVars final_qtvs ])

       -- We should never quantify over coercion variables; check this
       ; let co_vars = (TcTyVar -> Bool) -> [TcTyVar] -> [TcTyVar]
forall a. (a -> Bool) -> [a] -> [a]
filter TcTyVar -> Bool
isCoVar [TcTyVar]
final_qtvs
       ; massertPpr (null co_vars) (ppr co_vars)

       ; return final_qtvs }
  where
    -- zonk_quant returns a tyvar if it should be quantified over;
    -- otherwise, it returns Nothing. The latter case happens for
    -- non-meta-tyvars
    zonk_quant :: TcTyVar -> ZonkM (Maybe TcTyVar)
zonk_quant TcTyVar
tkv
      | Bool -> Bool
not (TcTyVar -> Bool
isTyVar TcTyVar
tkv)
      = Maybe TcTyVar -> ZonkM (Maybe TcTyVar)
forall a. a -> ZonkM a
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe TcTyVar
forall a. Maybe a
Nothing   -- this can happen for a covar that's associated with
                         -- a coercion hole. Test case: typecheck/should_compile/T2494

      | Bool
otherwise
      = TcTyVar -> Maybe TcTyVar
forall a. a -> Maybe a
Just (TcTyVar -> Maybe TcTyVar)
-> ZonkM TcTyVar -> ZonkM (Maybe TcTyVar)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> SkolemInfo -> TcTyVar -> ZonkM TcTyVar
skolemiseQuantifiedTyVar SkolemInfo
skol_info TcTyVar
tkv

isQuantifiableTv :: TcLevel   -- Level of the context, outside the quantification
                 -> TcTyVar
                 -> Bool
isQuantifiableTv :: TcLevel -> TcTyVar -> Bool
isQuantifiableTv TcLevel
outer_tclvl TcTyVar
tcv
  | TcTyVar -> Bool
isTcTyVar TcTyVar
tcv  -- Might be a CoVar; change this when gather covars separately
  = TcTyVar -> TcLevel
tcTyVarLevel TcTyVar
tcv TcLevel -> TcLevel -> Bool
forall a. Ord a => a -> a -> Bool
> TcLevel
outer_tclvl
  | Bool
otherwise
  = Bool
False

zonkAndSkolemise :: SkolemInfo -> TcTyCoVar -> ZonkM TcTyCoVar
-- A tyvar binder is never a unification variable (TauTv),
-- rather it is always a skolem. It *might* be a TyVarTv.
-- (Because non-CUSK type declarations use TyVarTvs.)
-- Regardless, it may have a kind that has not yet been zonked,
-- and may include kind unification variables.
zonkAndSkolemise :: SkolemInfo -> TcTyVar -> ZonkM TcTyVar
zonkAndSkolemise SkolemInfo
skol_info TcTyVar
tyvar
  | TcTyVar -> Bool
isTyVarTyVar TcTyVar
tyvar
     -- We want to preserve the binding location of the original TyVarTv.
     -- This is important for error messages. If we don't do this, then
     -- we get bad locations in, e.g., typecheck/should_fail/T2688
  = do { zonked_tyvar <- HasDebugCallStack => TcTyVar -> ZonkM TcTyVar
TcTyVar -> ZonkM TcTyVar
zonkTcTyVarToTcTyVar TcTyVar
tyvar
       ; skolemiseQuantifiedTyVar skol_info zonked_tyvar }

  | Bool
otherwise
  = Bool -> SDoc -> ZonkM TcTyVar -> ZonkM TcTyVar
forall a. HasCallStack => Bool -> SDoc -> a -> a
assertPpr (TcTyVar -> Bool
isImmutableTyVar TcTyVar
tyvar Bool -> Bool -> Bool
|| TcTyVar -> Bool
isCoVar TcTyVar
tyvar) (TcTyVar -> SDoc
pprTyVar TcTyVar
tyvar) (ZonkM TcTyVar -> ZonkM TcTyVar) -> ZonkM TcTyVar -> ZonkM TcTyVar
forall a b. (a -> b) -> a -> b
$
    TcTyVar -> ZonkM TcTyVar
zonkTyCoVarKind TcTyVar
tyvar

skolemiseQuantifiedTyVar :: SkolemInfo -> TcTyVar -> ZonkM TcTyVar
-- The quantified type variables often include meta type variables
-- we want to freeze them into ordinary type variables
-- The meta tyvar is updated to point to the new skolem TyVar.  Now any
-- bound occurrences of the original type variable will get zonked to
-- the immutable version.
--
-- We leave skolem TyVars alone; they are immutable.
--
-- This function is called on both kind and type variables,
-- but kind variables *only* if PolyKinds is on.

skolemiseQuantifiedTyVar :: SkolemInfo -> TcTyVar -> ZonkM TcTyVar
skolemiseQuantifiedTyVar SkolemInfo
skol_info TcTyVar
tv
  = case TcTyVar -> TcTyVarDetails
tcTyVarDetails TcTyVar
tv of
      MetaTv {} -> SkolemInfo -> TcTyVar -> ZonkM TcTyVar
skolemiseUnboundMetaTyVar SkolemInfo
skol_info TcTyVar
tv

      SkolemTv SkolemInfo
_ TcLevel
lvl Bool
_  -- It might be a skolem type variable,
                        -- for example from a user type signature
        -- But it might also be a shared meta-variable across several
        -- type declarations, each with its own skol_info. The first
        -- will skolemise it, but the other uses must update its
        -- skolem info (#22379)
        -> do { kind <- TcType -> ZonkM TcType
zonkTcType (TcTyVar -> TcType
tyVarKind TcTyVar
tv)
              ; let details = SkolemInfo -> TcLevel -> Bool -> TcTyVarDetails
SkolemTv SkolemInfo
skol_info TcLevel
lvl Bool
False
                    name = TcTyVar -> Name
tyVarName TcTyVar
tv
              ; return (mkTcTyVar name kind details) }

      TcTyVarDetails
_other -> String -> SDoc -> ZonkM TcTyVar
forall a. HasCallStack => String -> SDoc -> a
pprPanic String
"skolemiseQuantifiedTyVar" (TcTyVar -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcTyVar
tv) -- RuntimeUnk

-- | Default a type variable using the given defaulting strategy.
--
-- See Note [Type variable defaulting options] in GHC.Types.Basic.
defaultTyVar :: DefaultingStrategy
             -> TcTyVar    -- If it's a MetaTyVar then it is unbound
             -> TcM Bool   -- True <=> defaulted away altogether
defaultTyVar :: DefaultingStrategy -> TcTyVar -> TcRnIf TcGblEnv TcLclEnv Bool
defaultTyVar DefaultingStrategy
def_strat TcTyVar
tv
  | Bool -> Bool
not (TcTyVar -> Bool
isMetaTyVar TcTyVar
tv)
  Bool -> Bool -> Bool
|| TcTyVar -> Bool
isTyVarTyVar TcTyVar
tv
    -- Do not default TyVarTvs. Doing so would violate the invariants
    -- on TyVarTvs; see Note [TyVarTv] in GHC.Tc.Utils.TcMType.
    -- #13343 is an example; #14555 is another
    -- See Note [Inferring kinds for type declarations] in GHC.Tc.TyCl
  = Bool -> TcRnIf TcGblEnv TcLclEnv Bool
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
False

  | TcTyVar -> Bool
isRuntimeRepVar TcTyVar
tv
  , Bool
default_ns_vars
  = do { String -> SDoc -> TcRn ()
traceTc String
"Defaulting a RuntimeRep var to LiftedRep" (TcTyVar -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcTyVar
tv)
       ; ZonkM () -> TcRn ()
forall a. ZonkM a -> TcM a
liftZonkM (ZonkM () -> TcRn ()) -> ZonkM () -> TcRn ()
forall a b. (a -> b) -> a -> b
$ HasDebugCallStack => TcTyVar -> TcType -> ZonkM ()
TcTyVar -> TcType -> ZonkM ()
writeMetaTyVar TcTyVar
tv TcType
liftedRepTy
       ; Bool -> TcRnIf TcGblEnv TcLclEnv Bool
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
True }

  | TcTyVar -> Bool
isLevityVar TcTyVar
tv
  , Bool
default_ns_vars
  = do { String -> SDoc -> TcRn ()
traceTc String
"Defaulting a Levity var to Lifted" (TcTyVar -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcTyVar
tv)
       ; ZonkM () -> TcRn ()
forall a. ZonkM a -> TcM a
liftZonkM (ZonkM () -> TcRn ()) -> ZonkM () -> TcRn ()
forall a b. (a -> b) -> a -> b
$ HasDebugCallStack => TcTyVar -> TcType -> ZonkM ()
TcTyVar -> TcType -> ZonkM ()
writeMetaTyVar TcTyVar
tv TcType
liftedDataConTy
       ; Bool -> TcRnIf TcGblEnv TcLclEnv Bool
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
True }

  | TcTyVar -> Bool
isMultiplicityVar TcTyVar
tv
  , Bool
default_ns_vars
  = do { String -> SDoc -> TcRn ()
traceTc String
"Defaulting a Multiplicity var to Many" (TcTyVar -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcTyVar
tv)
       ; ZonkM () -> TcRn ()
forall a. ZonkM a -> TcM a
liftZonkM (ZonkM () -> TcRn ()) -> ZonkM () -> TcRn ()
forall a b. (a -> b) -> a -> b
$ HasDebugCallStack => TcTyVar -> TcType -> ZonkM ()
TcTyVar -> TcType -> ZonkM ()
writeMetaTyVar TcTyVar
tv TcType
manyDataConTy
       ; Bool -> TcRnIf TcGblEnv TcLclEnv Bool
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
True }

  | TcTyVar -> Bool
isConcreteTyVar TcTyVar
tv
    -- We don't want to quantify; but neither can we default to
    -- anything sensible.  (If it has kind RuntimeRep or Levity, as is
    -- often the case, it'll have been caught earlier by earlier
    -- cases. So in this exotic situation we just promote.  Not very
    -- satisfing, but it's very much a corner case: #23051
    -- We should really implement the plan in #20686.
  = do { lvl <- TcM TcLevel
getTcLevel
       ; _ <- promoteMetaTyVarTo lvl tv
       ; return True }

  | DefaultingStrategy
DefaultKindVars <- DefaultingStrategy
def_strat -- -XNoPolyKinds and this is a kind var: we must default it
  = TcTyVar -> TcRnIf TcGblEnv TcLclEnv Bool
default_kind_var TcTyVar
tv

  | Bool
otherwise
  = Bool -> TcRnIf TcGblEnv TcLclEnv Bool
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
False

  where
    default_ns_vars :: Bool
    default_ns_vars :: Bool
default_ns_vars = DefaultingStrategy -> Bool
defaultNonStandardTyVars DefaultingStrategy
def_strat
    default_kind_var :: TyVar -> TcM Bool
       -- defaultKindVar is used exclusively with -XNoPolyKinds
       -- See Note [Defaulting with -XNoPolyKinds]
       -- It takes an (unconstrained) meta tyvar and defaults it.
       -- Works only on vars of type *; for other kinds, it issues an error.
    default_kind_var :: TcTyVar -> TcRnIf TcGblEnv TcLclEnv Bool
default_kind_var TcTyVar
kv
      | TcType -> Bool
isLiftedTypeKind (TcTyVar -> TcType
tyVarKind TcTyVar
kv)
      = do { String -> SDoc -> TcRn ()
traceTc String
"Defaulting a kind var to *" (TcTyVar -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcTyVar
kv)
           ; ZonkM () -> TcRn ()
forall a. ZonkM a -> TcM a
liftZonkM (ZonkM () -> TcRn ()) -> ZonkM () -> TcRn ()
forall a b. (a -> b) -> a -> b
$ HasDebugCallStack => TcTyVar -> TcType -> ZonkM ()
TcTyVar -> TcType -> ZonkM ()
writeMetaTyVar TcTyVar
kv TcType
liftedTypeKind
           ; Bool -> TcRnIf TcGblEnv TcLclEnv Bool
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
True }
      | Bool
otherwise
      = do { TcRnMessage -> TcRn ()
addErr (TcRnMessage -> TcRn ()) -> TcRnMessage -> TcRn ()
forall a b. (a -> b) -> a -> b
$ TcTyVar -> TcType -> TcRnMessage
TcRnCannotDefaultKindVar TcTyVar
kv' (TcTyVar -> TcType
tyVarKind TcTyVar
kv')
           -- We failed to default it, so return False to say so.
           -- Hence, it'll get skolemised.  That might seem odd, but we must either
           -- promote, skolemise, or zap-to-Any, to satisfy GHC.Tc.Gen.HsType
           --    Note [Recipe for checking a signature]
           -- Otherwise we get level-number assertion failures. It doesn't matter much
           -- because we are in an error situation anyway.
           ; Bool -> TcRnIf TcGblEnv TcLclEnv Bool
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
False
        }
      where
        (TidyEnv
_, TcTyVar
kv') = TidyEnv -> TcTyVar -> (TidyEnv, TcTyVar)
tidyOpenTyCoVar TidyEnv
emptyTidyEnv TcTyVar
kv

-- | Default some unconstrained type variables, as specified
-- by the defaulting options:
--
--  - 'RuntimeRep' tyvars default to 'LiftedRep'
--  - 'Levity' tyvars default to 'Lifted'
--  - 'Multiplicity' tyvars default to 'Many'
--  - 'Type' tyvars from dv_kvs default to 'Type', when -XNoPolyKinds
--    (under -XNoPolyKinds, non-defaulting vars in dv_kvs is an error)
defaultTyVars :: NonStandardDefaultingStrategy
              -> CandidatesQTvs    -- ^ all candidates for quantification
              -> TcM [TcTyVar]     -- ^ those variables not defaulted
defaultTyVars :: NonStandardDefaultingStrategy -> CandidatesQTvs -> TcM [TcTyVar]
defaultTyVars NonStandardDefaultingStrategy
ns_strat CandidatesQTvs
dvs
  = do { poly_kinds <- Extension -> TcRnIf TcGblEnv TcLclEnv Bool
forall gbl lcl. Extension -> TcRnIf gbl lcl Bool
xoptM Extension
LangExt.PolyKinds
       ; let
           def_tvs, def_kvs :: DefaultingStrategy
           def_tvs = NonStandardDefaultingStrategy -> DefaultingStrategy
NonStandardDefaulting NonStandardDefaultingStrategy
ns_strat
           def_kvs | Bool
poly_kinds = DefaultingStrategy
def_tvs
                   | Bool
otherwise  = DefaultingStrategy
DefaultKindVars
             -- As -XNoPolyKinds precludes polymorphic kind variables, we default them.
             -- For example:
             --
             --   type F :: Type -> Type
             --   type family F a where
             --      F (a -> b) = b
             --
             -- Here we get `a :: TYPE r`, so to accept this program when -XNoPolyKinds is enabled
             -- we must default the kind variable `r :: RuntimeRep`.
             -- Test case: T20584.
       ; defaulted_kvs <- mapM (defaultTyVar def_kvs) dep_kvs
       ; defaulted_tvs <- mapM (defaultTyVar def_tvs) nondep_tvs
       ; let undefaulted_kvs = [ TcTyVar
kv | (TcTyVar
kv, Bool
False) <- [TcTyVar]
dep_kvs    [TcTyVar] -> [Bool] -> [(TcTyVar, Bool)]
forall a b. [a] -> [b] -> [(a, b)]
`zip` [Bool]
defaulted_kvs ]
             undefaulted_tvs = [ TcTyVar
tv | (TcTyVar
tv, Bool
False) <- [TcTyVar]
nondep_tvs [TcTyVar] -> [Bool] -> [(TcTyVar, Bool)]
forall a b. [a] -> [b] -> [(a, b)]
`zip` [Bool]
defaulted_tvs ]
       ; return (undefaulted_kvs ++ undefaulted_tvs) }
          -- NB: kvs before tvs because tvs may depend on kvs
  where
    ([TcTyVar]
dep_kvs, [TcTyVar]
nondep_tvs) = CandidatesQTvs -> ([TcTyVar], [TcTyVar])
candidateVars CandidatesQTvs
dvs

skolemiseUnboundMetaTyVar :: SkolemInfo -> TcTyVar -> ZonkM TyVar
-- We have a Meta tyvar with a ref-cell inside it
-- Skolemise it, so that we are totally out of Meta-tyvar-land
-- We create a skolem TcTyVar, not a regular TyVar
--   See Note [Zonking to Skolem]
--
-- Its level should be one greater than the ambient level, which will typically
-- be the same as the level on the meta-tyvar. But not invariably; for example
--    f :: (forall a b. SameKind a b) -> Int
-- The skolems 'a' and 'b' are bound by tcTKTelescope, at level 2; and they each
-- have a level-2 kind unification variable, since it might get unified with another
-- of the level-2 skolems e.g. 'k' in this version
--    f :: (forall k (a :: k) b. SameKind a b) -> Int
-- So when we quantify the kind vars at the top level of the signature, the ambient
-- level is 1, but we will quantify over kappa[2].

skolemiseUnboundMetaTyVar :: SkolemInfo -> TcTyVar -> ZonkM TcTyVar
skolemiseUnboundMetaTyVar SkolemInfo
skol_info TcTyVar
tv
  = Bool -> SDoc -> ZonkM TcTyVar -> ZonkM TcTyVar
forall a. HasCallStack => Bool -> SDoc -> a -> a
assertPpr (TcTyVar -> Bool
isMetaTyVar TcTyVar
tv) (TcTyVar -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcTyVar
tv) (ZonkM TcTyVar -> ZonkM TcTyVar) -> ZonkM TcTyVar -> ZonkM TcTyVar
forall a b. (a -> b) -> a -> b
$
    do  { TcTyVar -> ZonkM ()
forall {f :: * -> *}. MonadIO f => TcTyVar -> f ()
check_empty TcTyVar
tv
        -- Get the location and level from "here",
        -- i.e. where we are generalising
        ; ZonkGblEnv { zge_src_span = here, zge_tc_level = tc_lvl }
           <- ZonkM ZonkGblEnv
getZonkGblEnv
        ; kind   <- zonkTcType (tyVarKind tv)
        ; let tv_name = TcTyVar -> Name
tyVarName TcTyVar
tv
              -- See Note [Skolemising and identity]
              final_name | Name -> Bool
isSystemName Name
tv_name
                         = Unique -> OccName -> SrcSpan -> Name
mkInternalName (Name -> Unique
nameUnique Name
tv_name)
                                          (Name -> OccName
nameOccName Name
tv_name) SrcSpan
here
                         | Bool
otherwise
                         = Name
tv_name
              details    = SkolemInfo -> TcLevel -> Bool -> TcTyVarDetails
SkolemTv SkolemInfo
skol_info (TcLevel -> TcLevel
pushTcLevel TcLevel
tc_lvl) Bool
False
              final_tv   = Name -> TcType -> TcTyVarDetails -> TcTyVar
mkTcTyVar Name
final_name TcType
kind TcTyVarDetails
details

        ; traceZonk "Skolemising" (ppr tv <+> text ":=" <+> ppr final_tv)
        ; writeMetaTyVar tv (mkTyVarTy final_tv)
        ; return final_tv }
  where
    check_empty :: TcTyVar -> f ()
check_empty TcTyVar
tv       -- [Sept 04] Check for non-empty.
      = Bool -> f () -> f ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when Bool
debugIsOn (f () -> f ()) -> f () -> f ()
forall a b. (a -> b) -> a -> b
$  -- See Note [Silly Type Synonyms]
        do { cts <- TcTyVar -> f MetaDetails
forall (m :: * -> *). MonadIO m => TcTyVar -> m MetaDetails
readMetaTyVar TcTyVar
tv
           ; case cts of
               MetaDetails
Flexi       -> () -> f ()
forall a. a -> f a
forall (m :: * -> *) a. Monad m => a -> m a
return ()
               Indirect TcType
ty -> Bool -> String -> SDoc -> f () -> f ()
forall a. HasCallStack => Bool -> String -> SDoc -> a -> a
warnPprTrace Bool
True String
"skolemiseUnboundMetaTyVar" (TcTyVar -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcTyVar
tv SDoc -> SDoc -> SDoc
forall doc. IsDoc doc => doc -> doc -> doc
$$ TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
ty) (f () -> f ()) -> f () -> f ()
forall a b. (a -> b) -> a -> b
$
                              () -> f ()
forall a. a -> f a
forall (m :: * -> *) a. Monad m => a -> m a
return () }

{- Note [Error on unconstrained meta-variables]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider

* type C :: Type -> Type -> Constraint
  class (forall a. a b ~ a c) => C b c

* type T = forall a. Proxy a

* data (forall a. a b ~ a c) => T b c

* type instance F Int = Proxy Any
  where Any :: forall k. k

In the first three cases we will infer a :: Type -> kappa, but then
we get no further information on kappa. In the last, we will get
  Proxy kappa Any
but again will get no further info on kappa.

What do do?
 A. We could choose kappa := Type. But this only works when the kind of kappa
    is Type (true in this example, but not always).
 B. We could default to Any.
 C. We could quantify.
 D. We could error.

We choose (D), as described in #17567, and implement this choice in
doNotQuantifyTyVars.  Discussion of alternatives A-C is below.

NB: this is all rather similar to, but sadly not the same as
    Note [Naughty quantification candidates]

To do this, we must take an extra step before doing the final zonk to create
e.g. a TyCon. (There is no problem in the final term-level zonk. See the
section on alternative (B) below.) This extra step is needed only for
constructs that do not quantify their free meta-variables, such as a class
constraint or right-hand side of a type synonym.

Specifically: before the final zonk, every construct must either call
quantifyTyVars or doNotQuantifyTyVars. The latter issues an error
if it is passed any free variables. (Exception: we still default
RuntimeRep and Multiplicity variables.)

Because no meta-variables remain after quantifying or erroring, we perform
the zonk with NoFlexi, which panics upon seeing a meta-variable.

Alternatives A-C, not implemented:

A. As stated above, this works only sometimes. We might have a free
   meta-variable of kind Nat, for example.

B. This is what we used to do, but it caused Any to appear in error
   messages sometimes. See #17567 for several examples. Defaulting to
   Any during the final, whole-program zonk is OK, though, because
   we are completely done type-checking at that point. No chance to
   leak into an error message.

C. Examine the class declaration at the top of this Note again.
   Where should we quantify? We might imagine quantifying and
   putting the kind variable in the forall of the quantified constraint.
   But what if there are nested foralls? Which one should get the
   variable? Other constructs have other problems. (For example,
   the right-hand side of a type family instance equation may not
   be a poly-type.)

   More broadly, the GHC AST defines a set of places where it performs
   implicit lexical generalization. For example, in a type
   signature

     f :: Proxy a -> Bool

   the otherwise-unbound a is lexically quantified, giving us

     f :: forall a. Proxy a -> Bool

   The places that allow lexical quantification are marked in the AST with
   HsImplicitBndrs. HsImplicitBndrs offers a binding site for otherwise-unbound
   variables.

   Later, during type-checking, we discover that a's kind is unconstrained.
   We thus quantify *again*, to

     f :: forall {k} (a :: k). Proxy @k a -> Bool

   It is this second quantification that this Note is really about --
   let's call it *inferred quantification*.
   So there are two sorts of implicit quantification in types:
     1. Lexical quantification: signalled by HsImplicitBndrs, occurs over
        variables mentioned by the user but with no explicit binding site,
        suppressed by a user-written forall (by the forall-or-nothing rule,
        in Note [forall-or-nothing rule] in GHC.Hs.Type).
     2. Inferred quantification: no signal in HsSyn, occurs over unconstrained
        variables invented by the type-checker, possible only with -XPolyKinds,
        unaffected by forall-or-nothing rule
   These two quantifications are performed in different compiler phases, and are
   essentially unrelated. However, it is convenient
   for programmers to remember only one set of implicit quantification
   sites. So, we choose to use the same places (those with HsImplicitBndrs)
   for lexical quantification as for inferred quantification of unconstrained
   meta-variables. Accordingly, there is no quantification in a class
   constraint, or the other constructs that call doNotQuantifyTyVars.
-}

doNotQuantifyTyVars :: CandidatesQTvs
                    -> (TidyEnv -> ZonkM (TidyEnv, UninferrableTyVarCtx))
                            -- ^ like "the class context (D a b, E foogle)"
                    -> TcM ()
-- See Note [Error on unconstrained meta-variables]
doNotQuantifyTyVars :: CandidatesQTvs
-> (TidyEnv -> ZonkM (TidyEnv, UninferrableTyVarCtx)) -> TcRn ()
doNotQuantifyTyVars CandidatesQTvs
dvs TidyEnv -> ZonkM (TidyEnv, UninferrableTyVarCtx)
where_found
  | CandidatesQTvs -> Bool
isEmptyCandidates CandidatesQTvs
dvs
  = String -> SDoc -> TcRn ()
traceTc String
"doNotQuantifyTyVars has nothing to error on" SDoc
forall doc. IsOutput doc => doc
empty

  | Bool
otherwise
  = do { String -> SDoc -> TcRn ()
traceTc String
"doNotQuantifyTyVars" (CandidatesQTvs -> SDoc
forall a. Outputable a => a -> SDoc
ppr CandidatesQTvs
dvs)
       ; undefaulted <- NonStandardDefaultingStrategy -> CandidatesQTvs -> TcM [TcTyVar]
defaultTyVars NonStandardDefaultingStrategy
DefaultNonStandardTyVars CandidatesQTvs
dvs
          -- could have regular TyVars here, in an associated type RHS, or
          -- bound by a type declaration head. So filter looking only for
          -- metavars. e.g. b and c in `class (forall a. a b ~ a c) => C b c`
          -- are OK
       ; let leftover_metas = (TcTyVar -> Bool) -> [TcTyVar] -> [TcTyVar]
forall a. (a -> Bool) -> [a] -> [a]
filter TcTyVar -> Bool
isMetaTyVar [TcTyVar]
undefaulted
       ; unless (null leftover_metas) $
         do { let (tidy_env1, tidied_tvs) = tidyOpenTyCoVars emptyTidyEnv leftover_metas
            ; (tidy_env2, where_doc) <- liftZonkM $ where_found tidy_env1
            ; let msg = [TcTyVar] -> UninferrableTyVarCtx -> TcRnMessage
TcRnUninferrableTyVar [TcTyVar]
tidied_tvs UninferrableTyVarCtx
where_doc
            ; failWithTcM (tidy_env2, msg) }
       ; traceTc "doNotQuantifyTyVars success" empty }

{- Note [Defaulting with -XNoPolyKinds]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider

  data Compose f g a = Mk (f (g a))

We infer

  Compose :: forall k1 k2. (k2 -> *) -> (k1 -> k2) -> k1 -> *
  Mk :: forall k1 k2 (f :: k2 -> *) (g :: k1 -> k2) (a :: k1).
        f (g a) -> Compose k1 k2 f g a

Now, in another module, we have -XNoPolyKinds -XDataKinds in effect.
What does 'Mk mean? Pre GHC-8.0 with -XNoPolyKinds,
we just defaulted all kind variables to *. But that's no good here,
because the kind variables in 'Mk aren't of kind *, so defaulting to *
is ill-kinded.

After some debate on #11334, we decided to issue an error in this case.
The code is in defaultKindVar.

Note [What is a meta variable?]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A "meta type-variable", also know as a "unification variable" is a placeholder
introduced by the typechecker for an as-yet-unknown monotype.

For example, when we see a call `reverse (f xs)`, we know that we calling
    reverse :: forall a. [a] -> [a]
So we know that the argument `f xs` must be a "list of something". But what is
the "something"? We don't know until we explore the `f xs` a bit more. So we set
out what we do know at the call of `reverse` by instantiating its type with a fresh
meta tyvar, `alpha` say. So now the type of the argument `f xs`, and of the
result, is `[alpha]`. The unification variable `alpha` stands for the
as-yet-unknown type of the elements of the list.

As type inference progresses we may learn more about `alpha`. For example, suppose
`f` has the type
    f :: forall b. b -> [Maybe b]
Then we instantiate `f`'s type with another fresh unification variable, say
`beta`; and equate `f`'s result type with reverse's argument type, thus
`[alpha] ~ [Maybe beta]`.

Now we can solve this equality to learn that `alpha ~ Maybe beta`, so we've
refined our knowledge about `alpha`. And so on.

If you found this Note useful, you may also want to have a look at
Section 5 of "Practical type inference for higher rank types" (Peyton Jones,
Vytiniotis, Weirich and Shields. J. Functional Programming. 2011).

Note [Zonking to Skolem]
~~~~~~~~~~~~~~~~~~~~~~~~
We used to zonk quantified type variables to regular TyVars.  However, this
leads to problems.  Consider this program from the regression test suite:

  eval :: Int -> String -> String -> String
  eval 0 root actual = evalRHS 0 root actual

  evalRHS :: Int -> a
  evalRHS 0 root actual = eval 0 root actual

It leads to the deferral of an equality (wrapped in an implication constraint)

  forall a. () => ((String -> String -> String) ~ a)

which is propagated up to the toplevel (see GHC.Tc.Solver.tcSimplifyInferCheck).
In the meantime `a' is zonked and quantified to form `evalRHS's signature.
This has the *side effect* of also zonking the `a' in the deferred equality
(which at this point is being handed around wrapped in an implication
constraint).

Finally, the equality (with the zonked `a') will be handed back to the
simplifier by GHC.Tc.Module.tcRnSrcDecls calling GHC.Tc.Solver.tcSimplifyTop.
If we zonk `a' with a regular type variable, we will have this regular type
variable now floating around in the simplifier, which in many places assumes to
only see proper TcTyVars.

We can avoid this problem by zonking with a skolem TcTyVar.  The
skolem is rigid (which we require for a quantified variable), but is
still a TcTyVar that the simplifier knows how to deal with.

Note [Skolemising and identity]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In some places, we make a TyVarTv for a binder. E.g.
    class C a where ...
As Note [Inferring kinds for type declarations] discusses,
we make a TyVarTv for 'a'.  Later we skolemise it, and we'd
like to retain its identity, location info etc.  (If we don't
retain its identity we'll have to do some pointless swizzling;
see GHC.Tc.TyCl.swizzleTcTyConBndrs.  If we retain its identity
but not its location we'll lose the detailed binding site info.

Conclusion: use the Name of the TyVarTv.  But we don't want
to do that when skolemising random unification variables;
there the location we want is the skolemisation site.

Fortunately we can tell the difference: random unification
variables have System Names.  That's why final_name is
set based on the isSystemName test.


Note [Silly Type Synonyms]
~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider this:
        type C u a = u  -- Note 'a' unused

        foo :: (forall a. C u a -> C u a) -> u
        foo x = ...

        bar :: Num u => u
        bar = foo (\t -> t + t)

* From the (\t -> t+t) we get type  {Num d} =>  d -> d
  where d is fresh.

* Now unify with type of foo's arg, and we get:
        {Num (C d a)} =>  C d a -> C d a
  where a is fresh.

* Now abstract over the 'a', but float out the Num (C d a) constraint
  because it does not 'really' mention a.  (see exactTyVarsOfType)
  The arg to foo becomes
        \/\a -> \t -> t+t

* So we get a dict binding for Num (C d a), which is zonked to give
        a = ()
  Note (Sept 04): now that we are zonking quantified type variables
  on construction, the 'a' will be frozen as a regular tyvar on
  quantification, so the floated dict will still have type (C d a).
  Which renders this whole note moot; happily!]

* Then the \/\a abstraction has a zonked 'a' in it.

All very silly.   I think its harmless to ignore the problem.  We'll end up with
a \/\a in the final result but all the occurrences of a will be zonked to ()
-}

--------------------------------------------------------------------------------

-- | @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 -> TcType -> TcM a -> TcM (a, HsWrapper)
tcCheckUsage Name
name TcType
id_mult TcM a
thing_inside
  = do { (local_usage, result) <- TcM a -> TcM (UsageEnv, a)
forall a. TcM a -> TcM (UsageEnv, a)
tcCollectingUsage TcM a
thing_inside
       ; wrapper <- check_then_add_usage local_usage
       ; return (result, 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 -> SDoc -> TcRn ()
traceTc String
"check_then_add_usage" (TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
id_mult SDoc -> SDoc -> SDoc
forall doc. IsDoc doc => doc -> doc -> doc
$$ Usage -> SDoc
forall a. Outputable a => a -> SDoc
ppr Usage
actual_u)
           ; wrapper <- case Usage
actual_u of
               Usage
Bottom -> HsWrapper -> TcM HsWrapper
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return HsWrapper
idHsWrapper
               Usage
Zero     -> CtOrigin -> TcType -> TcType -> TcM HsWrapper
tcSubMult (Name -> CtOrigin
UsageEnvironmentOf Name
name) TcType
ManyTy TcType
id_mult
               MUsage TcType
m -> do { m <- TcType -> TcM TcType
promote_mult TcType
m
                              ; tcSubMult (UsageEnvironmentOf name) m id_mult }
           ; tcEmitBindingUsage (deleteUE uenv name)
           ; return 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 :: TcType -> TcM TcType
promote_mult TcType
m = do { fvs <- ZonkM CoVarSet -> TcM CoVarSet
forall a. ZonkM a -> TcM a
liftZonkM (ZonkM CoVarSet -> TcM CoVarSet) -> ZonkM CoVarSet -> TcM CoVarSet
forall a b. (a -> b) -> a -> b
$ CoVarSet -> ZonkM CoVarSet
zonkTyCoVarsAndFV (TcType -> CoVarSet
tyCoVarsOfType TcType
m)
                        ; any_promoted <- promoteTyVarSet fvs
                        ; if any_promoted then liftZonkM $ zonkTcType m else return m
                        }

{- *********************************************************************
*                                                                      *
         Short-cuts for overloaded numeric literals
*                                                                      *
********************************************************************* -}

-- Overloaded literals. Here mainly because it uses isIntTy etc

{- Note [Short cut for overloaded literals]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A literal like "3" means (fromInteger @ty (dNum :: Num ty) (3::Integer)).
But if we have a list like
  [4,2,3,2,4,4,2]::[Int]
we use a lot of compile time and space generating and solving all those Num
constraints, and generating calls to fromInteger etc.  Better just to cut to
the chase, and cough up an Int literal. Large collections of literals like this
sometimes appear in source files, so it's quite a worthwhile fix.

So we try to take advantage of whatever nearby type information we have,
to short-cut the process for built-in types.  We can do this in two places;

* In the typechecker, when we are about to typecheck the literal.
* If that fails, in the desugarer, once we know the final type.
-}

tcShortCutLit :: HsOverLit GhcRn -> ExpRhoType -> TcM (Maybe (HsOverLit GhcTc))
tcShortCutLit :: HsOverLit GhcRn -> ExpType -> TcM (Maybe (HsOverLit GhcTc))
tcShortCutLit lit :: HsOverLit GhcRn
lit@(OverLit { ol_val :: forall p. HsOverLit p -> OverLitVal
ol_val = OverLitVal
val, ol_ext :: forall p. HsOverLit p -> XOverLit p
ol_ext = OverLitRn Bool
rebindable LIdP GhcRn
_}) ExpType
exp_res_ty
  | Bool -> Bool
not Bool
rebindable
  , Just TcType
res_ty <- ExpType -> Maybe TcType
checkingExpType_maybe ExpType
exp_res_ty
  = do { dflags <- IOEnv (Env TcGblEnv TcLclEnv) DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags
       ; let platform = DynFlags -> Platform
targetPlatform DynFlags
dflags
       ; case shortCutLit platform val res_ty of
            Just HsExpr GhcTc
expr -> Maybe (HsOverLit GhcTc) -> TcM (Maybe (HsOverLit GhcTc))
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Maybe (HsOverLit GhcTc) -> TcM (Maybe (HsOverLit GhcTc)))
-> Maybe (HsOverLit GhcTc) -> TcM (Maybe (HsOverLit GhcTc))
forall a b. (a -> b) -> a -> b
$ HsOverLit GhcTc -> Maybe (HsOverLit GhcTc)
forall a. a -> Maybe a
Just (HsOverLit GhcTc -> Maybe (HsOverLit GhcTc))
-> HsOverLit GhcTc -> Maybe (HsOverLit GhcTc)
forall a b. (a -> b) -> a -> b
$
                         HsOverLit GhcRn
lit { ol_ext = OverLitTc False expr res_ty }
            Maybe (HsExpr GhcTc)
Nothing   -> Maybe (HsOverLit GhcTc) -> TcM (Maybe (HsOverLit GhcTc))
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe (HsOverLit GhcTc)
forall a. Maybe a
Nothing }
  | Bool
otherwise
  = Maybe (HsOverLit GhcTc) -> TcM (Maybe (HsOverLit GhcTc))
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe (HsOverLit GhcTc)
forall a. Maybe a
Nothing

shortCutLit :: Platform -> OverLitVal -> TcType -> Maybe (HsExpr GhcTc)
shortCutLit :: Platform -> OverLitVal -> TcType -> Maybe (HsExpr GhcTc)
shortCutLit Platform
platform OverLitVal
val TcType
res_ty
  = case OverLitVal
val of
      HsIntegral IntegralLit
int_lit    -> IntegralLit -> Maybe (HsExpr GhcTc)
go_integral IntegralLit
int_lit
      HsFractional FractionalLit
frac_lit -> FractionalLit -> Maybe (HsExpr GhcTc)
go_fractional FractionalLit
frac_lit
      HsIsString SourceText
s FastString
src      -> SourceText -> FastString -> Maybe (HsExpr GhcTc)
go_string   SourceText
s FastString
src
  where
    go_integral :: IntegralLit -> Maybe (HsExpr GhcTc)
go_integral int :: IntegralLit
int@(IL SourceText
src Bool
neg Integer
i)
      | TcType -> Bool
isIntTy TcType
res_ty  Bool -> Bool -> Bool
&& Platform -> Integer -> Bool
platformInIntRange  Platform
platform Integer
i
      = HsExpr GhcTc -> Maybe (HsExpr GhcTc)
forall a. a -> Maybe a
Just (XLitE GhcTc -> HsLit GhcTc -> HsExpr GhcTc
forall p. XLitE p -> HsLit p -> HsExpr p
HsLit XLitE GhcTc
NoExtField
noExtField (XHsInt GhcTc -> IntegralLit -> HsLit GhcTc
forall x. XHsInt x -> IntegralLit -> HsLit x
HsInt XHsInt GhcTc
NoExtField
noExtField IntegralLit
int))
      | TcType -> Bool
isWordTy TcType
res_ty Bool -> Bool -> Bool
&& Platform -> Integer -> Bool
platformInWordRange Platform
platform Integer
i
      = HsExpr GhcTc -> Maybe (HsExpr GhcTc)
forall a. a -> Maybe a
Just (DataCon -> HsLit GhcTc -> HsExpr GhcTc
mkLit DataCon
wordDataCon (XHsWordPrim GhcTc -> Integer -> HsLit GhcTc
forall x. XHsWordPrim x -> Integer -> HsLit x
HsWordPrim XHsWordPrim GhcTc
SourceText
src Integer
i))
      | TcType -> Bool
isIntegerTy TcType
res_ty
      = HsExpr GhcTc -> Maybe (HsExpr GhcTc)
forall a. a -> Maybe a
Just (XLitE GhcTc -> HsLit GhcTc -> HsExpr GhcTc
forall p. XLitE p -> HsLit p -> HsExpr p
HsLit XLitE GhcTc
NoExtField
noExtField (XHsInteger GhcTc -> Integer -> TcType -> HsLit GhcTc
forall x. XHsInteger x -> Integer -> TcType -> HsLit x
HsInteger XHsInteger GhcTc
SourceText
src Integer
i TcType
res_ty))
      | Bool
otherwise
      = FractionalLit -> Maybe (HsExpr GhcTc)
go_fractional (Bool -> Integer -> FractionalLit
integralFractionalLit Bool
neg Integer
i)
        -- The 'otherwise' case is important
        -- Consider (3 :: Float).  Syntactically it looks like an IntLit,
        -- so we'll call shortCutIntLit, but of course it's a float
        -- This can make a big difference for programs with a lot of
        -- literals, compiled without -O

    go_fractional :: FractionalLit -> Maybe (HsExpr GhcTc)
go_fractional FractionalLit
f
      | TcType -> Bool
isFloatTy TcType
res_ty Bool -> Bool -> Bool
&& Bool
valueInRange  = HsExpr GhcTc -> Maybe (HsExpr GhcTc)
forall a. a -> Maybe a
Just (DataCon -> HsLit GhcTc -> HsExpr GhcTc
mkLit DataCon
floatDataCon  (XHsFloatPrim GhcTc -> FractionalLit -> HsLit GhcTc
forall x. XHsFloatPrim x -> FractionalLit -> HsLit x
HsFloatPrim XHsFloatPrim GhcTc
NoExtField
noExtField FractionalLit
f))
      | TcType -> Bool
isDoubleTy TcType
res_ty Bool -> Bool -> Bool
&& Bool
valueInRange = HsExpr GhcTc -> Maybe (HsExpr GhcTc)
forall a. a -> Maybe a
Just (DataCon -> HsLit GhcTc -> HsExpr GhcTc
mkLit DataCon
doubleDataCon (XHsDoublePrim GhcTc -> FractionalLit -> HsLit GhcTc
forall x. XHsDoublePrim x -> FractionalLit -> HsLit x
HsDoublePrim XHsDoublePrim GhcTc
NoExtField
noExtField FractionalLit
f))
      | Bool
otherwise                         = Maybe (HsExpr GhcTc)
forall a. Maybe a
Nothing
      where
        valueInRange :: Bool
valueInRange =
          case FractionalLit
f of
            FL { fl_exp :: FractionalLit -> Integer
fl_exp = Integer
e } -> (-Integer
100) Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
<= Integer
e Bool -> Bool -> Bool
&& Integer
e Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
<= Integer
100
            -- We limit short-cutting Fractional Literals to when their power of 10
            -- is less than 100, which ensures desugaring isn't slow.

    go_string :: SourceText -> FastString -> Maybe (HsExpr GhcTc)
go_string SourceText
src FastString
s
      | TcType -> Bool
isStringTy TcType
res_ty = HsExpr GhcTc -> Maybe (HsExpr GhcTc)
forall a. a -> Maybe a
Just (XLitE GhcTc -> HsLit GhcTc -> HsExpr GhcTc
forall p. XLitE p -> HsLit p -> HsExpr p
HsLit XLitE GhcTc
NoExtField
noExtField (XHsString GhcTc -> FastString -> HsLit GhcTc
forall x. XHsString x -> FastString -> HsLit x
HsString XHsString GhcTc
SourceText
src FastString
s))
      | Bool
otherwise         = Maybe (HsExpr GhcTc)
forall a. Maybe a
Nothing

mkLit :: DataCon -> HsLit GhcTc -> HsExpr GhcTc
mkLit :: DataCon -> HsLit GhcTc -> HsExpr GhcTc
mkLit DataCon
con HsLit GhcTc
lit = XApp GhcTc -> LHsExpr GhcTc -> LHsExpr GhcTc -> HsExpr GhcTc
forall p. XApp p -> LHsExpr p -> LHsExpr p -> HsExpr p
HsApp XApp GhcTc
NoExtField
noExtField (DataCon -> LHsExpr GhcTc
nlHsDataCon DataCon
con) (HsLit GhcTc -> LHsExpr GhcTc
forall (p :: Pass). HsLit (GhcPass p) -> LHsExpr (GhcPass p)
nlHsLit HsLit GhcTc
lit)

------------------------------
hsOverLitName :: OverLitVal -> Name
-- Get the canonical 'fromX' name for a particular OverLitVal
hsOverLitName :: OverLitVal -> Name
hsOverLitName (HsIntegral {})   = Name
fromIntegerName
hsOverLitName (HsFractional {}) = Name
fromRationalName
hsOverLitName (HsIsString {})   = Name
fromStringName


{- *********************************************************************
*                                                                      *
              Promotion
*                                                                      *
********************************************************************* -}

promoteMetaTyVarTo :: HasDebugCallStack => TcLevel -> TcTyVar -> TcM Bool
-- When we float a constraint out of an implication we must restore
-- invariant (WantedInv) in Note [TcLevel invariants] in GHC.Tc.Utils.TcType
-- Return True <=> we did some promotion
-- Also returns either the original tyvar (no promotion) or the new one
-- See Note [Promoting unification variables]
promoteMetaTyVarTo :: HasDebugCallStack =>
TcLevel -> TcTyVar -> TcRnIf TcGblEnv TcLclEnv Bool
promoteMetaTyVarTo TcLevel
tclvl TcTyVar
tv
  | Bool -> SDoc -> Bool -> Bool
forall a. HasCallStack => Bool -> SDoc -> a -> a
assertPpr (TcTyVar -> Bool
isMetaTyVar TcTyVar
tv) (TcTyVar -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcTyVar
tv) (Bool -> Bool) -> Bool -> Bool
forall a b. (a -> b) -> a -> b
$
    TcTyVar -> TcLevel
tcTyVarLevel TcTyVar
tv TcLevel -> TcLevel -> Bool
`strictlyDeeperThan` TcLevel
tclvl
  = do { cloned_tv <- TcTyVar -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
cloneMetaTyVar TcTyVar
tv
       ; let rhs_tv = TcTyVar -> TcLevel -> TcTyVar
setMetaTyVarTcLevel TcTyVar
cloned_tv TcLevel
tclvl
       ; liftZonkM $ writeMetaTyVar tv (mkTyVarTy rhs_tv)
       ; traceTc "promoteTyVar" (ppr tv <+> text "-->" <+> ppr rhs_tv)
       ; return True }
   | Bool
otherwise
   = Bool -> TcRnIf TcGblEnv TcLclEnv Bool
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
False

-- Returns whether or not *any* tyvar is defaulted
promoteTyVarSet :: HasDebugCallStack => TcTyVarSet -> TcM Bool
promoteTyVarSet :: HasDebugCallStack => CoVarSet -> TcRnIf TcGblEnv TcLclEnv Bool
promoteTyVarSet CoVarSet
tvs
  = do { tclvl <- TcM TcLevel
getTcLevel
       ; bools <- mapM (promoteMetaTyVarTo tclvl)  $
                  filter isPromotableMetaTyVar $
                  nonDetEltsUniqSet tvs
         -- Non-determinism is OK because order of promotion doesn't matter
       ; return (or bools) }

{-
%************************************************************************
%*                                                                      *
             Representation polymorphism checks
*                                                                       *
***********************************************************************-}

-- | Check that the specified type has a fixed runtime representation.
--
-- If it isn't, throw a representation-polymorphism error appropriate
-- for the context (as specified by the 'FixedRuntimeRepProvenance').
--
-- Unlike the other representation polymorphism checks, which can emit
-- new Wanted constraints to be solved by the constraint solver, this function
-- does not emit any constraints: it has enough information to immediately
-- make a decision.
--
-- See (1) in Note [Representation polymorphism checking] in GHC.Tc.Utils.Concrete
checkTypeHasFixedRuntimeRep :: FixedRuntimeRepProvenance -> Type -> TcM ()
checkTypeHasFixedRuntimeRep :: FixedRuntimeRepProvenance -> TcType -> TcRn ()
checkTypeHasFixedRuntimeRep FixedRuntimeRepProvenance
prov TcType
ty =
  Bool -> TcRn () -> TcRn ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (HasDebugCallStack => TcType -> Bool
TcType -> Bool
typeHasFixedRuntimeRep TcType
ty)
    ((ErrInfo -> TcRnMessage) -> TcRn ()
addDetailedDiagnostic ((ErrInfo -> TcRnMessage) -> TcRn ())
-> (ErrInfo -> TcRnMessage) -> TcRn ()
forall a b. (a -> b) -> a -> b
$ TcType -> FixedRuntimeRepProvenance -> ErrInfo -> TcRnMessage
TcRnTypeDoesNotHaveFixedRuntimeRep TcType
ty FixedRuntimeRepProvenance
prov)

{-
%************************************************************************
%*                                                                      *
             Error messages
*                                                                       *
*************************************************************************

-}

-- See Note [Naughty quantification candidates]
naughtyQuantification :: TcType   -- original type user wanted to quantify
                      -> TcTyVar  -- naughty var
                      -> TyVarSet -- skolems that would escape
                      -> TcM a
naughtyQuantification :: forall a. TcType -> TcTyVar -> CoVarSet -> TcM a
naughtyQuantification TcType
orig_ty TcTyVar
tv CoVarSet
escapees
  = do { (orig_ty1, escapees') <- ZonkM (TcType, [TcTyVar]) -> TcM (TcType, [TcTyVar])
forall a. ZonkM a -> TcM a
liftZonkM (ZonkM (TcType, [TcTyVar]) -> TcM (TcType, [TcTyVar]))
-> ZonkM (TcType, [TcTyVar]) -> TcM (TcType, [TcTyVar])
forall a b. (a -> b) -> a -> b
$
           do { orig_ty1  <- TcType -> ZonkM TcType
zonkTcType TcType
orig_ty  -- in case it's not zonked
              ; escapees' <- zonkTcTyVarsToTcTyVars $
                             nonDetEltsUniqSet escapees
                             -- we'll just be printing, so no harmful non-determinism
              ; return (orig_ty1, escapees') }

       ; let fvs  = TcType -> [TcTyVar]
tyCoVarsOfTypeWellScoped TcType
orig_ty1
             env0 = TidyEnv -> [TcTyVar] -> TidyEnv
tidyFreeTyCoVars TidyEnv
emptyTidyEnv [TcTyVar]
fvs
             env  = TidyEnv
env0 TidyEnv -> [TcTyVar] -> TidyEnv
`delTidyEnvList` [TcTyVar]
escapees'
                    -- this avoids gratuitous renaming of the escaped
                    -- variables; very confusing to users!

             orig_ty'   = TidyEnv -> TcType -> TcType
tidyType TidyEnv
env TcType
orig_ty1
             tidied = (TcTyVar -> TcTyVar) -> [TcTyVar] -> [TcTyVar]
forall a b. (a -> b) -> [a] -> [b]
map (TidyEnv -> TcTyVar -> TcTyVar
tidyTyCoVarOcc TidyEnv
env) [TcTyVar]
escapees'
             msg = [TcTyVar] -> TcTyVar -> TcType -> TcRnMessage
TcRnSkolemEscape [TcTyVar]
tidied (TidyEnv -> TcTyVar -> TcTyVar
tidyTyCoVarOcc TidyEnv
env TcTyVar
tv) TcType
orig_ty'

       ; failWithTcM (env, msg) }