{-
(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.
-}

{-# LANGUAGE CPP, TupleSections, MultiWayIf #-}

module TcMType (
  TcTyVar, TcKind, TcType, TcTauType, TcThetaType, TcTyVarSet,

  --------------------------------
  -- Creating new mutable type variables
  newFlexiTyVar,
  newFlexiTyVarTy,              -- Kind -> TcM TcType
  newFlexiTyVarTys,             -- Int -> Kind -> TcM [TcType]
  newOpenFlexiTyVarTy, newOpenTypeKind,
  newMetaKindVar, newMetaKindVars, newMetaTyVarTyAtLevel,
  cloneMetaTyVar,
  newFmvTyVar, newFskTyVar,

  readMetaTyVar, writeMetaTyVar, writeMetaTyVarRef,
  newMetaDetails, isFilledMetaTyVar_maybe, isFilledMetaTyVar, isUnfilledMetaTyVar,

  --------------------------------
  -- Expected types
  ExpType(..), ExpSigmaType, ExpRhoType,
  mkCheckExpType,
  newInferExpType, newInferExpTypeInst, newInferExpTypeNoInst,
  readExpType, readExpType_maybe,
  expTypeToType, checkingExpType_maybe, checkingExpType,
  tauifyExpType, inferResultToType,

  --------------------------------
  -- Creating new evidence variables
  newEvVar, newEvVars, newDict,
  newWanted, newWanteds, newHoleCt, cloneWanted, cloneWC,
  emitWanted, emitWantedEq, emitWantedEvVar, emitWantedEvVars,
  emitDerivedEqs,
  newTcEvBinds, newNoTcEvBinds, addTcEvBind,

  newCoercionHole, fillCoercionHole, isFilledCoercionHole,
  unpackCoercionHole, unpackCoercionHole_maybe,
  checkCoercionHole,

  newImplication,

  --------------------------------
  -- Instantiation
  newMetaTyVars, newMetaTyVarX, newMetaTyVarsX,
  newMetaTyVarTyVars, newMetaTyVarTyVarX,
  newTyVarTyVar, cloneTyVarTyVar,
  newPatSigTyVar, newSkolemTyVar, newWildCardX,
  tcInstType,
  tcInstSkolTyVars, tcInstSkolTyVarsX, tcInstSkolTyVarsAt,
  tcSkolDFunType, tcSuperSkolTyVars, tcInstSuperSkolTyVarsX,

  freshenTyVarBndrs, freshenCoVarBndrsX,

  --------------------------------
  -- Zonking and tidying
  zonkTidyTcType, zonkTidyTcTypes, zonkTidyOrigin,
  tidyEvVar, tidyCt, tidySkolemInfo,
    zonkTcTyVar, zonkTcTyVars,
  zonkTcTyVarToTyVar, zonkTyVarTyVarPairs,
  zonkTyCoVarsAndFV, zonkTcTypeAndFV, zonkDTyCoVarSetAndFV,
  zonkTyCoVarsAndFVList,
  candidateQTyVarsOfType,  candidateQTyVarsOfKind,
  candidateQTyVarsOfTypes, candidateQTyVarsOfKinds,
  CandidatesQTvs(..), delCandidates, candidateKindVars, partitionCandidates,
  zonkAndSkolemise, skolemiseQuantifiedTyVar,
  defaultTyVar, quantifyTyVars, isQuantifiableTv,
  zonkTcType, zonkTcTypes, zonkCo,
  zonkTyCoVarKind,

  zonkEvVar, zonkWC, zonkSimples,
  zonkId, zonkCoVar,
  zonkCt, zonkSkolemInfo,

  skolemiseUnboundMetaTyVar,

  ------------------------------
  -- Levity polymorphism
  ensureNotLevPoly, checkForLevPoly, checkForLevPolyX, formatLevPolyErr
  ) where

#include "HsVersions.h"

-- friends:
import GhcPrelude

import TyCoRep
import TyCoPpr
import TcType
import Type
import TyCon
import Coercion
import Class
import Var
import Predicate
import TcOrigin

-- others:
import TcRnMonad        -- TcType, amongst others
import Constraint
import TcEvidence
import Id
import Name
import VarSet
import TysWiredIn
import TysPrim
import VarEnv
import NameEnv
import PrelNames
import Util
import Outputable
import FastString
import Bag
import Pair
import UniqSet
import DynFlags
import qualified GHC.LanguageExtensions as LangExt
import BasicTypes ( TypeOrKind(..) )

import Control.Monad
import Maybes
import Data.List        ( mapAccumL )
import Control.Arrow    ( second )
import qualified Data.Semigroup as Semi

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

mkKindName :: Unique -> Name
mkKindName :: Unique -> Name
mkKindName Unique
unique = Unique -> OccName -> Name
mkSystemName Unique
unique OccName
kind_var_occ

kind_var_occ :: OccName -- Just one for all MetaKindVars
                        -- They may be jiggled by tidying
kind_var_occ :: OccName
kind_var_occ = NameSpace -> String -> OccName
mkOccName NameSpace
tvName String
"k"

newMetaKindVar :: TcM TcKind
newMetaKindVar :: TcM TcKind
newMetaKindVar
  = do { TcTyVarDetails
details <- MetaInfo -> TcM TcTyVarDetails
newMetaDetails MetaInfo
TauTv
       ; Unique
uniq <- TcRnIf TcGblEnv TcLclEnv Unique
forall gbl lcl. TcRnIf gbl lcl Unique
newUnique
       ; let kv :: TyVar
kv = Name -> TcKind -> TcTyVarDetails -> TyVar
mkTcTyVar (Unique -> Name
mkKindName Unique
uniq) TcKind
liftedTypeKind TcTyVarDetails
details
       ; String -> SDoc -> TcRn ()
traceTc String
"newMetaKindVar" (TyVar -> SDoc
forall a. Outputable a => a -> SDoc
ppr TyVar
kv)
       ; TcKind -> TcM TcKind
forall (m :: * -> *) a. Monad m => a -> m a
return (TyVar -> TcKind
mkTyVarTy TyVar
kv) }

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

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

newEvVars :: TcThetaType -> TcM [EvVar]
newEvVars :: [TcKind] -> TcM [TyVar]
newEvVars [TcKind]
theta = (TcKind -> IOEnv (Env TcGblEnv TcLclEnv) TyVar)
-> [TcKind] -> TcM [TyVar]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM TcKind -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
forall gbl lcl. TcKind -> TcRnIf gbl lcl TyVar
newEvVar [TcKind]
theta

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

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

newWanted :: CtOrigin -> Maybe TypeOrKind -> PredType -> TcM CtEvidence
-- Deals with both equality and non-equality predicates
newWanted :: CtOrigin -> Maybe TypeOrKind -> TcKind -> TcM CtEvidence
newWanted CtOrigin
orig Maybe TypeOrKind
t_or_k TcKind
pty
  = do CtLoc
loc <- CtOrigin -> Maybe TypeOrKind -> TcM CtLoc
getCtLocM CtOrigin
orig Maybe TypeOrKind
t_or_k
       TcEvDest
d <- if TcKind -> Bool
isEqPrimPred TcKind
pty then 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
<$> TcKind -> IOEnv (Env TcGblEnv TcLclEnv) CoercionHole
newCoercionHole TcKind
pty
                                else TyVar -> TcEvDest
EvVarDest (TyVar -> TcEvDest)
-> IOEnv (Env TcGblEnv TcLclEnv) TyVar
-> IOEnv (Env TcGblEnv TcLclEnv) TcEvDest
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> TcKind -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
forall gbl lcl. TcKind -> TcRnIf gbl lcl TyVar
newEvVar TcKind
pty
       CtEvidence -> TcM CtEvidence
forall (m :: * -> *) a. Monad m => a -> m a
return (CtEvidence -> TcM CtEvidence) -> CtEvidence -> TcM CtEvidence
forall a b. (a -> b) -> a -> b
$ CtWanted :: TcKind -> TcEvDest -> ShadowInfo -> CtLoc -> CtEvidence
CtWanted { ctev_dest :: TcEvDest
ctev_dest = TcEvDest
d
                         , ctev_pred :: TcKind
ctev_pred = TcKind
pty
                         , ctev_nosh :: ShadowInfo
ctev_nosh = ShadowInfo
WDeriv
                         , ctev_loc :: CtLoc
ctev_loc = CtLoc
loc }

newWanteds :: CtOrigin -> ThetaType -> TcM [CtEvidence]
newWanteds :: CtOrigin -> [TcKind] -> TcM [CtEvidence]
newWanteds CtOrigin
orig = (TcKind -> TcM CtEvidence) -> [TcKind] -> TcM [CtEvidence]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM (CtOrigin -> Maybe TypeOrKind -> TcKind -> TcM CtEvidence
newWanted CtOrigin
orig Maybe TypeOrKind
forall a. Maybe a
Nothing)

-- | Create a new 'CHoleCan' 'Ct'.
newHoleCt :: Hole -> Id -> Type -> TcM Ct
newHoleCt :: Hole -> TyVar -> TcKind -> TcM Ct
newHoleCt Hole
hole TyVar
ev TcKind
ty = do
  CtLoc
loc <- CtOrigin -> Maybe TypeOrKind -> TcM CtLoc
getCtLocM CtOrigin
HoleOrigin Maybe TypeOrKind
forall a. Maybe a
Nothing
  Ct -> TcM Ct
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Ct -> TcM Ct) -> Ct -> TcM Ct
forall a b. (a -> b) -> a -> b
$ CHoleCan :: CtEvidence -> Hole -> Ct
CHoleCan { cc_ev :: CtEvidence
cc_ev = CtWanted :: TcKind -> TcEvDest -> ShadowInfo -> CtLoc -> CtEvidence
CtWanted { ctev_pred :: TcKind
ctev_pred = TcKind
ty
                                     , ctev_dest :: TcEvDest
ctev_dest = TyVar -> TcEvDest
EvVarDest TyVar
ev
                                     , ctev_nosh :: ShadowInfo
ctev_nosh = ShadowInfo
WDeriv
                                     , ctev_loc :: CtLoc
ctev_loc  = CtLoc
loc }
                  , cc_hole :: Hole
cc_hole = Hole
hole }

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

cloneWanted :: Ct -> TcM Ct
cloneWanted :: Ct -> TcM Ct
cloneWanted Ct
ct
  | ev :: CtEvidence
ev@(CtWanted { ctev_dest :: CtEvidence -> TcEvDest
ctev_dest = HoleDest {}, ctev_pred :: CtEvidence -> TcKind
ctev_pred = TcKind
pty }) <- Ct -> CtEvidence
ctEvidence Ct
ct
  = do { CoercionHole
co_hole <- TcKind -> IOEnv (Env TcGblEnv TcLclEnv) CoercionHole
newCoercionHole TcKind
pty
       ; Ct -> TcM Ct
forall (m :: * -> *) a. Monad m => a -> m a
return (CtEvidence -> Ct
mkNonCanonical (CtEvidence
ev { ctev_dest :: TcEvDest
ctev_dest = CoercionHole -> TcEvDest
HoleDest CoercionHole
co_hole })) }
  | Bool
otherwise
  = Ct -> TcM Ct
forall (m :: * -> *) a. Monad m => a -> m a
return 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 { Cts
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
       ; Bag Implication
implics' <- (Implication -> IOEnv (Env TcGblEnv TcLclEnv) Implication)
-> Bag Implication
-> IOEnv (Env TcGblEnv TcLclEnv) (Bag Implication)
forall (m :: * -> *) a b.
Monad m =>
(a -> m b) -> Bag a -> m (Bag b)
mapBagM Implication -> IOEnv (Env TcGblEnv TcLclEnv) Implication
cloneImplication Bag Implication
implics
       ; WantedConstraints -> TcM WantedConstraints
forall (m :: * -> *) a. Monad m => a -> m a
return (WantedConstraints
wc { wc_simple :: Cts
wc_simple = Cts
simples', wc_impl :: Bag Implication
wc_impl = Bag Implication
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 { EvBindsVar
binds'        <- EvBindsVar -> TcM EvBindsVar
cloneEvBindsVar EvBindsVar
binds
       ; WantedConstraints
inner_wanted' <- WantedConstraints -> TcM WantedConstraints
cloneWC WantedConstraints
inner_wanted
       ; Implication -> IOEnv (Env TcGblEnv TcLclEnv) Implication
forall (m :: * -> *) a. Monad m => a -> m a
return (Implication
implic { ic_binds :: EvBindsVar
ic_binds = EvBindsVar
binds', ic_wanted :: WantedConstraints
ic_wanted = WantedConstraints
inner_wanted' }) }

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

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

emitDerivedEqs :: CtOrigin -> [(TcType,TcType)] -> TcM ()
-- Emit some new derived nominal equalities
emitDerivedEqs :: CtOrigin -> [(TcKind, TcKind)] -> TcRn ()
emitDerivedEqs CtOrigin
origin [(TcKind, TcKind)]
pairs
  | [(TcKind, TcKind)] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [(TcKind, TcKind)]
pairs
  = () -> TcRn ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()
  | Bool
otherwise
  = do { CtLoc
loc <- CtOrigin -> Maybe TypeOrKind -> TcM CtLoc
getCtLocM CtOrigin
origin Maybe TypeOrKind
forall a. Maybe a
Nothing
       ; Cts -> TcRn ()
emitSimples ([Ct] -> Cts
forall a. [a] -> Bag a
listToBag (((TcKind, TcKind) -> Ct) -> [(TcKind, TcKind)] -> [Ct]
forall a b. (a -> b) -> [a] -> [b]
map (CtLoc -> (TcKind, TcKind) -> Ct
mk_one CtLoc
loc) [(TcKind, TcKind)]
pairs)) }
  where
    mk_one :: CtLoc -> (TcKind, TcKind) -> Ct
mk_one CtLoc
loc (TcKind
ty1, TcKind
ty2)
       = CtEvidence -> Ct
mkNonCanonical (CtEvidence -> Ct) -> CtEvidence -> Ct
forall a b. (a -> b) -> a -> b
$
         CtDerived :: TcKind -> CtLoc -> CtEvidence
CtDerived { ctev_pred :: TcKind
ctev_pred = TcKind -> TcKind -> TcKind
mkPrimEqPred TcKind
ty1 TcKind
ty2
                   , ctev_loc :: CtLoc
ctev_loc = CtLoc
loc }

-- | Emits a new equality constraint
emitWantedEq :: CtOrigin -> TypeOrKind -> Role -> TcType -> TcType -> TcM Coercion
emitWantedEq :: CtOrigin -> TypeOrKind -> Role -> TcKind -> TcKind -> TcM Coercion
emitWantedEq CtOrigin
origin TypeOrKind
t_or_k Role
role TcKind
ty1 TcKind
ty2
  = do { CoercionHole
hole <- TcKind -> IOEnv (Env TcGblEnv TcLclEnv) CoercionHole
newCoercionHole TcKind
pty
       ; CtLoc
loc <- CtOrigin -> Maybe TypeOrKind -> TcM CtLoc
getCtLocM CtOrigin
origin (TypeOrKind -> Maybe TypeOrKind
forall a. a -> Maybe a
Just TypeOrKind
t_or_k)
       ; Ct -> TcRn ()
emitSimple (Ct -> TcRn ()) -> Ct -> TcRn ()
forall a b. (a -> b) -> a -> b
$ CtEvidence -> Ct
mkNonCanonical (CtEvidence -> Ct) -> CtEvidence -> Ct
forall a b. (a -> b) -> a -> b
$
         CtWanted :: TcKind -> TcEvDest -> ShadowInfo -> CtLoc -> CtEvidence
CtWanted { ctev_pred :: TcKind
ctev_pred = TcKind
pty, ctev_dest :: TcEvDest
ctev_dest = CoercionHole -> TcEvDest
HoleDest CoercionHole
hole
                  , ctev_nosh :: ShadowInfo
ctev_nosh = ShadowInfo
WDeriv, ctev_loc :: CtLoc
ctev_loc = CtLoc
loc }
       ; Coercion -> TcM Coercion
forall (m :: * -> *) a. Monad m => a -> m a
return (CoercionHole -> Coercion
HoleCo CoercionHole
hole) }
  where
    pty :: TcKind
pty = Role -> TcKind -> TcKind -> TcKind
mkPrimEqPredRole Role
role TcKind
ty1 TcKind
ty2

-- | Creates a new EvVar and immediately emits it as a Wanted.
-- No equality predicates here.
emitWantedEvVar :: CtOrigin -> TcPredType -> TcM EvVar
emitWantedEvVar :: CtOrigin -> TcKind -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
emitWantedEvVar CtOrigin
origin TcKind
ty
  = do { TyVar
new_cv <- TcKind -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
forall gbl lcl. TcKind -> TcRnIf gbl lcl TyVar
newEvVar TcKind
ty
       ; CtLoc
loc <- CtOrigin -> Maybe TypeOrKind -> TcM CtLoc
getCtLocM CtOrigin
origin Maybe TypeOrKind
forall a. Maybe a
Nothing
       ; let ctev :: CtEvidence
ctev = CtWanted :: TcKind -> TcEvDest -> ShadowInfo -> CtLoc -> CtEvidence
CtWanted { ctev_dest :: TcEvDest
ctev_dest = TyVar -> TcEvDest
EvVarDest TyVar
new_cv
                             , ctev_pred :: TcKind
ctev_pred = TcKind
ty
                             , ctev_nosh :: ShadowInfo
ctev_nosh = ShadowInfo
WDeriv
                             , ctev_loc :: CtLoc
ctev_loc  = CtLoc
loc }
       ; Ct -> TcRn ()
emitSimple (Ct -> TcRn ()) -> Ct -> TcRn ()
forall a b. (a -> b) -> a -> b
$ CtEvidence -> Ct
mkNonCanonical CtEvidence
ctev
       ; TyVar -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
forall (m :: * -> *) a. Monad m => a -> m a
return TyVar
new_cv }

emitWantedEvVars :: CtOrigin -> [TcPredType] -> TcM [EvVar]
emitWantedEvVars :: CtOrigin -> [TcKind] -> TcM [TyVar]
emitWantedEvVars CtOrigin
orig = (TcKind -> IOEnv (Env TcGblEnv TcLclEnv) TyVar)
-> [TcKind] -> TcM [TyVar]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM (CtOrigin -> TcKind -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
emitWantedEvVar CtOrigin
orig)

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

predTypeOccName :: PredType -> OccName
predTypeOccName :: TcKind -> OccName
predTypeOccName TcKind
ty = case TcKind -> Pred
classifyPredType TcKind
ty of
    ClassPred Class
cls [TcKind]
_ -> 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 TcInstDcls.
newImplication :: TcM Implication
newImplication :: IOEnv (Env TcGblEnv TcLclEnv) Implication
newImplication
  = do TcLclEnv
env <- TcRnIf TcGblEnv TcLclEnv TcLclEnv
forall gbl lcl. TcRnIf gbl lcl lcl
getLclEnv
       Bool
warn_inaccessible <- WarningFlag -> TcRnIf TcGblEnv TcLclEnv Bool
forall gbl lcl. WarningFlag -> TcRnIf gbl lcl Bool
woptM WarningFlag
Opt_WarnInaccessibleCode
       Implication -> IOEnv (Env TcGblEnv TcLclEnv) Implication
forall (m :: * -> *) a. Monad m => a -> m a
return (Implication
implicationPrototype { ic_env :: TcLclEnv
ic_env = TcLclEnv
env
                                    , ic_warn_inaccessible :: Bool
ic_warn_inaccessible = Bool
warn_inaccessible })

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

newCoercionHole :: TcPredType -> TcM CoercionHole
newCoercionHole :: TcKind -> IOEnv (Env TcGblEnv TcLclEnv) CoercionHole
newCoercionHole TcKind
pred_ty
  = do { TyVar
co_var <- TcKind -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
forall gbl lcl. TcKind -> TcRnIf gbl lcl TyVar
newEvVar TcKind
pred_ty
       ; String -> SDoc -> TcRn ()
traceTc String
"New coercion hole:" (TyVar -> SDoc
forall a. Outputable a => a -> SDoc
ppr TyVar
co_var)
       ; IORef (Maybe Coercion)
ref <- Maybe Coercion
-> IOEnv (Env TcGblEnv TcLclEnv) (IORef (Maybe Coercion))
forall a env. a -> IOEnv env (IORef a)
newMutVar Maybe Coercion
forall a. Maybe a
Nothing
       ; CoercionHole -> IOEnv (Env TcGblEnv TcLclEnv) CoercionHole
forall (m :: * -> *) a. Monad m => a -> m a
return (CoercionHole -> IOEnv (Env TcGblEnv TcLclEnv) CoercionHole)
-> CoercionHole -> IOEnv (Env TcGblEnv TcLclEnv) CoercionHole
forall a b. (a -> b) -> a -> b
$ CoercionHole :: TyVar -> IORef (Maybe Coercion) -> CoercionHole
CoercionHole { ch_co_var :: TyVar
ch_co_var = TyVar
co_var, ch_ref :: IORef (Maybe Coercion)
ch_ref = IORef (Maybe Coercion)
ref } }

-- | 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 -> TyVar
ch_co_var = TyVar
cv }) Coercion
co
  = do {
#if defined(DEBUG)
       ; cts <- readTcRef ref
       ; whenIsJust cts $ \old_co ->
         pprPanic "Filling a filled coercion hole" (ppr cv $$ ppr co $$ ppr old_co)
#endif
       ; String -> SDoc -> TcRn ()
traceTc String
"Filling coercion hole" (TyVar -> SDoc
forall a. Outputable a => a -> SDoc
ppr TyVar
cv SDoc -> SDoc -> SDoc
<+> String -> SDoc
text String
":=" SDoc -> SDoc -> SDoc
<+> Coercion -> SDoc
forall a. Outputable a => a -> SDoc
ppr Coercion
co)
       ; IORef (Maybe Coercion) -> Maybe Coercion -> TcRn ()
forall a gbl lcl. TcRef a -> a -> TcRnIf gbl lcl ()
writeTcRef IORef (Maybe Coercion)
ref (Coercion -> Maybe Coercion
forall a. a -> Maybe a
Just Coercion
co) }

-- | Is a coercion hole filled in?
isFilledCoercionHole :: CoercionHole -> TcM Bool
isFilledCoercionHole :: CoercionHole -> TcRnIf TcGblEnv TcLclEnv Bool
isFilledCoercionHole (CoercionHole { ch_ref :: CoercionHole -> IORef (Maybe Coercion)
ch_ref = IORef (Maybe Coercion)
ref }) = Maybe Coercion -> Bool
forall a. Maybe a -> Bool
isJust (Maybe Coercion -> Bool)
-> IOEnv (Env TcGblEnv TcLclEnv) (Maybe Coercion)
-> TcRnIf TcGblEnv TcLclEnv Bool
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> IORef (Maybe Coercion)
-> IOEnv (Env TcGblEnv TcLclEnv) (Maybe Coercion)
forall a gbl lcl. TcRef a -> TcRnIf gbl lcl a
readTcRef IORef (Maybe Coercion)
ref

-- | Retrieve the contents of a coercion hole. Panics if the hole
-- is unfilled
unpackCoercionHole :: CoercionHole -> TcM Coercion
unpackCoercionHole :: CoercionHole -> TcM Coercion
unpackCoercionHole CoercionHole
hole
  = do { Maybe Coercion
contents <- CoercionHole -> IOEnv (Env TcGblEnv TcLclEnv) (Maybe Coercion)
unpackCoercionHole_maybe CoercionHole
hole
       ; case Maybe Coercion
contents of
           Just Coercion
co -> Coercion -> TcM Coercion
forall (m :: * -> *) a. Monad m => a -> m a
return Coercion
co
           Maybe Coercion
Nothing -> String -> SDoc -> TcM Coercion
forall a. HasCallStack => String -> SDoc -> a
pprPanic String
"Unfilled coercion hole" (CoercionHole -> SDoc
forall a. Outputable a => a -> SDoc
ppr CoercionHole
hole) }

-- | Retrieve the contents of a coercion hole, if it is filled
unpackCoercionHole_maybe :: CoercionHole -> TcM (Maybe Coercion)
unpackCoercionHole_maybe :: CoercionHole -> IOEnv (Env TcGblEnv TcLclEnv) (Maybe Coercion)
unpackCoercionHole_maybe (CoercionHole { ch_ref :: CoercionHole -> IORef (Maybe Coercion)
ch_ref = IORef (Maybe Coercion)
ref }) = IORef (Maybe Coercion)
-> IOEnv (Env TcGblEnv TcLclEnv) (Maybe Coercion)
forall a gbl lcl. TcRef a -> TcRnIf gbl lcl a
readTcRef IORef (Maybe Coercion)
ref

-- | Check that a coercion is appropriate for filling a hole. (The hole
-- itself is needed only for printing.
-- Always returns the checked coercion, but this return value is necessary
-- so that the input coercion is forced only when the output is forced.
checkCoercionHole :: CoVar -> Coercion -> TcM Coercion
checkCoercionHole :: TyVar -> Coercion -> TcM Coercion
checkCoercionHole TyVar
cv Coercion
co
  | Bool
debugIsOn
  = do { TcKind
cv_ty <- TcKind -> TcM TcKind
zonkTcType (TyVar -> TcKind
varType TyVar
cv)
                  -- co is already zonked, but cv might not be
       ; Coercion -> TcM Coercion
forall (m :: * -> *) a. Monad m => a -> m a
return (Coercion -> TcM Coercion) -> Coercion -> TcM Coercion
forall a b. (a -> b) -> a -> b
$
         ASSERT2( ok cv_ty
                , (text "Bad coercion hole" <+>
                   ppr cv <> colon <+> vcat [ ppr t1, ppr t2, ppr role
                                            , ppr cv_ty ]) )
         Coercion
co }
  | Bool
otherwise
  = Coercion -> TcM Coercion
forall (m :: * -> *) a. Monad m => a -> m a
return Coercion
co

  where
    (Pair TcKind
t1 TcKind
t2, Role
role) = Coercion -> (Pair TcKind, Role)
coercionKindRole Coercion
co
    ok :: TcKind -> Bool
ok TcKind
cv_ty | EqPred EqRel
cv_rel TcKind
cv_t1 TcKind
cv_t2 <- TcKind -> Pred
classifyPredType TcKind
cv_ty
             =  TcKind
t1 TcKind -> TcKind -> Bool
`eqType` TcKind
cv_t1
             Bool -> Bool -> Bool
&& TcKind
t2 TcKind -> TcKind -> Bool
`eqType` TcKind
cv_t2
             Bool -> Bool -> Bool
&& Role
role Role -> Role -> Bool
forall a. Eq a => a -> a -> Bool
== EqRel -> Role
eqRelRole EqRel
cv_rel
             | Bool
otherwise
             = Bool
False

{-
************************************************************************
*
    Expected types
*
************************************************************************

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.
And, because there is only one branch of the case, we won't trigger
Note [Case branches must never infer a non-tau type] of TcMatches.
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. This is triggered in
test gadt/gadt-escape1.

-}

-- actual data definition is in TcType

-- | Make an 'ExpType' suitable for inferring a type of kind * or #.
newInferExpTypeNoInst :: TcM ExpSigmaType
newInferExpTypeNoInst :: TcM ExpSigmaType
newInferExpTypeNoInst = Bool -> TcM ExpSigmaType
newInferExpType Bool
False

newInferExpTypeInst :: TcM ExpRhoType
newInferExpTypeInst :: TcM ExpSigmaType
newInferExpTypeInst = Bool -> TcM ExpSigmaType
newInferExpType Bool
True

newInferExpType :: Bool -> TcM ExpType
newInferExpType :: Bool -> TcM ExpSigmaType
newInferExpType Bool
inst
  = do { Unique
u <- TcRnIf TcGblEnv TcLclEnv Unique
forall gbl lcl. TcRnIf gbl lcl Unique
newUnique
       ; TcLevel
tclvl <- TcM TcLevel
getTcLevel
       ; String -> SDoc -> TcRn ()
traceTc String
"newOpenInferExpType" (Unique -> SDoc
forall a. Outputable a => a -> SDoc
ppr Unique
u SDoc -> SDoc -> SDoc
<+> Bool -> SDoc
forall a. Outputable a => a -> SDoc
ppr Bool
inst SDoc -> SDoc -> SDoc
<+> TcLevel -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcLevel
tclvl)
       ; IORef (Maybe TcKind)
ref <- Maybe TcKind
-> IOEnv (Env TcGblEnv TcLclEnv) (IORef (Maybe TcKind))
forall a env. a -> IOEnv env (IORef a)
newMutVar Maybe TcKind
forall a. Maybe a
Nothing
       ; ExpSigmaType -> TcM ExpSigmaType
forall (m :: * -> *) a. Monad m => a -> m a
return (InferResult -> ExpSigmaType
Infer (IR :: Unique -> TcLevel -> Bool -> IORef (Maybe TcKind) -> InferResult
IR { ir_uniq :: Unique
ir_uniq = Unique
u, ir_lvl :: TcLevel
ir_lvl = TcLevel
tclvl
                           , ir_ref :: IORef (Maybe TcKind)
ir_ref = IORef (Maybe TcKind)
ref, ir_inst :: Bool
ir_inst = Bool
inst })) }

-- | 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 :: ExpType -> TcM (Maybe TcType)
readExpType_maybe :: ExpSigmaType -> TcM (Maybe TcKind)
readExpType_maybe (Check TcKind
ty)                   = Maybe TcKind -> TcM (Maybe TcKind)
forall (m :: * -> *) a. Monad m => a -> m a
return (TcKind -> Maybe TcKind
forall a. a -> Maybe a
Just TcKind
ty)
readExpType_maybe (Infer (IR { ir_ref :: InferResult -> IORef (Maybe TcKind)
ir_ref = IORef (Maybe TcKind)
ref})) = IORef (Maybe TcKind) -> TcM (Maybe TcKind)
forall a env. IORef a -> IOEnv env a
readMutVar IORef (Maybe TcKind)
ref

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

-- | Returns the expected type when in checking mode.
checkingExpType_maybe :: ExpType -> Maybe TcType
checkingExpType_maybe :: ExpSigmaType -> Maybe TcKind
checkingExpType_maybe (Check TcKind
ty) = TcKind -> Maybe TcKind
forall a. a -> Maybe a
Just TcKind
ty
checkingExpType_maybe ExpSigmaType
_          = Maybe TcKind
forall a. Maybe a
Nothing

-- | Returns the expected type when in checking mode. Panics if in inference
-- mode.
checkingExpType :: String -> ExpType -> TcType
checkingExpType :: String -> ExpSigmaType -> TcKind
checkingExpType String
_   (Check TcKind
ty) = TcKind
ty
checkingExpType String
err ExpSigmaType
et         = String -> SDoc -> TcKind
forall a. HasCallStack => String -> SDoc -> a
pprPanic String
"checkingExpType" (String -> SDoc
text String
err SDoc -> SDoc -> SDoc
$$ ExpSigmaType -> SDoc
forall a. Outputable a => a -> SDoc
ppr ExpSigmaType
et)

tauifyExpType :: ExpType -> TcM ExpType
-- ^ Turn a (Infer hole) type into a (Check alpha),
-- where alpha is a fresh unification variable
tauifyExpType :: ExpSigmaType -> TcM ExpSigmaType
tauifyExpType (Check TcKind
ty)      = ExpSigmaType -> TcM ExpSigmaType
forall (m :: * -> *) a. Monad m => a -> m a
return (TcKind -> ExpSigmaType
Check TcKind
ty)  -- No-op for (Check ty)
tauifyExpType (Infer InferResult
inf_res) = do { TcKind
ty <- InferResult -> TcM TcKind
inferResultToType InferResult
inf_res
                                   ; ExpSigmaType -> TcM ExpSigmaType
forall (m :: * -> *) a. Monad m => a -> m a
return (TcKind -> ExpSigmaType
Check TcKind
ty) }

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

inferResultToType :: InferResult -> TcM Type
inferResultToType :: InferResult -> TcM TcKind
inferResultToType (IR { ir_uniq :: InferResult -> Unique
ir_uniq = Unique
u, ir_lvl :: InferResult -> TcLevel
ir_lvl = TcLevel
tc_lvl
                      , ir_ref :: InferResult -> IORef (Maybe TcKind)
ir_ref = IORef (Maybe TcKind)
ref })
  = do { TcKind
rr  <- TcLevel -> TcKind -> TcM TcKind
newMetaTyVarTyAtLevel TcLevel
tc_lvl TcKind
runtimeRepTy
       ; TcKind
tau <- TcLevel -> TcKind -> TcM TcKind
newMetaTyVarTyAtLevel TcLevel
tc_lvl (TcKind -> TcKind
tYPE TcKind
rr)
             -- See Note [TcLevel of ExpType]
       ; IORef (Maybe TcKind) -> Maybe TcKind -> TcRn ()
forall a env. IORef a -> a -> IOEnv env ()
writeMutVar IORef (Maybe TcKind)
ref (TcKind -> Maybe TcKind
forall a. a -> Maybe a
Just TcKind
tau)
       ; String -> SDoc -> TcRn ()
traceTc String
"Forcing ExpType to be monomorphic:"
                 (Unique -> SDoc
forall a. Outputable a => a -> SDoc
ppr Unique
u SDoc -> SDoc -> SDoc
<+> String -> SDoc
text String
":=" SDoc -> SDoc -> SDoc
<+> TcKind -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcKind
tau)
       ; TcKind -> TcM TcKind
forall (m :: * -> *) a. Monad m => a -> m a
return TcKind
tau }


{- *********************************************************************
*                                                                      *
        SkolemTvs (immutable)
*                                                                      *
********************************************************************* -}

tcInstType :: ([TyVar] -> TcM (TCvSubst, [TcTyVar]))
                   -- ^ How to instantiate the type variables
           -> Id                                            -- ^ Type to instantiate
           -> TcM ([(Name, TcTyVar)], TcThetaType, TcType)  -- ^ Result
                -- (type vars, preds (incl equalities), rho)
tcInstType :: ([TyVar] -> TcM (TCvSubst, [TyVar]))
-> TyVar -> TcM ([(Name, TyVar)], [TcKind], TcKind)
tcInstType [TyVar] -> TcM (TCvSubst, [TyVar])
inst_tyvars TyVar
id
  = case TcKind -> ([TyVar], TcKind)
tcSplitForAllTys (TyVar -> TcKind
idType TyVar
id) of
        ([],    TcKind
rho) -> let     -- There may be overloading despite no type variables;
                                --      (?x :: Int) => Int -> Int
                                ([TcKind]
theta, TcKind
tau) = TcKind -> ([TcKind], TcKind)
tcSplitPhiTy TcKind
rho
                            in
                            ([(Name, TyVar)], [TcKind], TcKind)
-> TcM ([(Name, TyVar)], [TcKind], TcKind)
forall (m :: * -> *) a. Monad m => a -> m a
return ([], [TcKind]
theta, TcKind
tau)

        ([TyVar]
tyvars, TcKind
rho) -> do { (TCvSubst
subst, [TyVar]
tyvars') <- [TyVar] -> TcM (TCvSubst, [TyVar])
inst_tyvars [TyVar]
tyvars
                            ; let ([TcKind]
theta, TcKind
tau) = TcKind -> ([TcKind], TcKind)
tcSplitPhiTy (TCvSubst -> TcKind -> TcKind
substTyAddInScope TCvSubst
subst TcKind
rho)
                                  tv_prs :: [(Name, TyVar)]
tv_prs       = (TyVar -> Name) -> [TyVar] -> [Name]
forall a b. (a -> b) -> [a] -> [b]
map TyVar -> Name
tyVarName [TyVar]
tyvars [Name] -> [TyVar] -> [(Name, TyVar)]
forall a b. [a] -> [b] -> [(a, b)]
`zip` [TyVar]
tyvars'
                            ; ([(Name, TyVar)], [TcKind], TcKind)
-> TcM ([(Name, TyVar)], [TcKind], TcKind)
forall (m :: * -> *) a. Monad m => a -> m a
return ([(Name, TyVar)]
tv_prs, [TcKind]
theta, TcKind
tau) }

tcSkolDFunType :: DFunId -> TcM ([TcTyVar], TcThetaType, TcType)
-- Instantiate a type signature with skolem constants.
-- We could give them fresh names, but no need to do so
tcSkolDFunType :: TyVar -> TcM ([TyVar], [TcKind], TcKind)
tcSkolDFunType TyVar
dfun
  = do { ([(Name, TyVar)]
tv_prs, [TcKind]
theta, TcKind
tau) <- ([TyVar] -> TcM (TCvSubst, [TyVar]))
-> TyVar -> TcM ([(Name, TyVar)], [TcKind], TcKind)
tcInstType [TyVar] -> TcM (TCvSubst, [TyVar])
tcInstSuperSkolTyVars TyVar
dfun
       ; ([TyVar], [TcKind], TcKind) -> TcM ([TyVar], [TcKind], TcKind)
forall (m :: * -> *) a. Monad m => a -> m a
return (((Name, TyVar) -> TyVar) -> [(Name, TyVar)] -> [TyVar]
forall a b. (a -> b) -> [a] -> [b]
map (Name, TyVar) -> TyVar
forall a b. (a, b) -> b
snd [(Name, TyVar)]
tv_prs, [TcKind]
theta, TcKind
tau) }

tcSuperSkolTyVars :: [TyVar] -> (TCvSubst, [TcTyVar])
-- Make skolem constants, but do *not* give them new names, as above
-- Moreover, make them "super skolems"; see comments with superSkolemTv
-- see Note [Kind substitution when instantiating]
-- Precondition: tyvars should be ordered by scoping
tcSuperSkolTyVars :: [TyVar] -> (TCvSubst, [TyVar])
tcSuperSkolTyVars = (TCvSubst -> TyVar -> (TCvSubst, TyVar))
-> TCvSubst -> [TyVar] -> (TCvSubst, [TyVar])
forall (t :: * -> *) a b c.
Traversable t =>
(a -> b -> (a, c)) -> a -> t b -> (a, t c)
mapAccumL TCvSubst -> TyVar -> (TCvSubst, TyVar)
tcSuperSkolTyVar TCvSubst
emptyTCvSubst

tcSuperSkolTyVar :: TCvSubst -> TyVar -> (TCvSubst, TcTyVar)
tcSuperSkolTyVar :: TCvSubst -> TyVar -> (TCvSubst, TyVar)
tcSuperSkolTyVar TCvSubst
subst TyVar
tv
  = (TCvSubst -> TyVar -> TyVar -> TCvSubst
extendTvSubstWithClone TCvSubst
subst TyVar
tv TyVar
new_tv, TyVar
new_tv)
  where
    kind :: TcKind
kind   = TCvSubst -> TcKind -> TcKind
substTyUnchecked TCvSubst
subst (TyVar -> TcKind
tyVarKind TyVar
tv)
    new_tv :: TyVar
new_tv = Name -> TcKind -> TcTyVarDetails -> TyVar
mkTcTyVar (TyVar -> Name
tyVarName TyVar
tv) TcKind
kind TcTyVarDetails
superSkolemTv

-- | Given a list of @['TyVar']@, skolemize the type variables,
-- returning a substitution mapping the original tyvars to the
-- skolems, and the list of newly bound skolems.
tcInstSkolTyVars :: [TyVar] -> TcM (TCvSubst, [TcTyVar])
-- See Note [Skolemising type variables]
tcInstSkolTyVars :: [TyVar] -> TcM (TCvSubst, [TyVar])
tcInstSkolTyVars = TCvSubst -> [TyVar] -> TcM (TCvSubst, [TyVar])
tcInstSkolTyVarsX TCvSubst
emptyTCvSubst

tcInstSkolTyVarsX :: TCvSubst -> [TyVar] -> TcM (TCvSubst, [TcTyVar])
-- See Note [Skolemising type variables]
tcInstSkolTyVarsX :: TCvSubst -> [TyVar] -> TcM (TCvSubst, [TyVar])
tcInstSkolTyVarsX = Bool -> TCvSubst -> [TyVar] -> TcM (TCvSubst, [TyVar])
tcInstSkolTyVarsPushLevel Bool
False

tcInstSuperSkolTyVars :: [TyVar] -> TcM (TCvSubst, [TcTyVar])
-- See Note [Skolemising type variables]
tcInstSuperSkolTyVars :: [TyVar] -> TcM (TCvSubst, [TyVar])
tcInstSuperSkolTyVars = TCvSubst -> [TyVar] -> TcM (TCvSubst, [TyVar])
tcInstSuperSkolTyVarsX TCvSubst
emptyTCvSubst

tcInstSuperSkolTyVarsX :: TCvSubst -> [TyVar] -> TcM (TCvSubst, [TcTyVar])
-- See Note [Skolemising type variables]
tcInstSuperSkolTyVarsX :: TCvSubst -> [TyVar] -> TcM (TCvSubst, [TyVar])
tcInstSuperSkolTyVarsX TCvSubst
subst = Bool -> TCvSubst -> [TyVar] -> TcM (TCvSubst, [TyVar])
tcInstSkolTyVarsPushLevel Bool
True TCvSubst
subst

tcInstSkolTyVarsPushLevel :: Bool -> TCvSubst -> [TyVar]
                          -> TcM (TCvSubst, [TcTyVar])
-- Skolemise one level deeper, hence pushTcLevel
-- See Note [Skolemising type variables]
tcInstSkolTyVarsPushLevel :: Bool -> TCvSubst -> [TyVar] -> TcM (TCvSubst, [TyVar])
tcInstSkolTyVarsPushLevel Bool
overlappable TCvSubst
subst [TyVar]
tvs
  = do { TcLevel
tc_lvl <- TcM TcLevel
getTcLevel
       ; let pushed_lvl :: TcLevel
pushed_lvl = TcLevel -> TcLevel
pushTcLevel TcLevel
tc_lvl
       ; TcLevel -> Bool -> TCvSubst -> [TyVar] -> TcM (TCvSubst, [TyVar])
tcInstSkolTyVarsAt TcLevel
pushed_lvl Bool
overlappable TCvSubst
subst [TyVar]
tvs }

tcInstSkolTyVarsAt :: TcLevel -> Bool
                   -> TCvSubst -> [TyVar]
                   -> TcM (TCvSubst, [TcTyVar])
tcInstSkolTyVarsAt :: TcLevel -> Bool -> TCvSubst -> [TyVar] -> TcM (TCvSubst, [TyVar])
tcInstSkolTyVarsAt TcLevel
lvl Bool
overlappable TCvSubst
subst [TyVar]
tvs
  = (Name -> TcKind -> TyVar)
-> TCvSubst -> [TyVar] -> TcM (TCvSubst, [TyVar])
freshenTyCoVarsX Name -> TcKind -> TyVar
new_skol_tv TCvSubst
subst [TyVar]
tvs
  where
    details :: TcTyVarDetails
details = TcLevel -> Bool -> TcTyVarDetails
SkolemTv TcLevel
lvl Bool
overlappable
    new_skol_tv :: Name -> TcKind -> TyVar
new_skol_tv Name
name TcKind
kind = Name -> TcKind -> TcTyVarDetails -> TyVar
mkTcTyVar Name
name TcKind
kind TcTyVarDetails
details

------------------
freshenTyVarBndrs :: [TyVar] -> TcM (TCvSubst, [TyVar])
-- ^ Give fresh uniques to a bunch of TyVars, but they stay
--   as TyVars, rather than becoming TcTyVars
-- Used in FamInst.newFamInst, and Inst.newClsInst
freshenTyVarBndrs :: [TyVar] -> TcM (TCvSubst, [TyVar])
freshenTyVarBndrs = (Name -> TcKind -> TyVar) -> [TyVar] -> TcM (TCvSubst, [TyVar])
freshenTyCoVars Name -> TcKind -> TyVar
mkTyVar

freshenCoVarBndrsX :: TCvSubst -> [CoVar] -> TcM (TCvSubst, [CoVar])
-- ^ Give fresh uniques to a bunch of CoVars
-- Used in FamInst.newFamInst
freshenCoVarBndrsX :: TCvSubst -> [TyVar] -> TcM (TCvSubst, [TyVar])
freshenCoVarBndrsX TCvSubst
subst = (Name -> TcKind -> TyVar)
-> TCvSubst -> [TyVar] -> TcM (TCvSubst, [TyVar])
freshenTyCoVarsX Name -> TcKind -> TyVar
mkCoVar TCvSubst
subst

------------------
freshenTyCoVars :: (Name -> Kind -> TyCoVar)
                -> [TyVar] -> TcM (TCvSubst, [TyCoVar])
freshenTyCoVars :: (Name -> TcKind -> TyVar) -> [TyVar] -> TcM (TCvSubst, [TyVar])
freshenTyCoVars Name -> TcKind -> TyVar
mk_tcv = (Name -> TcKind -> TyVar)
-> TCvSubst -> [TyVar] -> TcM (TCvSubst, [TyVar])
freshenTyCoVarsX Name -> TcKind -> TyVar
mk_tcv TCvSubst
emptyTCvSubst

freshenTyCoVarsX :: (Name -> Kind -> TyCoVar)
                 -> TCvSubst -> [TyCoVar]
                 -> TcM (TCvSubst, [TyCoVar])
freshenTyCoVarsX :: (Name -> TcKind -> TyVar)
-> TCvSubst -> [TyVar] -> TcM (TCvSubst, [TyVar])
freshenTyCoVarsX Name -> TcKind -> TyVar
mk_tcv = (TCvSubst
 -> TyVar -> IOEnv (Env TcGblEnv TcLclEnv) (TCvSubst, TyVar))
-> TCvSubst -> [TyVar] -> TcM (TCvSubst, [TyVar])
forall (m :: * -> *) acc x y.
Monad m =>
(acc -> x -> m (acc, y)) -> acc -> [x] -> m (acc, [y])
mapAccumLM ((Name -> TcKind -> TyVar)
-> TCvSubst
-> TyVar
-> IOEnv (Env TcGblEnv TcLclEnv) (TCvSubst, TyVar)
freshenTyCoVarX Name -> TcKind -> TyVar
mk_tcv)

freshenTyCoVarX :: (Name -> Kind -> TyCoVar)
                -> TCvSubst -> TyCoVar -> TcM (TCvSubst, TyCoVar)
-- This a complete freshening operation:
-- the skolems have a fresh unique, and a location from the monad
-- See Note [Skolemising type variables]
freshenTyCoVarX :: (Name -> TcKind -> TyVar)
-> TCvSubst
-> TyVar
-> IOEnv (Env TcGblEnv TcLclEnv) (TCvSubst, TyVar)
freshenTyCoVarX Name -> TcKind -> TyVar
mk_tcv TCvSubst
subst TyVar
tycovar
  = do { SrcSpan
loc  <- TcRn SrcSpan
getSrcSpanM
       ; Unique
uniq <- TcRnIf TcGblEnv TcLclEnv Unique
forall gbl lcl. TcRnIf gbl lcl Unique
newUnique
       ; let old_name :: Name
old_name = TyVar -> Name
tyVarName TyVar
tycovar
             new_name :: Name
new_name = Unique -> OccName -> SrcSpan -> Name
mkInternalName Unique
uniq (Name -> OccName
forall a. NamedThing a => a -> OccName
getOccName Name
old_name) SrcSpan
loc
             new_kind :: TcKind
new_kind = TCvSubst -> TcKind -> TcKind
substTyUnchecked TCvSubst
subst (TyVar -> TcKind
tyVarKind TyVar
tycovar)
             new_tcv :: TyVar
new_tcv  = Name -> TcKind -> TyVar
mk_tcv Name
new_name TcKind
new_kind
             subst1 :: TCvSubst
subst1   = TCvSubst -> TyVar -> TyVar -> TCvSubst
extendTCvSubstWithClone TCvSubst
subst TyVar
tycovar TyVar
new_tcv
       ; (TCvSubst, TyVar)
-> IOEnv (Env TcGblEnv TcLclEnv) (TCvSubst, TyVar)
forall (m :: * -> *) a. Monad m => a -> m a
return (TCvSubst
subst1, TyVar
new_tcv) }

{- Note [Skolemising type variables]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The tcInstSkolTyVars family of functions instantiate a list of TyVars
to fresh skolem TcTyVars. Important notes:

a) Level allocation. We generally skolemise /before/ calling
   pushLevelAndCaptureConstraints.  So we want their level to the level
   of the soon-to-be-created implication, which has a level ONE HIGHER
   than the current level.  Hence the pushTcLevel.  It feels like a
   slight hack.

b) The [TyVar] should be ordered (kind vars first)
   See Note [Kind substitution when instantiating]

c) It's a complete freshening operation: the skolems have a fresh
   unique, and a location from the monad

d) The resulting skolems are
        non-overlappable for tcInstSkolTyVars,
   but overlappable for tcInstSuperSkolTyVars
   See TcDerivInfer Note [Overlap and deriving] for an example
   of where this matters.

Note [Kind substitution when instantiating]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When we instantiate a bunch of kind and type variables, first we
expect them to be topologically sorted.
Then we have to instantiate the kind variables, build a substitution
from old variables to the new variables, then instantiate the type
variables substituting the original kind.

Exemple: If we want to instantiate
  [(k1 :: *), (k2 :: *), (a :: k1 -> k2), (b :: k1)]
we want
  [(?k1 :: *), (?k2 :: *), (?a :: ?k1 -> ?k2), (?b :: ?k1)]
instead of the buggous
  [(?k1 :: *), (?k2 :: *), (?a :: k1 -> k2), (?b :: k1)]


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

{-
Note [TyVarTv]
~~~~~~~~~~~~

A TyVarTv can unify with type *variables* only, including other TyVarTvs and
skolems. 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 (say, with a call to findDubTyVarTvs).

Before #15050 this (under the name SigTv) was 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).

The remaining uses of newTyVarTyVars are
* In kind signatures, see
  TcTyClsDecls Note [Inferring kinds for type declarations]
           and Note [Kind checking for GADTs]
* In partial type signatures, see Note [Quantified variables in partial type signatures]
-}

newMetaTyVarName :: FastString -> TcM Name
-- Makes a /System/ Name, which is eagerly eliminated by
-- the unifier; see TcUnify.nicer_to_update_tv1, and
-- TcCanonical.canEqTyVarTyVar (nicer_to_update_tv2)
newMetaTyVarName :: FastString -> TcRnIf TcGblEnv TcLclEnv Name
newMetaTyVarName FastString
str
  = do { Unique
uniq <- TcRnIf TcGblEnv TcLclEnv Unique
forall gbl lcl. TcRnIf gbl lcl Unique
newUnique
       ; Name -> TcRnIf TcGblEnv TcLclEnv Name
forall (m :: * -> *) a. Monad m => a -> m a
return (Unique -> OccName -> Name
mkSystemName Unique
uniq (FastString -> OccName
mkTyVarOccFS FastString
str)) }

cloneMetaTyVarName :: Name -> TcM Name
cloneMetaTyVarName :: Name -> TcRnIf TcGblEnv TcLclEnv Name
cloneMetaTyVarName Name
name
  = do { Unique
uniq <- TcRnIf TcGblEnv TcLclEnv Unique
forall gbl lcl. TcRnIf gbl lcl Unique
newUnique
       ; Name -> TcRnIf TcGblEnv TcLclEnv Name
forall (m :: * -> *) a. Monad m => a -> m a
return (Unique -> OccName -> Name
mkSystemName Unique
uniq (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.
-}

newAnonMetaTyVar :: MetaInfo -> Kind -> TcM TcTyVar
-- Make a new meta tyvar out of thin air
newAnonMetaTyVar :: MetaInfo -> TcKind -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
newAnonMetaTyVar MetaInfo
meta_info TcKind
kind
  = do  { let s :: FastString
s = case MetaInfo
meta_info of
                        MetaInfo
TauTv       -> String -> FastString
fsLit String
"t"
                        MetaInfo
FlatMetaTv  -> String -> FastString
fsLit String
"fmv"
                        MetaInfo
FlatSkolTv  -> String -> FastString
fsLit String
"fsk"
                        MetaInfo
TyVarTv      -> String -> FastString
fsLit String
"a"
        ; Name
name    <- FastString -> TcRnIf TcGblEnv TcLclEnv Name
newMetaTyVarName FastString
s
        ; TcTyVarDetails
details <- MetaInfo -> TcM TcTyVarDetails
newMetaDetails MetaInfo
meta_info
        ; let tyvar :: TyVar
tyvar = Name -> TcKind -> TcTyVarDetails -> TyVar
mkTcTyVar Name
name TcKind
kind TcTyVarDetails
details
        ; String -> SDoc -> TcRn ()
traceTc String
"newAnonMetaTyVar" (TyVar -> SDoc
forall a. Outputable a => a -> SDoc
ppr TyVar
tyvar)
        ; TyVar -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
forall (m :: * -> *) a. Monad m => a -> m a
return TyVar
tyvar }

-- makes a new skolem tv
newSkolemTyVar :: Name -> Kind -> TcM TcTyVar
newSkolemTyVar :: Name -> TcKind -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
newSkolemTyVar Name
name TcKind
kind
  = do { TcLevel
lvl <- TcM TcLevel
getTcLevel
       ; TyVar -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
forall (m :: * -> *) a. Monad m => a -> m a
return (Name -> TcKind -> TcTyVarDetails -> TyVar
mkTcTyVar Name
name TcKind
kind (TcLevel -> Bool -> TcTyVarDetails
SkolemTv TcLevel
lvl Bool
False)) }

newTyVarTyVar :: Name -> Kind -> TcM TcTyVar
-- See Note [TyVarTv]
-- Does not clone a fresh unique
newTyVarTyVar :: Name -> TcKind -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
newTyVarTyVar Name
name TcKind
kind
  = do { TcTyVarDetails
details <- MetaInfo -> TcM TcTyVarDetails
newMetaDetails MetaInfo
TyVarTv
       ; let tyvar :: TyVar
tyvar = Name -> TcKind -> TcTyVarDetails -> TyVar
mkTcTyVar Name
name TcKind
kind TcTyVarDetails
details
       ; String -> SDoc -> TcRn ()
traceTc String
"newTyVarTyVar" (TyVar -> SDoc
forall a. Outputable a => a -> SDoc
ppr TyVar
tyvar)
       ; TyVar -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
forall (m :: * -> *) a. Monad m => a -> m a
return TyVar
tyvar }

cloneTyVarTyVar :: Name -> Kind -> TcM TcTyVar
-- See Note [TyVarTv]
-- Clones a fresh unique
cloneTyVarTyVar :: Name -> TcKind -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
cloneTyVarTyVar Name
name TcKind
kind
  = do { TcTyVarDetails
details <- MetaInfo -> TcM TcTyVarDetails
newMetaDetails MetaInfo
TyVarTv
       ; Unique
uniq <- TcRnIf TcGblEnv TcLclEnv Unique
forall gbl lcl. TcRnIf gbl lcl Unique
newUnique
       ; let name' :: Name
name' = Name
name Name -> Unique -> Name
`setNameUnique` Unique
uniq
             tyvar :: TyVar
tyvar = Name -> TcKind -> TcTyVarDetails -> TyVar
mkTcTyVar Name
name' TcKind
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'
       ; String -> SDoc -> TcRn ()
traceTc String
"cloneTyVarTyVar" (TyVar -> SDoc
forall a. Outputable a => a -> SDoc
ppr TyVar
tyvar)
       ; TyVar -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
forall (m :: * -> *) a. Monad m => a -> m a
return TyVar
tyvar }

newPatSigTyVar :: Name -> Kind -> TcM TcTyVar
newPatSigTyVar :: Name -> TcKind -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
newPatSigTyVar Name
name TcKind
kind
  = do { TcTyVarDetails
details <- MetaInfo -> TcM TcTyVarDetails
newMetaDetails MetaInfo
TauTv
       ; Unique
uniq <- TcRnIf TcGblEnv TcLclEnv Unique
forall gbl lcl. TcRnIf gbl lcl Unique
newUnique
       ; let name' :: Name
name' = Name
name Name -> Unique -> Name
`setNameUnique` Unique
uniq
             tyvar :: TyVar
tyvar = Name -> TcKind -> TcTyVarDetails -> TyVar
mkTcTyVar Name
name' TcKind
kind TcTyVarDetails
details
         -- Don't use cloneMetaTyVar;
         -- same reasoning as in newTyVarTyVar
       ; String -> SDoc -> TcRn ()
traceTc String
"newPatSigTyVar" (TyVar -> SDoc
forall a. Outputable a => a -> SDoc
ppr TyVar
tyvar)
       ; TyVar -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
forall (m :: * -> *) a. Monad m => a -> m a
return TyVar
tyvar }

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

newFskTyVar :: TcType -> TcM TcTyVar
newFskTyVar :: TcKind -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
newFskTyVar TcKind
fam_ty
  = do { TcTyVarDetails
details <- MetaInfo -> TcM TcTyVarDetails
newMetaDetails MetaInfo
FlatSkolTv
       ; Name
name <- FastString -> TcRnIf TcGblEnv TcLclEnv Name
newMetaTyVarName (String -> FastString
fsLit String
"fsk")
       ; TyVar -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
forall (m :: * -> *) a. Monad m => a -> m a
return (Name -> TcKind -> TcTyVarDetails -> TyVar
mkTcTyVar Name
name (HasDebugCallStack => TcKind -> TcKind
TcKind -> TcKind
tcTypeKind TcKind
fam_ty) TcTyVarDetails
details) }

newFmvTyVar :: TcType -> TcM TcTyVar
-- Very like newMetaTyVar, except sets mtv_tclvl to one less
-- so that the fmv is untouchable.
newFmvTyVar :: TcKind -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
newFmvTyVar TcKind
fam_ty
  = do { TcTyVarDetails
details <- MetaInfo -> TcM TcTyVarDetails
newMetaDetails MetaInfo
FlatMetaTv
       ; Name
name <- FastString -> TcRnIf TcGblEnv TcLclEnv Name
newMetaTyVarName (String -> FastString
fsLit String
"s")
       ; TyVar -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
forall (m :: * -> *) a. Monad m => a -> m a
return (Name -> TcKind -> TcTyVarDetails -> TyVar
mkTcTyVar Name
name (HasDebugCallStack => TcKind -> TcKind
TcKind -> TcKind
tcTypeKind TcKind
fam_ty) TcTyVarDetails
details) }

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

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

-- Works for both type and kind variables
readMetaTyVar :: TyVar -> TcM MetaDetails
readMetaTyVar :: TyVar -> TcM MetaDetails
readMetaTyVar TyVar
tyvar = ASSERT2( isMetaTyVar tyvar, ppr tyvar )
                      IORef MetaDetails -> TcM MetaDetails
forall a env. IORef a -> IOEnv env a
readMutVar (TyVar -> IORef MetaDetails
metaTyVarRef TyVar
tyvar)

isFilledMetaTyVar_maybe :: TcTyVar -> TcM (Maybe Type)
isFilledMetaTyVar_maybe :: TyVar -> TcM (Maybe TcKind)
isFilledMetaTyVar_maybe TyVar
tv
 | MetaTv { mtv_ref :: TcTyVarDetails -> IORef MetaDetails
mtv_ref = IORef MetaDetails
ref } <- TyVar -> TcTyVarDetails
tcTyVarDetails TyVar
tv
 = do { MetaDetails
cts <- IORef MetaDetails -> TcM MetaDetails
forall a gbl lcl. TcRef a -> TcRnIf gbl lcl a
readTcRef IORef MetaDetails
ref
      ; case MetaDetails
cts of
          Indirect TcKind
ty -> Maybe TcKind -> TcM (Maybe TcKind)
forall (m :: * -> *) a. Monad m => a -> m a
return (TcKind -> Maybe TcKind
forall a. a -> Maybe a
Just TcKind
ty)
          MetaDetails
Flexi       -> Maybe TcKind -> TcM (Maybe TcKind)
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe TcKind
forall a. Maybe a
Nothing }
 | Bool
otherwise
 = Maybe TcKind -> TcM (Maybe TcKind)
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe TcKind
forall a. Maybe a
Nothing

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

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

--------------------
-- Works with both type and kind variables
writeMetaTyVar :: TcTyVar -> TcType -> TcM ()
-- Write into a currently-empty MetaTyVar

writeMetaTyVar :: TyVar -> TcKind -> TcRn ()
writeMetaTyVar TyVar
tyvar TcKind
ty
  | Bool -> Bool
not Bool
debugIsOn
  = TyVar -> IORef MetaDetails -> TcKind -> TcRn ()
writeMetaTyVarRef TyVar
tyvar (TyVar -> IORef MetaDetails
metaTyVarRef TyVar
tyvar) TcKind
ty

-- Everything from here on only happens if DEBUG is on
  | Bool -> Bool
not (TyVar -> Bool
isTcTyVar TyVar
tyvar)
  = ASSERT2( False, text "Writing to non-tc tyvar" <+> ppr tyvar )
    () -> TcRn ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()

  | MetaTv { mtv_ref :: TcTyVarDetails -> IORef MetaDetails
mtv_ref = IORef MetaDetails
ref } <- TyVar -> TcTyVarDetails
tcTyVarDetails TyVar
tyvar
  = TyVar -> IORef MetaDetails -> TcKind -> TcRn ()
writeMetaTyVarRef TyVar
tyvar IORef MetaDetails
ref TcKind
ty

  | Bool
otherwise
  = ASSERT2( False, text "Writing to non-meta tyvar" <+> ppr tyvar )
    () -> TcRn ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()

--------------------
writeMetaTyVarRef :: TcTyVar -> TcRef MetaDetails -> TcType -> TcM ()
-- Here the tyvar is for error checking only;
-- the ref cell must be for the same tyvar
writeMetaTyVarRef :: TyVar -> IORef MetaDetails -> TcKind -> TcRn ()
writeMetaTyVarRef TyVar
tyvar IORef MetaDetails
ref TcKind
ty
  | Bool -> Bool
not Bool
debugIsOn
  = do { String -> SDoc -> TcRn ()
traceTc String
"writeMetaTyVar" (TyVar -> SDoc
forall a. Outputable a => a -> SDoc
ppr TyVar
tyvar SDoc -> SDoc -> SDoc
<+> SDoc
dcolon SDoc -> SDoc -> SDoc
<+> TcKind -> SDoc
forall a. Outputable a => a -> SDoc
ppr (TyVar -> TcKind
tyVarKind TyVar
tyvar)
                                   SDoc -> SDoc -> SDoc
<+> String -> SDoc
text String
":=" SDoc -> SDoc -> SDoc
<+> TcKind -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcKind
ty)
       ; IORef MetaDetails -> MetaDetails -> TcRn ()
forall a gbl lcl. TcRef a -> a -> TcRnIf gbl lcl ()
writeTcRef IORef MetaDetails
ref (TcKind -> MetaDetails
Indirect TcKind
ty) }

  -- Everything from here on only happens if DEBUG is on
  | Bool
otherwise
  = do { MetaDetails
meta_details <- IORef MetaDetails -> TcM MetaDetails
forall a env. IORef a -> IOEnv env a
readMutVar IORef MetaDetails
ref;
       -- Zonk kinds to allow the error check to work
       ; TcKind
zonked_tv_kind <- TcKind -> TcM TcKind
zonkTcType TcKind
tv_kind
       ; TcKind
zonked_ty_kind <- TcKind -> TcM TcKind
zonkTcType TcKind
ty_kind
       ; let kind_check_ok :: Bool
kind_check_ok = TcKind -> Bool
tcIsConstraintKind TcKind
zonked_tv_kind
                          Bool -> Bool -> Bool
|| HasDebugCallStack => TcKind -> TcKind -> Bool
TcKind -> TcKind -> Bool
tcEqKind TcKind
zonked_ty_kind TcKind
zonked_tv_kind
             -- Hack alert! tcIsConstraintKind: see TcHsType
             -- Note [Extra-constraint holes in partial type signatures]

             kind_msg :: SDoc
kind_msg = SDoc -> Int -> SDoc -> SDoc
hang (String -> SDoc
text String
"Ill-kinded update to meta tyvar")
                           Int
2 (    TyVar -> SDoc
forall a. Outputable a => a -> SDoc
ppr TyVar
tyvar SDoc -> SDoc -> SDoc
<+> String -> SDoc
text String
"::" SDoc -> SDoc -> SDoc
<+> (TcKind -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcKind
tv_kind SDoc -> SDoc -> SDoc
$$ TcKind -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcKind
zonked_tv_kind)
                              SDoc -> SDoc -> SDoc
<+> String -> SDoc
text String
":="
                              SDoc -> SDoc -> SDoc
<+> TcKind -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcKind
ty SDoc -> SDoc -> SDoc
<+> String -> SDoc
text String
"::" SDoc -> SDoc -> SDoc
<+> (TcKind -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcKind
zonked_ty_kind) )

       ; String -> SDoc -> TcRn ()
traceTc String
"writeMetaTyVar" (TyVar -> SDoc
forall a. Outputable a => a -> SDoc
ppr TyVar
tyvar SDoc -> SDoc -> SDoc
<+> String -> SDoc
text String
":=" SDoc -> SDoc -> SDoc
<+> TcKind -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcKind
ty)

       -- Check for double updates
       ; MASSERT2( isFlexi meta_details, double_upd_msg meta_details )

       -- Check for level OK
       -- See Note [Level check when unifying]
       ; MASSERT2( level_check_ok, level_check_msg )

       -- Check Kinds ok
       ; MASSERT2( kind_check_ok, kind_msg )

       -- Do the write
       ; IORef MetaDetails -> MetaDetails -> TcRn ()
forall a env. IORef a -> a -> IOEnv env ()
writeMutVar IORef MetaDetails
ref (TcKind -> MetaDetails
Indirect TcKind
ty) }
  where
    tv_kind :: TcKind
tv_kind = TyVar -> TcKind
tyVarKind TyVar
tyvar
    ty_kind :: TcKind
ty_kind = HasDebugCallStack => TcKind -> TcKind
TcKind -> TcKind
tcTypeKind TcKind
ty

    tv_lvl :: TcLevel
tv_lvl = TyVar -> TcLevel
tcTyVarLevel TyVar
tyvar
    ty_lvl :: TcLevel
ty_lvl = TcKind -> TcLevel
tcTypeLevel TcKind
ty

    level_check_ok :: Bool
level_check_ok  = Bool -> Bool
not (TcLevel
ty_lvl TcLevel -> TcLevel -> Bool
`strictlyDeeperThan` TcLevel
tv_lvl)
    level_check_msg :: SDoc
level_check_msg = TcLevel -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcLevel
ty_lvl SDoc -> SDoc -> SDoc
$$ TcLevel -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcLevel
tv_lvl SDoc -> SDoc -> SDoc
$$ TyVar -> SDoc
forall a. Outputable a => a -> SDoc
ppr TyVar
tyvar SDoc -> SDoc -> SDoc
$$ TcKind -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcKind
ty

    double_upd_msg :: a -> SDoc
double_upd_msg a
details = SDoc -> Int -> SDoc -> SDoc
hang (String -> SDoc
text String
"Double update of meta tyvar")
                                Int
2 (TyVar -> SDoc
forall a. Outputable a => a -> SDoc
ppr TyVar
tyvar SDoc -> SDoc -> SDoc
$$ a -> SDoc
forall a. Outputable a => a -> SDoc
ppr a
details)

{- Note [Level check when unifying]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When unifying
     alpha:lvl := ty
we expect that the TcLevel of 'ty' will be <= lvl.
However, during unflatting we do
     fuv:l := ty:(l+1)
which is usually wrong; hence the check isFmmvTyVar in level_check_ok.
See Note [TcLevel assignment] in TcType.
-}

{-
% Generating fresh variables for pattern match check
-}


{-
************************************************************************
*                                                                      *
        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!
-}


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

newFlexiTyVarTy :: Kind -> TcM TcType
newFlexiTyVarTy :: TcKind -> TcM TcKind
newFlexiTyVarTy TcKind
kind = do
    TyVar
tc_tyvar <- TcKind -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
newFlexiTyVar TcKind
kind
    TcKind -> TcM TcKind
forall (m :: * -> *) a. Monad m => a -> m a
return (TyVar -> TcKind
mkTyVarTy TyVar
tc_tyvar)

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

newOpenTypeKind :: TcM TcKind
newOpenTypeKind :: TcM TcKind
newOpenTypeKind
  = do { TcKind
rr <- TcKind -> TcM TcKind
newFlexiTyVarTy TcKind
runtimeRepTy
       ; TcKind -> TcM TcKind
forall (m :: * -> *) a. Monad m => a -> m a
return (TcKind -> TcKind
tYPE TcKind
rr) }

-- | Create a tyvar that can be a lifted or unlifted type.
-- Returns alpha :: TYPE kappa, where both alpha and kappa are fresh
newOpenFlexiTyVarTy :: TcM TcType
newOpenFlexiTyVarTy :: TcM TcKind
newOpenFlexiTyVarTy
  = do { TcKind
kind <- TcM TcKind
newOpenTypeKind
       ; TcKind -> TcM TcKind
newFlexiTyVarTy TcKind
kind }

newMetaTyVars :: [TyVar] -> TcM (TCvSubst, [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 :: [TyVar] -> TcM (TCvSubst, [TyVar])
newMetaTyVars = TCvSubst -> [TyVar] -> TcM (TCvSubst, [TyVar])
newMetaTyVarsX TCvSubst
emptyTCvSubst
    -- emptyTCvSubst 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 :: TCvSubst -> [TyVar] -> TcM (TCvSubst, [TcTyVar])
-- Just like newMetaTyVars, but start with an existing substitution.
newMetaTyVarsX :: TCvSubst -> [TyVar] -> TcM (TCvSubst, [TyVar])
newMetaTyVarsX TCvSubst
subst = (TCvSubst
 -> TyVar -> IOEnv (Env TcGblEnv TcLclEnv) (TCvSubst, TyVar))
-> TCvSubst -> [TyVar] -> TcM (TCvSubst, [TyVar])
forall (m :: * -> *) acc x y.
Monad m =>
(acc -> x -> m (acc, y)) -> acc -> [x] -> m (acc, [y])
mapAccumLM TCvSubst
-> TyVar -> IOEnv (Env TcGblEnv TcLclEnv) (TCvSubst, TyVar)
newMetaTyVarX TCvSubst
subst

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

newMetaTyVarTyVars :: [TyVar] -> TcM (TCvSubst, [TcTyVar])
newMetaTyVarTyVars :: [TyVar] -> TcM (TCvSubst, [TyVar])
newMetaTyVarTyVars = (TCvSubst
 -> TyVar -> IOEnv (Env TcGblEnv TcLclEnv) (TCvSubst, TyVar))
-> TCvSubst -> [TyVar] -> TcM (TCvSubst, [TyVar])
forall (m :: * -> *) acc x y.
Monad m =>
(acc -> x -> m (acc, y)) -> acc -> [x] -> m (acc, [y])
mapAccumLM TCvSubst
-> TyVar -> IOEnv (Env TcGblEnv TcLclEnv) (TCvSubst, TyVar)
newMetaTyVarTyVarX TCvSubst
emptyTCvSubst

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

newWildCardX :: TCvSubst -> TyVar -> TcM (TCvSubst, TcTyVar)
newWildCardX :: TCvSubst
-> TyVar -> IOEnv (Env TcGblEnv TcLclEnv) (TCvSubst, TyVar)
newWildCardX TCvSubst
subst TyVar
tv
  = do { TyVar
new_tv <- MetaInfo -> TcKind -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
newAnonMetaTyVar MetaInfo
TauTv (HasCallStack => TCvSubst -> TcKind -> TcKind
TCvSubst -> TcKind -> TcKind
substTy TCvSubst
subst (TyVar -> TcKind
tyVarKind TyVar
tv))
       ; (TCvSubst, TyVar)
-> IOEnv (Env TcGblEnv TcLclEnv) (TCvSubst, TyVar)
forall (m :: * -> *) a. Monad m => a -> m a
return (TCvSubst -> TyVar -> TyVar -> TCvSubst
extendTvSubstWithClone TCvSubst
subst TyVar
tv TyVar
new_tv, TyVar
new_tv) }

new_meta_tv_x :: MetaInfo -> TCvSubst -> TyVar -> TcM (TCvSubst, TcTyVar)
new_meta_tv_x :: MetaInfo
-> TCvSubst
-> TyVar
-> IOEnv (Env TcGblEnv TcLclEnv) (TCvSubst, TyVar)
new_meta_tv_x MetaInfo
info TCvSubst
subst TyVar
tv
  = do  { TyVar
new_tv <- MetaInfo -> TyVar -> TcKind -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
cloneAnonMetaTyVar MetaInfo
info TyVar
tv TcKind
substd_kind
        ; let subst1 :: TCvSubst
subst1 = TCvSubst -> TyVar -> TyVar -> TCvSubst
extendTvSubstWithClone TCvSubst
subst TyVar
tv TyVar
new_tv
        ; (TCvSubst, TyVar)
-> IOEnv (Env TcGblEnv TcLclEnv) (TCvSubst, TyVar)
forall (m :: * -> *) a. Monad m => a -> m a
return (TCvSubst
subst1, TyVar
new_tv) }
  where
    substd_kind :: TcKind
substd_kind = TCvSubst -> TcKind -> TcKind
substTyUnchecked TCvSubst
subst (TyVar -> TcKind
tyVarKind TyVar
tv)
      -- NOTE: #12549 is fixed so we could use
      -- substTy here, but the tc_infer_args problem
      -- is not yet fixed so leaving as unchecked for now.
      -- OLD NOTE:
      -- Unchecked because we call newMetaTyVarX from
      -- tcInstTyBinder, which is called from tcInferApps
      -- which does not yet take enough trouble to ensure
      -- the in-scope set is right; e.g. #12785 trips
      -- if we use substTy here

newMetaTyVarTyAtLevel :: TcLevel -> TcKind -> TcM TcType
newMetaTyVarTyAtLevel :: TcLevel -> TcKind -> TcM TcKind
newMetaTyVarTyAtLevel TcLevel
tc_lvl TcKind
kind
  = do  { IORef MetaDetails
ref  <- MetaDetails -> IOEnv (Env TcGblEnv TcLclEnv) (IORef MetaDetails)
forall a env. a -> IOEnv env (IORef a)
newMutVar MetaDetails
Flexi
        ; Name
name <- FastString -> TcRnIf TcGblEnv TcLclEnv Name
newMetaTyVarName (String -> FastString
fsLit String
"p")
        ; let details :: TcTyVarDetails
details = MetaTv :: MetaInfo -> IORef MetaDetails -> TcLevel -> TcTyVarDetails
MetaTv { mtv_info :: MetaInfo
mtv_info  = MetaInfo
TauTv
                               , mtv_ref :: IORef MetaDetails
mtv_ref   = IORef MetaDetails
ref
                               , mtv_tclvl :: TcLevel
mtv_tclvl = TcLevel
tc_lvl }
        ; TcKind -> TcM TcKind
forall (m :: * -> *) a. Monad m => a -> m a
return (TyVar -> TcKind
mkTyVarTy (Name -> TcKind -> TcTyVarDetails -> TyVar
mkTcTyVar Name
name TcKind
kind TcTyVarDetails
details)) }

{- *********************************************************************
*                                                                      *
          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 sytactically 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 UniqDFM.

* 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 again to Note [Recipe for checking a signature] in
TcHsType).

 * 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.

So, we zap it, eagerly, to Any. We don't have to do this eager zapping
in terms (say, in `length []`) because terms are never re-examined before
the final zonk (which zaps any lingering metavariables to Any).

We do this eager zapping 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').

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 :: DTyVarSet -> DTyVarSet -> CoVarSet -> CandidatesQTvs
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 :: DTyVarSet -> DTyVarSet -> CoVarSet -> CandidatesQTvs
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
text String
"DV" SDoc -> SDoc -> SDoc
<+> SDoc -> SDoc
braces ((SDoc -> SDoc) -> [SDoc] -> SDoc
forall a. (a -> SDoc) -> [a] -> SDoc
pprWithCommas SDoc -> SDoc
forall a. a -> a
id [ String -> SDoc
text String
"dv_kvs =" SDoc -> SDoc -> SDoc
<+> DTyVarSet -> SDoc
forall a. Outputable a => a -> SDoc
ppr DTyVarSet
kvs
                                             , String -> SDoc
text String
"dv_tvs =" SDoc -> SDoc -> SDoc
<+> DTyVarSet -> SDoc
forall a. Outputable a => a -> SDoc
ppr DTyVarSet
tvs
                                             , String -> SDoc
text String
"dv_cvs =" SDoc -> SDoc -> SDoc
<+> CoVarSet -> SDoc
forall a. Outputable a => a -> SDoc
ppr CoVarSet
cvs ])


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

partitionCandidates :: CandidatesQTvs -> (TyVar -> Bool) -> (DTyVarSet, CandidatesQTvs)
partitionCandidates :: CandidatesQTvs -> (TyVar -> Bool) -> (DTyVarSet, CandidatesQTvs)
partitionCandidates dvs :: CandidatesQTvs
dvs@(DV { dv_kvs :: CandidatesQTvs -> DTyVarSet
dv_kvs = DTyVarSet
kvs, dv_tvs :: CandidatesQTvs -> DTyVarSet
dv_tvs = DTyVarSet
tvs }) TyVar -> Bool
pred
  = (DTyVarSet
extracted, CandidatesQTvs
dvs { dv_kvs :: DTyVarSet
dv_kvs = DTyVarSet
rest_kvs, dv_tvs :: DTyVarSet
dv_tvs = DTyVarSet
rest_tvs })
  where
    (DTyVarSet
extracted_kvs, DTyVarSet
rest_kvs) = (TyVar -> Bool) -> DTyVarSet -> (DTyVarSet, DTyVarSet)
partitionDVarSet TyVar -> Bool
pred DTyVarSet
kvs
    (DTyVarSet
extracted_tvs, DTyVarSet
rest_tvs) = (TyVar -> Bool) -> DTyVarSet -> (DTyVarSet, DTyVarSet)
partitionDVarSet TyVar -> Bool
pred DTyVarSet
tvs
    extracted :: DTyVarSet
extracted = DTyVarSet
extracted_kvs DTyVarSet -> DTyVarSet -> DTyVarSet
`unionDVarSet` DTyVarSet
extracted_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 :: TcKind -> TcM CandidatesQTvs
candidateQTyVarsOfType TcKind
ty = Bool -> CoVarSet -> CandidatesQTvs -> TcKind -> TcM CandidatesQTvs
collect_cand_qtvs Bool
False CoVarSet
emptyVarSet CandidatesQTvs
forall a. Monoid a => a
mempty TcKind
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 :: [TcKind] -> TcM CandidatesQTvs
candidateQTyVarsOfTypes [TcKind]
tys = (CandidatesQTvs -> TcKind -> TcM CandidatesQTvs)
-> CandidatesQTvs -> [TcKind] -> TcM CandidatesQTvs
forall (t :: * -> *) (m :: * -> *) b a.
(Foldable t, Monad m) =>
(b -> a -> m b) -> b -> t a -> m b
foldlM (Bool -> CoVarSet -> CandidatesQTvs -> TcKind -> TcM CandidatesQTvs
collect_cand_qtvs Bool
False CoVarSet
emptyVarSet) CandidatesQTvs
forall a. Monoid a => a
mempty [TcKind]
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 :: TcKind -> TcM CandidatesQTvs
candidateQTyVarsOfKind TcKind
ty = Bool -> CoVarSet -> CandidatesQTvs -> TcKind -> TcM CandidatesQTvs
collect_cand_qtvs Bool
True CoVarSet
emptyVarSet CandidatesQTvs
forall a. Monoid a => a
mempty TcKind
ty

candidateQTyVarsOfKinds :: [TcKind]    -- Not necessarily zonked
                       -> TcM CandidatesQTvs
candidateQTyVarsOfKinds :: [TcKind] -> TcM CandidatesQTvs
candidateQTyVarsOfKinds [TcKind]
tys = (CandidatesQTvs -> TcKind -> TcM CandidatesQTvs)
-> CandidatesQTvs -> [TcKind] -> TcM CandidatesQTvs
forall (t :: * -> *) (m :: * -> *) b a.
(Foldable t, Monad m) =>
(b -> a -> m b) -> b -> t a -> m b
foldM (Bool -> CoVarSet -> CandidatesQTvs -> TcKind -> TcM CandidatesQTvs
collect_cand_qtvs Bool
True CoVarSet
emptyVarSet) CandidatesQTvs
forall a. Monoid a => a
mempty [TcKind]
tys

delCandidates :: CandidatesQTvs -> [Var] -> CandidatesQTvs
delCandidates :: CandidatesQTvs -> [TyVar] -> 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 }) [TyVar]
vars
  = DV :: DTyVarSet -> DTyVarSet -> CoVarSet -> CandidatesQTvs
DV { dv_kvs :: DTyVarSet
dv_kvs = DTyVarSet
kvs DTyVarSet -> [TyVar] -> DTyVarSet
`delDVarSetList` [TyVar]
vars
       , dv_tvs :: DTyVarSet
dv_tvs = DTyVarSet
tvs DTyVarSet -> [TyVar] -> DTyVarSet
`delDVarSetList` [TyVar]
vars
       , dv_cvs :: CoVarSet
dv_cvs = CoVarSet
cvs CoVarSet -> [TyVar] -> CoVarSet
`delVarSetList`  [TyVar]
vars }

collect_cand_qtvs
  :: Bool            -- True <=> consider every fv in Type to be dependent
  -> 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 does the zap-naughty
--     stuff; 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 :: Bool -> CoVarSet -> CandidatesQTvs -> TcKind -> TcM CandidatesQTvs
collect_cand_qtvs Bool
is_dep CoVarSet
bound CandidatesQTvs
dvs TcKind
ty
  = CandidatesQTvs -> TcKind -> TcM CandidatesQTvs
go CandidatesQTvs
dvs TcKind
ty
  where
    is_bound :: TyVar -> Bool
is_bound TyVar
tv = TyVar
tv TyVar -> CoVarSet -> Bool
`elemVarSet` CoVarSet
bound

    -----------------
    go :: CandidatesQTvs -> TcType -> TcM CandidatesQTvs
    -- Uses accumulating-parameter style
    go :: CandidatesQTvs -> TcKind -> TcM CandidatesQTvs
go CandidatesQTvs
dv (AppTy TcKind
t1 TcKind
t2)     = (CandidatesQTvs -> TcKind -> TcM CandidatesQTvs)
-> CandidatesQTvs -> [TcKind] -> TcM CandidatesQTvs
forall (t :: * -> *) (m :: * -> *) b a.
(Foldable t, Monad m) =>
(b -> a -> m b) -> b -> t a -> m b
foldlM CandidatesQTvs -> TcKind -> TcM CandidatesQTvs
go CandidatesQTvs
dv [TcKind
t1, TcKind
t2]
    go CandidatesQTvs
dv (TyConApp TyCon
_ [TcKind]
tys)  = (CandidatesQTvs -> TcKind -> TcM CandidatesQTvs)
-> CandidatesQTvs -> [TcKind] -> TcM CandidatesQTvs
forall (t :: * -> *) (m :: * -> *) b a.
(Foldable t, Monad m) =>
(b -> a -> m b) -> b -> t a -> m b
foldlM CandidatesQTvs -> TcKind -> TcM CandidatesQTvs
go CandidatesQTvs
dv [TcKind]
tys
    go CandidatesQTvs
dv (FunTy AnonArgFlag
_ TcKind
arg TcKind
res) = (CandidatesQTvs -> TcKind -> TcM CandidatesQTvs)
-> CandidatesQTvs -> [TcKind] -> TcM CandidatesQTvs
forall (t :: * -> *) (m :: * -> *) b a.
(Foldable t, Monad m) =>
(b -> a -> m b) -> b -> t a -> m b
foldlM CandidatesQTvs -> TcKind -> TcM CandidatesQTvs
go CandidatesQTvs
dv [TcKind
arg, TcKind
res]
    go CandidatesQTvs
dv (LitTy {})        = CandidatesQTvs -> TcM CandidatesQTvs
forall (m :: * -> *) a. Monad m => a -> m a
return CandidatesQTvs
dv
    go CandidatesQTvs
dv (CastTy TcKind
ty Coercion
co)    = do CandidatesQTvs
dv1 <- CandidatesQTvs -> TcKind -> TcM CandidatesQTvs
go CandidatesQTvs
dv TcKind
ty
                                 CoVarSet -> CandidatesQTvs -> Coercion -> TcM CandidatesQTvs
collect_cand_qtvs_co CoVarSet
bound CandidatesQTvs
dv1 Coercion
co
    go CandidatesQTvs
dv (CoercionTy Coercion
co)   = CoVarSet -> CandidatesQTvs -> Coercion -> TcM CandidatesQTvs
collect_cand_qtvs_co CoVarSet
bound CandidatesQTvs
dv Coercion
co

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

    go CandidatesQTvs
dv (ForAllTy (Bndr TyVar
tv ArgFlag
_) TcKind
ty)
      = do { CandidatesQTvs
dv1 <- Bool -> CoVarSet -> CandidatesQTvs -> TcKind -> TcM CandidatesQTvs
collect_cand_qtvs Bool
True CoVarSet
bound CandidatesQTvs
dv (TyVar -> TcKind
tyVarKind TyVar
tv)
           ; Bool -> CoVarSet -> CandidatesQTvs -> TcKind -> TcM CandidatesQTvs
collect_cand_qtvs Bool
is_dep (CoVarSet
bound CoVarSet -> TyVar -> CoVarSet
`extendVarSet` TyVar
tv) CandidatesQTvs
dv1 TcKind
ty }

    -----------------
    go_tv :: CandidatesQTvs -> TyVar -> TcM CandidatesQTvs
go_tv dv :: CandidatesQTvs
dv@(DV { dv_kvs :: CandidatesQTvs -> DTyVarSet
dv_kvs = DTyVarSet
kvs, dv_tvs :: CandidatesQTvs -> DTyVarSet
dv_tvs = DTyVarSet
tvs }) TyVar
tv
      | TyVar
tv TyVar -> DTyVarSet -> Bool
`elemDVarSet` DTyVarSet
kvs
      = CandidatesQTvs -> TcM CandidatesQTvs
forall (m :: * -> *) a. Monad m => a -> m a
return CandidatesQTvs
dv  -- We have met this tyvar aleady

      | Bool -> Bool
not Bool
is_dep
      , TyVar
tv TyVar -> DTyVarSet -> Bool
`elemDVarSet` DTyVarSet
tvs
      = CandidatesQTvs -> TcM CandidatesQTvs
forall (m :: * -> *) a. Monad m => a -> m a
return CandidatesQTvs
dv  -- We have met this tyvar aleady

      | Bool
otherwise
      = do { TcKind
tv_kind <- TcKind -> TcM TcKind
zonkTcType (TyVar -> TcKind
tyVarKind TyVar
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

           ; TcLevel
cur_lvl <- TcM TcLevel
getTcLevel
           ; if |  TyVar -> TcLevel
tcTyVarLevel TyVar
tv TcLevel -> TcLevel -> Bool
forall a. Ord a => a -> a -> Bool
<= TcLevel
cur_lvl
                -> CandidatesQTvs -> TcM CandidatesQTvs
forall (m :: * -> *) a. Monad m => a -> m a
return CandidatesQTvs
dv   -- this variable is from an outer context; skip
                               -- See Note [Use level numbers ofor quantification]

                |  CoVarSet -> CoVarSet -> Bool
intersectsVarSet CoVarSet
bound (TcKind -> CoVarSet
tyCoVarsOfType TcKind
tv_kind)
                   -- the tyvar must not be from an outer context, but we have
                   -- already checked for this.
                   -- See Note [Naughty quantification candidates]
                -> do { String -> SDoc -> TcRn ()
traceTc String
"Zapping naughty quantifier" (SDoc -> TcRn ()) -> SDoc -> TcRn ()
forall a b. (a -> b) -> a -> b
$
                          [SDoc] -> SDoc
vcat [ TyVar -> SDoc
forall a. Outputable a => a -> SDoc
ppr TyVar
tv SDoc -> SDoc -> SDoc
<+> SDoc
dcolon SDoc -> SDoc -> SDoc
<+> TcKind -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcKind
tv_kind
                               , String -> SDoc
text String
"bound:" SDoc -> SDoc -> SDoc
<+> [TyVar] -> SDoc
pprTyVars (CoVarSet -> [TyVar]
forall elt. UniqSet elt -> [elt]
nonDetEltsUniqSet CoVarSet
bound)
                               , String -> SDoc
text String
"fvs:" SDoc -> SDoc -> SDoc
<+> [TyVar] -> SDoc
pprTyVars (CoVarSet -> [TyVar]
forall elt. UniqSet elt -> [elt]
nonDetEltsUniqSet (CoVarSet -> [TyVar]) -> CoVarSet -> [TyVar]
forall a b. (a -> b) -> a -> b
$
                                                            TcKind -> CoVarSet
tyCoVarsOfType TcKind
tv_kind) ]

                      ; TyVar -> TcKind -> TcRn ()
writeMetaTyVar TyVar
tv (TcKind -> TcKind
anyTypeOfKind TcKind
tv_kind)

                      -- See Note [Recurring into kinds for candidateQTyVars]
                      ; Bool -> CoVarSet -> CandidatesQTvs -> TcKind -> TcM CandidatesQTvs
collect_cand_qtvs Bool
True CoVarSet
bound CandidatesQTvs
dv TcKind
tv_kind }

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

                        -- See Note [Recurring into kinds for candidateQTyVars]
                      ; Bool -> CoVarSet -> CandidatesQTvs -> TcKind -> TcM CandidatesQTvs
collect_cand_qtvs Bool
True CoVarSet
bound CandidatesQTvs
dv' TcKind
tv_kind } }

collect_cand_qtvs_co :: VarSet -- bound variables
                     -> CandidatesQTvs -> Coercion
                     -> TcM CandidatesQTvs
collect_cand_qtvs_co :: CoVarSet -> CandidatesQTvs -> Coercion -> TcM CandidatesQTvs
collect_cand_qtvs_co CoVarSet
bound = CandidatesQTvs -> Coercion -> TcM CandidatesQTvs
go_co
  where
    go_co :: CandidatesQTvs -> Coercion -> TcM CandidatesQTvs
go_co CandidatesQTvs
dv (Refl TcKind
ty)             = Bool -> CoVarSet -> CandidatesQTvs -> TcKind -> TcM CandidatesQTvs
collect_cand_qtvs Bool
True CoVarSet
bound CandidatesQTvs
dv TcKind
ty
    go_co CandidatesQTvs
dv (GRefl Role
_ TcKind
ty MCoercionN
mco)      = do CandidatesQTvs
dv1 <- Bool -> CoVarSet -> CandidatesQTvs -> TcKind -> TcM CandidatesQTvs
collect_cand_qtvs Bool
True CoVarSet
bound CandidatesQTvs
dv TcKind
ty
                                        CandidatesQTvs -> MCoercionN -> TcM CandidatesQTvs
go_mco CandidatesQTvs
dv1 MCoercionN
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
_ 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 (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
_ TcKind
t1 TcKind
t2) = do CandidatesQTvs
dv1 <- CandidatesQTvs -> UnivCoProvenance -> TcM CandidatesQTvs
go_prov CandidatesQTvs
dv UnivCoProvenance
prov
                                        CandidatesQTvs
dv2 <- Bool -> CoVarSet -> CandidatesQTvs -> TcKind -> TcM CandidatesQTvs
collect_cand_qtvs Bool
True CoVarSet
bound CandidatesQTvs
dv1 TcKind
t1
                                        Bool -> CoVarSet -> CandidatesQTvs -> TcKind -> TcM CandidatesQTvs
collect_cand_qtvs Bool
True CoVarSet
bound CandidatesQTvs
dv2 TcKind
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 (NthCo Role
_ Int
_ 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 Maybe Coercion
m_co <- CoercionHole -> IOEnv (Env TcGblEnv TcLclEnv) (Maybe Coercion)
unpackCoercionHole_maybe CoercionHole
hole
           case Maybe Coercion
m_co of
             Just Coercion
co -> CandidatesQTvs -> Coercion -> TcM CandidatesQTvs
go_co CandidatesQTvs
dv Coercion
co
             Maybe Coercion
Nothing -> CandidatesQTvs -> TyVar -> TcM CandidatesQTvs
go_cv CandidatesQTvs
dv (CoercionHole -> TyVar
coHoleCoVar CoercionHole
hole)

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

    go_co CandidatesQTvs
dv (ForAllCo TyVar
tcv Coercion
kind_co Coercion
co)
      = do { CandidatesQTvs
dv1 <- CandidatesQTvs -> Coercion -> TcM CandidatesQTvs
go_co CandidatesQTvs
dv Coercion
kind_co
           ; CoVarSet -> CandidatesQTvs -> Coercion -> TcM CandidatesQTvs
collect_cand_qtvs_co (CoVarSet
bound CoVarSet -> TyVar -> CoVarSet
`extendVarSet` TyVar
tcv) CandidatesQTvs
dv1 Coercion
co }

    go_mco :: CandidatesQTvs -> MCoercionN -> TcM CandidatesQTvs
go_mco CandidatesQTvs
dv MCoercionN
MRefl    = CandidatesQTvs -> TcM CandidatesQTvs
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 UnivCoProvenance
UnsafeCoerceProv    = CandidatesQTvs -> TcM CandidatesQTvs
forall (m :: * -> *) a. Monad m => a -> m a
return CandidatesQTvs
dv
    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 (m :: * -> *) a. Monad m => a -> m a
return CandidatesQTvs
dv

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

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

    is_bound :: TyVar -> Bool
is_bound TyVar
tv = TyVar
tv TyVar -> 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 TyCoFVs, 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 TyCoFVs 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 TyCoFVs 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 of 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 and untouchable type variables]
in 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 TcSimplify.decideMonoTyVars and in
TcHsType.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 UniqDFM.
-}

quantifyTyVars
  :: 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 :: CandidatesQTvs -> TcM [TyVar]
quantifyTyVars dvs :: CandidatesQTvs
dvs@(DV{ dv_kvs :: CandidatesQTvs -> DTyVarSet
dv_kvs = DTyVarSet
dep_tkvs, dv_tvs :: CandidatesQTvs -> DTyVarSet
dv_tvs = DTyVarSet
nondep_tkvs })
       -- short-circuit common case
  | DTyVarSet -> Bool
isEmptyDVarSet DTyVarSet
dep_tkvs
  , DTyVarSet -> Bool
isEmptyDVarSet DTyVarSet
nondep_tkvs
  = do { String -> SDoc -> TcRn ()
traceTc String
"quantifyTyVars has nothing to quantify" SDoc
empty
       ; [TyVar] -> TcM [TyVar]
forall (m :: * -> *) a. Monad m => a -> m a
return [] }

  | Bool
otherwise
  = do { String -> SDoc -> TcRn ()
traceTc String
"quantifyTyVars 1" (CandidatesQTvs -> SDoc
forall a. Outputable a => a -> SDoc
ppr CandidatesQTvs
dvs)

       ; let dep_kvs :: [TyVar]
dep_kvs     = [TyVar] -> [TyVar]
scopedSort ([TyVar] -> [TyVar]) -> [TyVar] -> [TyVar]
forall a b. (a -> b) -> a -> b
$ DTyVarSet -> [TyVar]
dVarSetElems DTyVarSet
dep_tkvs
                       -- scopedSort: put the kind variables into
                       --    well-scoped order.
                       --    E.g.  [k, (a::k)] not the other way roud

             nondep_tvs :: [TyVar]
nondep_tvs  = DTyVarSet -> [TyVar]
dVarSetElems (DTyVarSet
nondep_tkvs DTyVarSet -> DTyVarSet -> DTyVarSet
`minusDVarSet` DTyVarSet
dep_tkvs)
                 -- 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 zonked by zonkTyCoVarsAndFV

             -- In the non-PolyKinds case, default the kind variables
             -- to *, and zonk the tyvars as usual.  Notice that this
             -- may make quantifyTyVars return a shorter list
             -- than it was passed, but that's ok
       ; Bool
poly_kinds  <- Extension -> TcRnIf TcGblEnv TcLclEnv Bool
forall gbl lcl. Extension -> TcRnIf gbl lcl Bool
xoptM Extension
LangExt.PolyKinds
       ; [TyVar]
dep_kvs'    <- (TyVar -> IOEnv (Env TcGblEnv TcLclEnv) (Maybe TyVar))
-> [TyVar] -> TcM [TyVar]
forall (m :: * -> *) a b.
Applicative m =>
(a -> m (Maybe b)) -> [a] -> m [b]
mapMaybeM (Bool -> TyVar -> IOEnv (Env TcGblEnv TcLclEnv) (Maybe TyVar)
zonk_quant (Bool -> Bool
not Bool
poly_kinds)) [TyVar]
dep_kvs
       ; [TyVar]
nondep_tvs' <- (TyVar -> IOEnv (Env TcGblEnv TcLclEnv) (Maybe TyVar))
-> [TyVar] -> TcM [TyVar]
forall (m :: * -> *) a b.
Applicative m =>
(a -> m (Maybe b)) -> [a] -> m [b]
mapMaybeM (Bool -> TyVar -> IOEnv (Env TcGblEnv TcLclEnv) (Maybe TyVar)
zonk_quant Bool
False)            [TyVar]
nondep_tvs
       ; let final_qtvs :: [TyVar]
final_qtvs = [TyVar]
dep_kvs' [TyVar] -> [TyVar] -> [TyVar]
forall a. [a] -> [a] -> [a]
++ [TyVar]
nondep_tvs'
           -- Because of the order, any kind variables
           -- mentioned in the kinds of the nondep_tvs'
           -- now refer to the dep_kvs'

       ; String -> SDoc -> TcRn ()
traceTc String
"quantifyTyVars 2"
           ([SDoc] -> SDoc
vcat [ String -> SDoc
text String
"nondep:"     SDoc -> SDoc -> SDoc
<+> [TyVar] -> SDoc
pprTyVars [TyVar]
nondep_tvs
                 , String -> SDoc
text String
"dep:"        SDoc -> SDoc -> SDoc
<+> [TyVar] -> SDoc
pprTyVars [TyVar]
dep_kvs
                 , String -> SDoc
text String
"dep_kvs'"    SDoc -> SDoc -> SDoc
<+> [TyVar] -> SDoc
pprTyVars [TyVar]
dep_kvs'
                 , String -> SDoc
text String
"nondep_tvs'" SDoc -> SDoc -> SDoc
<+> [TyVar] -> SDoc
pprTyVars [TyVar]
nondep_tvs' ])

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

       ; [TyVar] -> TcM [TyVar]
forall (m :: * -> *) a. Monad m => a -> m a
return [TyVar]
final_qtvs }
  where
    -- zonk_quant returns a tyvar if it should be quantified over;
    -- otherwise, it returns Nothing. The latter case happens for
    --    * Kind variables, with -XNoPolyKinds: don't quantify over these
    --    * RuntimeRep variables: we never quantify over these
    zonk_quant :: Bool -> TyVar -> IOEnv (Env TcGblEnv TcLclEnv) (Maybe TyVar)
zonk_quant Bool
default_kind TyVar
tkv
      | Bool -> Bool
not (TyVar -> Bool
isTyVar TyVar
tkv)
      = Maybe TyVar -> IOEnv (Env TcGblEnv TcLclEnv) (Maybe TyVar)
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe TyVar
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 -> Bool
not (TyVar -> Bool
isTcTyVar TyVar
tkv)
      = Maybe TyVar -> IOEnv (Env TcGblEnv TcLclEnv) (Maybe TyVar)
forall (m :: * -> *) a. Monad m => a -> m a
return (TyVar -> Maybe TyVar
forall a. a -> Maybe a
Just TyVar
tkv)  -- For associated types in a class with a standalone
                           -- kind signature, we have the class variables in
                           -- scope, and they are TyVars not TcTyVars
      | Bool
otherwise
      = do { Bool
deflt_done <- Bool -> TyVar -> TcRnIf TcGblEnv TcLclEnv Bool
defaultTyVar Bool
default_kind TyVar
tkv
           ; case Bool
deflt_done of
               Bool
True  -> Maybe TyVar -> IOEnv (Env TcGblEnv TcLclEnv) (Maybe TyVar)
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe TyVar
forall a. Maybe a
Nothing
               Bool
False -> do { TyVar
tv <- TyVar -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
skolemiseQuantifiedTyVar TyVar
tkv
                           ; Maybe TyVar -> IOEnv (Env TcGblEnv TcLclEnv) (Maybe TyVar)
forall (m :: * -> *) a. Monad m => a -> m a
return (TyVar -> Maybe TyVar
forall a. a -> Maybe a
Just TyVar
tv) } }

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

zonkAndSkolemise :: TcTyCoVar -> TcM 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 :: TyVar -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
zonkAndSkolemise TyVar
tyvar
  | TyVar -> Bool
isTyVarTyVar TyVar
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 { TyVar
zonked_tyvar <- HasDebugCallStack => TyVar -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
TyVar -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
zonkTcTyVarToTyVar TyVar
tyvar
       ; TyVar -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
skolemiseQuantifiedTyVar TyVar
zonked_tyvar }

  | Bool
otherwise
  = ASSERT2( isImmutableTyVar tyvar || isCoVar tyvar, pprTyVar tyvar )
    TyVar -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
zonkTyCoVarKind TyVar
tyvar

skolemiseQuantifiedTyVar :: TcTyVar -> TcM 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 :: TyVar -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
skolemiseQuantifiedTyVar TyVar
tv
  = case TyVar -> TcTyVarDetails
tcTyVarDetails TyVar
tv of
      SkolemTv {} -> do { TcKind
kind <- TcKind -> TcM TcKind
zonkTcType (TyVar -> TcKind
tyVarKind TyVar
tv)
                        ; TyVar -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
forall (m :: * -> *) a. Monad m => a -> m a
return (TyVar -> TcKind -> TyVar
setTyVarKind TyVar
tv TcKind
kind) }
        -- It might be a skolem type variable,
        -- for example from a user type signature

      MetaTv {} -> TyVar -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
skolemiseUnboundMetaTyVar TyVar
tv

      TcTyVarDetails
_other -> String -> SDoc -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
forall a. HasCallStack => String -> SDoc -> a
pprPanic String
"skolemiseQuantifiedTyVar" (TyVar -> SDoc
forall a. Outputable a => a -> SDoc
ppr TyVar
tv) -- RuntimeUnk

defaultTyVar :: Bool      -- True <=> please default this kind variable to *
             -> TcTyVar   -- If it's a MetaTyVar then it is unbound
             -> TcM Bool  -- True <=> defaulted away altogether

defaultTyVar :: Bool -> TyVar -> TcRnIf TcGblEnv TcLclEnv Bool
defaultTyVar Bool
default_kind TyVar
tv
  | Bool -> Bool
not (TyVar -> Bool
isMetaTyVar TyVar
tv)
  = Bool -> TcRnIf TcGblEnv TcLclEnv Bool
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
False

  | TyVar -> Bool
isTyVarTyVar TyVar
tv
    -- Do not default TyVarTvs. Doing so would violate the invariants
    -- on TyVarTvs; see Note [Signature skolems] in TcType.
    -- #13343 is an example; #14555 is another
    -- See Note [Inferring kinds for type declarations] in TcTyClsDecls
  = Bool -> TcRnIf TcGblEnv TcLclEnv Bool
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
False


  | TyVar -> Bool
isRuntimeRepVar TyVar
tv  -- Do not quantify over a RuntimeRep var
                        -- unless it is a TyVarTv, handled earlier
  = do { String -> SDoc -> TcRn ()
traceTc String
"Defaulting a RuntimeRep var to LiftedRep" (TyVar -> SDoc
forall a. Outputable a => a -> SDoc
ppr TyVar
tv)
       ; TyVar -> TcKind -> TcRn ()
writeMetaTyVar TyVar
tv TcKind
liftedRepTy
       ; Bool -> TcRnIf TcGblEnv TcLclEnv Bool
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
True }

  | Bool
default_kind            -- -XNoPolyKinds and this is a kind var
  = TyVar -> TcRnIf TcGblEnv TcLclEnv Bool
default_kind_var TyVar
tv     -- so default it to * if possible

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

  where
    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 :: TyVar -> TcRnIf TcGblEnv TcLclEnv Bool
default_kind_var TyVar
kv
      | TcKind -> Bool
isLiftedTypeKind (TyVar -> TcKind
tyVarKind TyVar
kv)
      = do { String -> SDoc -> TcRn ()
traceTc String
"Defaulting a kind var to *" (TyVar -> SDoc
forall a. Outputable a => a -> SDoc
ppr TyVar
kv)
           ; TyVar -> TcKind -> TcRn ()
writeMetaTyVar TyVar
kv TcKind
liftedTypeKind
           ; Bool -> TcRnIf TcGblEnv TcLclEnv Bool
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
True }
      | Bool
otherwise
      = do { SDoc -> TcRn ()
addErr ([SDoc] -> SDoc
vcat [ String -> SDoc
text String
"Cannot default kind variable" SDoc -> SDoc -> SDoc
<+> SDoc -> SDoc
quotes (TyVar -> SDoc
forall a. Outputable a => a -> SDoc
ppr TyVar
kv')
                          , String -> SDoc
text String
"of kind:" SDoc -> SDoc -> SDoc
<+> TcKind -> SDoc
forall a. Outputable a => a -> SDoc
ppr (TyVar -> TcKind
tyVarKind TyVar
kv')
                          , String -> SDoc
text String
"Perhaps enable PolyKinds or add a kind signature" ])
           -- 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 TcHsType
           --    Note [Recipe for checking a signature]
           -- Otherwise we get level-number assertion failures. It doesn't matter much
           -- because we are in an error siutation anyway.
           ; Bool -> TcRnIf TcGblEnv TcLclEnv Bool
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
False
        }
      where
        (TidyEnv
_, TyVar
kv') = TidyEnv -> TyVar -> (TidyEnv, TyVar)
tidyOpenTyCoVar TidyEnv
emptyTidyEnv TyVar
kv

skolemiseUnboundMetaTyVar :: TcTyVar -> TcM 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]
skolemiseUnboundMetaTyVar :: TyVar -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
skolemiseUnboundMetaTyVar TyVar
tv
  = ASSERT2( isMetaTyVar tv, ppr tv )
    do  { Bool -> TcRn () -> TcRn ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when Bool
debugIsOn (TyVar -> TcRn ()
check_empty TyVar
tv)
        ; SrcSpan
here <- TcRn SrcSpan
getSrcSpanM    -- Get the location from "here"
                                 -- ie where we are generalising
        ; TcKind
kind <- TcKind -> TcM TcKind
zonkTcType (TyVar -> TcKind
tyVarKind TyVar
tv)
        ; let tv_name :: Name
tv_name     = TyVar -> Name
tyVarName TyVar
tv
              -- See Note [Skolemising and identity]
              final_name :: Name
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
              final_tv :: TyVar
final_tv = Name -> TcKind -> TcTyVarDetails -> TyVar
mkTcTyVar Name
final_name TcKind
kind TcTyVarDetails
details

        ; String -> SDoc -> TcRn ()
traceTc String
"Skolemising" (TyVar -> SDoc
forall a. Outputable a => a -> SDoc
ppr TyVar
tv SDoc -> SDoc -> SDoc
<+> String -> SDoc
text String
":=" SDoc -> SDoc -> SDoc
<+> TyVar -> SDoc
forall a. Outputable a => a -> SDoc
ppr TyVar
final_tv)
        ; TyVar -> TcKind -> TcRn ()
writeMetaTyVar TyVar
tv (TyVar -> TcKind
mkTyVarTy TyVar
final_tv)
        ; TyVar -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
forall (m :: * -> *) a. Monad m => a -> m a
return TyVar
final_tv }

  where
    details :: TcTyVarDetails
details = TcLevel -> Bool -> TcTyVarDetails
SkolemTv (TyVar -> TcLevel
metaTyVarTcLevel TyVar
tv) Bool
False
    check_empty :: TyVar -> TcRn ()
check_empty TyVar
tv       -- [Sept 04] Check for non-empty.
      = Bool -> TcRn () -> TcRn ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when Bool
debugIsOn (TcRn () -> TcRn ()) -> TcRn () -> TcRn ()
forall a b. (a -> b) -> a -> b
$  -- See note [Silly Type Synonym]
        do { MetaDetails
cts <- TyVar -> TcM MetaDetails
readMetaTyVar TyVar
tv
           ; case MetaDetails
cts of
               MetaDetails
Flexi       -> () -> TcRn ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()
               Indirect TcKind
ty -> WARN( True, ppr tv $$ ppr ty )
                              () -> TcRn ()
forall (m :: * -> *) a. Monad m => a -> m a
return () }

{- 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 [What is zonking?]
~~~~~~~~~~~~~~~~~~~~~~~
GHC relies heavily on mutability in the typechecker for efficient operation.
For this reason, throughout much of the type checking process meta type
variables (the MetaTv constructor of TcTyVarDetails) are represented by mutable
variables (known as TcRefs).

Zonking is the process of ripping out these mutable variables and replacing them
with a real Type. This involves traversing the entire type expression, but the
interesting part of replacing the mutable variables occurs in zonkTyVarOcc.

There are two ways to zonk a Type:

 * zonkTcTypeToType, which is intended to be used at the end of type-checking
   for the final zonk. It has to deal with unfilled metavars, either by filling
   it with a value like Any or failing (determined by the UnboundTyVarZonker
   used).

 * zonkTcType, which will happily ignore unfilled metavars. This is the
   appropriate function to use while in the middle of type-checking.

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 TcSimplify.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 TcRnDriver.tcRnSrcDecls calling TcSimplify.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 TcTyClsDecls.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 ()

************************************************************************
*                                                                      *
              Zonking types
*                                                                      *
************************************************************************

-}

zonkTcTypeAndFV :: TcType -> TcM DTyCoVarSet
-- Zonk a type and take its free variables
-- With kind polymorphism it can be essential to zonk *first*
-- so that we find the right set of free variables.  Eg
--    forall k1. forall (a:k2). a
-- where k2:=k1 is in the substitution.  We don't want
-- k2 to look free in this type!
zonkTcTypeAndFV :: TcKind -> TcM DTyVarSet
zonkTcTypeAndFV TcKind
ty
  = TcKind -> DTyVarSet
tyCoVarsOfTypeDSet (TcKind -> DTyVarSet) -> TcM TcKind -> TcM DTyVarSet
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> TcKind -> TcM TcKind
zonkTcType TcKind
ty

zonkTyCoVar :: TyCoVar -> TcM TcType
-- Works on TyVars and TcTyVars
zonkTyCoVar :: TyVar -> TcM TcKind
zonkTyCoVar TyVar
tv | TyVar -> Bool
isTcTyVar TyVar
tv = TyVar -> TcM TcKind
zonkTcTyVar TyVar
tv
               | TyVar -> Bool
isTyVar   TyVar
tv = TyVar -> TcKind
mkTyVarTy (TyVar -> TcKind)
-> IOEnv (Env TcGblEnv TcLclEnv) TyVar -> TcM TcKind
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> TyVar -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
zonkTyCoVarKind TyVar
tv
               | Bool
otherwise    = ASSERT2( isCoVar tv, ppr tv )
                                Coercion -> TcKind
mkCoercionTy (Coercion -> TcKind) -> (TyVar -> Coercion) -> TyVar -> TcKind
forall b c a. (b -> c) -> (a -> b) -> a -> c
. TyVar -> Coercion
mkCoVarCo (TyVar -> TcKind)
-> IOEnv (Env TcGblEnv TcLclEnv) TyVar -> TcM TcKind
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> TyVar -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
zonkTyCoVarKind TyVar
tv
   -- Hackily, when typechecking type and class decls
   -- we have TyVars in scope added (only) in
   -- TcHsType.bindTyClTyVars, but it seems
   -- painful to make them into TcTyVars there

zonkTyCoVarsAndFV :: TyCoVarSet -> TcM TyCoVarSet
zonkTyCoVarsAndFV :: CoVarSet -> TcM CoVarSet
zonkTyCoVarsAndFV CoVarSet
tycovars
  = [TcKind] -> CoVarSet
tyCoVarsOfTypes ([TcKind] -> CoVarSet) -> TcM [TcKind] -> TcM CoVarSet
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (TyVar -> TcM TcKind) -> [TyVar] -> TcM [TcKind]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM TyVar -> TcM TcKind
zonkTyCoVar (CoVarSet -> [TyVar]
forall elt. UniqSet elt -> [elt]
nonDetEltsUniqSet CoVarSet
tycovars)
  -- It's OK to use nonDetEltsUniqSet here because we immediately forget about
  -- the ordering by turning it into a nondeterministic set and the order
  -- of zonking doesn't matter for determinism.

zonkDTyCoVarSetAndFV :: DTyCoVarSet -> TcM DTyCoVarSet
zonkDTyCoVarSetAndFV :: DTyVarSet -> TcM DTyVarSet
zonkDTyCoVarSetAndFV DTyVarSet
tycovars
  = [TyVar] -> DTyVarSet
mkDVarSet ([TyVar] -> DTyVarSet) -> TcM [TyVar] -> TcM DTyVarSet
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ([TyVar] -> TcM [TyVar]
zonkTyCoVarsAndFVList ([TyVar] -> TcM [TyVar]) -> [TyVar] -> TcM [TyVar]
forall a b. (a -> b) -> a -> b
$ DTyVarSet -> [TyVar]
dVarSetElems DTyVarSet
tycovars)

-- Takes a list of TyCoVars, zonks them and returns a
-- deterministically ordered list of their free variables.
zonkTyCoVarsAndFVList :: [TyCoVar] -> TcM [TyCoVar]
zonkTyCoVarsAndFVList :: [TyVar] -> TcM [TyVar]
zonkTyCoVarsAndFVList [TyVar]
tycovars
  = [TcKind] -> [TyVar]
tyCoVarsOfTypesList ([TcKind] -> [TyVar]) -> TcM [TcKind] -> TcM [TyVar]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (TyVar -> TcM TcKind) -> [TyVar] -> TcM [TcKind]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM TyVar -> TcM TcKind
zonkTyCoVar [TyVar]
tycovars

zonkTcTyVars :: [TcTyVar] -> TcM [TcType]
zonkTcTyVars :: [TyVar] -> TcM [TcKind]
zonkTcTyVars [TyVar]
tyvars = (TyVar -> TcM TcKind) -> [TyVar] -> TcM [TcKind]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM TyVar -> TcM TcKind
zonkTcTyVar [TyVar]
tyvars

-----------------  Types
zonkTyCoVarKind :: TyCoVar -> TcM TyCoVar
zonkTyCoVarKind :: TyVar -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
zonkTyCoVarKind TyVar
tv = do { TcKind
kind' <- TcKind -> TcM TcKind
zonkTcType (TyVar -> TcKind
tyVarKind TyVar
tv)
                        ; TyVar -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
forall (m :: * -> *) a. Monad m => a -> m a
return (TyVar -> TcKind -> TyVar
setTyVarKind TyVar
tv TcKind
kind') }

zonkTcTypes :: [TcType] -> TcM [TcType]
zonkTcTypes :: [TcKind] -> TcM [TcKind]
zonkTcTypes [TcKind]
tys = (TcKind -> TcM TcKind) -> [TcKind] -> TcM [TcKind]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM TcKind -> TcM TcKind
zonkTcType [TcKind]
tys

{-
************************************************************************
*                                                                      *
              Zonking constraints
*                                                                      *
************************************************************************
-}

zonkImplication :: Implication -> TcM Implication
zonkImplication :: Implication -> IOEnv (Env TcGblEnv TcLclEnv) Implication
zonkImplication implic :: Implication
implic@(Implic { ic_skols :: Implication -> [TyVar]
ic_skols  = [TyVar]
skols
                               , ic_given :: Implication -> [TyVar]
ic_given  = [TyVar]
given
                               , ic_wanted :: Implication -> WantedConstraints
ic_wanted = WantedConstraints
wanted
                               , ic_info :: Implication -> SkolemInfo
ic_info   = SkolemInfo
info })
  = do { [TyVar]
skols'  <- (TyVar -> IOEnv (Env TcGblEnv TcLclEnv) TyVar)
-> [TyVar] -> TcM [TyVar]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM TyVar -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
zonkTyCoVarKind [TyVar]
skols  -- Need to zonk their kinds!
                                                -- as #7230 showed
       ; [TyVar]
given'  <- (TyVar -> IOEnv (Env TcGblEnv TcLclEnv) TyVar)
-> [TyVar] -> TcM [TyVar]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM TyVar -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
zonkEvVar [TyVar]
given
       ; SkolemInfo
info'   <- SkolemInfo -> TcM SkolemInfo
zonkSkolemInfo SkolemInfo
info
       ; WantedConstraints
wanted' <- WantedConstraints -> TcM WantedConstraints
zonkWCRec WantedConstraints
wanted
       ; Implication -> IOEnv (Env TcGblEnv TcLclEnv) Implication
forall (m :: * -> *) a. Monad m => a -> m a
return (Implication
implic { ic_skols :: [TyVar]
ic_skols  = [TyVar]
skols'
                        , ic_given :: [TyVar]
ic_given  = [TyVar]
given'
                        , ic_wanted :: WantedConstraints
ic_wanted = WantedConstraints
wanted'
                        , ic_info :: SkolemInfo
ic_info   = SkolemInfo
info' }) }

zonkEvVar :: EvVar -> TcM EvVar
zonkEvVar :: TyVar -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
zonkEvVar TyVar
var = do { TcKind
ty' <- TcKind -> TcM TcKind
zonkTcType (TyVar -> TcKind
varType TyVar
var)
                   ; TyVar -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
forall (m :: * -> *) a. Monad m => a -> m a
return (TyVar -> TcKind -> TyVar
setVarType TyVar
var TcKind
ty') }


zonkWC :: WantedConstraints -> TcM WantedConstraints
zonkWC :: WantedConstraints -> TcM WantedConstraints
zonkWC WantedConstraints
wc = WantedConstraints -> TcM WantedConstraints
zonkWCRec WantedConstraints
wc

zonkWCRec :: WantedConstraints -> TcM WantedConstraints
zonkWCRec :: WantedConstraints -> TcM WantedConstraints
zonkWCRec (WC { wc_simple :: WantedConstraints -> Cts
wc_simple = Cts
simple, wc_impl :: WantedConstraints -> Bag Implication
wc_impl = Bag Implication
implic })
  = do { Cts
simple' <- Cts -> IOEnv (Env TcGblEnv TcLclEnv) Cts
zonkSimples Cts
simple
       ; Bag Implication
implic' <- (Implication -> IOEnv (Env TcGblEnv TcLclEnv) Implication)
-> Bag Implication
-> IOEnv (Env TcGblEnv TcLclEnv) (Bag Implication)
forall (m :: * -> *) a b.
Monad m =>
(a -> m b) -> Bag a -> m (Bag b)
mapBagM Implication -> IOEnv (Env TcGblEnv TcLclEnv) Implication
zonkImplication Bag Implication
implic
       ; WantedConstraints -> TcM WantedConstraints
forall (m :: * -> *) a. Monad m => a -> m a
return (WC :: Cts -> Bag Implication -> WantedConstraints
WC { wc_simple :: Cts
wc_simple = Cts
simple', wc_impl :: Bag Implication
wc_impl = Bag Implication
implic' }) }

zonkSimples :: Cts -> TcM Cts
zonkSimples :: Cts -> IOEnv (Env TcGblEnv TcLclEnv) Cts
zonkSimples Cts
cts = do { Cts
cts' <- (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
zonkCt Cts
cts
                     ; String -> SDoc -> TcRn ()
traceTc String
"zonkSimples done:" (Cts -> SDoc
forall a. Outputable a => a -> SDoc
ppr Cts
cts')
                     ; Cts -> IOEnv (Env TcGblEnv TcLclEnv) Cts
forall (m :: * -> *) a. Monad m => a -> m a
return Cts
cts' }

{- Note [zonkCt behaviour]
~~~~~~~~~~~~~~~~~~~~~~~~~~
zonkCt tries to maintain the canonical form of a Ct.  For example,
  - a CDictCan should stay a CDictCan;
  - a CTyEqCan should stay a CTyEqCan (if the LHS stays as a variable.).
  - a CHoleCan should stay a CHoleCan
  - a CIrredCan should stay a CIrredCan with its cc_insol flag intact

Why?, for example:
- For CDictCan, the @TcSimplify.expandSuperClasses@ step, which runs after the
  simple wanted and plugin loop, looks for @CDictCan@s. If a plugin is in use,
  constraints are zonked before being passed to the plugin. This means if we
  don't preserve a canonical form, @expandSuperClasses@ fails to expand
  superclasses. This is what happened in #11525.

- For CHoleCan, once we forget that it's a hole, we can never recover that info.

- For CIrredCan we want to see if a constraint is insoluble with insolubleWC

NB: we do not expect to see any CFunEqCans, because zonkCt is only
called on unflattened constraints.

NB: Constraints are always re-flattened etc by the canonicaliser in
@TcCanonical@ even if they come in as CDictCan. Only canonical constraints that
are actually in the inert set carry all the guarantees. So it is okay if zonkCt
creates e.g. a CDictCan where the cc_tyars are /not/ function free.
-}

zonkCt :: Ct -> TcM Ct
zonkCt :: Ct -> TcM Ct
zonkCt ct :: Ct
ct@(CHoleCan { cc_ev :: Ct -> CtEvidence
cc_ev = CtEvidence
ev })
  = do { CtEvidence
ev' <- CtEvidence -> TcM CtEvidence
zonkCtEvidence CtEvidence
ev
       ; Ct -> TcM Ct
forall (m :: * -> *) a. Monad m => a -> m a
return (Ct -> TcM Ct) -> Ct -> TcM Ct
forall a b. (a -> b) -> a -> b
$ Ct
ct { cc_ev :: CtEvidence
cc_ev = CtEvidence
ev' } }

zonkCt ct :: Ct
ct@(CDictCan { cc_ev :: Ct -> CtEvidence
cc_ev = CtEvidence
ev, cc_tyargs :: Ct -> [TcKind]
cc_tyargs = [TcKind]
args })
  = do { CtEvidence
ev'   <- CtEvidence -> TcM CtEvidence
zonkCtEvidence CtEvidence
ev
       ; [TcKind]
args' <- (TcKind -> TcM TcKind) -> [TcKind] -> TcM [TcKind]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM TcKind -> TcM TcKind
zonkTcType [TcKind]
args
       ; Ct -> TcM Ct
forall (m :: * -> *) a. Monad m => a -> m a
return (Ct -> TcM Ct) -> Ct -> TcM Ct
forall a b. (a -> b) -> a -> b
$ Ct
ct { cc_ev :: CtEvidence
cc_ev = CtEvidence
ev', cc_tyargs :: [TcKind]
cc_tyargs = [TcKind]
args' } }

zonkCt (CTyEqCan { cc_ev :: Ct -> CtEvidence
cc_ev = CtEvidence
ev })
  = CtEvidence -> Ct
mkNonCanonical (CtEvidence -> Ct) -> TcM CtEvidence -> TcM Ct
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> CtEvidence -> TcM CtEvidence
zonkCtEvidence CtEvidence
ev
  -- CTyEqCan has some delicate invariants that may be violated by
  -- zonking (documented with the Ct type) , so we don't want to create
  -- a CTyEqCan here. Besides, this will be canonicalized again anyway,
  -- so there is very little benefit in keeping the CTyEqCan constructor.

zonkCt ct :: Ct
ct@(CIrredCan { cc_ev :: Ct -> CtEvidence
cc_ev = CtEvidence
ev }) -- Preserve the cc_insol flag
  = do { CtEvidence
ev' <- CtEvidence -> TcM CtEvidence
zonkCtEvidence CtEvidence
ev
       ; Ct -> TcM Ct
forall (m :: * -> *) a. Monad m => a -> m a
return (Ct
ct { cc_ev :: CtEvidence
cc_ev = CtEvidence
ev' }) }

zonkCt Ct
ct
  = ASSERT( not (isCFunEqCan ct) )
  -- We do not expect to see any CFunEqCans, because zonkCt is only called on
  -- unflattened constraints.
    do { CtEvidence
fl' <- CtEvidence -> TcM CtEvidence
zonkCtEvidence (Ct -> CtEvidence
ctEvidence Ct
ct)
       ; Ct -> TcM Ct
forall (m :: * -> *) a. Monad m => a -> m a
return (CtEvidence -> Ct
mkNonCanonical CtEvidence
fl') }

zonkCtEvidence :: CtEvidence -> TcM CtEvidence
zonkCtEvidence :: CtEvidence -> TcM CtEvidence
zonkCtEvidence ctev :: CtEvidence
ctev@(CtGiven { ctev_pred :: CtEvidence -> TcKind
ctev_pred = TcKind
pred })
  = do { TcKind
pred' <- TcKind -> TcM TcKind
zonkTcType TcKind
pred
       ; CtEvidence -> TcM CtEvidence
forall (m :: * -> *) a. Monad m => a -> m a
return (CtEvidence
ctev { ctev_pred :: TcKind
ctev_pred = TcKind
pred'}) }
zonkCtEvidence ctev :: CtEvidence
ctev@(CtWanted { ctev_pred :: CtEvidence -> TcKind
ctev_pred = TcKind
pred, ctev_dest :: CtEvidence -> TcEvDest
ctev_dest = TcEvDest
dest })
  = do { TcKind
pred' <- TcKind -> TcM TcKind
zonkTcType TcKind
pred
       ; let dest' :: TcEvDest
dest' = case TcEvDest
dest of
                       EvVarDest TyVar
ev -> TyVar -> TcEvDest
EvVarDest (TyVar -> TcEvDest) -> TyVar -> TcEvDest
forall a b. (a -> b) -> a -> b
$ TyVar -> TcKind -> TyVar
setVarType TyVar
ev TcKind
pred'
                         -- necessary in simplifyInfer
                       HoleDest CoercionHole
h   -> CoercionHole -> TcEvDest
HoleDest CoercionHole
h
       ; CtEvidence -> TcM CtEvidence
forall (m :: * -> *) a. Monad m => a -> m a
return (CtEvidence
ctev { ctev_pred :: TcKind
ctev_pred = TcKind
pred', ctev_dest :: TcEvDest
ctev_dest = TcEvDest
dest' }) }
zonkCtEvidence ctev :: CtEvidence
ctev@(CtDerived { ctev_pred :: CtEvidence -> TcKind
ctev_pred = TcKind
pred })
  = do { TcKind
pred' <- TcKind -> TcM TcKind
zonkTcType TcKind
pred
       ; CtEvidence -> TcM CtEvidence
forall (m :: * -> *) a. Monad m => a -> m a
return (CtEvidence
ctev { ctev_pred :: TcKind
ctev_pred = TcKind
pred' }) }

zonkSkolemInfo :: SkolemInfo -> TcM SkolemInfo
zonkSkolemInfo :: SkolemInfo -> TcM SkolemInfo
zonkSkolemInfo (SigSkol UserTypeCtxt
cx TcKind
ty [(Name, TyVar)]
tv_prs)  = do { TcKind
ty' <- TcKind -> TcM TcKind
zonkTcType TcKind
ty
                                            ; SkolemInfo -> TcM SkolemInfo
forall (m :: * -> *) a. Monad m => a -> m a
return (UserTypeCtxt -> TcKind -> [(Name, TyVar)] -> SkolemInfo
SigSkol UserTypeCtxt
cx TcKind
ty' [(Name, TyVar)]
tv_prs) }
zonkSkolemInfo (InferSkol [(Name, TcKind)]
ntys) = do { [(Name, TcKind)]
ntys' <- ((Name, TcKind) -> IOEnv (Env TcGblEnv TcLclEnv) (Name, TcKind))
-> [(Name, TcKind)]
-> IOEnv (Env TcGblEnv TcLclEnv) [(Name, TcKind)]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM (Name, TcKind) -> IOEnv (Env TcGblEnv TcLclEnv) (Name, TcKind)
forall a. (a, TcKind) -> IOEnv (Env TcGblEnv TcLclEnv) (a, TcKind)
do_one [(Name, TcKind)]
ntys
                                     ; SkolemInfo -> TcM SkolemInfo
forall (m :: * -> *) a. Monad m => a -> m a
return ([(Name, TcKind)] -> SkolemInfo
InferSkol [(Name, TcKind)]
ntys') }
  where
    do_one :: (a, TcKind) -> IOEnv (Env TcGblEnv TcLclEnv) (a, TcKind)
do_one (a
n, TcKind
ty) = do { TcKind
ty' <- TcKind -> TcM TcKind
zonkTcType TcKind
ty; (a, TcKind) -> IOEnv (Env TcGblEnv TcLclEnv) (a, TcKind)
forall (m :: * -> *) a. Monad m => a -> m a
return (a
n, TcKind
ty') }
zonkSkolemInfo SkolemInfo
skol_info = SkolemInfo -> TcM SkolemInfo
forall (m :: * -> *) a. Monad m => a -> m a
return SkolemInfo
skol_info

{-
%************************************************************************
%*                                                                      *
\subsection{Zonking -- the main work-horses: zonkTcType, zonkTcTyVar}
*                                                                      *
*              For internal use only!                                  *
*                                                                      *
************************************************************************

-}

-- zonkId is used *during* typechecking just to zonk the Id's type
zonkId :: TcId -> TcM TcId
zonkId :: TyVar -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
zonkId TyVar
id
  = do { TcKind
ty' <- TcKind -> TcM TcKind
zonkTcType (TyVar -> TcKind
idType TyVar
id)
       ; TyVar -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
forall (m :: * -> *) a. Monad m => a -> m a
return (TyVar -> TcKind -> TyVar
Id.setIdType TyVar
id TcKind
ty') }

zonkCoVar :: CoVar -> TcM CoVar
zonkCoVar :: TyVar -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
zonkCoVar = TyVar -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
zonkId

-- | A suitable TyCoMapper for zonking a type during type-checking,
-- before all metavars are filled in.
zonkTcTypeMapper :: TyCoMapper () TcM
zonkTcTypeMapper :: TyCoMapper () TcM
zonkTcTypeMapper = TyCoMapper :: forall env (m :: * -> *).
(env -> TyVar -> m TcKind)
-> (env -> TyVar -> m Coercion)
-> (env -> CoercionHole -> m Coercion)
-> (env -> TyVar -> ArgFlag -> m (env, TyVar))
-> (TyCon -> m TyCon)
-> TyCoMapper env m
TyCoMapper
  { tcm_tyvar :: () -> TyVar -> TcM TcKind
tcm_tyvar = (TyVar -> TcM TcKind) -> () -> TyVar -> TcM TcKind
forall a b. a -> b -> a
const TyVar -> TcM TcKind
zonkTcTyVar
  , tcm_covar :: () -> TyVar -> TcM Coercion
tcm_covar = (TyVar -> TcM Coercion) -> () -> TyVar -> TcM Coercion
forall a b. a -> b -> a
const (\TyVar
cv -> TyVar -> Coercion
mkCoVarCo (TyVar -> Coercion)
-> IOEnv (Env TcGblEnv TcLclEnv) TyVar -> TcM Coercion
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> TyVar -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
zonkTyCoVarKind TyVar
cv)
  , tcm_hole :: () -> CoercionHole -> TcM Coercion
tcm_hole  = () -> CoercionHole -> TcM Coercion
hole
  , tcm_tycobinder :: () -> TyVar -> ArgFlag -> TcM ((), TyVar)
tcm_tycobinder = \()
_env TyVar
tv ArgFlag
_vis -> ((), ) (TyVar -> ((), TyVar))
-> IOEnv (Env TcGblEnv TcLclEnv) TyVar -> TcM ((), TyVar)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> TyVar -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
zonkTyCoVarKind TyVar
tv
  , tcm_tycon :: TyCon -> TcM TyCon
tcm_tycon      = TyCon -> TcM TyCon
zonkTcTyCon }
  where
    hole :: () -> CoercionHole -> TcM Coercion
    hole :: () -> CoercionHole -> TcM Coercion
hole ()
_ hole :: CoercionHole
hole@(CoercionHole { ch_ref :: CoercionHole -> IORef (Maybe Coercion)
ch_ref = IORef (Maybe Coercion)
ref, ch_co_var :: CoercionHole -> TyVar
ch_co_var = TyVar
cv })
      = do { Maybe Coercion
contents <- IORef (Maybe Coercion)
-> IOEnv (Env TcGblEnv TcLclEnv) (Maybe Coercion)
forall a gbl lcl. TcRef a -> TcRnIf gbl lcl a
readTcRef IORef (Maybe Coercion)
ref
           ; case Maybe Coercion
contents of
               Just Coercion
co -> do { Coercion
co' <- Coercion -> TcM Coercion
zonkCo Coercion
co
                             ; TyVar -> Coercion -> TcM Coercion
checkCoercionHole TyVar
cv Coercion
co' }
               Maybe Coercion
Nothing -> do { TyVar
cv' <- TyVar -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
zonkCoVar TyVar
cv
                             ; Coercion -> TcM Coercion
forall (m :: * -> *) a. Monad m => a -> m a
return (Coercion -> TcM Coercion) -> Coercion -> TcM Coercion
forall a b. (a -> b) -> a -> b
$ CoercionHole -> Coercion
HoleCo (CoercionHole
hole { ch_co_var :: TyVar
ch_co_var = TyVar
cv' }) } }

zonkTcTyCon :: TcTyCon -> TcM TcTyCon
-- Only called on TcTyCons
-- A non-poly TcTyCon may have unification
-- variables that need zonking, but poly ones cannot
zonkTcTyCon :: TyCon -> TcM TyCon
zonkTcTyCon TyCon
tc
 | TyCon -> Bool
tcTyConIsPoly TyCon
tc = TyCon -> TcM TyCon
forall (m :: * -> *) a. Monad m => a -> m a
return TyCon
tc
 | Bool
otherwise        = do { TcKind
tck' <- TcKind -> TcM TcKind
zonkTcType (TyCon -> TcKind
tyConKind TyCon
tc)
                         ; TyCon -> TcM TyCon
forall (m :: * -> *) a. Monad m => a -> m a
return (TyCon -> TcKind -> TyCon
setTcTyConKind TyCon
tc TcKind
tck') }

-- For unbound, mutable tyvars, zonkType uses the function given to it
-- For tyvars bound at a for-all, zonkType zonks them to an immutable
--      type variable and zonks the kind too
zonkTcType :: TcType -> TcM TcType
zonkTcType :: TcKind -> TcM TcKind
zonkTcType = TyCoMapper () TcM -> () -> TcKind -> TcM TcKind
forall (m :: * -> *) env.
Monad m =>
TyCoMapper env m -> env -> TcKind -> m TcKind
mapType TyCoMapper () TcM
zonkTcTypeMapper ()

-- | "Zonk" a coercion -- really, just zonk any types in the coercion
zonkCo :: Coercion -> TcM Coercion
zonkCo :: Coercion -> TcM Coercion
zonkCo = TyCoMapper () TcM -> () -> Coercion -> TcM Coercion
forall (m :: * -> *) env.
Monad m =>
TyCoMapper env m -> env -> Coercion -> m Coercion
mapCoercion TyCoMapper () TcM
zonkTcTypeMapper ()

zonkTcTyVar :: TcTyVar -> TcM TcType
-- Simply look through all Flexis
zonkTcTyVar :: TyVar -> TcM TcKind
zonkTcTyVar TyVar
tv
  | TyVar -> Bool
isTcTyVar TyVar
tv
  = case TyVar -> TcTyVarDetails
tcTyVarDetails TyVar
tv of
      SkolemTv {}   -> TcM TcKind
zonk_kind_and_return
      RuntimeUnk {} -> TcM TcKind
zonk_kind_and_return
      MetaTv { mtv_ref :: TcTyVarDetails -> IORef MetaDetails
mtv_ref = IORef MetaDetails
ref }
         -> do { MetaDetails
cts <- IORef MetaDetails -> TcM MetaDetails
forall a env. IORef a -> IOEnv env a
readMutVar IORef MetaDetails
ref
               ; case MetaDetails
cts of
                    MetaDetails
Flexi       -> TcM TcKind
zonk_kind_and_return
                    Indirect TcKind
ty -> do { TcKind
zty <- TcKind -> TcM TcKind
zonkTcType TcKind
ty
                                      ; IORef MetaDetails -> MetaDetails -> TcRn ()
forall a gbl lcl. TcRef a -> a -> TcRnIf gbl lcl ()
writeTcRef IORef MetaDetails
ref (TcKind -> MetaDetails
Indirect TcKind
zty)
                                        -- See Note [Sharing in zonking]
                                      ; TcKind -> TcM TcKind
forall (m :: * -> *) a. Monad m => a -> m a
return TcKind
zty } }

  | Bool
otherwise -- coercion variable
  = TcM TcKind
zonk_kind_and_return
  where
    zonk_kind_and_return :: TcM TcKind
zonk_kind_and_return = do { TyVar
z_tv <- TyVar -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
zonkTyCoVarKind TyVar
tv
                              ; TcKind -> TcM TcKind
forall (m :: * -> *) a. Monad m => a -> m a
return (TyVar -> TcKind
mkTyVarTy TyVar
z_tv) }

-- Variant that assumes that any result of zonking is still a TyVar.
-- Should be used only on skolems and TyVarTvs
zonkTcTyVarToTyVar :: HasDebugCallStack => TcTyVar -> TcM TcTyVar
zonkTcTyVarToTyVar :: TyVar -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
zonkTcTyVarToTyVar TyVar
tv
  = do { TcKind
ty <- TyVar -> TcM TcKind
zonkTcTyVar TyVar
tv
       ; let tv' :: TyVar
tv' = case TcKind -> Maybe TyVar
tcGetTyVar_maybe TcKind
ty of
                     Just TyVar
tv' -> TyVar
tv'
                     Maybe TyVar
Nothing  -> String -> SDoc -> TyVar
forall a. HasCallStack => String -> SDoc -> a
pprPanic String
"zonkTcTyVarToTyVar"
                                          (TyVar -> SDoc
forall a. Outputable a => a -> SDoc
ppr TyVar
tv SDoc -> SDoc -> SDoc
$$ TcKind -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcKind
ty)
       ; TyVar -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
forall (m :: * -> *) a. Monad m => a -> m a
return TyVar
tv' }

zonkTyVarTyVarPairs :: [(Name,TcTyVar)] -> TcM [(Name,TcTyVar)]
zonkTyVarTyVarPairs :: [(Name, TyVar)] -> TcM [(Name, TyVar)]
zonkTyVarTyVarPairs [(Name, TyVar)]
prs
  = ((Name, TyVar) -> IOEnv (Env TcGblEnv TcLclEnv) (Name, TyVar))
-> [(Name, TyVar)] -> TcM [(Name, TyVar)]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM (Name, TyVar) -> IOEnv (Env TcGblEnv TcLclEnv) (Name, TyVar)
forall a. (a, TyVar) -> IOEnv (Env TcGblEnv TcLclEnv) (a, TyVar)
do_one [(Name, TyVar)]
prs
  where
    do_one :: (a, TyVar) -> IOEnv (Env TcGblEnv TcLclEnv) (a, TyVar)
do_one (a
nm, TyVar
tv) = do { TyVar
tv' <- HasDebugCallStack => TyVar -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
TyVar -> IOEnv (Env TcGblEnv TcLclEnv) TyVar
zonkTcTyVarToTyVar TyVar
tv
                         ; (a, TyVar) -> IOEnv (Env TcGblEnv TcLclEnv) (a, TyVar)
forall (m :: * -> *) a. Monad m => a -> m a
return (a
nm, TyVar
tv') }

{- Note [Sharing in zonking]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose we have
   alpha :-> beta :-> gamma :-> ty
where the ":->" means that the unification variable has been
filled in with Indirect. Then when zonking alpha, it'd be nice
to short-circuit beta too, so we end up with
   alpha :-> zty
   beta  :-> zty
   gamma :-> zty
where zty is the zonked version of ty.  That way, if we come across
beta later, we'll have less work to do.  (And indeed the same for
alpha.)

This is easily achieved: just overwrite (Indirect ty) with (Indirect
zty).  Non-systematic perf comparisons suggest that this is a modest
win.

But c.f Note [Sharing when zonking to Type] in TcHsSyn.

%************************************************************************
%*                                                                      *
                 Tidying
*                                                                      *
************************************************************************
-}

zonkTidyTcType :: TidyEnv -> TcType -> TcM (TidyEnv, TcType)
zonkTidyTcType :: TidyEnv -> TcKind -> TcM (TidyEnv, TcKind)
zonkTidyTcType TidyEnv
env TcKind
ty = do { TcKind
ty' <- TcKind -> TcM TcKind
zonkTcType TcKind
ty
                           ; (TidyEnv, TcKind) -> TcM (TidyEnv, TcKind)
forall (m :: * -> *) a. Monad m => a -> m a
return (TidyEnv -> TcKind -> (TidyEnv, TcKind)
tidyOpenType TidyEnv
env TcKind
ty') }

zonkTidyTcTypes :: TidyEnv -> [TcType] -> TcM (TidyEnv, [TcType])
zonkTidyTcTypes :: TidyEnv -> [TcKind] -> TcM (TidyEnv, [TcKind])
zonkTidyTcTypes = [TcKind] -> TidyEnv -> [TcKind] -> TcM (TidyEnv, [TcKind])
zonkTidyTcTypes' []
  where zonkTidyTcTypes' :: [TcKind] -> TidyEnv -> [TcKind] -> TcM (TidyEnv, [TcKind])
zonkTidyTcTypes' [TcKind]
zs TidyEnv
env [] = (TidyEnv, [TcKind]) -> TcM (TidyEnv, [TcKind])
forall (m :: * -> *) a. Monad m => a -> m a
return (TidyEnv
env, [TcKind] -> [TcKind]
forall a. [a] -> [a]
reverse [TcKind]
zs)
        zonkTidyTcTypes' [TcKind]
zs TidyEnv
env (TcKind
ty:[TcKind]
tys)
          = do { (TidyEnv
env', TcKind
ty') <- TidyEnv -> TcKind -> TcM (TidyEnv, TcKind)
zonkTidyTcType TidyEnv
env TcKind
ty
               ; [TcKind] -> TidyEnv -> [TcKind] -> TcM (TidyEnv, [TcKind])
zonkTidyTcTypes' (TcKind
ty'TcKind -> [TcKind] -> [TcKind]
forall a. a -> [a] -> [a]
:[TcKind]
zs) TidyEnv
env' [TcKind]
tys }

zonkTidyOrigin :: TidyEnv -> CtOrigin -> TcM (TidyEnv, CtOrigin)
zonkTidyOrigin :: TidyEnv -> CtOrigin -> TcM (TidyEnv, CtOrigin)
zonkTidyOrigin TidyEnv
env (GivenOrigin SkolemInfo
skol_info)
  = do { SkolemInfo
skol_info1 <- SkolemInfo -> TcM SkolemInfo
zonkSkolemInfo SkolemInfo
skol_info
       ; let skol_info2 :: SkolemInfo
skol_info2 = TidyEnv -> SkolemInfo -> SkolemInfo
tidySkolemInfo TidyEnv
env SkolemInfo
skol_info1
       ; (TidyEnv, CtOrigin) -> TcM (TidyEnv, CtOrigin)
forall (m :: * -> *) a. Monad m => a -> m a
return (TidyEnv
env, SkolemInfo -> CtOrigin
GivenOrigin SkolemInfo
skol_info2) }
zonkTidyOrigin TidyEnv
env orig :: CtOrigin
orig@(TypeEqOrigin { uo_actual :: CtOrigin -> TcKind
uo_actual   = TcKind
act
                                      , uo_expected :: CtOrigin -> TcKind
uo_expected = TcKind
exp })
  = do { (TidyEnv
env1, TcKind
act') <- TidyEnv -> TcKind -> TcM (TidyEnv, TcKind)
zonkTidyTcType TidyEnv
env  TcKind
act
       ; (TidyEnv
env2, TcKind
exp') <- TidyEnv -> TcKind -> TcM (TidyEnv, TcKind)
zonkTidyTcType TidyEnv
env1 TcKind
exp
       ; (TidyEnv, CtOrigin) -> TcM (TidyEnv, CtOrigin)
forall (m :: * -> *) a. Monad m => a -> m a
return ( TidyEnv
env2, CtOrigin
orig { uo_actual :: TcKind
uo_actual   = TcKind
act'
                             , uo_expected :: TcKind
uo_expected = TcKind
exp' }) }
zonkTidyOrigin TidyEnv
env (KindEqOrigin TcKind
ty1 Maybe TcKind
m_ty2 CtOrigin
orig Maybe TypeOrKind
t_or_k)
  = do { (TidyEnv
env1, TcKind
ty1')   <- TidyEnv -> TcKind -> TcM (TidyEnv, TcKind)
zonkTidyTcType TidyEnv
env  TcKind
ty1
       ; (TidyEnv
env2, Maybe TcKind
m_ty2') <- case Maybe TcKind
m_ty2 of
                             Just TcKind
ty2 -> (TcKind -> Maybe TcKind)
-> (TidyEnv, TcKind) -> (TidyEnv, Maybe TcKind)
forall (a :: * -> * -> *) b c d.
Arrow a =>
a b c -> a (d, b) (d, c)
second TcKind -> Maybe TcKind
forall a. a -> Maybe a
Just ((TidyEnv, TcKind) -> (TidyEnv, Maybe TcKind))
-> TcM (TidyEnv, TcKind)
-> IOEnv (Env TcGblEnv TcLclEnv) (TidyEnv, Maybe TcKind)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> TidyEnv -> TcKind -> TcM (TidyEnv, TcKind)
zonkTidyTcType TidyEnv
env1 TcKind
ty2
                             Maybe TcKind
Nothing  -> (TidyEnv, Maybe TcKind)
-> IOEnv (Env TcGblEnv TcLclEnv) (TidyEnv, Maybe TcKind)
forall (m :: * -> *) a. Monad m => a -> m a
return (TidyEnv
env1, Maybe TcKind
forall a. Maybe a
Nothing)
       ; (TidyEnv
env3, CtOrigin
orig')  <- TidyEnv -> CtOrigin -> TcM (TidyEnv, CtOrigin)
zonkTidyOrigin TidyEnv
env2 CtOrigin
orig
       ; (TidyEnv, CtOrigin) -> TcM (TidyEnv, CtOrigin)
forall (m :: * -> *) a. Monad m => a -> m a
return (TidyEnv
env3, TcKind -> Maybe TcKind -> CtOrigin -> Maybe TypeOrKind -> CtOrigin
KindEqOrigin TcKind
ty1' Maybe TcKind
m_ty2' CtOrigin
orig' Maybe TypeOrKind
t_or_k) }
zonkTidyOrigin TidyEnv
env (FunDepOrigin1 TcKind
p1 CtOrigin
o1 RealSrcSpan
l1 TcKind
p2 CtOrigin
o2 RealSrcSpan
l2)
  = do { (TidyEnv
env1, TcKind
p1') <- TidyEnv -> TcKind -> TcM (TidyEnv, TcKind)
zonkTidyTcType TidyEnv
env  TcKind
p1
       ; (TidyEnv
env2, TcKind
p2') <- TidyEnv -> TcKind -> TcM (TidyEnv, TcKind)
zonkTidyTcType TidyEnv
env1 TcKind
p2
       ; (TidyEnv, CtOrigin) -> TcM (TidyEnv, CtOrigin)
forall (m :: * -> *) a. Monad m => a -> m a
return (TidyEnv
env2, TcKind
-> CtOrigin
-> RealSrcSpan
-> TcKind
-> CtOrigin
-> RealSrcSpan
-> CtOrigin
FunDepOrigin1 TcKind
p1' CtOrigin
o1 RealSrcSpan
l1 TcKind
p2' CtOrigin
o2 RealSrcSpan
l2) }
zonkTidyOrigin TidyEnv
env (FunDepOrigin2 TcKind
p1 CtOrigin
o1 TcKind
p2 SrcSpan
l2)
  = do { (TidyEnv
env1, TcKind
p1') <- TidyEnv -> TcKind -> TcM (TidyEnv, TcKind)
zonkTidyTcType TidyEnv
env  TcKind
p1
       ; (TidyEnv
env2, TcKind
p2') <- TidyEnv -> TcKind -> TcM (TidyEnv, TcKind)
zonkTidyTcType TidyEnv
env1 TcKind
p2
       ; (TidyEnv
env3, CtOrigin
o1') <- TidyEnv -> CtOrigin -> TcM (TidyEnv, CtOrigin)
zonkTidyOrigin TidyEnv
env2 CtOrigin
o1
       ; (TidyEnv, CtOrigin) -> TcM (TidyEnv, CtOrigin)
forall (m :: * -> *) a. Monad m => a -> m a
return (TidyEnv
env3, TcKind -> CtOrigin -> TcKind -> SrcSpan -> CtOrigin
FunDepOrigin2 TcKind
p1' CtOrigin
o1' TcKind
p2' SrcSpan
l2) }
zonkTidyOrigin TidyEnv
env CtOrigin
orig = (TidyEnv, CtOrigin) -> TcM (TidyEnv, CtOrigin)
forall (m :: * -> *) a. Monad m => a -> m a
return (TidyEnv
env, CtOrigin
orig)

----------------
tidyCt :: TidyEnv -> Ct -> Ct
-- Used only in error reporting
-- Also converts it to non-canonical
tidyCt :: TidyEnv -> Ct -> Ct
tidyCt TidyEnv
env Ct
ct
  = case Ct
ct of
     CHoleCan { cc_ev :: Ct -> CtEvidence
cc_ev = CtEvidence
ev }
       -> Ct
ct { cc_ev :: CtEvidence
cc_ev = TidyEnv -> CtEvidence -> CtEvidence
tidy_ev TidyEnv
env CtEvidence
ev }
     Ct
_ -> CtEvidence -> Ct
mkNonCanonical (TidyEnv -> CtEvidence -> CtEvidence
tidy_ev TidyEnv
env (Ct -> CtEvidence
ctEvidence Ct
ct))
  where
    tidy_ev :: TidyEnv -> CtEvidence -> CtEvidence
     -- NB: we do not tidy the ctev_evar field because we don't
     --     show it in error messages
    tidy_ev :: TidyEnv -> CtEvidence -> CtEvidence
tidy_ev TidyEnv
env ctev :: CtEvidence
ctev@(CtGiven { ctev_pred :: CtEvidence -> TcKind
ctev_pred = TcKind
pred })
      = CtEvidence
ctev { ctev_pred :: TcKind
ctev_pred = TidyEnv -> TcKind -> TcKind
tidyType TidyEnv
env TcKind
pred }
    tidy_ev TidyEnv
env ctev :: CtEvidence
ctev@(CtWanted { ctev_pred :: CtEvidence -> TcKind
ctev_pred = TcKind
pred })
      = CtEvidence
ctev { ctev_pred :: TcKind
ctev_pred = TidyEnv -> TcKind -> TcKind
tidyType TidyEnv
env TcKind
pred }
    tidy_ev TidyEnv
env ctev :: CtEvidence
ctev@(CtDerived { ctev_pred :: CtEvidence -> TcKind
ctev_pred = TcKind
pred })
      = CtEvidence
ctev { ctev_pred :: TcKind
ctev_pred = TidyEnv -> TcKind -> TcKind
tidyType TidyEnv
env TcKind
pred }

----------------
tidyEvVar :: TidyEnv -> EvVar -> EvVar
tidyEvVar :: TidyEnv -> TyVar -> TyVar
tidyEvVar TidyEnv
env TyVar
var = TyVar -> TcKind -> TyVar
setVarType TyVar
var (TidyEnv -> TcKind -> TcKind
tidyType TidyEnv
env (TyVar -> TcKind
varType TyVar
var))

----------------
tidySkolemInfo :: TidyEnv -> SkolemInfo -> SkolemInfo
tidySkolemInfo :: TidyEnv -> SkolemInfo -> SkolemInfo
tidySkolemInfo TidyEnv
env (DerivSkol TcKind
ty)         = TcKind -> SkolemInfo
DerivSkol (TidyEnv -> TcKind -> TcKind
tidyType TidyEnv
env TcKind
ty)
tidySkolemInfo TidyEnv
env (SigSkol UserTypeCtxt
cx TcKind
ty [(Name, TyVar)]
tv_prs) = TidyEnv -> UserTypeCtxt -> TcKind -> [(Name, TyVar)] -> SkolemInfo
tidySigSkol TidyEnv
env UserTypeCtxt
cx TcKind
ty [(Name, TyVar)]
tv_prs
tidySkolemInfo TidyEnv
env (InferSkol [(Name, TcKind)]
ids)        = [(Name, TcKind)] -> SkolemInfo
InferSkol ((TcKind -> TcKind) -> [(Name, TcKind)] -> [(Name, TcKind)]
forall b c a. (b -> c) -> [(a, b)] -> [(a, c)]
mapSnd (TidyEnv -> TcKind -> TcKind
tidyType TidyEnv
env) [(Name, TcKind)]
ids)
tidySkolemInfo TidyEnv
env (UnifyForAllSkol TcKind
ty)   = TcKind -> SkolemInfo
UnifyForAllSkol (TidyEnv -> TcKind -> TcKind
tidyType TidyEnv
env TcKind
ty)
tidySkolemInfo TidyEnv
_   SkolemInfo
info                   = SkolemInfo
info

tidySigSkol :: TidyEnv -> UserTypeCtxt
            -> TcType -> [(Name,TcTyVar)] -> SkolemInfo
-- We need to take special care when tidying SigSkol
-- See Note [SigSkol SkolemInfo] in Origin
tidySigSkol :: TidyEnv -> UserTypeCtxt -> TcKind -> [(Name, TyVar)] -> SkolemInfo
tidySigSkol TidyEnv
env UserTypeCtxt
cx TcKind
ty [(Name, TyVar)]
tv_prs
  = UserTypeCtxt -> TcKind -> [(Name, TyVar)] -> SkolemInfo
SigSkol UserTypeCtxt
cx (TidyEnv -> TcKind -> TcKind
tidy_ty TidyEnv
env TcKind
ty) [(Name, TyVar)]
tv_prs'
  where
    tv_prs' :: [(Name, TyVar)]
tv_prs' = (TyVar -> TyVar) -> [(Name, TyVar)] -> [(Name, TyVar)]
forall b c a. (b -> c) -> [(a, b)] -> [(a, c)]
mapSnd (TidyEnv -> TyVar -> TyVar
tidyTyCoVarOcc TidyEnv
env) [(Name, TyVar)]
tv_prs
    inst_env :: NameEnv TyVar
inst_env = [(Name, TyVar)] -> NameEnv TyVar
forall a. [(Name, a)] -> NameEnv a
mkNameEnv [(Name, TyVar)]
tv_prs'

    tidy_ty :: TidyEnv -> TcKind -> TcKind
tidy_ty TidyEnv
env (ForAllTy (Bndr TyVar
tv ArgFlag
vis) TcKind
ty)
      = VarBndr TyVar ArgFlag -> TcKind -> TcKind
ForAllTy (TyVar -> ArgFlag -> VarBndr TyVar ArgFlag
forall var argf. var -> argf -> VarBndr var argf
Bndr TyVar
tv' ArgFlag
vis) (TidyEnv -> TcKind -> TcKind
tidy_ty TidyEnv
env' TcKind
ty)
      where
        (TidyEnv
env', TyVar
tv') = TidyEnv -> TyVar -> (TidyEnv, TyVar)
tidy_tv_bndr TidyEnv
env TyVar
tv

    tidy_ty TidyEnv
env ty :: TcKind
ty@(FunTy AnonArgFlag
_ TcKind
arg TcKind
res)
      = TcKind
ty { ft_arg :: TcKind
ft_arg = TidyEnv -> TcKind -> TcKind
tidyType TidyEnv
env TcKind
arg, ft_res :: TcKind
ft_res = TidyEnv -> TcKind -> TcKind
tidy_ty TidyEnv
env TcKind
res }

    tidy_ty TidyEnv
env TcKind
ty = TidyEnv -> TcKind -> TcKind
tidyType TidyEnv
env TcKind
ty

    tidy_tv_bndr :: TidyEnv -> TyCoVar -> (TidyEnv, TyCoVar)
    tidy_tv_bndr :: TidyEnv -> TyVar -> (TidyEnv, TyVar)
tidy_tv_bndr env :: TidyEnv
env@(TidyOccEnv
occ_env, NameEnv TyVar
subst) TyVar
tv
      | Just TyVar
tv' <- NameEnv TyVar -> Name -> Maybe TyVar
forall a. NameEnv a -> Name -> Maybe a
lookupNameEnv NameEnv TyVar
inst_env (TyVar -> Name
tyVarName TyVar
tv)
      = ((TidyOccEnv
occ_env, NameEnv TyVar -> TyVar -> TyVar -> NameEnv TyVar
forall a. VarEnv a -> TyVar -> a -> VarEnv a
extendVarEnv NameEnv TyVar
subst TyVar
tv TyVar
tv'), TyVar
tv')

      | Bool
otherwise
      = TidyEnv -> TyVar -> (TidyEnv, TyVar)
tidyVarBndr TidyEnv
env TyVar
tv

-------------------------------------------------------------------------
{-
%************************************************************************
%*                                                                      *
             Levity polymorphism checks
*                                                                      *
************************************************************************

See Note [Levity polymorphism checking] in DsMonad

-}

-- | According to the rules around representation polymorphism
-- (see https://gitlab.haskell.org/ghc/ghc/wikis/no-sub-kinds), no binder
-- can have a representation-polymorphic type. This check ensures
-- that we respect this rule. It is a bit regrettable that this error
-- occurs in zonking, after which we should have reported all errors.
-- But it's hard to see where else to do it, because this can be discovered
-- only after all solving is done. And, perhaps most importantly, this
-- isn't really a compositional property of a type system, so it's
-- not a terrible surprise that the check has to go in an awkward spot.
ensureNotLevPoly :: Type  -- its zonked type
                 -> SDoc  -- where this happened
                 -> TcM ()
ensureNotLevPoly :: TcKind -> SDoc -> TcRn ()
ensureNotLevPoly TcKind
ty SDoc
doc
  = TcRn () -> TcRn ()
whenNoErrs (TcRn () -> TcRn ()) -> TcRn () -> TcRn ()
forall a b. (a -> b) -> a -> b
$   -- sometimes we end up zonking bogus definitions of type
                   -- forall a. a. See, for example, test ghci/scripts/T9140
    SDoc -> TcKind -> TcRn ()
checkForLevPoly SDoc
doc TcKind
ty

  -- See Note [Levity polymorphism checking] in DsMonad
checkForLevPoly :: SDoc -> Type -> TcM ()
checkForLevPoly :: SDoc -> TcKind -> TcRn ()
checkForLevPoly = (SDoc -> TcRn ()) -> SDoc -> TcKind -> TcRn ()
forall (m :: * -> *).
Monad m =>
(SDoc -> m ()) -> SDoc -> TcKind -> m ()
checkForLevPolyX SDoc -> TcRn ()
addErr

checkForLevPolyX :: Monad m
                 => (SDoc -> m ())  -- how to report an error
                 -> SDoc -> Type -> m ()
checkForLevPolyX :: (SDoc -> m ()) -> SDoc -> TcKind -> m ()
checkForLevPolyX SDoc -> m ()
add_err SDoc
extra TcKind
ty
  | TcKind -> Bool
isTypeLevPoly TcKind
ty
  = SDoc -> m ()
add_err (TcKind -> SDoc
formatLevPolyErr TcKind
ty SDoc -> SDoc -> SDoc
$$ SDoc
extra)
  | Bool
otherwise
  = () -> m ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()

formatLevPolyErr :: Type  -- levity-polymorphic type
                 -> SDoc
formatLevPolyErr :: TcKind -> SDoc
formatLevPolyErr TcKind
ty
  = SDoc -> Int -> SDoc -> SDoc
hang (String -> SDoc
text String
"A levity-polymorphic type is not allowed here:")
       Int
2 ([SDoc] -> SDoc
vcat [ String -> SDoc
text String
"Type:" SDoc -> SDoc -> SDoc
<+> TcKind -> SDoc
pprWithTYPE TcKind
tidy_ty
               , String -> SDoc
text String
"Kind:" SDoc -> SDoc -> SDoc
<+> TcKind -> SDoc
pprWithTYPE TcKind
tidy_ki ])
  where
    (TidyEnv
tidy_env, TcKind
tidy_ty) = TidyEnv -> TcKind -> (TidyEnv, TcKind)
tidyOpenType TidyEnv
emptyTidyEnv TcKind
ty
    tidy_ki :: TcKind
tidy_ki             = TidyEnv -> TcKind -> TcKind
tidyType TidyEnv
tidy_env (HasDebugCallStack => TcKind -> TcKind
TcKind -> TcKind
tcTypeKind TcKind
ty)