o%
% (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
\begin{code}
module TcMType (
TcTyVar, TcKind, TcType, TcTauType, TcThetaType, TcTyVarSet,
newFlexiTyVar,
newFlexiTyVarTy,
newFlexiTyVarTys,
newPolyFlexiTyVarTy,
newMetaKindVar, newMetaKindVars,
mkTcTyVarName, cloneMetaTyVar,
newMetaTyVar, readMetaTyVar, writeMetaTyVar, writeMetaTyVarRef,
newMetaDetails, isFilledMetaTyVar, isFlexiMetaTyVar,
newEvVar, newEvVars, newEq, newDict,
newWantedEvVar, newWantedEvVars,
newTcEvBinds, addTcEvBind,
newFlatWanted, newFlatWanteds,
tcInstTyVars, newSigTyVar,
tcInstType,
tcInstSkolTyVars, tcInstSuperSkolTyVars,tcInstSuperSkolTyVarsX,
tcInstSigTyVarsLoc, tcInstSigTyVars,
tcInstSkolTyVar, tcInstSkolType,
tcSkolDFunType, tcSuperSkolTyVars,
zonkTcPredType,
skolemiseUnboundMetaTyVar,
zonkTcTyVar, zonkTcTyVars, zonkTyVarsAndFV, zonkTcTypeAndFV,
zonkQuantifiedTyVar, quantifyTyVars,
zonkTcTyVarBndr, zonkTcType, zonkTcTypes, zonkTcThetaType,
zonkTcKind, defaultKindVarToStar,
zonkEvVar, zonkWC, zonkFlats, zonkId, zonkCt, zonkCts, zonkSkolemInfo,
tcGetGlobalTyVars,
) where
#include "HsVersions.h"
import TypeRep
import TcType
import TcEvidence
import Type
import Class
import TyCon
import Var
import TcRnMonad
import Id
import Name
import VarSet
import PrelNames
import DynFlags
import Util
import Outputable
import FastString
import SrcLoc
import Bag
import Control.Monad
import Data.List ( partition, mapAccumL )
\end{code}
%************************************************************************
%* *
Kind variables
%* *
%************************************************************************
\begin{code}
mkKindName :: Unique -> Name
mkKindName unique = mkSystemName unique kind_var_occ
kind_var_occ :: OccName
kind_var_occ = mkOccName tvName "k"
newMetaKindVar :: TcM TcKind
newMetaKindVar = do { uniq <- newUnique
; details <- newMetaDetails TauTv
; let kv = mkTcTyVar (mkKindName uniq) superKind details
; return (mkTyVarTy kv) }
newMetaKindVars :: Int -> TcM [TcKind]
newMetaKindVars n = mapM (\ _ -> newMetaKindVar) (nOfThem n ())
\end{code}
%************************************************************************
%* *
Evidence variables; range over constraints we can abstract over
%* *
%************************************************************************
\begin{code}
newEvVars :: TcThetaType -> TcM [EvVar]
newEvVars theta = mapM newEvVar theta
newWantedEvVar :: TcPredType -> TcM EvVar
newWantedEvVar = newEvVar
newWantedEvVars :: TcThetaType -> TcM [EvVar]
newWantedEvVars theta = mapM newWantedEvVar theta
newEvVar :: TcPredType -> TcM EvVar
newEvVar ty = do { name <- newSysName (predTypeOccName ty)
; return (mkLocalId name ty) }
newEq :: TcType -> TcType -> TcM EvVar
newEq ty1 ty2
= do { name <- newSysName (mkVarOccFS (fsLit "cobox"))
; return (mkLocalId name (mkTcEqPred ty1 ty2)) }
newDict :: Class -> [TcType] -> TcM DictId
newDict cls tys
= do { name <- newSysName (mkDictOcc (getOccName cls))
; return (mkLocalId name (mkClassPred cls tys)) }
predTypeOccName :: PredType -> OccName
predTypeOccName ty = case classifyPredType ty of
ClassPred cls _ -> mkDictOcc (getOccName cls)
EqPred _ _ -> mkVarOccFS (fsLit "cobox")
TuplePred _ -> mkVarOccFS (fsLit "tup")
IrredPred _ -> mkVarOccFS (fsLit "irred")
\end{code}
*********************************************************************************
* *
* Wanted constraints
* *
*********************************************************************************
\begin{code}
newFlatWanted :: CtOrigin -> PredType -> TcM Ct
newFlatWanted orig pty
= do loc <- getCtLoc orig
v <- newWantedEvVar pty
return $ mkNonCanonical $
CtWanted { ctev_evar = v
, ctev_pred = pty
, ctev_loc = loc }
newFlatWanteds :: CtOrigin -> ThetaType -> TcM [Ct]
newFlatWanteds orig = mapM (newFlatWanted orig)
\end{code}
%************************************************************************
%* *
SkolemTvs (immutable)
%* *
%************************************************************************
\begin{code}
tcInstType :: ([TyVar] -> TcM (TvSubst, [TcTyVar]))
-> TcType
-> TcM ([TcTyVar], TcThetaType, TcType)
tcInstType inst_tyvars ty
= case tcSplitForAllTys ty of
([], rho) -> let
(theta, tau) = tcSplitPhiTy rho
in
return ([], theta, tau)
(tyvars, rho) -> do { (subst, tyvars') <- inst_tyvars tyvars
; let (theta, tau) = tcSplitPhiTy (substTy subst rho)
; return (tyvars', theta, tau) }
tcSkolDFunType :: Type -> TcM ([TcTyVar], TcThetaType, TcType)
tcSkolDFunType ty = tcInstType (\tvs -> return (tcSuperSkolTyVars tvs)) ty
tcSuperSkolTyVars :: [TyVar] -> (TvSubst, [TcTyVar])
tcSuperSkolTyVars = mapAccumL tcSuperSkolTyVar (mkTopTvSubst [])
tcSuperSkolTyVar :: TvSubst -> TyVar -> (TvSubst, TcTyVar)
tcSuperSkolTyVar subst tv
= (extendTvSubst subst tv (mkTyVarTy new_tv), new_tv)
where
kind = substTy subst (tyVarKind tv)
new_tv = mkTcTyVar (tyVarName tv) kind superSkolemTv
tcInstSkolTyVar :: SrcSpan -> Bool -> TvSubst -> TyVar
-> TcRnIf gbl lcl (TvSubst, TcTyVar)
tcInstSkolTyVar loc overlappable subst tyvar
= do { uniq <- newUnique
; let new_name = mkInternalName uniq occ loc
new_tv = mkTcTyVar new_name kind (SkolemTv overlappable)
; return (extendTvSubst subst tyvar (mkTyVarTy new_tv), new_tv) }
where
old_name = tyVarName tyvar
occ = nameOccName old_name
kind = substTy subst (tyVarKind tyvar)
tcInstSkolTyVars :: [TyVar] -> TcM (TvSubst, [TcTyVar])
tcInstSkolTyVars = tcInstSkolTyVarsX (mkTopTvSubst [])
tcInstSuperSkolTyVars :: [TyVar] -> TcM [TcTyVar]
tcInstSuperSkolTyVars = fmap snd . tcInstSkolTyVars' True (mkTopTvSubst [])
tcInstSkolTyVarsX, tcInstSuperSkolTyVarsX
:: TvSubst -> [TyVar] -> TcM (TvSubst, [TcTyVar])
tcInstSkolTyVarsX subst = tcInstSkolTyVars' False subst
tcInstSuperSkolTyVarsX subst = tcInstSkolTyVars' True subst
tcInstSkolTyVars' :: Bool -> TvSubst -> [TyVar] -> TcM (TvSubst, [TcTyVar])
tcInstSkolTyVars' isSuperSkol subst tvs
= do { loc <- getSrcSpanM
; mapAccumLM (tcInstSkolTyVar loc isSuperSkol) subst tvs }
tcInstSigTyVarsLoc :: SrcSpan -> [TyVar] -> TcRnIf gbl lcl (TvSubst, [TcTyVar])
tcInstSigTyVarsLoc loc = mapAccumLM (tcInstSkolTyVar loc False) (mkTopTvSubst [])
tcInstSigTyVars :: [TyVar] -> TcRnIf gbl lcl (TvSubst, [TcTyVar])
tcInstSigTyVars = mapAccumLM inst_tv (mkTopTvSubst [])
where
inst_tv subst tv = tcInstSkolTyVar (getSrcSpan tv) False subst tv
tcInstSkolType :: TcType -> TcM ([TcTyVar], TcThetaType, TcType)
tcInstSkolType ty = tcInstType tcInstSkolTyVars ty
newSigTyVar :: Name -> Kind -> TcM TcTyVar
newSigTyVar name kind
= do { uniq <- newUnique
; let name' = setNameUnique name uniq
; details <- newMetaDetails SigTv
; return (mkTcTyVar name' kind details) }
newMetaDetails :: MetaInfo -> TcM TcTyVarDetails
newMetaDetails info
= do { ref <- newMutVar Flexi
; untch <- getUntouchables
; return (MetaTv { mtv_info = info, mtv_ref = ref, mtv_untch = untch }) }
\end{code}
Note [Kind substitution when instantiating]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When we instantiate a bunch of kind and type variables, first we
expect them to be sorted (kind variables first, then type variables).
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 :: BOX), (k2 :: BOX), (a :: k1 -> k2), (b :: k1)]
we want
[(?k1 :: BOX), (?k2 :: BOX), (?a :: ?k1 -> ?k2), (?b :: ?k1)]
instead of the buggous
[(?k1 :: BOX), (?k2 :: BOX), (?a :: k1 -> k2), (?b :: k1)]
%************************************************************************
%* *
MetaTvs (meta type variables; mutable)
%* *
%************************************************************************
\begin{code}
newMetaTyVar :: MetaInfo -> Kind -> TcM TcTyVar
newMetaTyVar meta_info kind
= do { uniq <- newUnique
; let name = mkTcTyVarName uniq s
s = case meta_info of
PolyTv -> fsLit "s"
TauTv -> fsLit "t"
SigTv -> fsLit "a"
; details <- newMetaDetails meta_info
; return (mkTcTyVar name kind details) }
cloneMetaTyVar :: TcTyVar -> TcM TcTyVar
cloneMetaTyVar tv
= ASSERT( isTcTyVar tv )
do { uniq <- newUnique
; ref <- newMutVar Flexi
; let name' = setNameUnique (tyVarName tv) uniq
details' = case tcTyVarDetails tv of
details@(MetaTv {}) -> details { mtv_ref = ref }
_ -> pprPanic "cloneMetaTyVar" (ppr tv)
; return (mkTcTyVar name' (tyVarKind tv) details') }
mkTcTyVarName :: Unique -> FastString -> Name
mkTcTyVarName uniq str = mkSysTvName uniq str
readMetaTyVar :: TyVar -> TcM MetaDetails
readMetaTyVar tyvar = ASSERT2( isMetaTyVar tyvar, ppr tyvar )
readMutVar (metaTvRef tyvar)
isFilledMetaTyVar :: TyVar -> TcM Bool
isFilledMetaTyVar tv
| not (isTcTyVar tv) = return False
| MetaTv { mtv_ref = ref } <- tcTyVarDetails tv
= do { details <- readMutVar ref
; return (isIndirect details) }
| otherwise = return False
isFlexiMetaTyVar :: TyVar -> TcM Bool
isFlexiMetaTyVar tv
| not (isTcTyVar tv) = return False
| MetaTv { mtv_ref = ref } <- tcTyVarDetails tv
= do { details <- readMutVar ref
; return (isFlexi details) }
| otherwise = return False
writeMetaTyVar :: TcTyVar -> TcType -> TcM ()
writeMetaTyVar tyvar ty
| not debugIsOn
= writeMetaTyVarRef tyvar (metaTvRef tyvar) ty
| not (isTcTyVar tyvar)
= WARN( True, text "Writing to non-tc tyvar" <+> ppr tyvar )
return ()
| MetaTv { mtv_ref = ref } <- tcTyVarDetails tyvar
= writeMetaTyVarRef tyvar ref ty
| otherwise
= WARN( True, text "Writing to non-meta tyvar" <+> ppr tyvar )
return ()
writeMetaTyVarRef :: TcTyVar -> TcRef MetaDetails -> TcType -> TcM ()
writeMetaTyVarRef tyvar ref ty
| not debugIsOn
= do { traceTc "writeMetaTyVar" (ppr tyvar <+> text ":=" <+> ppr ty)
; writeMutVar ref (Indirect ty) }
| otherwise
= do { meta_details <- readMutVar ref;
; zonked_tv_kind <- zonkTcKind tv_kind
; zonked_ty_kind <- zonkTcKind ty_kind
; ASSERT2( isFlexi meta_details,
hang (text "Double update of meta tyvar")
2 (ppr tyvar $$ ppr meta_details) )
traceTc "writeMetaTyVar" (ppr tyvar <+> text ":=" <+> ppr ty)
; writeMutVar ref (Indirect ty)
; when ( not (isPredTy tv_kind)
&& not (zonked_ty_kind `tcIsSubKind` zonked_tv_kind))
$ WARN( True, hang (text "Ill-kinded update to meta tyvar")
2 ( ppr tyvar <+> text "::" <+> ppr tv_kind
<+> text ":="
<+> ppr ty <+> text "::" <+> ppr ty_kind) )
(return ()) }
where
tv_kind = tyVarKind tyvar
ty_kind = typeKind ty
\end{code}
%************************************************************************
%* *
MetaTvs: TauTvs
%* *
%************************************************************************
\begin{code}
newFlexiTyVar :: Kind -> TcM TcTyVar
newFlexiTyVar kind = newMetaTyVar TauTv kind
newFlexiTyVarTy :: Kind -> TcM TcType
newFlexiTyVarTy kind = do
tc_tyvar <- newFlexiTyVar kind
return (TyVarTy tc_tyvar)
newFlexiTyVarTys :: Int -> Kind -> TcM [TcType]
newFlexiTyVarTys n kind = mapM newFlexiTyVarTy (nOfThem n kind)
newPolyFlexiTyVarTy :: TcM TcType
newPolyFlexiTyVarTy = do { tv <- newMetaTyVar PolyTv liftedTypeKind
; return (TyVarTy tv) }
tcInstTyVars :: [TKVar] -> TcM ([TcTyVar], [TcType], TvSubst)
tcInstTyVars tyvars = tcInstTyVarsX emptyTvSubst tyvars
tcInstTyVarsX :: TvSubst -> [TKVar] -> TcM ([TcTyVar], [TcType], TvSubst)
tcInstTyVarsX subst tyvars =
do { (subst', tyvars') <- mapAccumLM tcInstTyVarX subst tyvars
; return (tyvars', mkTyVarTys tyvars', subst') }
tcInstTyVarX :: TvSubst -> TKVar -> TcM (TvSubst, TcTyVar)
tcInstTyVarX subst tyvar
= do { uniq <- newUnique
; details <- newMetaDetails TauTv
; let name = mkSystemName uniq (getOccName tyvar)
kind = substTy subst (tyVarKind tyvar)
new_tv = mkTcTyVar name kind details
; return (extendTvSubst subst tyvar (mkTyVarTy new_tv), new_tv) }
\end{code}
%************************************************************************
%* *
Quantification
%* *
%************************************************************************
Note [quantifyTyVars]
~~~~~~~~~~~~~~~~~~~~~
quantifyTyVars is give the free vars of a type that we
are about to wrap in a forall.
It takes these free type/kind variables and
1. Zonks them and remove globals
2. Partitions into type and kind variables (kvs1, tvs)
3. Extends kvs1 with free kind vars in the kinds of tvs (removing globals)
4. Calls zonkQuantifiedTyVar on each
Step (3) is often unimportant, because the kind variable is often
also free in the type. Eg
Typeable k (a::k)
has free vars {k,a}. But the type (see Trac #7916)
(f::k->*) (a::k)
has free vars {f,a}, but we must add 'k' as well! Hence step (3).
\begin{code}
quantifyTyVars :: TcTyVarSet -> TcTyVarSet -> TcM [TcTyVar]
quantifyTyVars gbl_tvs tkvs
= do { tkvs <- zonkTyVarsAndFV tkvs
; gbl_tvs <- zonkTyVarsAndFV gbl_tvs
; let (kvs, tvs) = partitionVarSet isKindVar (closeOverKinds tkvs `minusVarSet` gbl_tvs)
kvs2 = varSetElems kvs
qtvs = varSetElems tvs
; poly_kinds <- xoptM Opt_PolyKinds
; qkvs <- if poly_kinds
then return kvs2
else do { let (meta_kvs, skolem_kvs) = partition is_meta kvs2
is_meta kv = isTcTyVar kv && isMetaTyVar kv
; mapM_ defaultKindVarToStar meta_kvs
; return skolem_kvs }
; mapM zonk_quant (qkvs ++ qtvs) }
where
zonk_quant tkv
| isTcTyVar tkv = zonkQuantifiedTyVar tkv
| otherwise = return tkv
zonkQuantifiedTyVar :: TcTyVar -> TcM TcTyVar
zonkQuantifiedTyVar tv
= ASSERT2( isTcTyVar tv, ppr tv )
case tcTyVarDetails tv of
SkolemTv {} -> do { kind <- zonkTcKind (tyVarKind tv)
; return $ setTyVarKind tv kind }
MetaTv { mtv_ref = ref } ->
do when debugIsOn $ do
cts <- readMutVar ref
case cts of
Flexi -> return ()
Indirect ty -> WARN( True, ppr tv $$ ppr ty )
return ()
skolemiseUnboundMetaTyVar tv vanillaSkolemTv
_other -> pprPanic "zonkQuantifiedTyVar" (ppr tv)
defaultKindVarToStar :: TcTyVar -> TcM Kind
defaultKindVarToStar kv
= do { ASSERT( isKindVar kv && isMetaTyVar kv )
writeMetaTyVar kv liftedTypeKind
; return liftedTypeKind }
skolemiseUnboundMetaTyVar :: TcTyVar -> TcTyVarDetails -> TcM TyVar
skolemiseUnboundMetaTyVar tv details
= ASSERT2( isMetaTyVar tv, ppr tv )
do { span <- getSrcSpanM
; uniq <- newUnique
; kind <- zonkTcKind (tyVarKind tv)
; let final_kind = defaultKind kind
final_name = mkInternalName uniq (getOccName tv) span
final_tv = mkTcTyVar final_name final_kind details
; writeMetaTyVar tv (mkTyVarTy final_tv)
; return final_tv }
\end{code}
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. 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 [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
%* *
%************************************************************************
@tcGetGlobalTyVars@ returns a fully-zonked set of tyvars free in the environment.
To improve subsequent calls to the same function it writes the zonked set back into
the environment.
\begin{code}
tcGetGlobalTyVars :: TcM TcTyVarSet
tcGetGlobalTyVars
= do { (TcLclEnv {tcl_tyvars = gtv_var}) <- getLclEnv
; gbl_tvs <- readMutVar gtv_var
; gbl_tvs' <- zonkTyVarsAndFV gbl_tvs
; writeMutVar gtv_var gbl_tvs'
; return gbl_tvs' }
where
\end{code}
----------------- Type variables
\begin{code}
zonkTcTypeAndFV :: TcType -> TcM TyVarSet
zonkTcTypeAndFV ty = do { ty <- zonkTcType ty; return (tyVarsOfType ty) }
zonkTyVar :: TyVar -> TcM TcType
zonkTyVar tv | isTcTyVar tv = zonkTcTyVar tv
| otherwise = return (mkTyVarTy tv)
zonkTyVarsAndFV :: TyVarSet -> TcM TyVarSet
zonkTyVarsAndFV tyvars = tyVarsOfTypes <$> mapM zonkTyVar (varSetElems tyvars)
zonkTcTyVars :: [TcTyVar] -> TcM [TcType]
zonkTcTyVars tyvars = mapM zonkTcTyVar tyvars
zonkTyVarKind :: TyVar -> TcM TyVar
zonkTyVarKind tv = do { kind' <- zonkTcKind (tyVarKind tv)
; return (setTyVarKind tv kind') }
zonkTcTypes :: [TcType] -> TcM [TcType]
zonkTcTypes tys = mapM zonkTcType tys
zonkTcThetaType :: TcThetaType -> TcM TcThetaType
zonkTcThetaType theta = mapM zonkTcPredType theta
zonkTcPredType :: TcPredType -> TcM TcPredType
zonkTcPredType = zonkTcType
\end{code}
--------------- Constraints
\begin{code}
zonkImplication :: Implication -> TcM (Bag Implication)
zonkImplication implic@(Implic { ic_untch = untch
, ic_binds = binds_var
, ic_skols = skols
, ic_given = given
, ic_wanted = wanted
, ic_info = info })
= do { skols' <- mapM zonkTcTyVarBndr skols
; given' <- mapM zonkEvVar given
; info' <- zonkSkolemInfo info
; wanted' <- zonkWCRec binds_var untch wanted
; if isEmptyWC wanted'
then return emptyBag
else return $ unitBag $
implic { ic_fsks = []
, ic_skols = skols'
, ic_given = given'
, ic_wanted = wanted'
, ic_info = info' } }
zonkEvVar :: EvVar -> TcM EvVar
zonkEvVar var = do { ty' <- zonkTcType (varType var)
; return (setVarType var ty') }
zonkWC :: EvBindsVar
-> WantedConstraints -> TcM WantedConstraints
zonkWC binds_var wc
= do { untch <- getUntouchables
; zonkWCRec binds_var untch wc }
zonkWCRec :: EvBindsVar
-> Untouchables
-> WantedConstraints -> TcM WantedConstraints
zonkWCRec binds_var untch (WC { wc_flat = flat, wc_impl = implic, wc_insol = insol })
= do { flat' <- zonkFlats binds_var untch flat
; implic' <- flatMapBagM zonkImplication implic
; insol' <- zonkCts insol
; return (WC { wc_flat = flat', wc_impl = implic', wc_insol = insol' }) }
zonkFlats :: EvBindsVar -> Untouchables -> Cts -> TcM Cts
zonkFlats binds_var untch cts
= do {
cts <- foldrBagM unflatten_one emptyCts cts
; zonkCts cts }
where
unflatten_one orig_ct cts
= do { zct <- zonkCt orig_ct
; mct <- try_zonk_fun_eq orig_ct zct
; return $ maybe cts (`consBag` cts) mct }
try_zonk_fun_eq orig_ct zct
| EqPred ty_lhs ty_rhs <- classifyPredType (ctPred zct)
, Just tv <- getTyVar_maybe ty_rhs
, ASSERT2( not (isFloatedTouchableMetaTyVar untch tv), ppr tv )
isTouchableMetaTyVar untch tv
, not (isSigTyVar tv) || isTyVarTy ty_lhs
, typeKind ty_lhs `tcIsSubKind` tyVarKind tv
, not (tv `elemVarSet` tyVarsOfType ty_lhs)
= ASSERT2( case tcSplitTyConApp_maybe ty_lhs of { Just (tc,_) -> isSynFamilyTyCon tc; _ -> False }, ppr orig_ct )
do { writeMetaTyVar tv ty_lhs
; let evterm = EvCoercion (mkTcNomReflCo ty_lhs)
evvar = ctev_evar (cc_ev zct)
; when (isWantedCt orig_ct) $
addTcEvBind binds_var evvar evterm
; traceTc "zonkFlats/unflattening" $
vcat [ text "zct = " <+> ppr zct,
text "binds_var = " <+> ppr binds_var ]
; return Nothing }
| otherwise
= return (Just zct)
\end{code}
Note [Unflattening while zonking]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A bunch of wanted constraints could contain wanted equations of the form
(F taus ~ alpha) where alpha is either an ordinary unification variable, or
a flatten unification variable.
These are ordinary wanted constraints and can/should be solved by
ordinary unification alpha := F taus. However the constraint solving
algorithm does not do that, as their 'inert' form is F taus ~ alpha.
Hence, we need an extra step to 'unflatten' these equations by
performing unification. This unification, if it happens at the end of
constraint solving, cannot produce any more interactions in the
constraint solver so it is safe to do it as the very very last step.
We choose therefore to do it during zonking, in the function
zonkFlats. This is in analogy to the zonking of given "flatten skolems"
which are eliminated in favor of the underlying type that they are
equal to.
Note that, because we now have to affect *evidence* while zonking
(setting some evidence binds to identities), we have to pass to the
zonkWC function an evidence variable to collect all the extra
variables.
Note [How to unflatten]
~~~~~~~~~~~~~~~~~~~~~~~
How do we unflatten during zonking. Consider a bunch of flat constraints.
Consider them one by one. For each such constraint C
* Zonk C (to apply current substitution)
* If C is of form F tys ~ alpha,
where alpha is touchable
and alpha is not mentioned in tys
then unify alpha := F tys
and discard C
After processing all the flat constraints, zonk them again to propagate
the inforamtion from later ones to earlier ones. Eg
Start: (F alpha ~ beta, G Int ~ alpha)
Then we get beta := F alpha
alpha := G Int
but we must apply the second unification to the first constraint.
\begin{code}
zonkCts :: Cts -> TcM Cts
zonkCts = mapBagM zonkCt
zonkCt :: Ct -> TcM Ct
zonkCt ct@(CHoleCan { cc_ev = ev })
= do { ev' <- zonkCtEvidence ev
; return $ ct { cc_ev = ev' } }
zonkCt ct
= do { fl' <- zonkCtEvidence (cc_ev ct)
; return (mkNonCanonical fl') }
zonkCtEvidence :: CtEvidence -> TcM CtEvidence
zonkCtEvidence ctev@(CtGiven { ctev_pred = pred })
= do { pred' <- zonkTcType pred
; return (ctev { ctev_pred = pred'}) }
zonkCtEvidence ctev@(CtWanted { ctev_pred = pred })
= do { pred' <- zonkTcType pred
; return (ctev { ctev_pred = pred' }) }
zonkCtEvidence ctev@(CtDerived { ctev_pred = pred })
= do { pred' <- zonkTcType pred
; return (ctev { ctev_pred = pred' }) }
zonkSkolemInfo :: SkolemInfo -> TcM SkolemInfo
zonkSkolemInfo (SigSkol cx ty) = do { ty' <- zonkTcType ty
; return (SigSkol cx ty') }
zonkSkolemInfo (InferSkol ntys) = do { ntys' <- mapM do_one ntys
; return (InferSkol ntys') }
where
do_one (n, ty) = do { ty' <- zonkTcType ty; return (n, ty') }
zonkSkolemInfo skol_info = return skol_info
\end{code}
%************************************************************************
%* *
\subsection{Zonking -- the main work-horses: zonkTcType, zonkTcTyVar}
%* *
%* For internal use only! *
%* *
%************************************************************************
\begin{code}
zonkId :: TcId -> TcM TcId
zonkId id
= do { ty' <- zonkTcType (idType id)
; return (Id.setIdType id ty') }
zonkTcType :: TcType -> TcM TcType
zonkTcType ty
= go ty
where
go (TyConApp tc tys) = do tys' <- mapM go tys
return (TyConApp tc tys')
go (LitTy n) = return (LitTy n)
go (FunTy arg res) = do arg' <- go arg
res' <- go res
return (FunTy arg' res')
go (AppTy fun arg) = do fun' <- go fun
arg' <- go arg
return (mkAppTy fun' arg')
go (TyVarTy tyvar) | isTcTyVar tyvar = zonkTcTyVar tyvar
| otherwise = TyVarTy <$> updateTyVarKindM go tyvar
go (ForAllTy tv ty) = do { tv' <- zonkTcTyVarBndr tv
; ty' <- go ty
; return (ForAllTy tv' ty') }
zonkTcTyVarBndr :: TcTyVar -> TcM TcTyVar
zonkTcTyVarBndr tyvar
= ASSERT2( isImmutableTyVar tyvar, ppr tyvar ) do
updateTyVarKindM zonkTcType tyvar
zonkTcTyVar :: TcTyVar -> TcM TcType
zonkTcTyVar tv
= ASSERT2( isTcTyVar tv, ppr tv ) do
case tcTyVarDetails tv of
SkolemTv {} -> zonk_kind_and_return
RuntimeUnk {} -> zonk_kind_and_return
FlatSkol ty -> zonkTcType ty
MetaTv { mtv_ref = ref }
-> do { cts <- readMutVar ref
; case cts of
Flexi -> zonk_kind_and_return
Indirect ty -> zonkTcType ty }
where
zonk_kind_and_return = do { z_tv <- zonkTyVarKind tv
; return (TyVarTy z_tv) }
\end{code}
%************************************************************************
%* *
Zonking kinds
%* *
%************************************************************************
\begin{code}
zonkTcKind :: TcKind -> TcM TcKind
zonkTcKind k = zonkTcType k
\end{code}