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


Type subsumption and unification
-}

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

module TcUnify (
  -- Full-blown subsumption
  tcWrapResult, tcWrapResultO, tcSkolemise, tcSkolemiseET,
  tcSubTypeHR, tcSubTypeO, tcSubType_NC, tcSubTypeDS,
  tcSubTypeDS_NC_O, tcSubTypeET,
  checkConstraints, checkTvConstraints,
  buildImplicationFor, emitResidualTvConstraint,

  -- Various unifications
  unifyType, unifyKind,
  uType, promoteTcType,
  swapOverTyVars, canSolveByUnification,

  --------------------------------
  -- Holes
  tcInferInst, tcInferNoInst,
  matchExpectedListTy,
  matchExpectedTyConApp,
  matchExpectedAppTy,
  matchExpectedFunTys,
  matchActualFunTys, matchActualFunTysPart,
  matchExpectedFunKind,

  metaTyVarUpdateOK, occCheckForErrors, MetaTyVarUpdateResult(..)

  ) where

#include "HsVersions.h"

import GhcPrelude

import GHC.Hs
import TyCoRep
import TyCoPpr( debugPprType )
import TcMType
import TcRnMonad
import TcType
import Type
import Coercion
import TcEvidence
import Constraint
import Predicate
import TcOrigin
import Name( isSystemName )
import Inst
import TyCon
import TysWiredIn
import TysPrim( tYPE )
import Var
import VarSet
import VarEnv
import ErrUtils
import DynFlags
import BasicTypes
import Bag
import Util
import qualified GHC.LanguageExtensions as LangExt
import Outputable

import Data.Maybe( isNothing )
import Control.Monad
import Control.Arrow ( second )

{-
************************************************************************
*                                                                      *
             matchExpected functions
*                                                                      *
************************************************************************

Note [Herald for matchExpectedFunTys]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The 'herald' always looks like:
   "The equation(s) for 'f' have"
   "The abstraction (\x.e) takes"
   "The section (+ x) expects"
   "The function 'f' is applied to"

This is used to construct a message of form

   The abstraction `\Just 1 -> ...' takes two arguments
   but its type `Maybe a -> a' has only one

   The equation(s) for `f' have two arguments
   but its type `Maybe a -> a' has only one

   The section `(f 3)' requires 'f' to take two arguments
   but its type `Int -> Int' has only one

   The function 'f' is applied to two arguments
   but its type `Int -> Int' has only one

When visible type applications (e.g., `f @Int 1 2`, as in #13902) enter the
picture, we have a choice in deciding whether to count the type applications as
proper arguments:

   The function 'f' is applied to one visible type argument
     and two value arguments
   but its type `forall a. a -> a` has only one visible type argument
     and one value argument

Or whether to include the type applications as part of the herald itself:

   The expression 'f @Int' is applied to two arguments
   but its type `Int -> Int` has only one

The latter is easier to implement and is arguably easier to understand, so we
choose to implement that option.

Note [matchExpectedFunTys]
~~~~~~~~~~~~~~~~~~~~~~~~~~
matchExpectedFunTys checks that a sigma has the form
of an n-ary function.  It passes the decomposed type to the
thing_inside, and returns a wrapper to coerce between the two types

It's used wherever a language construct must have a functional type,
namely:
        A lambda expression
        A function definition
     An operator section

This function must be written CPS'd because it needs to fill in the
ExpTypes produced for arguments before it can fill in the ExpType
passed in.

-}

-- Use this one when you have an "expected" type.
matchExpectedFunTys :: forall a.
                       SDoc   -- See Note [Herald for matchExpectedFunTys]
                    -> Arity
                    -> ExpRhoType  -- deeply skolemised
                    -> ([ExpSigmaType] -> ExpRhoType -> TcM a)
                          -- must fill in these ExpTypes here
                    -> TcM (a, HsWrapper)
-- If    matchExpectedFunTys n ty = (_, wrap)
-- then  wrap : (t1 -> ... -> tn -> ty_r) ~> ty,
--   where [t1, ..., tn], ty_r are passed to the thing_inside
matchExpectedFunTys :: SDoc
-> Arity
-> ExpRhoType
-> ([ExpRhoType] -> ExpRhoType -> TcM a)
-> TcM (a, HsWrapper)
matchExpectedFunTys SDoc
herald Arity
arity ExpRhoType
orig_ty [ExpRhoType] -> ExpRhoType -> TcM a
thing_inside
  = case ExpRhoType
orig_ty of
      Check TcType
ty -> [ExpRhoType] -> Arity -> TcType -> TcM (a, HsWrapper)
go [] Arity
arity TcType
ty
      ExpRhoType
_        -> [ExpRhoType] -> Arity -> ExpRhoType -> TcM (a, HsWrapper)
defer [] Arity
arity ExpRhoType
orig_ty
  where
    go :: [ExpRhoType] -> Arity -> TcType -> TcM (a, HsWrapper)
go [ExpRhoType]
acc_arg_tys Arity
0 TcType
ty
      = do { a
result <- [ExpRhoType] -> ExpRhoType -> TcM a
thing_inside ([ExpRhoType] -> [ExpRhoType]
forall a. [a] -> [a]
reverse [ExpRhoType]
acc_arg_tys) (TcType -> ExpRhoType
mkCheckExpType TcType
ty)
           ; (a, HsWrapper) -> TcM (a, HsWrapper)
forall (m :: * -> *) a. Monad m => a -> m a
return (a
result, HsWrapper
idHsWrapper) }

    go [ExpRhoType]
acc_arg_tys Arity
n TcType
ty
      | Just TcType
ty' <- TcType -> Maybe TcType
tcView TcType
ty = [ExpRhoType] -> Arity -> TcType -> TcM (a, HsWrapper)
go [ExpRhoType]
acc_arg_tys Arity
n TcType
ty'

    go [ExpRhoType]
acc_arg_tys Arity
n (FunTy { ft_af :: TcType -> AnonArgFlag
ft_af = AnonArgFlag
af, ft_arg :: TcType -> TcType
ft_arg = TcType
arg_ty, ft_res :: TcType -> TcType
ft_res = TcType
res_ty })
      = ASSERT( af == VisArg )
        do { (a
result, HsWrapper
wrap_res) <- [ExpRhoType] -> Arity -> TcType -> TcM (a, HsWrapper)
go (TcType -> ExpRhoType
mkCheckExpType TcType
arg_ty ExpRhoType -> [ExpRhoType] -> [ExpRhoType]
forall a. a -> [a] -> [a]
: [ExpRhoType]
acc_arg_tys)
                                      (Arity
nArity -> Arity -> Arity
forall a. Num a => a -> a -> a
-Arity
1) TcType
res_ty
           ; (a, HsWrapper) -> TcM (a, HsWrapper)
forall (m :: * -> *) a. Monad m => a -> m a
return ( a
result
                    , HsWrapper -> HsWrapper -> TcType -> TcType -> SDoc -> HsWrapper
mkWpFun HsWrapper
idHsWrapper HsWrapper
wrap_res TcType
arg_ty TcType
res_ty SDoc
doc ) }
      where
        doc :: SDoc
doc = String -> SDoc
text String
"When inferring the argument type of a function with type" SDoc -> SDoc -> SDoc
<+>
              SDoc -> SDoc
quotes (ExpRhoType -> SDoc
forall a. Outputable a => a -> SDoc
ppr ExpRhoType
orig_ty)

    go [ExpRhoType]
acc_arg_tys Arity
n ty :: TcType
ty@(TyVarTy Var
tv)
      | Var -> Bool
isMetaTyVar Var
tv
      = do { MetaDetails
cts <- Var -> TcM MetaDetails
readMetaTyVar Var
tv
           ; case MetaDetails
cts of
               Indirect TcType
ty' -> [ExpRhoType] -> Arity -> TcType -> TcM (a, HsWrapper)
go [ExpRhoType]
acc_arg_tys Arity
n TcType
ty'
               MetaDetails
Flexi        -> [ExpRhoType] -> Arity -> ExpRhoType -> TcM (a, HsWrapper)
defer [ExpRhoType]
acc_arg_tys Arity
n (TcType -> ExpRhoType
mkCheckExpType TcType
ty) }

       -- In all other cases we bale out into ordinary unification
       -- However unlike the meta-tyvar case, we are sure that the
       -- number of arguments doesn't match arity of the original
       -- type, so we can add a bit more context to the error message
       -- (cf #7869).
       --
       -- It is not always an error, because specialized type may have
       -- different arity, for example:
       --
       -- > f1 = f2 'a'
       -- > f2 :: Monad m => m Bool
       -- > f2 = undefined
       --
       -- But in that case we add specialized type into error context
       -- anyway, because it may be useful. See also #9605.
    go [ExpRhoType]
acc_arg_tys Arity
n TcType
ty = (TidyEnv -> TcM (TidyEnv, SDoc))
-> TcM (a, HsWrapper) -> TcM (a, HsWrapper)
forall a. (TidyEnv -> TcM (TidyEnv, SDoc)) -> TcM a -> TcM a
addErrCtxtM TidyEnv -> TcM (TidyEnv, SDoc)
mk_ctxt (TcM (a, HsWrapper) -> TcM (a, HsWrapper))
-> TcM (a, HsWrapper) -> TcM (a, HsWrapper)
forall a b. (a -> b) -> a -> b
$
                          [ExpRhoType] -> Arity -> ExpRhoType -> TcM (a, HsWrapper)
defer [ExpRhoType]
acc_arg_tys Arity
n (TcType -> ExpRhoType
mkCheckExpType TcType
ty)

    ------------
    defer :: [ExpSigmaType] -> Arity -> ExpRhoType -> TcM (a, HsWrapper)
    defer :: [ExpRhoType] -> Arity -> ExpRhoType -> TcM (a, HsWrapper)
defer [ExpRhoType]
acc_arg_tys Arity
n ExpRhoType
fun_ty
      = do { [ExpRhoType]
more_arg_tys <- Arity
-> IOEnv (Env TcGblEnv TcLclEnv) ExpRhoType
-> IOEnv (Env TcGblEnv TcLclEnv) [ExpRhoType]
forall (m :: * -> *) a. Applicative m => Arity -> m a -> m [a]
replicateM Arity
n IOEnv (Env TcGblEnv TcLclEnv) ExpRhoType
newInferExpTypeNoInst
           ; ExpRhoType
res_ty       <- IOEnv (Env TcGblEnv TcLclEnv) ExpRhoType
newInferExpTypeInst
           ; a
result       <- [ExpRhoType] -> ExpRhoType -> TcM a
thing_inside ([ExpRhoType] -> [ExpRhoType]
forall a. [a] -> [a]
reverse [ExpRhoType]
acc_arg_tys [ExpRhoType] -> [ExpRhoType] -> [ExpRhoType]
forall a. [a] -> [a] -> [a]
++ [ExpRhoType]
more_arg_tys) ExpRhoType
res_ty
           ; [TcType]
more_arg_tys <- (ExpRhoType -> IOEnv (Env TcGblEnv TcLclEnv) TcType)
-> [ExpRhoType] -> IOEnv (Env TcGblEnv TcLclEnv) [TcType]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM ExpRhoType -> IOEnv (Env TcGblEnv TcLclEnv) TcType
readExpType [ExpRhoType]
more_arg_tys
           ; TcType
res_ty       <- ExpRhoType -> IOEnv (Env TcGblEnv TcLclEnv) TcType
readExpType ExpRhoType
res_ty
           ; let unif_fun_ty :: TcType
unif_fun_ty = [TcType] -> TcType -> TcType
mkVisFunTys [TcType]
more_arg_tys TcType
res_ty
           ; HsWrapper
wrap <- CtOrigin -> UserTypeCtxt -> TcType -> ExpRhoType -> TcM HsWrapper
tcSubTypeDS CtOrigin
AppOrigin UserTypeCtxt
GenSigCtxt TcType
unif_fun_ty ExpRhoType
fun_ty
                         -- Not a good origin at all :-(
           ; (a, HsWrapper) -> TcM (a, HsWrapper)
forall (m :: * -> *) a. Monad m => a -> m a
return (a
result, HsWrapper
wrap) }

    ------------
    mk_ctxt :: TidyEnv -> TcM (TidyEnv, MsgDoc)
    mk_ctxt :: TidyEnv -> TcM (TidyEnv, SDoc)
mk_ctxt TidyEnv
env = do { (TidyEnv
env', TcType
ty) <- TidyEnv -> TcType -> TcM (TidyEnv, TcType)
zonkTidyTcType TidyEnv
env TcType
orig_tc_ty
                     ; let ([TcType]
args, TcType
_) = TcType -> ([TcType], TcType)
tcSplitFunTys TcType
ty
                           n_actual :: Arity
n_actual = [TcType] -> Arity
forall (t :: * -> *) a. Foldable t => t a -> Arity
length [TcType]
args
                           (TidyEnv
env'', TcType
orig_ty') = TidyEnv -> TcType -> (TidyEnv, TcType)
tidyOpenType TidyEnv
env' TcType
orig_tc_ty
                     ; (TidyEnv, SDoc) -> TcM (TidyEnv, SDoc)
forall (m :: * -> *) a. Monad m => a -> m a
return ( TidyEnv
env''
                              , TcType -> TcType -> Arity -> Arity -> SDoc -> SDoc
mk_fun_tys_msg TcType
orig_ty' TcType
ty Arity
n_actual Arity
arity SDoc
herald) }
      where
        orig_tc_ty :: TcType
orig_tc_ty = String -> ExpRhoType -> TcType
checkingExpType String
"matchExpectedFunTys" ExpRhoType
orig_ty
            -- this is safe b/c we're called from "go"

-- Like 'matchExpectedFunTys', but used when you have an "actual" type,
-- for example in function application
matchActualFunTys :: SDoc   -- See Note [Herald for matchExpectedFunTys]
                  -> CtOrigin
                  -> Maybe (HsExpr GhcRn)   -- the thing with type TcSigmaType
                  -> Arity
                  -> TcSigmaType
                  -> TcM (HsWrapper, [TcSigmaType], TcSigmaType)
-- If    matchActualFunTys n ty = (wrap, [t1,..,tn], ty_r)
-- then  wrap : ty ~> (t1 -> ... -> tn -> ty_r)
matchActualFunTys :: SDoc
-> CtOrigin
-> Maybe (HsExpr GhcRn)
-> Arity
-> TcType
-> TcM (HsWrapper, [TcType], TcType)
matchActualFunTys SDoc
herald CtOrigin
ct_orig Maybe (HsExpr GhcRn)
mb_thing Arity
arity TcType
ty
  = SDoc
-> CtOrigin
-> Maybe (HsExpr GhcRn)
-> Arity
-> TcType
-> [TcType]
-> Arity
-> TcM (HsWrapper, [TcType], TcType)
matchActualFunTysPart SDoc
herald CtOrigin
ct_orig Maybe (HsExpr GhcRn)
mb_thing Arity
arity TcType
ty [] Arity
arity

-- | Variant of 'matchActualFunTys' that works when supplied only part
-- (that is, to the right of some arrows) of the full function type
matchActualFunTysPart :: SDoc -- See Note [Herald for matchExpectedFunTys]
                      -> CtOrigin
                      -> Maybe (HsExpr GhcRn)  -- the thing with type TcSigmaType
                      -> Arity
                      -> TcSigmaType
                      -> [TcSigmaType] -- reversed args. See (*) below.
                      -> Arity   -- overall arity of the function, for errs
                      -> TcM (HsWrapper, [TcSigmaType], TcSigmaType)
matchActualFunTysPart :: SDoc
-> CtOrigin
-> Maybe (HsExpr GhcRn)
-> Arity
-> TcType
-> [TcType]
-> Arity
-> TcM (HsWrapper, [TcType], TcType)
matchActualFunTysPart SDoc
herald CtOrigin
ct_orig Maybe (HsExpr GhcRn)
mb_thing Arity
arity TcType
orig_ty
                      [TcType]
orig_old_args Arity
full_arity
  = Arity -> [TcType] -> TcType -> TcM (HsWrapper, [TcType], TcType)
go Arity
arity [TcType]
orig_old_args TcType
orig_ty
-- Does not allocate unnecessary meta variables: if the input already is
-- a function, we just take it apart.  Not only is this efficient,
-- it's important for higher rank: the argument might be of form
--              (forall a. ty) -> other
-- If allocated (fresh-meta-var1 -> fresh-meta-var2) and unified, we'd
-- hide the forall inside a meta-variable

-- (*) Sometimes it's necessary to call matchActualFunTys with only part
-- (that is, to the right of some arrows) of the type of the function in
-- question. (See TcExpr.tcArgs.) This argument is the reversed list of
-- arguments already seen (that is, not part of the TcSigmaType passed
-- in elsewhere).

  where
    -- This function has a bizarre mechanic: it accumulates arguments on
    -- the way down and also builds an argument list on the way up. Why:
    -- 1. The returns args list and the accumulated args list might be different.
    --    The accumulated args include all the arg types for the function,
    --    including those from before this function was called. The returned
    --    list should include only those arguments produced by this call of
    --    matchActualFunTys
    --
    -- 2. The HsWrapper can be built only on the way up. It seems (more)
    --    bizarre to build the HsWrapper but not the arg_tys.
    --
    -- Refactoring is welcome.
    go :: Arity
       -> [TcSigmaType] -- accumulator of arguments (reversed)
       -> TcSigmaType   -- the remainder of the type as we're processing
       -> TcM (HsWrapper, [TcSigmaType], TcSigmaType)
    go :: Arity -> [TcType] -> TcType -> TcM (HsWrapper, [TcType], TcType)
go Arity
0 [TcType]
_ TcType
ty = (HsWrapper, [TcType], TcType) -> TcM (HsWrapper, [TcType], TcType)
forall (m :: * -> *) a. Monad m => a -> m a
return (HsWrapper
idHsWrapper, [], TcType
ty)

    go Arity
n [TcType]
acc_args TcType
ty
      | Bool -> Bool
not ([Var] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Var]
tvs Bool -> Bool -> Bool
&& [TcType] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [TcType]
theta)
      = do { (HsWrapper
wrap1, TcType
rho) <- CtOrigin -> TcType -> TcM (HsWrapper, TcType)
topInstantiate CtOrigin
ct_orig TcType
ty
           ; (HsWrapper
wrap2, [TcType]
arg_tys, TcType
res_ty) <- Arity -> [TcType] -> TcType -> TcM (HsWrapper, [TcType], TcType)
go Arity
n [TcType]
acc_args TcType
rho
           ; (HsWrapper, [TcType], TcType) -> TcM (HsWrapper, [TcType], TcType)
forall (m :: * -> *) a. Monad m => a -> m a
return (HsWrapper
wrap2 HsWrapper -> HsWrapper -> HsWrapper
<.> HsWrapper
wrap1, [TcType]
arg_tys, TcType
res_ty) }
      where
        ([Var]
tvs, [TcType]
theta, TcType
_) = TcType -> ([Var], [TcType], TcType)
tcSplitSigmaTy TcType
ty

    go Arity
n [TcType]
acc_args TcType
ty
      | Just TcType
ty' <- TcType -> Maybe TcType
tcView TcType
ty = Arity -> [TcType] -> TcType -> TcM (HsWrapper, [TcType], TcType)
go Arity
n [TcType]
acc_args TcType
ty'

    go Arity
n [TcType]
acc_args (FunTy { ft_af :: TcType -> AnonArgFlag
ft_af = AnonArgFlag
af, ft_arg :: TcType -> TcType
ft_arg = TcType
arg_ty, ft_res :: TcType -> TcType
ft_res = TcType
res_ty })
      = ASSERT( af == VisArg )
        do { (HsWrapper
wrap_res, [TcType]
tys, TcType
ty_r) <- Arity -> [TcType] -> TcType -> TcM (HsWrapper, [TcType], TcType)
go (Arity
nArity -> Arity -> Arity
forall a. Num a => a -> a -> a
-Arity
1) (TcType
arg_ty TcType -> [TcType] -> [TcType]
forall a. a -> [a] -> [a]
: [TcType]
acc_args) TcType
res_ty
           ; (HsWrapper, [TcType], TcType) -> TcM (HsWrapper, [TcType], TcType)
forall (m :: * -> *) a. Monad m => a -> m a
return ( HsWrapper -> HsWrapper -> TcType -> TcType -> SDoc -> HsWrapper
mkWpFun HsWrapper
idHsWrapper HsWrapper
wrap_res TcType
arg_ty TcType
ty_r SDoc
doc
                    , TcType
arg_ty TcType -> [TcType] -> [TcType]
forall a. a -> [a] -> [a]
: [TcType]
tys, TcType
ty_r ) }
      where
        doc :: SDoc
doc = String -> SDoc
text String
"When inferring the argument type of a function with type" SDoc -> SDoc -> SDoc
<+>
              SDoc -> SDoc
quotes (TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
orig_ty)

    go Arity
n [TcType]
acc_args ty :: TcType
ty@(TyVarTy Var
tv)
      | Var -> Bool
isMetaTyVar Var
tv
      = do { MetaDetails
cts <- Var -> TcM MetaDetails
readMetaTyVar Var
tv
           ; case MetaDetails
cts of
               Indirect TcType
ty' -> Arity -> [TcType] -> TcType -> TcM (HsWrapper, [TcType], TcType)
go Arity
n [TcType]
acc_args TcType
ty'
               MetaDetails
Flexi        -> Arity -> TcType -> TcM (HsWrapper, [TcType], TcType)
defer Arity
n TcType
ty }

       -- In all other cases we bale out into ordinary unification
       -- However unlike the meta-tyvar case, we are sure that the
       -- number of arguments doesn't match arity of the original
       -- type, so we can add a bit more context to the error message
       -- (cf #7869).
       --
       -- It is not always an error, because specialized type may have
       -- different arity, for example:
       --
       -- > f1 = f2 'a'
       -- > f2 :: Monad m => m Bool
       -- > f2 = undefined
       --
       -- But in that case we add specialized type into error context
       -- anyway, because it may be useful. See also #9605.
    go Arity
n [TcType]
acc_args TcType
ty = (TidyEnv -> TcM (TidyEnv, SDoc))
-> TcM (HsWrapper, [TcType], TcType)
-> TcM (HsWrapper, [TcType], TcType)
forall a. (TidyEnv -> TcM (TidyEnv, SDoc)) -> TcM a -> TcM a
addErrCtxtM ([TcType] -> TcType -> TidyEnv -> TcM (TidyEnv, SDoc)
mk_ctxt ([TcType] -> [TcType]
forall a. [a] -> [a]
reverse [TcType]
acc_args) TcType
ty) (TcM (HsWrapper, [TcType], TcType)
 -> TcM (HsWrapper, [TcType], TcType))
-> TcM (HsWrapper, [TcType], TcType)
-> TcM (HsWrapper, [TcType], TcType)
forall a b. (a -> b) -> a -> b
$
                       Arity -> TcType -> TcM (HsWrapper, [TcType], TcType)
defer Arity
n TcType
ty

    ------------
    defer :: Arity -> TcType -> TcM (HsWrapper, [TcType], TcType)
defer Arity
n TcType
fun_ty
      = do { [TcType]
arg_tys <- Arity
-> IOEnv (Env TcGblEnv TcLclEnv) TcType
-> IOEnv (Env TcGblEnv TcLclEnv) [TcType]
forall (m :: * -> *) a. Applicative m => Arity -> m a -> m [a]
replicateM Arity
n IOEnv (Env TcGblEnv TcLclEnv) TcType
newOpenFlexiTyVarTy
           ; TcType
res_ty  <- IOEnv (Env TcGblEnv TcLclEnv) TcType
newOpenFlexiTyVarTy
           ; let unif_fun_ty :: TcType
unif_fun_ty = [TcType] -> TcType -> TcType
mkVisFunTys [TcType]
arg_tys TcType
res_ty
           ; TcCoercionN
co <- Maybe (HsExpr GhcRn) -> TcType -> TcType -> TcM TcCoercionN
unifyType Maybe (HsExpr GhcRn)
mb_thing TcType
fun_ty TcType
unif_fun_ty
           ; (HsWrapper, [TcType], TcType) -> TcM (HsWrapper, [TcType], TcType)
forall (m :: * -> *) a. Monad m => a -> m a
return (TcCoercionN -> HsWrapper
mkWpCastN TcCoercionN
co, [TcType]
arg_tys, TcType
res_ty) }

    ------------
    mk_ctxt :: [TcSigmaType] -> TcSigmaType -> TidyEnv -> TcM (TidyEnv, MsgDoc)
    mk_ctxt :: [TcType] -> TcType -> TidyEnv -> TcM (TidyEnv, SDoc)
mk_ctxt [TcType]
arg_tys TcType
res_ty TidyEnv
env
      = do { let ty :: TcType
ty = [TcType] -> TcType -> TcType
mkVisFunTys [TcType]
arg_tys TcType
res_ty
           ; (TidyEnv
env1, TcType
zonked) <- TidyEnv -> TcType -> TcM (TidyEnv, TcType)
zonkTidyTcType TidyEnv
env TcType
ty
                   -- zonking might change # of args
           ; let ([TcType]
zonked_args, TcType
_) = TcType -> ([TcType], TcType)
tcSplitFunTys TcType
zonked
                 n_actual :: Arity
n_actual         = [TcType] -> Arity
forall (t :: * -> *) a. Foldable t => t a -> Arity
length [TcType]
zonked_args
                 (TidyEnv
env2, TcType
unzonked) = TidyEnv -> TcType -> (TidyEnv, TcType)
tidyOpenType TidyEnv
env1 TcType
ty
           ; (TidyEnv, SDoc) -> TcM (TidyEnv, SDoc)
forall (m :: * -> *) a. Monad m => a -> m a
return ( TidyEnv
env2
                    , TcType -> TcType -> Arity -> Arity -> SDoc -> SDoc
mk_fun_tys_msg TcType
unzonked TcType
zonked Arity
n_actual Arity
full_arity SDoc
herald) }

mk_fun_tys_msg :: TcType  -- the full type passed in (unzonked)
               -> TcType  -- the full type passed in (zonked)
               -> Arity   -- the # of args found
               -> Arity   -- the # of args wanted
               -> SDoc    -- overall herald
               -> SDoc
mk_fun_tys_msg :: TcType -> TcType -> Arity -> Arity -> SDoc -> SDoc
mk_fun_tys_msg TcType
full_ty TcType
ty Arity
n_args Arity
full_arity SDoc
herald
  = SDoc
herald SDoc -> SDoc -> SDoc
<+> Arity -> SDoc -> SDoc
speakNOf Arity
full_arity (String -> SDoc
text String
"argument") SDoc -> SDoc -> SDoc
<> SDoc
comma SDoc -> SDoc -> SDoc
$$
    if Arity
n_args Arity -> Arity -> Bool
forall a. Eq a => a -> a -> Bool
== Arity
full_arity
      then String -> SDoc
text String
"its type is" SDoc -> SDoc -> SDoc
<+> SDoc -> SDoc
quotes (TcType -> SDoc
pprType TcType
full_ty) SDoc -> SDoc -> SDoc
<>
           SDoc
comma SDoc -> SDoc -> SDoc
$$
           String -> SDoc
text String
"it is specialized to" SDoc -> SDoc -> SDoc
<+> SDoc -> SDoc
quotes (TcType -> SDoc
pprType TcType
ty)
      else [SDoc] -> SDoc
sep [String -> SDoc
text String
"but its type" SDoc -> SDoc -> SDoc
<+> SDoc -> SDoc
quotes (TcType -> SDoc
pprType TcType
ty),
                if Arity
n_args Arity -> Arity -> Bool
forall a. Eq a => a -> a -> Bool
== Arity
0 then String -> SDoc
text String
"has none"
                else String -> SDoc
text String
"has only" SDoc -> SDoc -> SDoc
<+> Arity -> SDoc
speakN Arity
n_args]

----------------------
matchExpectedListTy :: TcRhoType -> TcM (TcCoercionN, TcRhoType)
-- Special case for lists
matchExpectedListTy :: TcType -> TcM (TcCoercionN, TcType)
matchExpectedListTy TcType
exp_ty
 = do { (TcCoercionN
co, [TcType
elt_ty]) <- TyCon -> TcType -> TcM (TcCoercionN, [TcType])
matchExpectedTyConApp TyCon
listTyCon TcType
exp_ty
      ; (TcCoercionN, TcType) -> TcM (TcCoercionN, TcType)
forall (m :: * -> *) a. Monad m => a -> m a
return (TcCoercionN
co, TcType
elt_ty) }

---------------------
matchExpectedTyConApp :: TyCon                -- T :: forall kv1 ... kvm. k1 -> ... -> kn -> *
                      -> TcRhoType            -- orig_ty
                      -> TcM (TcCoercionN,    -- T k1 k2 k3 a b c ~N orig_ty
                              [TcSigmaType])  -- Element types, k1 k2 k3 a b c

-- It's used for wired-in tycons, so we call checkWiredInTyCon
-- Precondition: never called with FunTyCon
-- Precondition: input type :: *
-- Postcondition: (T k1 k2 k3 a b c) is well-kinded

matchExpectedTyConApp :: TyCon -> TcType -> TcM (TcCoercionN, [TcType])
matchExpectedTyConApp TyCon
tc TcType
orig_ty
  = ASSERT(tc /= funTyCon) go orig_ty
  where
    go :: TcType -> TcM (TcCoercionN, [TcType])
go TcType
ty
       | Just TcType
ty' <- TcType -> Maybe TcType
tcView TcType
ty
       = TcType -> TcM (TcCoercionN, [TcType])
go TcType
ty'

    go ty :: TcType
ty@(TyConApp TyCon
tycon [TcType]
args)
       | TyCon
tc TyCon -> TyCon -> Bool
forall a. Eq a => a -> a -> Bool
== TyCon
tycon  -- Common case
       = (TcCoercionN, [TcType]) -> TcM (TcCoercionN, [TcType])
forall (m :: * -> *) a. Monad m => a -> m a
return (TcType -> TcCoercionN
mkTcNomReflCo TcType
ty, [TcType]
args)

    go (TyVarTy Var
tv)
       | Var -> Bool
isMetaTyVar Var
tv
       = do { MetaDetails
cts <- Var -> TcM MetaDetails
readMetaTyVar Var
tv
            ; case MetaDetails
cts of
                Indirect TcType
ty -> TcType -> TcM (TcCoercionN, [TcType])
go TcType
ty
                MetaDetails
Flexi       -> TcM (TcCoercionN, [TcType])
defer }

    go TcType
_ = TcM (TcCoercionN, [TcType])
defer

    -- If the common case does not occur, instantiate a template
    -- T k1 .. kn t1 .. tm, and unify with the original type
    -- Doing it this way ensures that the types we return are
    -- kind-compatible with T.  For example, suppose we have
    --       matchExpectedTyConApp T (f Maybe)
    -- where data T a = MkT a
    -- Then we don't want to instantiate T's data constructors with
    --    (a::*) ~ Maybe
    -- because that'll make types that are utterly ill-kinded.
    -- This happened in #7368
    defer :: TcM (TcCoercionN, [TcType])
defer
      = do { (TCvSubst
_, [Var]
arg_tvs) <- [Var] -> TcM (TCvSubst, [Var])
newMetaTyVars (TyCon -> [Var]
tyConTyVars TyCon
tc)
           ; String -> SDoc -> TcRn ()
traceTc String
"matchExpectedTyConApp" (TyCon -> SDoc
forall a. Outputable a => a -> SDoc
ppr TyCon
tc SDoc -> SDoc -> SDoc
$$ [Var] -> SDoc
forall a. Outputable a => a -> SDoc
ppr (TyCon -> [Var]
tyConTyVars TyCon
tc) SDoc -> SDoc -> SDoc
$$ [Var] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [Var]
arg_tvs)
           ; let args :: [TcType]
args = [Var] -> [TcType]
mkTyVarTys [Var]
arg_tvs
                 tc_template :: TcType
tc_template = TyCon -> [TcType] -> TcType
mkTyConApp TyCon
tc [TcType]
args
           ; TcCoercionN
co <- Maybe (HsExpr GhcRn) -> TcType -> TcType -> TcM TcCoercionN
unifyType Maybe (HsExpr GhcRn)
forall a. Maybe a
Nothing TcType
tc_template TcType
orig_ty
           ; (TcCoercionN, [TcType]) -> TcM (TcCoercionN, [TcType])
forall (m :: * -> *) a. Monad m => a -> m a
return (TcCoercionN
co, [TcType]
args) }

----------------------
matchExpectedAppTy :: TcRhoType                         -- orig_ty
                   -> TcM (TcCoercion,                   -- m a ~N orig_ty
                           (TcSigmaType, TcSigmaType))  -- Returns m, a
-- If the incoming type is a mutable type variable of kind k, then
-- matchExpectedAppTy returns a new type variable (m: * -> k); note the *.

matchExpectedAppTy :: TcType -> TcM (TcCoercionN, (TcType, TcType))
matchExpectedAppTy TcType
orig_ty
  = TcType -> TcM (TcCoercionN, (TcType, TcType))
go TcType
orig_ty
  where
    go :: TcType -> TcM (TcCoercionN, (TcType, TcType))
go TcType
ty
      | Just TcType
ty' <- TcType -> Maybe TcType
tcView TcType
ty = TcType -> TcM (TcCoercionN, (TcType, TcType))
go TcType
ty'

      | Just (TcType
fun_ty, TcType
arg_ty) <- TcType -> Maybe (TcType, TcType)
tcSplitAppTy_maybe TcType
ty
      = (TcCoercionN, (TcType, TcType))
-> TcM (TcCoercionN, (TcType, TcType))
forall (m :: * -> *) a. Monad m => a -> m a
return (TcType -> TcCoercionN
mkTcNomReflCo TcType
orig_ty, (TcType
fun_ty, TcType
arg_ty))

    go (TyVarTy Var
tv)
      | Var -> Bool
isMetaTyVar Var
tv
      = do { MetaDetails
cts <- Var -> TcM MetaDetails
readMetaTyVar Var
tv
           ; case MetaDetails
cts of
               Indirect TcType
ty -> TcType -> TcM (TcCoercionN, (TcType, TcType))
go TcType
ty
               MetaDetails
Flexi       -> TcM (TcCoercionN, (TcType, TcType))
defer }

    go TcType
_ = TcM (TcCoercionN, (TcType, TcType))
defer

    -- Defer splitting by generating an equality constraint
    defer :: TcM (TcCoercionN, (TcType, TcType))
defer
      = do { TcType
ty1 <- TcType -> IOEnv (Env TcGblEnv TcLclEnv) TcType
newFlexiTyVarTy TcType
kind1
           ; TcType
ty2 <- TcType -> IOEnv (Env TcGblEnv TcLclEnv) TcType
newFlexiTyVarTy TcType
kind2
           ; TcCoercionN
co <- Maybe (HsExpr GhcRn) -> TcType -> TcType -> TcM TcCoercionN
unifyType Maybe (HsExpr GhcRn)
forall a. Maybe a
Nothing (TcType -> TcType -> TcType
mkAppTy TcType
ty1 TcType
ty2) TcType
orig_ty
           ; (TcCoercionN, (TcType, TcType))
-> TcM (TcCoercionN, (TcType, TcType))
forall (m :: * -> *) a. Monad m => a -> m a
return (TcCoercionN
co, (TcType
ty1, TcType
ty2)) }

    orig_kind :: TcType
orig_kind = HasDebugCallStack => TcType -> TcType
TcType -> TcType
tcTypeKind TcType
orig_ty
    kind1 :: TcType
kind1 = TcType -> TcType -> TcType
mkVisFunTy TcType
liftedTypeKind TcType
orig_kind
    kind2 :: TcType
kind2 = TcType
liftedTypeKind    -- m :: * -> k
                              -- arg type :: *

{-
************************************************************************
*                                                                      *
                Subsumption checking
*                                                                      *
************************************************************************

Note [Subsumption checking: tcSubType]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
All the tcSubType calls have the form
                tcSubType actual_ty expected_ty
which checks
                actual_ty <= expected_ty

That is, that a value of type actual_ty is acceptable in
a place expecting a value of type expected_ty.  I.e. that

    actual ty   is more polymorphic than   expected_ty

It returns a coercion function
        co_fn :: actual_ty ~ expected_ty
which takes an HsExpr of type actual_ty into one of type
expected_ty.

These functions do not actually check for subsumption. They check if
expected_ty is an appropriate annotation to use for something of type
actual_ty. This difference matters when thinking about visible type
application. For example,

   forall a. a -> forall b. b -> b
      DOES NOT SUBSUME
   forall a b. a -> b -> b

because the type arguments appear in a different order. (Neither does
it work the other way around.) BUT, these types are appropriate annotations
for one another. Because the user directs annotations, it's OK if some
arguments shuffle around -- after all, it's what the user wants.
Bottom line: none of this changes with visible type application.

There are a number of wrinkles (below).

Notice that Wrinkle 1 and 2 both require eta-expansion, which technically
may increase termination.  We just put up with this, in exchange for getting
more predictable type inference.

Wrinkle 1: Note [Deep skolemisation]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We want   (forall a. Int -> a -> a)  <=  (Int -> forall a. a->a)
(see section 4.6 of "Practical type inference for higher rank types")
So we must deeply-skolemise the RHS before we instantiate the LHS.

That is why tc_sub_type starts with a call to tcSkolemise (which does the
deep skolemisation), and then calls the DS variant (which assumes
that expected_ty is deeply skolemised)

Wrinkle 2: Note [Co/contra-variance of subsumption checking]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider  g :: (Int -> Int) -> Int
  f1 :: (forall a. a -> a) -> Int
  f1 = g

  f2 :: (forall a. a -> a) -> Int
  f2 x = g x
f2 will typecheck, and it would be odd/fragile if f1 did not.
But f1 will only typecheck if we have that
    (Int->Int) -> Int  <=  (forall a. a->a) -> Int
And that is only true if we do the full co/contravariant thing
in the subsumption check.  That happens in the FunTy case of
tcSubTypeDS_NC_O, and is the sole reason for the WpFun form of
HsWrapper.

Another powerful reason for doing this co/contra stuff is visible
in #9569, involving instantiation of constraint variables,
and again involving eta-expansion.

Wrinkle 3: Note [Higher rank types]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider tc150:
  f y = \ (x::forall a. a->a). blah
The following happens:
* We will infer the type of the RHS, ie with a res_ty = alpha.
* Then the lambda will split  alpha := beta -> gamma.
* And then we'll check tcSubType IsSwapped beta (forall a. a->a)

So it's important that we unify beta := forall a. a->a, rather than
skolemising the type.
-}


-- | Call this variant when you are in a higher-rank situation and
-- you know the right-hand type is deeply skolemised.
tcSubTypeHR :: CtOrigin               -- ^ of the actual type
            -> Maybe (HsExpr GhcRn)   -- ^ If present, it has type ty_actual
            -> TcSigmaType -> ExpRhoType -> TcM HsWrapper
tcSubTypeHR :: CtOrigin
-> Maybe (HsExpr GhcRn) -> TcType -> ExpRhoType -> TcM HsWrapper
tcSubTypeHR CtOrigin
orig = CtOrigin
-> UserTypeCtxt
-> Maybe (HsExpr GhcRn)
-> TcType
-> ExpRhoType
-> TcM HsWrapper
tcSubTypeDS_NC_O CtOrigin
orig UserTypeCtxt
GenSigCtxt

------------------------
tcSubTypeET :: CtOrigin -> UserTypeCtxt
            -> ExpSigmaType -> TcSigmaType -> TcM HsWrapper
-- If wrap = tc_sub_type_et t1 t2
--    => wrap :: t1 ~> t2
tcSubTypeET :: CtOrigin -> UserTypeCtxt -> ExpRhoType -> TcType -> TcM HsWrapper
tcSubTypeET CtOrigin
orig UserTypeCtxt
ctxt (Check TcType
ty_actual) TcType
ty_expected
  = CtOrigin
-> CtOrigin -> UserTypeCtxt -> TcType -> TcType -> TcM HsWrapper
tc_sub_tc_type CtOrigin
eq_orig CtOrigin
orig UserTypeCtxt
ctxt TcType
ty_actual TcType
ty_expected
  where
    eq_orig :: CtOrigin
eq_orig = TypeEqOrigin :: TcType -> TcType -> Maybe SDoc -> Bool -> CtOrigin
TypeEqOrigin { uo_actual :: TcType
uo_actual   = TcType
ty_expected
                           , uo_expected :: TcType
uo_expected = TcType
ty_actual
                           , uo_thing :: Maybe SDoc
uo_thing    = Maybe SDoc
forall a. Maybe a
Nothing
                           , uo_visible :: Bool
uo_visible  = Bool
True }

tcSubTypeET CtOrigin
_ UserTypeCtxt
_ (Infer InferResult
inf_res) TcType
ty_expected
  = ASSERT2( not (ir_inst inf_res), ppr inf_res $$ ppr ty_expected )
      -- An (Infer inf_res) ExpSigmaType passed into tcSubTypeET never
      -- has the ir_inst field set.  Reason: in patterns (which is what
      -- tcSubTypeET is used for) do not aggressively instantiate
    do { TcCoercionN
co <- TcType -> InferResult -> TcM TcCoercionN
fill_infer_result TcType
ty_expected InferResult
inf_res
               -- Since ir_inst is false, we can skip fillInferResult
               -- and go straight to fill_infer_result

       ; HsWrapper -> TcM HsWrapper
forall (m :: * -> *) a. Monad m => a -> m a
return (TcCoercionN -> HsWrapper
mkWpCastN (TcCoercionN -> TcCoercionN
mkTcSymCo TcCoercionN
co)) }

------------------------
tcSubTypeO :: CtOrigin      -- ^ of the actual type
           -> UserTypeCtxt  -- ^ of the expected type
           -> TcSigmaType
           -> ExpRhoType
           -> TcM HsWrapper
tcSubTypeO :: CtOrigin -> UserTypeCtxt -> TcType -> ExpRhoType -> TcM HsWrapper
tcSubTypeO CtOrigin
orig UserTypeCtxt
ctxt TcType
ty_actual ExpRhoType
ty_expected
  = TcType -> ExpRhoType -> TcM HsWrapper -> TcM HsWrapper
forall a. TcType -> ExpRhoType -> TcM a -> TcM a
addSubTypeCtxt TcType
ty_actual ExpRhoType
ty_expected (TcM HsWrapper -> TcM HsWrapper) -> TcM HsWrapper -> TcM HsWrapper
forall a b. (a -> b) -> a -> b
$
    do { String -> SDoc -> TcRn ()
traceTc String
"tcSubTypeDS_O" ([SDoc] -> SDoc
vcat [ CtOrigin -> SDoc
pprCtOrigin CtOrigin
orig
                                       , UserTypeCtxt -> SDoc
pprUserTypeCtxt UserTypeCtxt
ctxt
                                       , TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
ty_actual
                                       , ExpRhoType -> SDoc
forall a. Outputable a => a -> SDoc
ppr ExpRhoType
ty_expected ])
       ; CtOrigin
-> UserTypeCtxt
-> Maybe (HsExpr GhcRn)
-> TcType
-> ExpRhoType
-> TcM HsWrapper
tcSubTypeDS_NC_O CtOrigin
orig UserTypeCtxt
ctxt Maybe (HsExpr GhcRn)
forall a. Maybe a
Nothing TcType
ty_actual ExpRhoType
ty_expected }

addSubTypeCtxt :: TcType -> ExpType -> TcM a -> TcM a
addSubTypeCtxt :: TcType -> ExpRhoType -> TcM a -> TcM a
addSubTypeCtxt TcType
ty_actual ExpRhoType
ty_expected TcM a
thing_inside
 | TcType -> Bool
isRhoTy TcType
ty_actual        -- If there is no polymorphism involved, the
 , ExpRhoType -> Bool
isRhoExpTy ExpRhoType
ty_expected   -- TypeEqOrigin stuff (added by the _NC functions)
 = TcM a
thing_inside             -- gives enough context by itself
 | Bool
otherwise
 = (TidyEnv -> TcM (TidyEnv, SDoc)) -> TcM a -> TcM a
forall a. (TidyEnv -> TcM (TidyEnv, SDoc)) -> TcM a -> TcM a
addErrCtxtM TidyEnv -> TcM (TidyEnv, SDoc)
mk_msg TcM a
thing_inside
  where
    mk_msg :: TidyEnv -> TcM (TidyEnv, SDoc)
mk_msg TidyEnv
tidy_env
      = do { (TidyEnv
tidy_env, TcType
ty_actual)   <- TidyEnv -> TcType -> TcM (TidyEnv, TcType)
zonkTidyTcType TidyEnv
tidy_env TcType
ty_actual
                   -- might not be filled if we're debugging. ugh.
           ; Maybe TcType
mb_ty_expected          <- ExpRhoType -> TcM (Maybe TcType)
readExpType_maybe ExpRhoType
ty_expected
           ; (TidyEnv
tidy_env, ExpRhoType
ty_expected) <- case Maybe TcType
mb_ty_expected of
                                          Just TcType
ty -> (TcType -> ExpRhoType)
-> (TidyEnv, TcType) -> (TidyEnv, ExpRhoType)
forall (a :: * -> * -> *) b c d.
Arrow a =>
a b c -> a (d, b) (d, c)
second TcType -> ExpRhoType
mkCheckExpType ((TidyEnv, TcType) -> (TidyEnv, ExpRhoType))
-> TcM (TidyEnv, TcType)
-> IOEnv (Env TcGblEnv TcLclEnv) (TidyEnv, ExpRhoType)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$>
                                                     TidyEnv -> TcType -> TcM (TidyEnv, TcType)
zonkTidyTcType TidyEnv
tidy_env TcType
ty
                                          Maybe TcType
Nothing -> (TidyEnv, ExpRhoType)
-> IOEnv (Env TcGblEnv TcLclEnv) (TidyEnv, ExpRhoType)
forall (m :: * -> *) a. Monad m => a -> m a
return (TidyEnv
tidy_env, ExpRhoType
ty_expected)
           ; TcType
ty_expected             <- ExpRhoType -> IOEnv (Env TcGblEnv TcLclEnv) TcType
readExpType ExpRhoType
ty_expected
           ; (TidyEnv
tidy_env, TcType
ty_expected) <- TidyEnv -> TcType -> TcM (TidyEnv, TcType)
zonkTidyTcType TidyEnv
tidy_env TcType
ty_expected
           ; let msg :: SDoc
msg = [SDoc] -> SDoc
vcat [ SDoc -> Arity -> SDoc -> SDoc
hang (String -> SDoc
text String
"When checking that:")
                                 Arity
4 (TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
ty_actual)
                            , Arity -> SDoc -> SDoc
nest Arity
2 (SDoc -> Arity -> SDoc -> SDoc
hang (String -> SDoc
text String
"is more polymorphic than:")
                                         Arity
2 (TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
ty_expected)) ]
           ; (TidyEnv, SDoc) -> TcM (TidyEnv, SDoc)
forall (m :: * -> *) a. Monad m => a -> m a
return (TidyEnv
tidy_env, SDoc
msg) }

---------------
-- The "_NC" variants do not add a typechecker-error context;
-- the caller is assumed to do that

tcSubType_NC :: UserTypeCtxt -> TcSigmaType -> TcSigmaType -> TcM HsWrapper
-- Checks that actual <= expected
-- Returns HsWrapper :: actual ~ expected
tcSubType_NC :: UserTypeCtxt -> TcType -> TcType -> TcM HsWrapper
tcSubType_NC UserTypeCtxt
ctxt TcType
ty_actual TcType
ty_expected
  = do { String -> SDoc -> TcRn ()
traceTc String
"tcSubType_NC" ([SDoc] -> SDoc
vcat [UserTypeCtxt -> SDoc
pprUserTypeCtxt UserTypeCtxt
ctxt, TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
ty_actual, TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
ty_expected])
       ; CtOrigin
-> CtOrigin -> UserTypeCtxt -> TcType -> TcType -> TcM HsWrapper
tc_sub_tc_type CtOrigin
origin CtOrigin
origin UserTypeCtxt
ctxt TcType
ty_actual TcType
ty_expected }
  where
    origin :: CtOrigin
origin = TypeEqOrigin :: TcType -> TcType -> Maybe SDoc -> Bool -> CtOrigin
TypeEqOrigin { uo_actual :: TcType
uo_actual   = TcType
ty_actual
                          , uo_expected :: TcType
uo_expected = TcType
ty_expected
                          , uo_thing :: Maybe SDoc
uo_thing    = Maybe SDoc
forall a. Maybe a
Nothing
                          , uo_visible :: Bool
uo_visible  = Bool
True }

tcSubTypeDS :: CtOrigin -> UserTypeCtxt -> TcSigmaType -> ExpRhoType -> TcM HsWrapper
-- Just like tcSubType, but with the additional precondition that
-- ty_expected is deeply skolemised (hence "DS")
tcSubTypeDS :: CtOrigin -> UserTypeCtxt -> TcType -> ExpRhoType -> TcM HsWrapper
tcSubTypeDS CtOrigin
orig UserTypeCtxt
ctxt TcType
ty_actual ExpRhoType
ty_expected
  = TcType -> ExpRhoType -> TcM HsWrapper -> TcM HsWrapper
forall a. TcType -> ExpRhoType -> TcM a -> TcM a
addSubTypeCtxt TcType
ty_actual ExpRhoType
ty_expected (TcM HsWrapper -> TcM HsWrapper) -> TcM HsWrapper -> TcM HsWrapper
forall a b. (a -> b) -> a -> b
$
    do { String -> SDoc -> TcRn ()
traceTc String
"tcSubTypeDS_NC" ([SDoc] -> SDoc
vcat [UserTypeCtxt -> SDoc
pprUserTypeCtxt UserTypeCtxt
ctxt, TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
ty_actual, ExpRhoType -> SDoc
forall a. Outputable a => a -> SDoc
ppr ExpRhoType
ty_expected])
       ; CtOrigin
-> UserTypeCtxt
-> Maybe (HsExpr GhcRn)
-> TcType
-> ExpRhoType
-> TcM HsWrapper
tcSubTypeDS_NC_O CtOrigin
orig UserTypeCtxt
ctxt Maybe (HsExpr GhcRn)
forall a. Maybe a
Nothing TcType
ty_actual ExpRhoType
ty_expected }

tcSubTypeDS_NC_O :: CtOrigin   -- origin used for instantiation only
                 -> UserTypeCtxt
                 -> Maybe (HsExpr GhcRn)
                 -> TcSigmaType -> ExpRhoType -> TcM HsWrapper
-- Just like tcSubType, but with the additional precondition that
-- ty_expected is deeply skolemised
tcSubTypeDS_NC_O :: CtOrigin
-> UserTypeCtxt
-> Maybe (HsExpr GhcRn)
-> TcType
-> ExpRhoType
-> TcM HsWrapper
tcSubTypeDS_NC_O CtOrigin
inst_orig UserTypeCtxt
ctxt Maybe (HsExpr GhcRn)
m_thing TcType
ty_actual ExpRhoType
ty_expected
  = case ExpRhoType
ty_expected of
      Infer InferResult
inf_res -> CtOrigin -> TcType -> InferResult -> TcM HsWrapper
fillInferResult CtOrigin
inst_orig TcType
ty_actual InferResult
inf_res
      Check TcType
ty      -> CtOrigin
-> CtOrigin -> UserTypeCtxt -> TcType -> TcType -> TcM HsWrapper
tc_sub_type_ds CtOrigin
eq_orig CtOrigin
inst_orig UserTypeCtxt
ctxt TcType
ty_actual TcType
ty
         where
           eq_orig :: CtOrigin
eq_orig = TypeEqOrigin :: TcType -> TcType -> Maybe SDoc -> Bool -> CtOrigin
TypeEqOrigin { uo_actual :: TcType
uo_actual = TcType
ty_actual, uo_expected :: TcType
uo_expected = TcType
ty
                                  , uo_thing :: Maybe SDoc
uo_thing  = HsExpr GhcRn -> SDoc
forall a. Outputable a => a -> SDoc
ppr (HsExpr GhcRn -> SDoc) -> Maybe (HsExpr GhcRn) -> Maybe SDoc
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Maybe (HsExpr GhcRn)
m_thing
                                  , uo_visible :: Bool
uo_visible = Bool
True }

---------------
tc_sub_tc_type :: CtOrigin   -- used when calling uType
               -> CtOrigin   -- used when instantiating
               -> UserTypeCtxt -> TcSigmaType -> TcSigmaType -> TcM HsWrapper
-- If wrap = tc_sub_type t1 t2
--    => wrap :: t1 ~> t2
tc_sub_tc_type :: CtOrigin
-> CtOrigin -> UserTypeCtxt -> TcType -> TcType -> TcM HsWrapper
tc_sub_tc_type CtOrigin
eq_orig CtOrigin
inst_orig UserTypeCtxt
ctxt TcType
ty_actual TcType
ty_expected
  | TcType -> Bool
definitely_poly TcType
ty_expected      -- See Note [Don't skolemise unnecessarily]
  , Bool -> Bool
not (TcType -> Bool
possibly_poly TcType
ty_actual)
  = do { String -> SDoc -> TcRn ()
traceTc String
"tc_sub_tc_type (drop to equality)" (SDoc -> TcRn ()) -> SDoc -> TcRn ()
forall a b. (a -> b) -> a -> b
$
         [SDoc] -> SDoc
vcat [ String -> SDoc
text String
"ty_actual   =" SDoc -> SDoc -> SDoc
<+> TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
ty_actual
              , String -> SDoc
text String
"ty_expected =" SDoc -> SDoc -> SDoc
<+> TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
ty_expected ]
       ; TcCoercionN -> HsWrapper
mkWpCastN (TcCoercionN -> HsWrapper) -> TcM TcCoercionN -> TcM HsWrapper
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$>
         TypeOrKind -> CtOrigin -> TcType -> TcType -> TcM TcCoercionN
uType TypeOrKind
TypeLevel CtOrigin
eq_orig TcType
ty_actual TcType
ty_expected }

  | Bool
otherwise   -- This is the general case
  = do { String -> SDoc -> TcRn ()
traceTc String
"tc_sub_tc_type (general case)" (SDoc -> TcRn ()) -> SDoc -> TcRn ()
forall a b. (a -> b) -> a -> b
$
         [SDoc] -> SDoc
vcat [ String -> SDoc
text String
"ty_actual   =" SDoc -> SDoc -> SDoc
<+> TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
ty_actual
              , String -> SDoc
text String
"ty_expected =" SDoc -> SDoc -> SDoc
<+> TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
ty_expected ]
       ; (HsWrapper
sk_wrap, HsWrapper
inner_wrap) <- UserTypeCtxt
-> TcType
-> ([Var] -> TcType -> TcM HsWrapper)
-> TcM (HsWrapper, HsWrapper)
forall result.
UserTypeCtxt
-> TcType
-> ([Var] -> TcType -> TcM result)
-> TcM (HsWrapper, result)
tcSkolemise UserTypeCtxt
ctxt TcType
ty_expected (([Var] -> TcType -> TcM HsWrapper) -> TcM (HsWrapper, HsWrapper))
-> ([Var] -> TcType -> TcM HsWrapper) -> TcM (HsWrapper, HsWrapper)
forall a b. (a -> b) -> a -> b
$
                                                   \ [Var]
_ TcType
sk_rho ->
                                  CtOrigin
-> CtOrigin -> UserTypeCtxt -> TcType -> TcType -> TcM HsWrapper
tc_sub_type_ds CtOrigin
eq_orig CtOrigin
inst_orig UserTypeCtxt
ctxt
                                                 TcType
ty_actual TcType
sk_rho
       ; HsWrapper -> TcM HsWrapper
forall (m :: * -> *) a. Monad m => a -> m a
return (HsWrapper
sk_wrap HsWrapper -> HsWrapper -> HsWrapper
<.> HsWrapper
inner_wrap) }
  where
    possibly_poly :: TcType -> Bool
possibly_poly TcType
ty
      | TcType -> Bool
isForAllTy TcType
ty                        = Bool
True
      | Just (TcType
_, TcType
res) <- TcType -> Maybe (TcType, TcType)
splitFunTy_maybe TcType
ty = TcType -> Bool
possibly_poly TcType
res
      | Bool
otherwise                            = Bool
False
      -- NB *not* tcSplitFunTy, because here we want
      -- to decompose type-class arguments too

    definitely_poly :: TcType -> Bool
definitely_poly TcType
ty
      | ([Var]
tvs, [TcType]
theta, TcType
tau) <- TcType -> ([Var], [TcType], TcType)
tcSplitSigmaTy TcType
ty
      , (Var
tv:[Var]
_) <- [Var]
tvs
      , [TcType] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [TcType]
theta
      , EqRel -> Var -> TcType -> Bool
isInsolubleOccursCheck EqRel
NomEq Var
tv TcType
tau
      = Bool
True
      | Bool
otherwise
      = Bool
False

{- Note [Don't skolemise unnecessarily]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose we are trying to solve
    (Char->Char) <= (forall a. a->a)
We could skolemise the 'forall a', and then complain
that (Char ~ a) is insoluble; but that's a pretty obscure
error.  It's better to say that
    (Char->Char) ~ (forall a. a->a)
fails.

So roughly:
 * if the ty_expected has an outermost forall
      (i.e. skolemisation is the next thing we'd do)
 * and the ty_actual has no top-level polymorphism (but looking deeply)
then we can revert to simple equality.  But we need to be careful.
These examples are all fine:

 * (Char -> forall a. a->a) <= (forall a. Char -> a -> a)
      Polymorphism is buried in ty_actual

 * (Char->Char) <= (forall a. Char -> Char)
      ty_expected isn't really polymorphic

 * (Char->Char) <= (forall a. (a~Char) => a -> a)
      ty_expected isn't really polymorphic

 * (Char->Char) <= (forall a. F [a] Char -> Char)
                   where type instance F [x] t = t
     ty_expected isn't really polymorphic

If we prematurely go to equality we'll reject a program we should
accept (e.g. #13752).  So the test (which is only to improve
error message) is very conservative:
 * ty_actual is /definitely/ monomorphic
 * ty_expected is /definitely/ polymorphic
-}

---------------
tc_sub_type_ds :: CtOrigin    -- used when calling uType
               -> CtOrigin    -- used when instantiating
               -> UserTypeCtxt -> TcSigmaType -> TcRhoType -> TcM HsWrapper
-- If wrap = tc_sub_type_ds t1 t2
--    => wrap :: t1 ~> t2
-- Here is where the work actually happens!
-- Precondition: ty_expected is deeply skolemised
tc_sub_type_ds :: CtOrigin
-> CtOrigin -> UserTypeCtxt -> TcType -> TcType -> TcM HsWrapper
tc_sub_type_ds CtOrigin
eq_orig CtOrigin
inst_orig UserTypeCtxt
ctxt TcType
ty_actual TcType
ty_expected
  = do { String -> SDoc -> TcRn ()
traceTc String
"tc_sub_type_ds" (SDoc -> TcRn ()) -> SDoc -> TcRn ()
forall a b. (a -> b) -> a -> b
$
         [SDoc] -> SDoc
vcat [ String -> SDoc
text String
"ty_actual   =" SDoc -> SDoc -> SDoc
<+> TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
ty_actual
              , String -> SDoc
text String
"ty_expected =" SDoc -> SDoc -> SDoc
<+> TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
ty_expected ]
       ; TcType -> TcType -> TcM HsWrapper
go TcType
ty_actual TcType
ty_expected }
  where
    go :: TcType -> TcType -> TcM HsWrapper
go TcType
ty_a TcType
ty_e | Just TcType
ty_a' <- TcType -> Maybe TcType
tcView TcType
ty_a = TcType -> TcType -> TcM HsWrapper
go TcType
ty_a' TcType
ty_e
                 | Just TcType
ty_e' <- TcType -> Maybe TcType
tcView TcType
ty_e = TcType -> TcType -> TcM HsWrapper
go TcType
ty_a  TcType
ty_e'

    go (TyVarTy Var
tv_a) TcType
ty_e
      = do { LookupTyVarResult
lookup_res <- Var -> TcM LookupTyVarResult
lookupTcTyVar Var
tv_a
           ; case LookupTyVarResult
lookup_res of
               Filled TcType
ty_a' ->
                 do { String -> SDoc -> TcRn ()
traceTc String
"tcSubTypeDS_NC_O following filled act meta-tyvar:"
                        (Var -> SDoc
forall a. Outputable a => a -> SDoc
ppr Var
tv_a SDoc -> SDoc -> SDoc
<+> String -> SDoc
text String
"-->" SDoc -> SDoc -> SDoc
<+> TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
ty_a')
                    ; CtOrigin
-> CtOrigin -> UserTypeCtxt -> TcType -> TcType -> TcM HsWrapper
tc_sub_type_ds CtOrigin
eq_orig CtOrigin
inst_orig UserTypeCtxt
ctxt TcType
ty_a' TcType
ty_e }
               Unfilled TcTyVarDetails
_   -> TcM HsWrapper
unify }

    -- Historical note (Sept 16): there was a case here for
    --    go ty_a (TyVarTy alpha)
    -- which, in the impredicative case unified  alpha := ty_a
    -- where th_a is a polytype.  Not only is this probably bogus (we
    -- simply do not have decent story for impredicative types), but it
    -- caused #12616 because (also bizarrely) 'deriving' code had
    -- -XImpredicativeTypes on.  I deleted the entire case.

    go (FunTy { ft_af :: TcType -> AnonArgFlag
ft_af = AnonArgFlag
VisArg, ft_arg :: TcType -> TcType
ft_arg = TcType
act_arg, ft_res :: TcType -> TcType
ft_res = TcType
act_res })
       (FunTy { ft_af :: TcType -> AnonArgFlag
ft_af = AnonArgFlag
VisArg, ft_arg :: TcType -> TcType
ft_arg = TcType
exp_arg, ft_res :: TcType -> TcType
ft_res = TcType
exp_res })
      = -- See Note [Co/contra-variance of subsumption checking]
        do { HsWrapper
res_wrap <- CtOrigin
-> CtOrigin -> UserTypeCtxt -> TcType -> TcType -> TcM HsWrapper
tc_sub_type_ds CtOrigin
eq_orig CtOrigin
inst_orig  UserTypeCtxt
ctxt       TcType
act_res TcType
exp_res
           ; HsWrapper
arg_wrap <- CtOrigin
-> CtOrigin -> UserTypeCtxt -> TcType -> TcType -> TcM HsWrapper
tc_sub_tc_type CtOrigin
eq_orig CtOrigin
given_orig UserTypeCtxt
GenSigCtxt TcType
exp_arg TcType
act_arg
                         -- GenSigCtxt: See Note [Setting the argument context]
           ; HsWrapper -> TcM HsWrapper
forall (m :: * -> *) a. Monad m => a -> m a
return (HsWrapper -> HsWrapper -> TcType -> TcType -> SDoc -> HsWrapper
mkWpFun HsWrapper
arg_wrap HsWrapper
res_wrap TcType
exp_arg TcType
exp_res SDoc
doc) }
               -- arg_wrap :: exp_arg ~> act_arg
               -- res_wrap :: act-res ~> exp_res
      where
        given_orig :: CtOrigin
given_orig = SkolemInfo -> CtOrigin
GivenOrigin (UserTypeCtxt -> TcType -> [(Name, Var)] -> SkolemInfo
SigSkol UserTypeCtxt
GenSigCtxt TcType
exp_arg [])
        doc :: SDoc
doc = String -> SDoc
text String
"When checking that" SDoc -> SDoc -> SDoc
<+> SDoc -> SDoc
quotes (TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
ty_actual) SDoc -> SDoc -> SDoc
<+>
              String -> SDoc
text String
"is more polymorphic than" SDoc -> SDoc -> SDoc
<+> SDoc -> SDoc
quotes (TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
ty_expected)

    go TcType
ty_a TcType
ty_e
      | let ([Var]
tvs, [TcType]
theta, TcType
_) = TcType -> ([Var], [TcType], TcType)
tcSplitSigmaTy TcType
ty_a
      , Bool -> Bool
not ([Var] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Var]
tvs Bool -> Bool -> Bool
&& [TcType] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [TcType]
theta)
      = do { (HsWrapper
in_wrap, TcType
in_rho) <- CtOrigin -> TcType -> TcM (HsWrapper, TcType)
topInstantiate CtOrigin
inst_orig TcType
ty_a
           ; HsWrapper
body_wrap <- CtOrigin
-> CtOrigin -> UserTypeCtxt -> TcType -> TcType -> TcM HsWrapper
tc_sub_type_ds
                            (CtOrigin
eq_orig { uo_actual :: TcType
uo_actual = TcType
in_rho
                                     , uo_expected :: TcType
uo_expected = TcType
ty_expected })
                            CtOrigin
inst_orig UserTypeCtxt
ctxt TcType
in_rho TcType
ty_e
           ; HsWrapper -> TcM HsWrapper
forall (m :: * -> *) a. Monad m => a -> m a
return (HsWrapper
body_wrap HsWrapper -> HsWrapper -> HsWrapper
<.> HsWrapper
in_wrap) }

      | Bool
otherwise   -- Revert to unification
      = TcM HsWrapper
inst_and_unify
         -- It's still possible that ty_actual has nested foralls. Instantiate
         -- these, as there's no way unification will succeed with them in.
         -- See typecheck/should_compile/T11305 for an example of when this
         -- is important. The problem is that we're checking something like
         --  a -> forall b. b -> b     <=   alpha beta gamma
         -- where we end up with alpha := (->)

    inst_and_unify :: TcM HsWrapper
inst_and_unify = do { (HsWrapper
wrap, TcType
rho_a) <- CtOrigin -> TcType -> TcM (HsWrapper, TcType)
deeplyInstantiate CtOrigin
inst_orig TcType
ty_actual

                           -- If we haven't recurred through an arrow, then
                           -- the eq_orig will list ty_actual. In this case,
                           -- we want to update the origin to reflect the
                           -- instantiation. If we *have* recurred through
                           -- an arrow, it's better not to update.
                        ; let eq_orig' :: CtOrigin
eq_orig' = case CtOrigin
eq_orig of
                                TypeEqOrigin { uo_actual :: CtOrigin -> TcType
uo_actual   = TcType
orig_ty_actual }
                                  |  TcType
orig_ty_actual HasDebugCallStack => TcType -> TcType -> Bool
TcType -> TcType -> Bool
`tcEqType` TcType
ty_actual
                                  ,  Bool -> Bool
not (HsWrapper -> Bool
isIdHsWrapper HsWrapper
wrap)
                                  -> CtOrigin
eq_orig { uo_actual :: TcType
uo_actual = TcType
rho_a }
                                CtOrigin
_ -> CtOrigin
eq_orig

                        ; TcCoercionN
cow <- TypeOrKind -> CtOrigin -> TcType -> TcType -> TcM TcCoercionN
uType TypeOrKind
TypeLevel CtOrigin
eq_orig' TcType
rho_a TcType
ty_expected
                        ; HsWrapper -> TcM HsWrapper
forall (m :: * -> *) a. Monad m => a -> m a
return (TcCoercionN -> HsWrapper
mkWpCastN TcCoercionN
cow HsWrapper -> HsWrapper -> HsWrapper
<.> HsWrapper
wrap) }


     -- use versions without synonyms expanded
    unify :: TcM HsWrapper
unify = TcCoercionN -> HsWrapper
mkWpCastN (TcCoercionN -> HsWrapper) -> TcM TcCoercionN -> TcM HsWrapper
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> TypeOrKind -> CtOrigin -> TcType -> TcType -> TcM TcCoercionN
uType TypeOrKind
TypeLevel CtOrigin
eq_orig TcType
ty_actual TcType
ty_expected

{- Note [Settting the argument context]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider we are doing the ambiguity check for the (bogus)
  f :: (forall a b. C b => a -> a) -> Int

We'll call
   tcSubType ((forall a b. C b => a->a) -> Int )
             ((forall a b. C b => a->a) -> Int )

with a UserTypeCtxt of (FunSigCtxt "f").  Then we'll do the co/contra thing
on the argument type of the (->) -- and at that point we want to switch
to a UserTypeCtxt of GenSigCtxt.  Why?

* Error messages.  If we stick with FunSigCtxt we get errors like
     * Could not deduce: C b
       from the context: C b0
        bound by the type signature for:
            f :: forall a b. C b => a->a
  But of course f does not have that type signature!
  Example tests: T10508, T7220a, Simple14

* Implications. We may decide to build an implication for the whole
  ambiguity check, but we don't need one for each level within it,
  and TcUnify.alwaysBuildImplication checks the UserTypeCtxt.
  See Note [When to build an implication]
-}

-----------------
-- needs both un-type-checked (for origins) and type-checked (for wrapping)
-- expressions
tcWrapResult :: HsExpr GhcRn -> HsExpr GhcTcId -> TcSigmaType -> ExpRhoType
             -> TcM (HsExpr GhcTcId)
tcWrapResult :: HsExpr GhcRn
-> HsExpr GhcTcId -> TcType -> ExpRhoType -> TcM (HsExpr GhcTcId)
tcWrapResult HsExpr GhcRn
rn_expr = CtOrigin
-> HsExpr GhcRn
-> HsExpr GhcTcId
-> TcType
-> ExpRhoType
-> TcM (HsExpr GhcTcId)
tcWrapResultO (HsExpr GhcRn -> CtOrigin
exprCtOrigin HsExpr GhcRn
rn_expr) HsExpr GhcRn
rn_expr

-- | Sometimes we don't have a @HsExpr Name@ to hand, and this is more
-- convenient.
tcWrapResultO :: CtOrigin -> HsExpr GhcRn -> HsExpr GhcTcId -> TcSigmaType -> ExpRhoType
               -> TcM (HsExpr GhcTcId)
tcWrapResultO :: CtOrigin
-> HsExpr GhcRn
-> HsExpr GhcTcId
-> TcType
-> ExpRhoType
-> TcM (HsExpr GhcTcId)
tcWrapResultO CtOrigin
orig HsExpr GhcRn
rn_expr HsExpr GhcTcId
expr TcType
actual_ty ExpRhoType
res_ty
  = do { String -> SDoc -> TcRn ()
traceTc String
"tcWrapResult" ([SDoc] -> SDoc
vcat [ String -> SDoc
text String
"Actual:  " SDoc -> SDoc -> SDoc
<+> TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
actual_ty
                                      , String -> SDoc
text String
"Expected:" SDoc -> SDoc -> SDoc
<+> ExpRhoType -> SDoc
forall a. Outputable a => a -> SDoc
ppr ExpRhoType
res_ty ])
       ; HsWrapper
cow <- CtOrigin
-> UserTypeCtxt
-> Maybe (HsExpr GhcRn)
-> TcType
-> ExpRhoType
-> TcM HsWrapper
tcSubTypeDS_NC_O CtOrigin
orig UserTypeCtxt
GenSigCtxt
                                 (HsExpr GhcRn -> Maybe (HsExpr GhcRn)
forall a. a -> Maybe a
Just HsExpr GhcRn
rn_expr) TcType
actual_ty ExpRhoType
res_ty
       ; HsExpr GhcTcId -> TcM (HsExpr GhcTcId)
forall (m :: * -> *) a. Monad m => a -> m a
return (HsWrapper -> HsExpr GhcTcId -> HsExpr GhcTcId
forall (id :: Pass).
HsWrapper -> HsExpr (GhcPass id) -> HsExpr (GhcPass id)
mkHsWrap HsWrapper
cow HsExpr GhcTcId
expr) }


{- **********************************************************************
%*                                                                      *
            ExpType functions: tcInfer, fillInferResult
%*                                                                      *
%********************************************************************* -}

-- | Infer a type using a fresh ExpType
-- See also Note [ExpType] in TcMType
-- Does not attempt to instantiate the inferred type
tcInferNoInst :: (ExpSigmaType -> TcM a) -> TcM (a, TcSigmaType)
tcInferNoInst :: (ExpRhoType -> TcM a) -> TcM (a, TcType)
tcInferNoInst = Bool -> (ExpRhoType -> TcM a) -> TcM (a, TcType)
forall a. Bool -> (ExpRhoType -> TcM a) -> TcM (a, TcType)
tcInfer Bool
False

tcInferInst :: (ExpRhoType -> TcM a) -> TcM (a, TcRhoType)
tcInferInst :: (ExpRhoType -> TcM a) -> TcM (a, TcType)
tcInferInst = Bool -> (ExpRhoType -> TcM a) -> TcM (a, TcType)
forall a. Bool -> (ExpRhoType -> TcM a) -> TcM (a, TcType)
tcInfer Bool
True

tcInfer :: Bool -> (ExpSigmaType -> TcM a) -> TcM (a, TcSigmaType)
tcInfer :: Bool -> (ExpRhoType -> TcM a) -> TcM (a, TcType)
tcInfer Bool
instantiate ExpRhoType -> TcM a
tc_check
  = do { ExpRhoType
res_ty <- Bool -> IOEnv (Env TcGblEnv TcLclEnv) ExpRhoType
newInferExpType Bool
instantiate
       ; a
result <- ExpRhoType -> TcM a
tc_check ExpRhoType
res_ty
       ; TcType
res_ty <- ExpRhoType -> IOEnv (Env TcGblEnv TcLclEnv) TcType
readExpType ExpRhoType
res_ty
       ; (a, TcType) -> TcM (a, TcType)
forall (m :: * -> *) a. Monad m => a -> m a
return (a
result, TcType
res_ty) }

fillInferResult :: CtOrigin -> TcType -> InferResult -> TcM HsWrapper
-- If wrap = fillInferResult t1 t2
--    => wrap :: t1 ~> t2
-- See Note [Deep instantiation of InferResult]
fillInferResult :: CtOrigin -> TcType -> InferResult -> TcM HsWrapper
fillInferResult CtOrigin
orig TcType
ty inf_res :: InferResult
inf_res@(IR { ir_inst :: InferResult -> Bool
ir_inst = Bool
instantiate_me })
  | Bool
instantiate_me
  = do { (HsWrapper
wrap, TcType
rho) <- CtOrigin -> TcType -> TcM (HsWrapper, TcType)
deeplyInstantiate CtOrigin
orig TcType
ty
       ; TcCoercionN
co <- TcType -> InferResult -> TcM TcCoercionN
fill_infer_result TcType
rho InferResult
inf_res
       ; HsWrapper -> TcM HsWrapper
forall (m :: * -> *) a. Monad m => a -> m a
return (TcCoercionN -> HsWrapper
mkWpCastN TcCoercionN
co HsWrapper -> HsWrapper -> HsWrapper
<.> HsWrapper
wrap) }

  | Bool
otherwise
  = do { TcCoercionN
co <- TcType -> InferResult -> TcM TcCoercionN
fill_infer_result TcType
ty InferResult
inf_res
       ; HsWrapper -> TcM HsWrapper
forall (m :: * -> *) a. Monad m => a -> m a
return (TcCoercionN -> HsWrapper
mkWpCastN TcCoercionN
co) }

fill_infer_result :: TcType -> InferResult -> TcM TcCoercionN
-- If wrap = fill_infer_result t1 t2
--    => wrap :: t1 ~> t2
fill_infer_result :: TcType -> InferResult -> TcM TcCoercionN
fill_infer_result TcType
orig_ty (IR { ir_uniq :: InferResult -> Unique
ir_uniq = Unique
u, ir_lvl :: InferResult -> TcLevel
ir_lvl = TcLevel
res_lvl
                            , ir_ref :: InferResult -> IORef (Maybe TcType)
ir_ref = IORef (Maybe TcType)
ref })
  = do { (TcCoercionN
ty_co, TcType
ty_to_fill_with) <- TcLevel -> TcType -> TcM (TcCoercionN, TcType)
promoteTcType TcLevel
res_lvl TcType
orig_ty

       ; String -> SDoc -> TcRn ()
traceTc String
"Filling ExpType" (SDoc -> TcRn ()) -> SDoc -> TcRn ()
forall a b. (a -> b) -> a -> b
$
         Unique -> SDoc
forall a. Outputable a => a -> SDoc
ppr Unique
u SDoc -> SDoc -> SDoc
<+> String -> SDoc
text String
":=" SDoc -> SDoc -> SDoc
<+> TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
ty_to_fill_with

       ; Bool -> TcRn () -> TcRn ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when Bool
debugIsOn (TcType -> TcRn ()
forall gbl lcl. TcType -> IOEnv (Env gbl lcl) ()
check_hole TcType
ty_to_fill_with)

       ; IORef (Maybe TcType) -> Maybe TcType -> TcRn ()
forall a gbl lcl. TcRef a -> a -> TcRnIf gbl lcl ()
writeTcRef IORef (Maybe TcType)
ref (TcType -> Maybe TcType
forall a. a -> Maybe a
Just TcType
ty_to_fill_with)

       ; TcCoercionN -> TcM TcCoercionN
forall (m :: * -> *) a. Monad m => a -> m a
return TcCoercionN
ty_co }
  where
    check_hole :: TcType -> IOEnv (Env gbl lcl) ()
check_hole TcType
ty   -- Debug check only
      = do { let ty_lvl :: TcLevel
ty_lvl = TcType -> TcLevel
tcTypeLevel TcType
ty
           ; MASSERT2( not (ty_lvl `strictlyDeeperThan` res_lvl),
                       ppr u $$ ppr res_lvl $$ ppr ty_lvl $$
                       ppr ty <+> dcolon <+> ppr (tcTypeKind ty) $$ ppr orig_ty )
           ; Maybe TcType
cts <- IORef (Maybe TcType) -> TcRnIf gbl lcl (Maybe TcType)
forall a gbl lcl. TcRef a -> TcRnIf gbl lcl a
readTcRef IORef (Maybe TcType)
ref
           ; case Maybe TcType
cts of
               Just TcType
already_there -> String -> SDoc -> IOEnv (Env gbl lcl) ()
forall a. HasCallStack => String -> SDoc -> a
pprPanic String
"writeExpType"
                                       ([SDoc] -> SDoc
vcat [ Unique -> SDoc
forall a. Outputable a => a -> SDoc
ppr Unique
u
                                             , TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
ty
                                             , TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
already_there ])
               Maybe TcType
Nothing -> () -> IOEnv (Env gbl lcl) ()
forall (m :: * -> *) a. Monad m => a -> m a
return () }

{- Note [Deep instantiation of InferResult]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In some cases we want to deeply instantiate before filling in
an InferResult, and in some cases not.  That's why InferReult
has the ir_inst flag.

ir_inst = True: deeply instantiate
----------------------------------

1. Consider
    f x = (*)
   We want to instantiate the type of (*) before returning, else we
   will infer the type
     f :: forall {a}. a -> forall b. Num b => b -> b -> b
   This is surely confusing for users.

   And worse, the monomorphism restriction won't work properly. The MR is
   dealt with in simplifyInfer, and simplifyInfer has no way of
   instantiating. This could perhaps be worked around, but it may be
   hard to know even when instantiation should happen.

2. Another reason.  Consider
       f :: (?x :: Int) => a -> a
       g y = let ?x = 3::Int in f
   Here want to instantiate f's type so that the ?x::Int constraint
   gets discharged by the enclosing implicit-parameter binding.

ir_inst = False: do not instantiate
-----------------------------------

1. Consider this (which uses visible type application):

    (let { f :: forall a. a -> a; f x = x } in f) @Int

   We'll call TcExpr.tcInferFun to infer the type of the (let .. in f)
   And we don't want to instantite the type of 'f' when we reach it,
   else the outer visible type application won't work

2. :type +v. When we say

     :type +v const @Int

   we really want `forall b. Int -> b -> Int`. Note that this is *not*
   instantiated.

3. Pattern bindings. For example:

     foo x
       | blah <- const @Int
       = (blah x False, blah x 'z')

   Note that `blah` is polymorphic. (This isn't a terribly compelling
   reason, but the choice of ir_inst does matter here.)

Discussion
----------
We thought that we should just remove the ir_inst flag, in favor of
always instantiating. Essentially: motivations (1) and (3) for ir_inst = False
are not terribly exciting. However, motivation (2) is quite important.
Furthermore, there really was not much of a simplification of the code
in removing ir_inst, and working around it to enable flows like what we
see in (2) is annoying. This was done in #17173.

-}

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

promoteTcType :: TcLevel -> TcType -> TcM (TcCoercion, TcType)
-- See Note [Promoting a type]
-- promoteTcType level ty = (co, ty')
--   * Returns ty'  whose max level is just 'level'
--             and  whose kind is ~# to the kind of 'ty'
--             and  whose kind has form TYPE rr
--   * and co :: ty ~ ty'
--   * and emits constraints to justify the coercion
promoteTcType :: TcLevel -> TcType -> TcM (TcCoercionN, TcType)
promoteTcType TcLevel
dest_lvl TcType
ty
  = do { TcLevel
cur_lvl <- TcM TcLevel
getTcLevel
       ; if (TcLevel
cur_lvl TcLevel -> TcLevel -> Bool
`sameDepthAs` TcLevel
dest_lvl)
         then TcM (TcCoercionN, TcType)
dont_promote_it
         else TcM (TcCoercionN, TcType)
promote_it }
  where
    promote_it :: TcM (TcCoercion, TcType)
    promote_it :: TcM (TcCoercionN, TcType)
promote_it  -- Emit a constraint  (alpha :: TYPE rr) ~ ty
                -- where alpha and rr are fresh and from level dest_lvl
      = do { TcType
rr      <- TcLevel -> TcType -> IOEnv (Env TcGblEnv TcLclEnv) TcType
newMetaTyVarTyAtLevel TcLevel
dest_lvl TcType
runtimeRepTy
           ; TcType
prom_ty <- TcLevel -> TcType -> IOEnv (Env TcGblEnv TcLclEnv) TcType
newMetaTyVarTyAtLevel TcLevel
dest_lvl (TcType -> TcType
tYPE TcType
rr)
           ; let eq_orig :: CtOrigin
eq_orig = TypeEqOrigin :: TcType -> TcType -> Maybe SDoc -> Bool -> CtOrigin
TypeEqOrigin { uo_actual :: TcType
uo_actual   = TcType
ty
                                        , uo_expected :: TcType
uo_expected = TcType
prom_ty
                                        , uo_thing :: Maybe SDoc
uo_thing    = Maybe SDoc
forall a. Maybe a
Nothing
                                        , uo_visible :: Bool
uo_visible  = Bool
False }

           ; TcCoercionN
co <- CtOrigin
-> TypeOrKind -> Role -> TcType -> TcType -> TcM TcCoercionN
emitWantedEq CtOrigin
eq_orig TypeOrKind
TypeLevel Role
Nominal TcType
ty TcType
prom_ty
           ; (TcCoercionN, TcType) -> TcM (TcCoercionN, TcType)
forall (m :: * -> *) a. Monad m => a -> m a
return (TcCoercionN
co, TcType
prom_ty) }

    dont_promote_it :: TcM (TcCoercion, TcType)
    dont_promote_it :: TcM (TcCoercionN, TcType)
dont_promote_it  -- Check that ty :: TYPE rr, for some (fresh) rr
      = do { TcType
res_kind <- IOEnv (Env TcGblEnv TcLclEnv) TcType
newOpenTypeKind
           ; let ty_kind :: TcType
ty_kind = HasDebugCallStack => TcType -> TcType
TcType -> TcType
tcTypeKind TcType
ty
                 kind_orig :: CtOrigin
kind_orig = TypeEqOrigin :: TcType -> TcType -> Maybe SDoc -> Bool -> CtOrigin
TypeEqOrigin { uo_actual :: TcType
uo_actual   = TcType
ty_kind
                                          , uo_expected :: TcType
uo_expected = TcType
res_kind
                                          , uo_thing :: Maybe SDoc
uo_thing    = Maybe SDoc
forall a. Maybe a
Nothing
                                          , uo_visible :: Bool
uo_visible  = Bool
False }
           ; TcCoercionN
ki_co <- TypeOrKind -> CtOrigin -> TcType -> TcType -> TcM TcCoercionN
uType TypeOrKind
KindLevel CtOrigin
kind_orig (HasDebugCallStack => TcType -> TcType
TcType -> TcType
tcTypeKind TcType
ty) TcType
res_kind
           ; let co :: TcCoercionN
co = Role -> TcType -> TcCoercionN -> TcCoercionN
mkTcGReflRightCo Role
Nominal TcType
ty TcCoercionN
ki_co
           ; (TcCoercionN, TcType) -> TcM (TcCoercionN, TcType)
forall (m :: * -> *) a. Monad m => a -> m a
return (TcCoercionN
co, TcType
ty TcType -> TcCoercionN -> TcType
`mkCastTy` TcCoercionN
ki_co) }

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

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

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

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

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

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

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


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

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

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

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

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

{- *********************************************************************
*                                                                      *
                    Generalisation
*                                                                      *
********************************************************************* -}

-- | Take an "expected type" and strip off quantifiers to expose the
-- type underneath, binding the new skolems for the @thing_inside@.
-- The returned 'HsWrapper' has type @specific_ty -> expected_ty@.
tcSkolemise :: UserTypeCtxt -> TcSigmaType
            -> ([TcTyVar] -> TcType -> TcM result)
         -- ^ These are only ever used for scoped type variables.
            -> TcM (HsWrapper, result)
        -- ^ The expression has type: spec_ty -> expected_ty

tcSkolemise :: UserTypeCtxt
-> TcType
-> ([Var] -> TcType -> TcM result)
-> TcM (HsWrapper, result)
tcSkolemise UserTypeCtxt
ctxt TcType
expected_ty [Var] -> TcType -> TcM result
thing_inside
   -- We expect expected_ty to be a forall-type
   -- If not, the call is a no-op
  = do  { String -> SDoc -> TcRn ()
traceTc String
"tcSkolemise" SDoc
Outputable.empty
        ; (HsWrapper
wrap, [(Name, Var)]
tv_prs, [Var]
given, TcType
rho') <- TcType -> TcM (HsWrapper, [(Name, Var)], [Var], TcType)
deeplySkolemise TcType
expected_ty

        ; TcLevel
lvl <- TcM TcLevel
getTcLevel
        ; Bool -> TcRn () -> TcRn ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when Bool
debugIsOn (TcRn () -> TcRn ()) -> TcRn () -> TcRn ()
forall a b. (a -> b) -> a -> b
$
              String -> SDoc -> TcRn ()
traceTc String
"tcSkolemise" (SDoc -> TcRn ()) -> SDoc -> TcRn ()
forall a b. (a -> b) -> a -> b
$ [SDoc] -> SDoc
vcat [
                TcLevel -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcLevel
lvl,
                String -> SDoc
text String
"expected_ty" SDoc -> SDoc -> SDoc
<+> TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
expected_ty,
                String -> SDoc
text String
"inst tyvars" SDoc -> SDoc -> SDoc
<+> [(Name, Var)] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [(Name, Var)]
tv_prs,
                String -> SDoc
text String
"given"       SDoc -> SDoc -> SDoc
<+> [Var] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [Var]
given,
                String -> SDoc
text String
"inst type"   SDoc -> SDoc -> SDoc
<+> TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
rho' ]

        -- Generally we must check that the "forall_tvs" havn't been constrained
        -- The interesting bit here is that we must include the free variables
        -- of the expected_ty.  Here's an example:
        --       runST (newVar True)
        -- Here, if we don't make a check, we'll get a type (ST s (MutVar s Bool))
        -- for (newVar True), with s fresh.  Then we unify with the runST's arg type
        -- forall s'. ST s' a. That unifies s' with s, and a with MutVar s Bool.
        -- So now s' isn't unconstrained because it's linked to a.
        --
        -- However [Oct 10] now that the untouchables are a range of
        -- TcTyVars, all this is handled automatically with no need for
        -- extra faffing around

        ; let tvs' :: [Var]
tvs' = ((Name, Var) -> Var) -> [(Name, Var)] -> [Var]
forall a b. (a -> b) -> [a] -> [b]
map (Name, Var) -> Var
forall a b. (a, b) -> b
snd [(Name, Var)]
tv_prs
              skol_info :: SkolemInfo
skol_info = UserTypeCtxt -> TcType -> [(Name, Var)] -> SkolemInfo
SigSkol UserTypeCtxt
ctxt TcType
expected_ty [(Name, Var)]
tv_prs

        ; (TcEvBinds
ev_binds, result
result) <- SkolemInfo
-> [Var] -> [Var] -> TcM result -> TcM (TcEvBinds, result)
forall result.
SkolemInfo
-> [Var] -> [Var] -> TcM result -> TcM (TcEvBinds, result)
checkConstraints SkolemInfo
skol_info [Var]
tvs' [Var]
given (TcM result -> TcM (TcEvBinds, result))
-> TcM result -> TcM (TcEvBinds, result)
forall a b. (a -> b) -> a -> b
$
                                [Var] -> TcType -> TcM result
thing_inside [Var]
tvs' TcType
rho'

        ; (HsWrapper, result) -> TcM (HsWrapper, result)
forall (m :: * -> *) a. Monad m => a -> m a
return (HsWrapper
wrap HsWrapper -> HsWrapper -> HsWrapper
<.> TcEvBinds -> HsWrapper
mkWpLet TcEvBinds
ev_binds, result
result) }
          -- The ev_binds returned by checkConstraints is very
          -- often empty, in which case mkWpLet is a no-op

-- | Variant of 'tcSkolemise' that takes an ExpType
tcSkolemiseET :: UserTypeCtxt -> ExpSigmaType
              -> (ExpRhoType -> TcM result)
              -> TcM (HsWrapper, result)
tcSkolemiseET :: UserTypeCtxt
-> ExpRhoType
-> (ExpRhoType -> TcM result)
-> TcM (HsWrapper, result)
tcSkolemiseET UserTypeCtxt
_ et :: ExpRhoType
et@(Infer {}) ExpRhoType -> TcM result
thing_inside
  = (HsWrapper
idHsWrapper, ) (result -> (HsWrapper, result))
-> TcM result -> TcM (HsWrapper, result)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ExpRhoType -> TcM result
thing_inside ExpRhoType
et
tcSkolemiseET UserTypeCtxt
ctxt (Check TcType
ty) ExpRhoType -> TcM result
thing_inside
  = UserTypeCtxt
-> TcType
-> ([Var] -> TcType -> TcM result)
-> TcM (HsWrapper, result)
forall result.
UserTypeCtxt
-> TcType
-> ([Var] -> TcType -> TcM result)
-> TcM (HsWrapper, result)
tcSkolemise UserTypeCtxt
ctxt TcType
ty (([Var] -> TcType -> TcM result) -> TcM (HsWrapper, result))
-> ([Var] -> TcType -> TcM result) -> TcM (HsWrapper, result)
forall a b. (a -> b) -> a -> b
$ \[Var]
_ -> ExpRhoType -> TcM result
thing_inside (ExpRhoType -> TcM result)
-> (TcType -> ExpRhoType) -> TcType -> TcM result
forall b c a. (b -> c) -> (a -> b) -> a -> c
. TcType -> ExpRhoType
mkCheckExpType

checkConstraints :: SkolemInfo
                 -> [TcTyVar]           -- Skolems
                 -> [EvVar]             -- Given
                 -> TcM result
                 -> TcM (TcEvBinds, result)

checkConstraints :: SkolemInfo
-> [Var] -> [Var] -> TcM result -> TcM (TcEvBinds, result)
checkConstraints SkolemInfo
skol_info [Var]
skol_tvs [Var]
given TcM result
thing_inside
  = do { Bool
implication_needed <- SkolemInfo -> [Var] -> [Var] -> TcM Bool
implicationNeeded SkolemInfo
skol_info [Var]
skol_tvs [Var]
given

       ; if Bool
implication_needed
         then do { (TcLevel
tclvl, WantedConstraints
wanted, result
result) <- TcM result -> TcM (TcLevel, WantedConstraints, result)
forall a. TcM a -> TcM (TcLevel, WantedConstraints, a)
pushLevelAndCaptureConstraints TcM result
thing_inside
                 ; (Bag Implication
implics, TcEvBinds
ev_binds) <- TcLevel
-> SkolemInfo
-> [Var]
-> [Var]
-> WantedConstraints
-> TcM (Bag Implication, TcEvBinds)
buildImplicationFor TcLevel
tclvl SkolemInfo
skol_info [Var]
skol_tvs [Var]
given WantedConstraints
wanted
                 ; String -> SDoc -> TcRn ()
traceTc String
"checkConstraints" (TcLevel -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcLevel
tclvl SDoc -> SDoc -> SDoc
$$ [Var] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [Var]
skol_tvs)
                 ; Bag Implication -> TcRn ()
emitImplications Bag Implication
implics
                 ; (TcEvBinds, result) -> TcM (TcEvBinds, result)
forall (m :: * -> *) a. Monad m => a -> m a
return (TcEvBinds
ev_binds, result
result) }

         else -- Fast path.  We check every function argument with
              -- tcPolyExpr, which uses tcSkolemise and hence checkConstraints.
              -- So this fast path is well-exercised
              do { result
res <- TcM result
thing_inside
                 ; (TcEvBinds, result) -> TcM (TcEvBinds, result)
forall (m :: * -> *) a. Monad m => a -> m a
return (TcEvBinds
emptyTcEvBinds, result
res) } }

checkTvConstraints :: SkolemInfo
                   -> [TcTyVar]          -- Skolem tyvars
                   -> TcM result
                   -> TcM result

checkTvConstraints :: SkolemInfo -> [Var] -> TcM result -> TcM result
checkTvConstraints SkolemInfo
skol_info [Var]
skol_tvs TcM result
thing_inside
  = do { (TcLevel
tclvl, WantedConstraints
wanted, result
result) <- TcM result -> TcM (TcLevel, WantedConstraints, result)
forall a. TcM a -> TcM (TcLevel, WantedConstraints, a)
pushLevelAndCaptureConstraints TcM result
thing_inside
       ; SkolemInfo
-> Maybe SDoc -> [Var] -> TcLevel -> WantedConstraints -> TcRn ()
emitResidualTvConstraint SkolemInfo
skol_info Maybe SDoc
forall a. Maybe a
Nothing [Var]
skol_tvs TcLevel
tclvl WantedConstraints
wanted
       ; result -> TcM result
forall (m :: * -> *) a. Monad m => a -> m a
return result
result }

emitResidualTvConstraint :: SkolemInfo -> Maybe SDoc -> [TcTyVar]
                         -> TcLevel -> WantedConstraints -> TcM ()
emitResidualTvConstraint :: SkolemInfo
-> Maybe SDoc -> [Var] -> TcLevel -> WantedConstraints -> TcRn ()
emitResidualTvConstraint SkolemInfo
skol_info Maybe SDoc
m_telescope [Var]
skol_tvs TcLevel
tclvl WantedConstraints
wanted
  | WantedConstraints -> Bool
isEmptyWC WantedConstraints
wanted
  , Maybe SDoc -> Bool
forall a. Maybe a -> Bool
isNothing Maybe SDoc
m_telescope Bool -> Bool -> Bool
|| [Var]
skol_tvs [Var] -> Arity -> Bool
forall a. [a] -> Arity -> Bool
`lengthAtMost` Arity
1
    -- If m_telescope is (Just d), we must do the bad-telescope check,
    -- so we must /not/ discard the implication even if there are no
    -- wanted constraints. See Note [Checking telescopes] in Constraint.
    -- Lacking this check led to #16247
  = () -> TcRn ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()

  | Bool
otherwise
  = do { EvBindsVar
ev_binds <- TcM EvBindsVar
newNoTcEvBinds
       ; Implication
implic   <- TcM Implication
newImplication
       ; let status :: ImplicStatus
status | WantedConstraints -> Bool
insolubleWC WantedConstraints
wanted = ImplicStatus
IC_Insoluble
                    | Bool
otherwise          = ImplicStatus
IC_Unsolved
             -- If the inner constraints are insoluble,
             -- we should mark the outer one similarly,
             -- so that insolubleWC works on the outer one

       ; Implication -> TcRn ()
emitImplication (Implication -> TcRn ()) -> Implication -> TcRn ()
forall a b. (a -> b) -> a -> b
$
         Implication
implic { ic_status :: ImplicStatus
ic_status    = ImplicStatus
status
                , ic_tclvl :: TcLevel
ic_tclvl     = TcLevel
tclvl
                , ic_skols :: [Var]
ic_skols     = [Var]
skol_tvs
                , ic_no_eqs :: Bool
ic_no_eqs    = Bool
True
                , ic_telescope :: Maybe SDoc
ic_telescope = Maybe SDoc
m_telescope
                , ic_wanted :: WantedConstraints
ic_wanted    = WantedConstraints
wanted
                , ic_binds :: EvBindsVar
ic_binds     = EvBindsVar
ev_binds
                , ic_info :: SkolemInfo
ic_info      = SkolemInfo
skol_info } }

implicationNeeded :: SkolemInfo -> [TcTyVar] -> [EvVar] -> TcM Bool
-- See Note [When to build an implication]
implicationNeeded :: SkolemInfo -> [Var] -> [Var] -> TcM Bool
implicationNeeded SkolemInfo
skol_info [Var]
skol_tvs [Var]
given
  | [Var] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Var]
skol_tvs
  , [Var] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Var]
given
  , Bool -> Bool
not (SkolemInfo -> Bool
alwaysBuildImplication SkolemInfo
skol_info)
  = -- Empty skolems and givens
    do { TcLevel
tc_lvl <- TcM TcLevel
getTcLevel
       ; if Bool -> Bool
not (TcLevel -> Bool
isTopTcLevel TcLevel
tc_lvl)  -- No implication needed if we are
         then Bool -> TcM Bool
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
False             -- already inside an implication
         else
    do { DynFlags
dflags <- IOEnv (Env TcGblEnv TcLclEnv) DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags       -- If any deferral can happen,
                                     -- we must build an implication
       ; Bool -> TcM Bool
forall (m :: * -> *) a. Monad m => a -> m a
return (GeneralFlag -> DynFlags -> Bool
gopt GeneralFlag
Opt_DeferTypeErrors DynFlags
dflags Bool -> Bool -> Bool
||
                 GeneralFlag -> DynFlags -> Bool
gopt GeneralFlag
Opt_DeferTypedHoles DynFlags
dflags Bool -> Bool -> Bool
||
                 GeneralFlag -> DynFlags -> Bool
gopt GeneralFlag
Opt_DeferOutOfScopeVariables DynFlags
dflags) } }

  | Bool
otherwise     -- Non-empty skolems or givens
  = Bool -> TcM Bool
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
True   -- Definitely need an implication

alwaysBuildImplication :: SkolemInfo -> Bool
-- See Note [When to build an implication]
alwaysBuildImplication :: SkolemInfo -> Bool
alwaysBuildImplication SkolemInfo
_ = Bool
False

{-  Commmented out for now while I figure out about error messages.
    See #14185

alwaysBuildImplication (SigSkol ctxt _ _)
  = case ctxt of
      FunSigCtxt {} -> True  -- RHS of a binding with a signature
      _             -> False
alwaysBuildImplication (RuleSkol {})      = True
alwaysBuildImplication (InstSkol {})      = True
alwaysBuildImplication (FamInstSkol {})   = True
alwaysBuildImplication _                  = False
-}

buildImplicationFor :: TcLevel -> SkolemInfo -> [TcTyVar]
                   -> [EvVar] -> WantedConstraints
                   -> TcM (Bag Implication, TcEvBinds)
buildImplicationFor :: TcLevel
-> SkolemInfo
-> [Var]
-> [Var]
-> WantedConstraints
-> TcM (Bag Implication, TcEvBinds)
buildImplicationFor TcLevel
tclvl SkolemInfo
skol_info [Var]
skol_tvs [Var]
given WantedConstraints
wanted
  | WantedConstraints -> Bool
isEmptyWC WantedConstraints
wanted Bool -> Bool -> Bool
&& [Var] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Var]
given
             -- Optimisation : if there are no wanteds, and no givens
             -- don't generate an implication at all.
             -- Reason for the (null given): we don't want to lose
             -- the "inaccessible alternative" error check
  = (Bag Implication, TcEvBinds) -> TcM (Bag Implication, TcEvBinds)
forall (m :: * -> *) a. Monad m => a -> m a
return (Bag Implication
forall a. Bag a
emptyBag, TcEvBinds
emptyTcEvBinds)

  | Bool
otherwise
  = ASSERT2( all (isSkolemTyVar <||> isTyVarTyVar) skol_tvs, ppr skol_tvs )
      -- Why allow TyVarTvs? Because implicitly declared kind variables in
      -- non-CUSK type declarations are TyVarTvs, and we need to bring them
      -- into scope as a skolem in an implication. This is OK, though,
      -- because TyVarTvs will always remain tyvars, even after unification.
    do { EvBindsVar
ev_binds_var <- TcM EvBindsVar
newTcEvBinds
       ; Implication
implic <- TcM Implication
newImplication
       ; let implic' :: Implication
implic' = Implication
implic { ic_tclvl :: TcLevel
ic_tclvl  = TcLevel
tclvl
                              , ic_skols :: [Var]
ic_skols  = [Var]
skol_tvs
                              , ic_given :: [Var]
ic_given  = [Var]
given
                              , ic_wanted :: WantedConstraints
ic_wanted = WantedConstraints
wanted
                              , ic_binds :: EvBindsVar
ic_binds  = EvBindsVar
ev_binds_var
                              , ic_info :: SkolemInfo
ic_info   = SkolemInfo
skol_info }

       ; (Bag Implication, TcEvBinds) -> TcM (Bag Implication, TcEvBinds)
forall (m :: * -> *) a. Monad m => a -> m a
return (Implication -> Bag Implication
forall a. a -> Bag a
unitBag Implication
implic', EvBindsVar -> TcEvBinds
TcEvBinds EvBindsVar
ev_binds_var) }

{- Note [When to build an implication]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose we have some 'skolems' and some 'givens', and we are
considering whether to wrap the constraints in their scope into an
implication.  We must /always/ so if either 'skolems' or 'givens' are
non-empty.  But what if both are empty?  You might think we could
always drop the implication.  Other things being equal, the fewer
implications the better.  Less clutter and overhead.  But we must
take care:

* If we have an unsolved [W] g :: a ~# b, and -fdefer-type-errors,
  we'll make a /term-level/ evidence binding for 'g = error "blah"'.
  We must have an EvBindsVar those bindings!, otherwise they end up as
  top-level unlifted bindings, which are verboten. This only matters
  at top level, so we check for that
  See also Note [Deferred errors for coercion holes] in TcErrors.
  cf #14149 for an example of what goes wrong.

* If you have
     f :: Int;  f = f_blah
     g :: Bool; g = g_blah
  If we don't build an implication for f or g (no tyvars, no givens),
  the constraints for f_blah and g_blah are solved together.  And that
  can yield /very/ confusing error messages, because we can get
      [W] C Int b1    -- from f_blah
      [W] C Int b2    -- from g_blan
  and fundpes can yield [D] b1 ~ b2, even though the two functions have
  literally nothing to do with each other.  #14185 is an example.
  Building an implication keeps them separage.
-}

{-
************************************************************************
*                                                                      *
                Boxy unification
*                                                                      *
************************************************************************

The exported functions are all defined as versions of some
non-exported generic functions.
-}

unifyType :: Maybe (HsExpr GhcRn)   -- ^ If present, has type 'ty1'
          -> TcTauType -> TcTauType -> TcM TcCoercionN
-- Actual and expected types
-- Returns a coercion : ty1 ~ ty2
unifyType :: Maybe (HsExpr GhcRn) -> TcType -> TcType -> TcM TcCoercionN
unifyType Maybe (HsExpr GhcRn)
thing TcType
ty1 TcType
ty2 = String -> SDoc -> TcRn ()
traceTc String
"utype" (TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
ty1 SDoc -> SDoc -> SDoc
$$ TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
ty2 SDoc -> SDoc -> SDoc
$$ Maybe (HsExpr GhcRn) -> SDoc
forall a. Outputable a => a -> SDoc
ppr Maybe (HsExpr GhcRn)
thing) TcRn () -> TcM TcCoercionN -> TcM TcCoercionN
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>>
                          TypeOrKind -> CtOrigin -> TcType -> TcType -> TcM TcCoercionN
uType TypeOrKind
TypeLevel CtOrigin
origin TcType
ty1 TcType
ty2
  where
    origin :: CtOrigin
origin = TypeEqOrigin :: TcType -> TcType -> Maybe SDoc -> Bool -> CtOrigin
TypeEqOrigin { uo_actual :: TcType
uo_actual = TcType
ty1, uo_expected :: TcType
uo_expected = TcType
ty2
                          , uo_thing :: Maybe SDoc
uo_thing  = HsExpr GhcRn -> SDoc
forall a. Outputable a => a -> SDoc
ppr (HsExpr GhcRn -> SDoc) -> Maybe (HsExpr GhcRn) -> Maybe SDoc
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Maybe (HsExpr GhcRn)
thing
                          , uo_visible :: Bool
uo_visible = Bool
True } -- always called from a visible context

unifyKind :: Maybe (HsType GhcRn) -> TcKind -> TcKind -> TcM CoercionN
unifyKind :: Maybe (HsType GhcRn) -> TcType -> TcType -> TcM TcCoercionN
unifyKind Maybe (HsType GhcRn)
thing TcType
ty1 TcType
ty2 = String -> SDoc -> TcRn ()
traceTc String
"ukind" (TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
ty1 SDoc -> SDoc -> SDoc
$$ TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
ty2 SDoc -> SDoc -> SDoc
$$ Maybe (HsType GhcRn) -> SDoc
forall a. Outputable a => a -> SDoc
ppr Maybe (HsType GhcRn)
thing) TcRn () -> TcM TcCoercionN -> TcM TcCoercionN
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>>
                          TypeOrKind -> CtOrigin -> TcType -> TcType -> TcM TcCoercionN
uType TypeOrKind
KindLevel CtOrigin
origin TcType
ty1 TcType
ty2
  where origin :: CtOrigin
origin = TypeEqOrigin :: TcType -> TcType -> Maybe SDoc -> Bool -> CtOrigin
TypeEqOrigin { uo_actual :: TcType
uo_actual = TcType
ty1, uo_expected :: TcType
uo_expected = TcType
ty2
                              , uo_thing :: Maybe SDoc
uo_thing  = HsType GhcRn -> SDoc
forall a. Outputable a => a -> SDoc
ppr (HsType GhcRn -> SDoc) -> Maybe (HsType GhcRn) -> Maybe SDoc
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Maybe (HsType GhcRn)
thing
                              , uo_visible :: Bool
uo_visible = Bool
True } -- also always from a visible context

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

{-
%************************************************************************
%*                                                                      *
                 uType and friends
%*                                                                      *
%************************************************************************

uType is the heart of the unifier.
-}

uType, uType_defer
  :: TypeOrKind
  -> CtOrigin
  -> TcType    -- ty1 is the *actual* type
  -> TcType    -- ty2 is the *expected* type
  -> TcM CoercionN

--------------
-- It is always safe to defer unification to the main constraint solver
-- See Note [Deferred unification]
uType_defer :: TypeOrKind -> CtOrigin -> TcType -> TcType -> TcM TcCoercionN
uType_defer TypeOrKind
t_or_k CtOrigin
origin TcType
ty1 TcType
ty2
  = do { TcCoercionN
co <- CtOrigin
-> TypeOrKind -> Role -> TcType -> TcType -> TcM TcCoercionN
emitWantedEq CtOrigin
origin TypeOrKind
t_or_k Role
Nominal TcType
ty1 TcType
ty2

       -- Error trace only
       -- NB. do *not* call mkErrInfo unless tracing is on,
       --     because it is hugely expensive (#5631)
       ; DumpFlag -> TcRn () -> TcRn ()
forall gbl lcl. DumpFlag -> TcRnIf gbl lcl () -> TcRnIf gbl lcl ()
whenDOptM DumpFlag
Opt_D_dump_tc_trace (TcRn () -> TcRn ()) -> TcRn () -> TcRn ()
forall a b. (a -> b) -> a -> b
$ do
            { [ErrCtxt]
ctxt <- TcM [ErrCtxt]
getErrCtxt
            ; SDoc
doc <- TidyEnv -> [ErrCtxt] -> TcM SDoc
mkErrInfo TidyEnv
emptyTidyEnv [ErrCtxt]
ctxt
            ; String -> SDoc -> TcRn ()
traceTc String
"utype_defer" ([SDoc] -> SDoc
vcat [ TcType -> SDoc
debugPprType TcType
ty1
                                          , TcType -> SDoc
debugPprType TcType
ty2
                                          , CtOrigin -> SDoc
pprCtOrigin CtOrigin
origin
                                          , SDoc
doc])
            ; String -> SDoc -> TcRn ()
traceTc String
"utype_defer2" (TcCoercionN -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcCoercionN
co)
            }
       ; TcCoercionN -> TcM TcCoercionN
forall (m :: * -> *) a. Monad m => a -> m a
return TcCoercionN
co }

--------------
uType :: TypeOrKind -> CtOrigin -> TcType -> TcType -> TcM TcCoercionN
uType TypeOrKind
t_or_k CtOrigin
origin TcType
orig_ty1 TcType
orig_ty2
  = do { TcLevel
tclvl <- TcM TcLevel
getTcLevel
       ; String -> SDoc -> TcRn ()
traceTc String
"u_tys" (SDoc -> TcRn ()) -> SDoc -> TcRn ()
forall a b. (a -> b) -> a -> b
$ [SDoc] -> SDoc
vcat
              [ String -> SDoc
text String
"tclvl" SDoc -> SDoc -> SDoc
<+> TcLevel -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcLevel
tclvl
              , [SDoc] -> SDoc
sep [ TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
orig_ty1, String -> SDoc
text String
"~", TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
orig_ty2]
              , CtOrigin -> SDoc
pprCtOrigin CtOrigin
origin]
       ; TcCoercionN
co <- TcType -> TcType -> TcM TcCoercionN
go TcType
orig_ty1 TcType
orig_ty2
       ; if TcCoercionN -> Bool
isReflCo TcCoercionN
co
            then String -> SDoc -> TcRn ()
traceTc String
"u_tys yields no coercion" SDoc
Outputable.empty
            else String -> SDoc -> TcRn ()
traceTc String
"u_tys yields coercion:" (TcCoercionN -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcCoercionN
co)
       ; TcCoercionN -> TcM TcCoercionN
forall (m :: * -> *) a. Monad m => a -> m a
return TcCoercionN
co }
  where
    go :: TcType -> TcType -> TcM CoercionN
        -- The arguments to 'go' are always semantically identical
        -- to orig_ty{1,2} except for looking through type synonyms

     -- Unwrap casts before looking for variables. This way, we can easily
     -- recognize (t |> co) ~ (t |> co), which is nice. Previously, we
     -- didn't do it this way, and then the unification above was deferred.
    go :: TcType -> TcType -> TcM TcCoercionN
go (CastTy TcType
t1 TcCoercionN
co1) TcType
t2
      = do { TcCoercionN
co_tys <- TypeOrKind -> CtOrigin -> TcType -> TcType -> TcM TcCoercionN
uType TypeOrKind
t_or_k CtOrigin
origin TcType
t1 TcType
t2
           ; TcCoercionN -> TcM TcCoercionN
forall (m :: * -> *) a. Monad m => a -> m a
return (Role -> TcType -> TcCoercionN -> TcCoercionN -> TcCoercionN
mkCoherenceLeftCo Role
Nominal TcType
t1 TcCoercionN
co1 TcCoercionN
co_tys) }

    go TcType
t1 (CastTy TcType
t2 TcCoercionN
co2)
      = do { TcCoercionN
co_tys <- TypeOrKind -> CtOrigin -> TcType -> TcType -> TcM TcCoercionN
uType TypeOrKind
t_or_k CtOrigin
origin TcType
t1 TcType
t2
           ; TcCoercionN -> TcM TcCoercionN
forall (m :: * -> *) a. Monad m => a -> m a
return (Role -> TcType -> TcCoercionN -> TcCoercionN -> TcCoercionN
mkCoherenceRightCo Role
Nominal TcType
t2 TcCoercionN
co2 TcCoercionN
co_tys) }

        -- Variables; go for uUnfilledVar
        -- Note that we pass in *original* (before synonym expansion),
        -- so that type variables tend to get filled in with
        -- the most informative version of the type
    go (TyVarTy Var
tv1) TcType
ty2
      = do { LookupTyVarResult
lookup_res <- Var -> TcM LookupTyVarResult
lookupTcTyVar Var
tv1
           ; case LookupTyVarResult
lookup_res of
               Filled TcType
ty1   -> do { String -> SDoc -> TcRn ()
traceTc String
"found filled tyvar" (Var -> SDoc
forall a. Outputable a => a -> SDoc
ppr Var
tv1 SDoc -> SDoc -> SDoc
<+> String -> SDoc
text String
":->" SDoc -> SDoc -> SDoc
<+> TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
ty1)
                                  ; TcType -> TcType -> TcM TcCoercionN
go TcType
ty1 TcType
ty2 }
               Unfilled TcTyVarDetails
_ -> CtOrigin
-> TypeOrKind -> SwapFlag -> Var -> TcType -> TcM TcCoercionN
uUnfilledVar CtOrigin
origin TypeOrKind
t_or_k SwapFlag
NotSwapped Var
tv1 TcType
ty2 }
    go TcType
ty1 (TyVarTy Var
tv2)
      = do { LookupTyVarResult
lookup_res <- Var -> TcM LookupTyVarResult
lookupTcTyVar Var
tv2
           ; case LookupTyVarResult
lookup_res of
               Filled TcType
ty2   -> do { String -> SDoc -> TcRn ()
traceTc String
"found filled tyvar" (Var -> SDoc
forall a. Outputable a => a -> SDoc
ppr Var
tv2 SDoc -> SDoc -> SDoc
<+> String -> SDoc
text String
":->" SDoc -> SDoc -> SDoc
<+> TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
ty2)
                                  ; TcType -> TcType -> TcM TcCoercionN
go TcType
ty1 TcType
ty2 }
               Unfilled TcTyVarDetails
_ -> CtOrigin
-> TypeOrKind -> SwapFlag -> Var -> TcType -> TcM TcCoercionN
uUnfilledVar CtOrigin
origin TypeOrKind
t_or_k SwapFlag
IsSwapped Var
tv2 TcType
ty1 }

      -- See Note [Expanding synonyms during unification]
    go ty1 :: TcType
ty1@(TyConApp TyCon
tc1 []) (TyConApp TyCon
tc2 [])
      | TyCon
tc1 TyCon -> TyCon -> Bool
forall a. Eq a => a -> a -> Bool
== TyCon
tc2
      = TcCoercionN -> TcM TcCoercionN
forall (m :: * -> *) a. Monad m => a -> m a
return (TcCoercionN -> TcM TcCoercionN) -> TcCoercionN -> TcM TcCoercionN
forall a b. (a -> b) -> a -> b
$ TcType -> TcCoercionN
mkNomReflCo TcType
ty1

        -- See Note [Expanding synonyms during unification]
        --
        -- Also NB that we recurse to 'go' so that we don't push a
        -- new item on the origin stack. As a result if we have
        --   type Foo = Int
        -- and we try to unify  Foo ~ Bool
        -- we'll end up saying "can't match Foo with Bool"
        -- rather than "can't match "Int with Bool".  See #4535.
    go TcType
ty1 TcType
ty2
      | Just TcType
ty1' <- TcType -> Maybe TcType
tcView TcType
ty1 = TcType -> TcType -> TcM TcCoercionN
go TcType
ty1' TcType
ty2
      | Just TcType
ty2' <- TcType -> Maybe TcType
tcView TcType
ty2 = TcType -> TcType -> TcM TcCoercionN
go TcType
ty1  TcType
ty2'

        -- Functions (or predicate functions) just check the two parts
    go (FunTy AnonArgFlag
_ TcType
fun1 TcType
arg1) (FunTy AnonArgFlag
_ TcType
fun2 TcType
arg2)
      = do { TcCoercionN
co_l <- TypeOrKind -> CtOrigin -> TcType -> TcType -> TcM TcCoercionN
uType TypeOrKind
t_or_k CtOrigin
origin TcType
fun1 TcType
fun2
           ; TcCoercionN
co_r <- TypeOrKind -> CtOrigin -> TcType -> TcType -> TcM TcCoercionN
uType TypeOrKind
t_or_k CtOrigin
origin TcType
arg1 TcType
arg2
           ; TcCoercionN -> TcM TcCoercionN
forall (m :: * -> *) a. Monad m => a -> m a
return (TcCoercionN -> TcM TcCoercionN) -> TcCoercionN -> TcM TcCoercionN
forall a b. (a -> b) -> a -> b
$ Role -> TcCoercionN -> TcCoercionN -> TcCoercionN
mkFunCo Role
Nominal TcCoercionN
co_l TcCoercionN
co_r }

        -- Always defer if a type synonym family (type function)
        -- is involved.  (Data families behave rigidly.)
    go ty1 :: TcType
ty1@(TyConApp TyCon
tc1 [TcType]
_) TcType
ty2
      | TyCon -> Bool
isTypeFamilyTyCon TyCon
tc1 = TcType -> TcType -> TcM TcCoercionN
defer TcType
ty1 TcType
ty2
    go TcType
ty1 ty2 :: TcType
ty2@(TyConApp TyCon
tc2 [TcType]
_)
      | TyCon -> Bool
isTypeFamilyTyCon TyCon
tc2 = TcType -> TcType -> TcM TcCoercionN
defer TcType
ty1 TcType
ty2

    go (TyConApp TyCon
tc1 [TcType]
tys1) (TyConApp TyCon
tc2 [TcType]
tys2)
      -- See Note [Mismatched type lists and application decomposition]
      | TyCon
tc1 TyCon -> TyCon -> Bool
forall a. Eq a => a -> a -> Bool
== TyCon
tc2, [TcType] -> [TcType] -> Bool
forall a b. [a] -> [b] -> Bool
equalLength [TcType]
tys1 [TcType]
tys2
      = ASSERT2( isGenerativeTyCon tc1 Nominal, ppr tc1 )
        do { [TcCoercionN]
cos <- (CtOrigin -> TcType -> TcType -> TcM TcCoercionN)
-> [CtOrigin]
-> [TcType]
-> [TcType]
-> IOEnv (Env TcGblEnv TcLclEnv) [TcCoercionN]
forall (m :: * -> *) a b c d.
Monad m =>
(a -> b -> c -> m d) -> [a] -> [b] -> [c] -> m [d]
zipWith3M (TypeOrKind -> CtOrigin -> TcType -> TcType -> TcM TcCoercionN
uType TypeOrKind
t_or_k) [CtOrigin]
origins' [TcType]
tys1 [TcType]
tys2
           ; TcCoercionN -> TcM TcCoercionN
forall (m :: * -> *) a. Monad m => a -> m a
return (TcCoercionN -> TcM TcCoercionN) -> TcCoercionN -> TcM TcCoercionN
forall a b. (a -> b) -> a -> b
$ HasDebugCallStack => Role -> TyCon -> [TcCoercionN] -> TcCoercionN
Role -> TyCon -> [TcCoercionN] -> TcCoercionN
mkTyConAppCo Role
Nominal TyCon
tc1 [TcCoercionN]
cos }
      where
        origins' :: [CtOrigin]
origins' = (Bool -> CtOrigin) -> [Bool] -> [CtOrigin]
forall a b. (a -> b) -> [a] -> [b]
map (\Bool
is_vis -> if Bool
is_vis then CtOrigin
origin else CtOrigin -> CtOrigin
toInvisibleOrigin CtOrigin
origin)
                       (TyCon -> [Bool]
tcTyConVisibilities TyCon
tc1)

    go (LitTy TyLit
m) ty :: TcType
ty@(LitTy TyLit
n)
      | TyLit
m TyLit -> TyLit -> Bool
forall a. Eq a => a -> a -> Bool
== TyLit
n
      = TcCoercionN -> TcM TcCoercionN
forall (m :: * -> *) a. Monad m => a -> m a
return (TcCoercionN -> TcM TcCoercionN) -> TcCoercionN -> TcM TcCoercionN
forall a b. (a -> b) -> a -> b
$ TcType -> TcCoercionN
mkNomReflCo TcType
ty

        -- See Note [Care with type applications]
        -- Do not decompose FunTy against App;
        -- it's often a type error, so leave it for the constraint solver
    go (AppTy TcType
s1 TcType
t1) (AppTy TcType
s2 TcType
t2)
      = Bool -> TcType -> TcType -> TcType -> TcType -> TcM TcCoercionN
go_app (TcType -> Bool
isNextArgVisible TcType
s1) TcType
s1 TcType
t1 TcType
s2 TcType
t2

    go (AppTy TcType
s1 TcType
t1) (TyConApp TyCon
tc2 [TcType]
ts2)
      | Just ([TcType]
ts2', TcType
t2') <- [TcType] -> Maybe ([TcType], TcType)
forall a. [a] -> Maybe ([a], a)
snocView [TcType]
ts2
      = ASSERT( not (mustBeSaturated tc2) )
        Bool -> TcType -> TcType -> TcType -> TcType -> TcM TcCoercionN
go_app (TyCon -> [TcType] -> Bool
isNextTyConArgVisible TyCon
tc2 [TcType]
ts2') TcType
s1 TcType
t1 (TyCon -> [TcType] -> TcType
TyConApp TyCon
tc2 [TcType]
ts2') TcType
t2'

    go (TyConApp TyCon
tc1 [TcType]
ts1) (AppTy TcType
s2 TcType
t2)
      | Just ([TcType]
ts1', TcType
t1') <- [TcType] -> Maybe ([TcType], TcType)
forall a. [a] -> Maybe ([a], a)
snocView [TcType]
ts1
      = ASSERT( not (mustBeSaturated tc1) )
        Bool -> TcType -> TcType -> TcType -> TcType -> TcM TcCoercionN
go_app (TyCon -> [TcType] -> Bool
isNextTyConArgVisible TyCon
tc1 [TcType]
ts1') (TyCon -> [TcType] -> TcType
TyConApp TyCon
tc1 [TcType]
ts1') TcType
t1' TcType
s2 TcType
t2

    go (CoercionTy TcCoercionN
co1) (CoercionTy TcCoercionN
co2)
      = do { let ty1 :: TcType
ty1 = TcCoercionN -> TcType
coercionType TcCoercionN
co1
                 ty2 :: TcType
ty2 = TcCoercionN -> TcType
coercionType TcCoercionN
co2
           ; TcCoercionN
kco <- TypeOrKind -> CtOrigin -> TcType -> TcType -> TcM TcCoercionN
uType TypeOrKind
KindLevel
                          (TcType -> Maybe TcType -> CtOrigin -> Maybe TypeOrKind -> CtOrigin
KindEqOrigin TcType
orig_ty1 (TcType -> Maybe TcType
forall a. a -> Maybe a
Just TcType
orig_ty2) CtOrigin
origin
                                        (TypeOrKind -> Maybe TypeOrKind
forall a. a -> Maybe a
Just TypeOrKind
t_or_k))
                          TcType
ty1 TcType
ty2
           ; TcCoercionN -> TcM TcCoercionN
forall (m :: * -> *) a. Monad m => a -> m a
return (TcCoercionN -> TcM TcCoercionN) -> TcCoercionN -> TcM TcCoercionN
forall a b. (a -> b) -> a -> b
$ Role -> TcCoercionN -> TcCoercionN -> TcCoercionN -> TcCoercionN
mkProofIrrelCo Role
Nominal TcCoercionN
kco TcCoercionN
co1 TcCoercionN
co2 }

        -- Anything else fails
        -- E.g. unifying for-all types, which is relative unusual
    go TcType
ty1 TcType
ty2 = TcType -> TcType -> TcM TcCoercionN
defer TcType
ty1 TcType
ty2

    ------------------
    defer :: TcType -> TcType -> TcM TcCoercionN
defer TcType
ty1 TcType
ty2   -- See Note [Check for equality before deferring]
      | TcType
ty1 HasDebugCallStack => TcType -> TcType -> Bool
TcType -> TcType -> Bool
`tcEqType` TcType
ty2 = TcCoercionN -> TcM TcCoercionN
forall (m :: * -> *) a. Monad m => a -> m a
return (TcType -> TcCoercionN
mkNomReflCo TcType
ty1)
      | Bool
otherwise          = TypeOrKind -> CtOrigin -> TcType -> TcType -> TcM TcCoercionN
uType_defer TypeOrKind
t_or_k CtOrigin
origin TcType
ty1 TcType
ty2

    ------------------
    go_app :: Bool -> TcType -> TcType -> TcType -> TcType -> TcM TcCoercionN
go_app Bool
vis TcType
s1 TcType
t1 TcType
s2 TcType
t2
      = do { TcCoercionN
co_s <- TypeOrKind -> CtOrigin -> TcType -> TcType -> TcM TcCoercionN
uType TypeOrKind
t_or_k CtOrigin
origin TcType
s1 TcType
s2
           ; let arg_origin :: CtOrigin
arg_origin
                   | Bool
vis       = CtOrigin
origin
                   | Bool
otherwise = CtOrigin -> CtOrigin
toInvisibleOrigin CtOrigin
origin
           ; TcCoercionN
co_t <- TypeOrKind -> CtOrigin -> TcType -> TcType -> TcM TcCoercionN
uType TypeOrKind
t_or_k CtOrigin
arg_origin TcType
t1 TcType
t2
           ; TcCoercionN -> TcM TcCoercionN
forall (m :: * -> *) a. Monad m => a -> m a
return (TcCoercionN -> TcM TcCoercionN) -> TcCoercionN -> TcM TcCoercionN
forall a b. (a -> b) -> a -> b
$ TcCoercionN -> TcCoercionN -> TcCoercionN
mkAppCo TcCoercionN
co_s TcCoercionN
co_t }

{- Note [Check for equality before deferring]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Particularly in ambiguity checks we can get equalities like (ty ~ ty).
If ty involves a type function we may defer, which isn't very sensible.
An egregious example of this was in test T9872a, which has a type signature
       Proxy :: Proxy (Solutions Cubes)
Doing the ambiguity check on this signature generates the equality
   Solutions Cubes ~ Solutions Cubes
and currently the constraint solver normalises both sides at vast cost.
This little short-cut in 'defer' helps quite a bit.

Note [Care with type applications]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Note: type applications need a bit of care!
They can match FunTy and TyConApp, so use splitAppTy_maybe
NB: we've already dealt with type variables and Notes,
so if one type is an App the other one jolly well better be too

Note [Mismatched type lists and application decomposition]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When we find two TyConApps, you might think that the argument lists
are guaranteed equal length.  But they aren't. Consider matching
        w (T x) ~ Foo (T x y)
We do match (w ~ Foo) first, but in some circumstances we simply create
a deferred constraint; and then go ahead and match (T x ~ T x y).
This came up in #3950.

So either
   (a) either we must check for identical argument kinds
       when decomposing applications,

   (b) or we must be prepared for ill-kinded unification sub-problems

Currently we adopt (b) since it seems more robust -- no need to maintain
a global invariant.

Note [Expanding synonyms during unification]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We expand synonyms during unification, but:
 * We expand *after* the variable case so that we tend to unify
   variables with un-expanded type synonym. This just makes it
   more likely that the inferred types will mention type synonyms
   understandable to the user

 * Similarly, we expand *after* the CastTy case, just in case the
   CastTy wraps a variable.

 * We expand *before* the TyConApp case.  For example, if we have
      type Phantom a = Int
   and are unifying
      Phantom Int ~ Phantom Char
   it is *wrong* to unify Int and Char.

 * The problem case immediately above can happen only with arguments
   to the tycon. So we check for nullary tycons *before* expanding.
   This is particularly helpful when checking (* ~ *), because * is
   now a type synonym.

Note [Deferred Unification]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
We may encounter a unification ty1 ~ ty2 that cannot be performed syntactically,
and yet its consistency is undetermined. Previously, there was no way to still
make it consistent. So a mismatch error was issued.

Now these unifications are deferred until constraint simplification, where type
family instances and given equations may (or may not) establish the consistency.
Deferred unifications are of the form
                F ... ~ ...
or              x ~ ...
where F is a type function and x is a type variable.
E.g.
        id :: x ~ y => x -> y
        id e = e

involves the unification x = y. It is deferred until we bring into account the
context x ~ y to establish that it holds.

If available, we defer original types (rather than those where closed type
synonyms have already been expanded via tcCoreView).  This is, as usual, to
improve error messages.


************************************************************************
*                                                                      *
                 uUnfilledVar and friends
*                                                                      *
************************************************************************

@uunfilledVar@ is called when at least one of the types being unified is a
variable.  It does {\em not} assume that the variable is a fixed point
of the substitution; rather, notice that @uVar@ (defined below) nips
back into @uTys@ if it turns out that the variable is already bound.
-}

----------
uUnfilledVar :: CtOrigin
             -> TypeOrKind
             -> SwapFlag
             -> TcTyVar        -- Tyvar 1: not necessarily a meta-tyvar
                               --    definitely not a /filled/ meta-tyvar
             -> TcTauType      -- Type 2
             -> TcM Coercion
-- "Unfilled" means that the variable is definitely not a filled-in meta tyvar
--            It might be a skolem, or untouchable, or meta

uUnfilledVar :: CtOrigin
-> TypeOrKind -> SwapFlag -> Var -> TcType -> TcM TcCoercionN
uUnfilledVar CtOrigin
origin TypeOrKind
t_or_k SwapFlag
swapped Var
tv1 TcType
ty2
  = do { TcType
ty2 <- TcType -> IOEnv (Env TcGblEnv TcLclEnv) TcType
zonkTcType TcType
ty2
             -- Zonk to expose things to the
             -- occurs check, and so that if ty2
             -- looks like a type variable then it
             -- /is/ a type variable
       ; CtOrigin
-> TypeOrKind -> SwapFlag -> Var -> TcType -> TcM TcCoercionN
uUnfilledVar1 CtOrigin
origin TypeOrKind
t_or_k SwapFlag
swapped Var
tv1 TcType
ty2 }

----------
uUnfilledVar1 :: CtOrigin
              -> TypeOrKind
              -> SwapFlag
              -> TcTyVar        -- Tyvar 1: not necessarily a meta-tyvar
                                --    definitely not a /filled/ meta-tyvar
              -> TcTauType      -- Type 2, zonked
              -> TcM Coercion
uUnfilledVar1 :: CtOrigin
-> TypeOrKind -> SwapFlag -> Var -> TcType -> TcM TcCoercionN
uUnfilledVar1 CtOrigin
origin TypeOrKind
t_or_k SwapFlag
swapped Var
tv1 TcType
ty2
  | Just Var
tv2 <- TcType -> Maybe Var
tcGetTyVar_maybe TcType
ty2
  = Var -> TcM TcCoercionN
go Var
tv2

  | Bool
otherwise
  = CtOrigin
-> TypeOrKind -> SwapFlag -> Var -> TcType -> TcM TcCoercionN
uUnfilledVar2 CtOrigin
origin TypeOrKind
t_or_k SwapFlag
swapped Var
tv1 TcType
ty2

  where
    -- 'go' handles the case where both are
    -- tyvars so we might want to swap
    -- E.g. maybe tv2 is a meta-tyvar and tv1 is not
    go :: Var -> TcM TcCoercionN
go Var
tv2 | Var
tv1 Var -> Var -> Bool
forall a. Eq a => a -> a -> Bool
== Var
tv2  -- Same type variable => no-op
           = TcCoercionN -> TcM TcCoercionN
forall (m :: * -> *) a. Monad m => a -> m a
return (TcType -> TcCoercionN
mkNomReflCo (Var -> TcType
mkTyVarTy Var
tv1))

           | Var -> Var -> Bool
swapOverTyVars Var
tv1 Var
tv2   -- Distinct type variables
               -- Swap meta tyvar to the left if poss
           = do { Var
tv1 <- Var -> TcM Var
zonkTyCoVarKind Var
tv1
                     -- We must zonk tv1's kind because that might
                     -- not have happened yet, and it's an invariant of
                     -- uUnfilledTyVar2 that ty2 is fully zonked
                     -- Omitting this caused #16902
                ; CtOrigin
-> TypeOrKind -> SwapFlag -> Var -> TcType -> TcM TcCoercionN
uUnfilledVar2 CtOrigin
origin TypeOrKind
t_or_k (SwapFlag -> SwapFlag
flipSwap SwapFlag
swapped)
                           Var
tv2 (Var -> TcType
mkTyVarTy Var
tv1) }

           | Bool
otherwise
           = CtOrigin
-> TypeOrKind -> SwapFlag -> Var -> TcType -> TcM TcCoercionN
uUnfilledVar2 CtOrigin
origin TypeOrKind
t_or_k SwapFlag
swapped Var
tv1 TcType
ty2

----------
uUnfilledVar2 :: CtOrigin
              -> TypeOrKind
              -> SwapFlag
              -> TcTyVar        -- Tyvar 1: not necessarily a meta-tyvar
                                --    definitely not a /filled/ meta-tyvar
              -> TcTauType      -- Type 2, zonked
              -> TcM Coercion
uUnfilledVar2 :: CtOrigin
-> TypeOrKind -> SwapFlag -> Var -> TcType -> TcM TcCoercionN
uUnfilledVar2 CtOrigin
origin TypeOrKind
t_or_k SwapFlag
swapped Var
tv1 TcType
ty2
  = do { DynFlags
dflags  <- IOEnv (Env TcGblEnv TcLclEnv) DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags
       ; TcLevel
cur_lvl <- TcM TcLevel
getTcLevel
       ; DynFlags -> TcLevel -> TcM TcCoercionN
go DynFlags
dflags TcLevel
cur_lvl }
  where
    go :: DynFlags -> TcLevel -> TcM TcCoercionN
go DynFlags
dflags TcLevel
cur_lvl
      | TcLevel -> Var -> TcType -> Bool
canSolveByUnification TcLevel
cur_lvl Var
tv1 TcType
ty2
      , Just TcType
ty2' <- DynFlags -> Var -> TcType -> Maybe TcType
metaTyVarUpdateOK DynFlags
dflags Var
tv1 TcType
ty2
      = do { TcCoercionN
co_k <- TypeOrKind -> CtOrigin -> TcType -> TcType -> TcM TcCoercionN
uType TypeOrKind
KindLevel CtOrigin
kind_origin (HasDebugCallStack => TcType -> TcType
TcType -> TcType
tcTypeKind TcType
ty2') (Var -> TcType
tyVarKind Var
tv1)
           ; String -> SDoc -> TcRn ()
traceTc String
"uUnfilledVar2 ok" (SDoc -> TcRn ()) -> SDoc -> TcRn ()
forall a b. (a -> b) -> a -> b
$
             [SDoc] -> SDoc
vcat [ Var -> SDoc
forall a. Outputable a => a -> SDoc
ppr Var
tv1 SDoc -> SDoc -> SDoc
<+> SDoc
dcolon SDoc -> SDoc -> SDoc
<+> TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr (Var -> TcType
tyVarKind Var
tv1)
                  , TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
ty2 SDoc -> SDoc -> SDoc
<+> SDoc
dcolon SDoc -> SDoc -> SDoc
<+> TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr (HasDebugCallStack => TcType -> TcType
TcType -> TcType
tcTypeKind  TcType
ty2)
                  , Bool -> SDoc
forall a. Outputable a => a -> SDoc
ppr (TcCoercionN -> Bool
isTcReflCo TcCoercionN
co_k), TcCoercionN -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcCoercionN
co_k ]

           ; if TcCoercionN -> Bool
isTcReflCo TcCoercionN
co_k
               -- Only proceed if the kinds match
               -- NB: tv1 should still be unfilled, despite the kind unification
               --     because tv1 is not free in ty2 (or, hence, in its kind)
             then do { Var -> TcType -> TcRn ()
writeMetaTyVar Var
tv1 TcType
ty2'
                     ; TcCoercionN -> TcM TcCoercionN
forall (m :: * -> *) a. Monad m => a -> m a
return (TcType -> TcCoercionN
mkTcNomReflCo TcType
ty2') }

             else TcM TcCoercionN
defer } -- This cannot be solved now.  See TcCanonical
                          -- Note [Equalities with incompatible kinds]

      | Bool
otherwise
      = do { String -> SDoc -> TcRn ()
traceTc String
"uUnfilledVar2 not ok" (Var -> SDoc
forall a. Outputable a => a -> SDoc
ppr Var
tv1 SDoc -> SDoc -> SDoc
$$ TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
ty2)
               -- Occurs check or an untouchable: just defer
               -- NB: occurs check isn't necessarily fatal:
               --     eg tv1 occured in type family parameter
            ; TcM TcCoercionN
defer }

    ty1 :: TcType
ty1 = Var -> TcType
mkTyVarTy Var
tv1
    kind_origin :: CtOrigin
kind_origin = TcType -> Maybe TcType -> CtOrigin -> Maybe TypeOrKind -> CtOrigin
KindEqOrigin TcType
ty1 (TcType -> Maybe TcType
forall a. a -> Maybe a
Just TcType
ty2) CtOrigin
origin (TypeOrKind -> Maybe TypeOrKind
forall a. a -> Maybe a
Just TypeOrKind
t_or_k)

    defer :: TcM TcCoercionN
defer = SwapFlag
-> (TcType -> TcType -> TcM TcCoercionN)
-> TcType
-> TcType
-> TcM TcCoercionN
forall a b. SwapFlag -> (a -> a -> b) -> a -> a -> b
unSwap SwapFlag
swapped (TypeOrKind -> CtOrigin -> TcType -> TcType -> TcM TcCoercionN
uType_defer TypeOrKind
t_or_k CtOrigin
origin) TcType
ty1 TcType
ty2

swapOverTyVars :: TcTyVar -> TcTyVar -> Bool
swapOverTyVars :: Var -> Var -> Bool
swapOverTyVars Var
tv1 Var
tv2
  -- Level comparison: see Note [TyVar/TyVar orientation]
  | TcLevel
lvl1 TcLevel -> TcLevel -> Bool
`strictlyDeeperThan` TcLevel
lvl2 = Bool
False
  | TcLevel
lvl2 TcLevel -> TcLevel -> Bool
`strictlyDeeperThan` TcLevel
lvl1 = Bool
True

  -- Priority: see Note [TyVar/TyVar orientation]
  | Arity
pri1 Arity -> Arity -> Bool
forall a. Ord a => a -> a -> Bool
> Arity
pri2 = Bool
False
  | Arity
pri2 Arity -> Arity -> Bool
forall a. Ord a => a -> a -> Bool
> Arity
pri1 = Bool
True

  -- Names: see Note [TyVar/TyVar orientation]
  | Name -> Bool
isSystemName Name
tv2_name, Bool -> Bool
not (Name -> Bool
isSystemName Name
tv1_name) = Bool
True

  | Bool
otherwise = Bool
False

  where
    lvl1 :: TcLevel
lvl1 = Var -> TcLevel
tcTyVarLevel Var
tv1
    lvl2 :: TcLevel
lvl2 = Var -> TcLevel
tcTyVarLevel Var
tv2
    pri1 :: Arity
pri1 = Var -> Arity
lhsPriority Var
tv1
    pri2 :: Arity
pri2 = Var -> Arity
lhsPriority Var
tv2
    tv1_name :: Name
tv1_name = Var -> Name
Var.varName Var
tv1
    tv2_name :: Name
tv2_name = Var -> Name
Var.varName Var
tv2


lhsPriority :: TcTyVar -> Int
-- Higher => more important to be on the LHS
-- See Note [TyVar/TyVar orientation]
lhsPriority :: Var -> Arity
lhsPriority Var
tv
  = ASSERT2( isTyVar tv, ppr tv)
    case Var -> TcTyVarDetails
tcTyVarDetails Var
tv of
      TcTyVarDetails
RuntimeUnk  -> Arity
0
      SkolemTv {} -> Arity
0
      MetaTv { mtv_info :: TcTyVarDetails -> MetaInfo
mtv_info = MetaInfo
info } -> case MetaInfo
info of
                                     MetaInfo
FlatSkolTv -> Arity
1
                                     MetaInfo
TyVarTv    -> Arity
2
                                     MetaInfo
TauTv      -> Arity
3
                                     MetaInfo
FlatMetaTv -> Arity
4
{- Note [TyVar/TyVar orientation]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Given (a ~ b), should we orient the CTyEqCan as (a~b) or (b~a)?
This is a surprisingly tricky question!

First note: only swap if you have to!
   See Note [Avoid unnecessary swaps]

So we look for a positive reason to swap, using a three-step test:

* Level comparison. If 'a' has deeper level than 'b',
  put 'a' on the left.  See Note [Deeper level on the left]

* Priority.  If the levels are the same, look at what kind of
  type variable it is, using 'lhsPriority'

  - FlatMetaTv: Always put on the left.
    See Note [Fmv Orientation Invariant]
    NB: FlatMetaTvs always have the current level, never an
        outer one.  So nothing can be deeper than a FlatMetaTv


  - TyVarTv/TauTv: if we have  tyv_tv ~ tau_tv, put tau_tv
                   on the left because there are fewer
                   restrictions on updating TauTvs

  - TyVarTv/TauTv:  put on the left either
     a) Because it's touchable and can be unified, or
     b) Even if it's not touchable, TcSimplify.floatEqualities
        looks for meta tyvars on the left

  - FlatSkolTv: Put on the left in preference to a SkolemTv
                See Note [Eliminate flat-skols]

* Names. If the level and priority comparisons are all
  equal, try to eliminate a TyVars with a System Name in
  favour of ones with a Name derived from a user type signature

* Age.  At one point in the past we tried to break any remaining
  ties by eliminating the younger type variable, based on their
  Uniques.  See Note [Eliminate younger unification variables]
  (which also explains why we don't do this any more)

Note [Deeper level on the left]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The most important thing is that we want to put tyvars with
the deepest level on the left.  The reason to do so differs for
Wanteds and Givens, but either way, deepest wins!  Simple.

* Wanteds.  Putting the deepest variable on the left maximise the
  chances that it's a touchable meta-tyvar which can be solved.

* Givens. Suppose we have something like
     forall a[2]. b[1] ~ a[2] => beta[1] ~ a[2]

  If we orient the Given a[2] on the left, we'll rewrite the Wanted to
  (beta[1] ~ b[1]), and that can float out of the implication.
  Otherwise it can't.  By putting the deepest variable on the left
  we maximise our changes of eliminating skolem capture.

  See also TcSMonad Note [Let-bound skolems] for another reason
  to orient with the deepest skolem on the left.

  IMPORTANT NOTE: this test does a level-number comparison on
  skolems, so it's important that skolems have (accurate) level
  numbers.

See #15009 for an further analysis of why "deepest on the left"
is a good plan.

Note [Fmv Orientation Invariant]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   * We always orient a constraint
        fmv ~ alpha
     with fmv on the left, even if alpha is
     a touchable unification variable

Reason: doing it the other way round would unify alpha:=fmv, but that
really doesn't add any info to alpha.  But a later constraint alpha ~
Int might unlock everything.  Comment:9 of #12526 gives a detailed
example.

WARNING: I've gone to and fro on this one several times.
I'm now pretty sure that unifying alpha:=fmv is a bad idea!
So orienting with fmvs on the left is a good thing.

This example comes from IndTypesPerfMerge. (Others include
T10226, T10009.)
    From the ambiguity check for
      f :: (F a ~ a) => a
    we get:
          [G] F a ~ a
          [WD] F alpha ~ alpha, alpha ~ a

    From Givens we get
          [G] F a ~ fsk, fsk ~ a

    Now if we flatten we get
          [WD] alpha ~ fmv, F alpha ~ fmv, alpha ~ a

    Now, if we unified alpha := fmv, we'd get
          [WD] F fmv ~ fmv, [WD] fmv ~ a
    And now we are stuck.

So instead the Fmv Orientation Invariant puts the fmv on the
left, giving
      [WD] fmv ~ alpha, [WD] F alpha ~ fmv, [WD] alpha ~ a

    Now we get alpha:=a, and everything works out

Note [Eliminate flat-skols]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose we have  [G] Num (F [a])
then we flatten to
     [G] Num fsk
     [G] F [a] ~ fsk
where fsk is a flatten-skolem (FlatSkolTv). Suppose we have
      type instance F [a] = a
then we'll reduce the second constraint to
     [G] a ~ fsk
and then replace all uses of 'a' with fsk.  That's bad because
in error messages instead of saying 'a' we'll say (F [a]).  In all
places, including those where the programmer wrote 'a' in the first
place.  Very confusing!  See #7862.

Solution: re-orient a~fsk to fsk~a, so that we preferentially eliminate
the fsk.

Note [Avoid unnecessary swaps]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If we swap without actually improving matters, we can get an infinite loop.
Consider
    work item:  a ~ b
   inert item:  b ~ c
We canonicalise the work-item to (a ~ c).  If we then swap it before
adding to the inert set, we'll add (c ~ a), and therefore kick out the
inert guy, so we get
   new work item:  b ~ c
   inert item:     c ~ a
And now the cycle just repeats

Note [Eliminate younger unification variables]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Given a choice of unifying
     alpha := beta   or   beta := alpha
we try, if possible, to eliminate the "younger" one, as determined
by `ltUnique`.  Reason: the younger one is less likely to appear free in
an existing inert constraint, and hence we are less likely to be forced
into kicking out and rewriting inert constraints.

This is a performance optimisation only.  It turns out to fix
#14723 all by itself, but clearly not reliably so!

It's simple to implement (see nicer_to_update_tv2 in swapOverTyVars).
But, to my surprise, it didn't seem to make any significant difference
to the compiler's performance, so I didn't take it any further.  Still
it seemed to too nice to discard altogether, so I'm leaving these
notes.  SLPJ Jan 18.
-}

-- @trySpontaneousSolve wi@ solves equalities where one side is a
-- touchable unification variable.
-- Returns True <=> spontaneous solve happened
canSolveByUnification :: TcLevel -> TcTyVar -> TcType -> Bool
canSolveByUnification :: TcLevel -> Var -> TcType -> Bool
canSolveByUnification TcLevel
tclvl Var
tv TcType
xi
  | TcLevel -> Var -> Bool
isTouchableMetaTyVar TcLevel
tclvl Var
tv
  = case Var -> MetaInfo
metaTyVarInfo Var
tv of
      MetaInfo
TyVarTv -> TcType -> Bool
is_tyvar TcType
xi
      MetaInfo
_       -> Bool
True

  | Bool
otherwise    -- Untouchable
  = Bool
False
  where
    is_tyvar :: TcType -> Bool
is_tyvar TcType
xi
      = case TcType -> Maybe Var
tcGetTyVar_maybe TcType
xi of
          Maybe Var
Nothing -> Bool
False
          Just Var
tv -> case Var -> TcTyVarDetails
tcTyVarDetails Var
tv of
                       MetaTv { mtv_info :: TcTyVarDetails -> MetaInfo
mtv_info = MetaInfo
info }
                                   -> case MetaInfo
info of
                                        MetaInfo
TyVarTv -> Bool
True
                                        MetaInfo
_       -> Bool
False
                       SkolemTv {} -> Bool
True
                       TcTyVarDetails
RuntimeUnk  -> Bool
True

{- Note [Prevent unification with type families]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We prevent unification with type families because of an uneasy compromise.
It's perfectly sound to unify with type families, and it even improves the
error messages in the testsuite. It also modestly improves performance, at
least in some cases. But it's disastrous for test case perf/compiler/T3064.
Here is the problem: Suppose we have (F ty) where we also have [G] F ty ~ a.
What do we do? Do we reduce F? Or do we use the given? Hard to know what's
best. GHC reduces. This is a disaster for T3064, where the type's size
spirals out of control during reduction. (We're not helped by the fact that
the flattener re-flattens all the arguments every time around.) If we prevent
unification with type families, then the solver happens to use the equality
before expanding the type family.

It would be lovely in the future to revisit this problem and remove this
extra, unnecessary check. But we retain it for now as it seems to work
better in practice.

Note [Refactoring hazard: checkTauTvUpdate]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
I (Richard E.) have a sad story about refactoring this code, retained here
to prevent others (or a future me!) from falling into the same traps.

It all started with #11407, which was caused by the fact that the TyVarTy
case of defer_me didn't look in the kind. But it seemed reasonable to
simply remove the defer_me check instead.

It referred to two Notes (since removed) that were out of date, and the
fast_check code in occurCheckExpand seemed to do just about the same thing as
defer_me. The one piece that defer_me did that wasn't repeated by
occurCheckExpand was the type-family check. (See Note [Prevent unification
with type families].) So I checked the result of occurCheckExpand for any
type family occurrences and deferred if there were any. This was done
in commit e9bf7bb5cc9fb3f87dd05111aa23da76b86a8967 .

This approach turned out not to be performant, because the expanded
type was bigger than the original type, and tyConsOfType (needed to
see if there are any type family occurrences) looks through type
synonyms. So it then struck me that we could dispense with the
defer_me check entirely. This simplified the code nicely, and it cut
the allocations in T5030 by half. But, as documented in Note [Prevent
unification with type families], this destroyed performance in
T3064. Regardless, I missed this regression and the change was
committed as 3f5d1a13f112f34d992f6b74656d64d95a3f506d .

Bottom lines:
 * defer_me is back, but now fixed w.r.t. #11407.
 * Tread carefully before you start to refactor here. There can be
   lots of hard-to-predict consequences.

Note [Type synonyms and the occur check]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Generally speaking we try to update a variable with type synonyms not
expanded, which improves later error messages, unless looking
inside a type synonym may help resolve a spurious occurs check
error. Consider:
          type A a = ()

          f :: (A a -> a -> ()) -> ()
          f = \ _ -> ()

          x :: ()
          x = f (\ x p -> p x)

We will eventually get a constraint of the form t ~ A t. The ok function above will
properly expand the type (A t) to just (), which is ok to be unified with t. If we had
unified with the original type A t, we would lead the type checker into an infinite loop.

Hence, if the occurs check fails for a type synonym application, then (and *only* then),
the ok function expands the synonym to detect opportunities for occurs check success using
the underlying definition of the type synonym.

The same applies later on in the constraint interaction code; see TcInteract,
function @occ_check_ok@.

Note [Non-TcTyVars in TcUnify]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Because the same code is now shared between unifying types and unifying
kinds, we sometimes will see proper TyVars floating around the unifier.
Example (from test case polykinds/PolyKinds12):

    type family Apply (f :: k1 -> k2) (x :: k1) :: k2
    type instance Apply g y = g y

When checking the instance declaration, we first *kind-check* the LHS
and RHS, discovering that the instance really should be

    type instance Apply k3 k4 (g :: k3 -> k4) (y :: k3) = g y

During this kind-checking, all the tyvars will be TcTyVars. Then, however,
as a second pass, we desugar the RHS (which is done in functions prefixed
with "tc" in TcTyClsDecls"). By this time, all the kind-vars are proper
TyVars, not TcTyVars, get some kind unification must happen.

Thus, we always check if a TyVar is a TcTyVar before asking if it's a
meta-tyvar.

This used to not be necessary for type-checking (that is, before * :: *)
because expressions get desugared via an algorithm separate from
type-checking (with wrappers, etc.). Types get desugared very differently,
causing this wibble in behavior seen here.
-}

data LookupTyVarResult  -- The result of a lookupTcTyVar call
  = Unfilled TcTyVarDetails     -- SkolemTv or virgin MetaTv
  | Filled   TcType

lookupTcTyVar :: TcTyVar -> TcM LookupTyVarResult
lookupTcTyVar :: Var -> TcM LookupTyVarResult
lookupTcTyVar Var
tyvar
  | MetaTv { mtv_ref :: TcTyVarDetails -> IORef MetaDetails
mtv_ref = IORef MetaDetails
ref } <- TcTyVarDetails
details
  = do { MetaDetails
meta_details <- IORef MetaDetails -> TcM MetaDetails
forall a env. IORef a -> IOEnv env a
readMutVar IORef MetaDetails
ref
       ; case MetaDetails
meta_details of
           Indirect TcType
ty -> LookupTyVarResult -> TcM LookupTyVarResult
forall (m :: * -> *) a. Monad m => a -> m a
return (TcType -> LookupTyVarResult
Filled TcType
ty)
           MetaDetails
Flexi -> do { Bool
is_touchable <- Var -> TcM Bool
isTouchableTcM Var
tyvar
                             -- Note [Unifying untouchables]
                       ; if Bool
is_touchable then
                            LookupTyVarResult -> TcM LookupTyVarResult
forall (m :: * -> *) a. Monad m => a -> m a
return (TcTyVarDetails -> LookupTyVarResult
Unfilled TcTyVarDetails
details)
                         else
                            LookupTyVarResult -> TcM LookupTyVarResult
forall (m :: * -> *) a. Monad m => a -> m a
return (TcTyVarDetails -> LookupTyVarResult
Unfilled TcTyVarDetails
vanillaSkolemTv) } }
  | Bool
otherwise
  = LookupTyVarResult -> TcM LookupTyVarResult
forall (m :: * -> *) a. Monad m => a -> m a
return (TcTyVarDetails -> LookupTyVarResult
Unfilled TcTyVarDetails
details)
  where
    details :: TcTyVarDetails
details = Var -> TcTyVarDetails
tcTyVarDetails Var
tyvar

{-
Note [Unifying untouchables]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We treat an untouchable type variable as if it was a skolem.  That
ensures it won't unify with anything.  It's a slight hack, because
we return a made-up TcTyVarDetails, but I think it works smoothly.
-}

-- | Breaks apart a function kind into its pieces.
matchExpectedFunKind
  :: Outputable fun
  => fun             -- ^ type, only for errors
  -> Arity           -- ^ n: number of desired arrows
  -> TcKind          -- ^ fun_ kind
  -> TcM Coercion    -- ^ co :: fun_kind ~ (arg1 -> ... -> argn -> res)

matchExpectedFunKind :: fun -> Arity -> TcType -> TcM TcCoercionN
matchExpectedFunKind fun
hs_ty Arity
n TcType
k = Arity -> TcType -> TcM TcCoercionN
go Arity
n TcType
k
  where
    go :: Arity -> TcType -> TcM TcCoercionN
go Arity
0 TcType
k = TcCoercionN -> TcM TcCoercionN
forall (m :: * -> *) a. Monad m => a -> m a
return (TcType -> TcCoercionN
mkNomReflCo TcType
k)

    go Arity
n TcType
k | Just TcType
k' <- TcType -> Maybe TcType
tcView TcType
k = Arity -> TcType -> TcM TcCoercionN
go Arity
n TcType
k'

    go Arity
n k :: TcType
k@(TyVarTy Var
kvar)
      | Var -> Bool
isMetaTyVar Var
kvar
      = do { MetaDetails
maybe_kind <- Var -> TcM MetaDetails
readMetaTyVar Var
kvar
           ; case MetaDetails
maybe_kind of
                Indirect TcType
fun_kind -> Arity -> TcType -> TcM TcCoercionN
go Arity
n TcType
fun_kind
                MetaDetails
Flexi ->             Arity -> TcType -> TcM TcCoercionN
defer Arity
n TcType
k }

    go Arity
n (FunTy AnonArgFlag
_ TcType
arg TcType
res)
      = do { TcCoercionN
co <- Arity -> TcType -> TcM TcCoercionN
go (Arity
nArity -> Arity -> Arity
forall a. Num a => a -> a -> a
-Arity
1) TcType
res
           ; TcCoercionN -> TcM TcCoercionN
forall (m :: * -> *) a. Monad m => a -> m a
return (Role -> TcCoercionN -> TcCoercionN -> TcCoercionN
mkTcFunCo Role
Nominal (TcType -> TcCoercionN
mkTcNomReflCo TcType
arg) TcCoercionN
co) }

    go Arity
n TcType
other
     = Arity -> TcType -> TcM TcCoercionN
defer Arity
n TcType
other

    defer :: Arity -> TcType -> TcM TcCoercionN
defer Arity
n TcType
k
      = do { [TcType]
arg_kinds <- Arity -> IOEnv (Env TcGblEnv TcLclEnv) [TcType]
newMetaKindVars Arity
n
           ; TcType
res_kind  <- IOEnv (Env TcGblEnv TcLclEnv) TcType
newMetaKindVar
           ; let new_fun :: TcType
new_fun = [TcType] -> TcType -> TcType
mkVisFunTys [TcType]
arg_kinds TcType
res_kind
                 origin :: CtOrigin
origin  = TypeEqOrigin :: TcType -> TcType -> Maybe SDoc -> Bool -> CtOrigin
TypeEqOrigin { uo_actual :: TcType
uo_actual   = TcType
k
                                        , uo_expected :: TcType
uo_expected = TcType
new_fun
                                        , uo_thing :: Maybe SDoc
uo_thing    = SDoc -> Maybe SDoc
forall a. a -> Maybe a
Just (fun -> SDoc
forall a. Outputable a => a -> SDoc
ppr fun
hs_ty)
                                        , uo_visible :: Bool
uo_visible  = Bool
True
                                        }
           ; TypeOrKind -> CtOrigin -> TcType -> TcType -> TcM TcCoercionN
uType TypeOrKind
KindLevel CtOrigin
origin TcType
k TcType
new_fun }

{- *********************************************************************
*                                                                      *
                 Occurrence checking
*                                                                      *
********************************************************************* -}


{-  Note [Occurrence checking: look inside kinds]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose we are considering unifying
   (alpha :: *)  ~  Int -> (beta :: alpha -> alpha)
This may be an error (what is that alpha doing inside beta's kind?),
but we must not make the mistake of actually unifying or we'll
build an infinite data structure.  So when looking for occurrences
of alpha in the rhs, we must look in the kinds of type variables
that occur there.

NB: we may be able to remove the problem via expansion; see
    Note [Occurs check expansion].  So we have to try that.

Note [Checking for foralls]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Unless we have -XImpredicativeTypes (which is a totally unsupported
feature), we do not want to unify
    alpha ~ (forall a. a->a) -> Int
So we look for foralls hidden inside the type, and it's convenient
to do that at the same time as the occurs check (which looks for
occurrences of alpha).

However, it's not just a question of looking for foralls /anywhere/!
Consider
   (alpha :: forall k. k->*)  ~  (beta :: forall k. k->*)
This is legal; e.g. dependent/should_compile/T11635.

We don't want to reject it because of the forall in beta's kind,
but (see Note [Occurrence checking: look inside kinds]) we do
need to look in beta's kind.  So we carry a flag saying if a 'forall'
is OK, and sitch the flag on when stepping inside a kind.

Why is it OK?  Why does it not count as impredicative polymorphism?
The reason foralls are bad is because we reply on "seeing" foralls
when doing implicit instantiation.  But the forall inside the kind is
fine.  We'll generate a kind equality constraint
  (forall k. k->*) ~ (forall k. k->*)
to check that the kinds of lhs and rhs are compatible.  If alpha's
kind had instead been
  (alpha :: kappa)
then this kind equality would rightly complain about unifying kappa
with (forall k. k->*)

-}

data MetaTyVarUpdateResult a
  = MTVU_OK a
  | MTVU_Bad     -- Forall, predicate, or type family
  | MTVU_Occurs
    deriving (a -> MetaTyVarUpdateResult b -> MetaTyVarUpdateResult a
(a -> b) -> MetaTyVarUpdateResult a -> MetaTyVarUpdateResult b
(forall a b.
 (a -> b) -> MetaTyVarUpdateResult a -> MetaTyVarUpdateResult b)
-> (forall a b.
    a -> MetaTyVarUpdateResult b -> MetaTyVarUpdateResult a)
-> Functor MetaTyVarUpdateResult
forall a b. a -> MetaTyVarUpdateResult b -> MetaTyVarUpdateResult a
forall a b.
(a -> b) -> MetaTyVarUpdateResult a -> MetaTyVarUpdateResult b
forall (f :: * -> *).
(forall a b. (a -> b) -> f a -> f b)
-> (forall a b. a -> f b -> f a) -> Functor f
<$ :: a -> MetaTyVarUpdateResult b -> MetaTyVarUpdateResult a
$c<$ :: forall a b. a -> MetaTyVarUpdateResult b -> MetaTyVarUpdateResult a
fmap :: (a -> b) -> MetaTyVarUpdateResult a -> MetaTyVarUpdateResult b
$cfmap :: forall a b.
(a -> b) -> MetaTyVarUpdateResult a -> MetaTyVarUpdateResult b
Functor)

instance Applicative MetaTyVarUpdateResult where
      pure :: a -> MetaTyVarUpdateResult a
pure = a -> MetaTyVarUpdateResult a
forall a. a -> MetaTyVarUpdateResult a
MTVU_OK
      <*> :: MetaTyVarUpdateResult (a -> b)
-> MetaTyVarUpdateResult a -> MetaTyVarUpdateResult b
(<*>) = MetaTyVarUpdateResult (a -> b)
-> MetaTyVarUpdateResult a -> MetaTyVarUpdateResult b
forall (m :: * -> *) a b. Monad m => m (a -> b) -> m a -> m b
ap

instance Monad MetaTyVarUpdateResult where
  MTVU_OK a
x    >>= :: MetaTyVarUpdateResult a
-> (a -> MetaTyVarUpdateResult b) -> MetaTyVarUpdateResult b
>>= a -> MetaTyVarUpdateResult b
k = a -> MetaTyVarUpdateResult b
k a
x
  MetaTyVarUpdateResult a
MTVU_Bad     >>= a -> MetaTyVarUpdateResult b
_ = MetaTyVarUpdateResult b
forall a. MetaTyVarUpdateResult a
MTVU_Bad
  MetaTyVarUpdateResult a
MTVU_Occurs  >>= a -> MetaTyVarUpdateResult b
_ = MetaTyVarUpdateResult b
forall a. MetaTyVarUpdateResult a
MTVU_Occurs

occCheckForErrors :: DynFlags -> TcTyVar -> Type -> MetaTyVarUpdateResult ()
-- Just for error-message generation; so we return MetaTyVarUpdateResult
-- so the caller can report the right kind of error
-- Check whether
--   a) the given variable occurs in the given type.
--   b) there is a forall in the type (unless we have -XImpredicativeTypes)
occCheckForErrors :: DynFlags -> Var -> TcType -> MetaTyVarUpdateResult ()
occCheckForErrors DynFlags
dflags Var
tv TcType
ty
  = case DynFlags -> Bool -> Var -> TcType -> MetaTyVarUpdateResult ()
preCheck DynFlags
dflags Bool
True Var
tv TcType
ty of
      MTVU_OK ()
_   -> () -> MetaTyVarUpdateResult ()
forall a. a -> MetaTyVarUpdateResult a
MTVU_OK ()
      MetaTyVarUpdateResult ()
MTVU_Bad    -> MetaTyVarUpdateResult ()
forall a. MetaTyVarUpdateResult a
MTVU_Bad
      MetaTyVarUpdateResult ()
MTVU_Occurs -> case [Var] -> TcType -> Maybe TcType
occCheckExpand [Var
tv] TcType
ty of
                       Maybe TcType
Nothing -> MetaTyVarUpdateResult ()
forall a. MetaTyVarUpdateResult a
MTVU_Occurs
                       Just TcType
_  -> () -> MetaTyVarUpdateResult ()
forall a. a -> MetaTyVarUpdateResult a
MTVU_OK ()

----------------
metaTyVarUpdateOK :: DynFlags
                  -> TcTyVar             -- tv :: k1
                  -> TcType              -- ty :: k2
                  -> Maybe TcType        -- possibly-expanded ty
-- (metaTyVarUpdateOK tv ty)
-- We are about to update the meta-tyvar tv with ty
-- Check (a) that tv doesn't occur in ty (occurs check)
--       (b) that ty does not have any foralls
--           (in the impredicative case), or type functions
--
-- We have two possible outcomes:
-- (1) Return the type to update the type variable with,
--        [we know the update is ok]
-- (2) Return Nothing,
--        [the update might be dodgy]
--
-- Note that "Nothing" does not mean "definite error".  For example
--   type family F a
--   type instance F Int = Int
-- consider
--   a ~ F a
-- This is perfectly reasonable, if we later get a ~ Int.  For now, though,
-- we return Nothing, leaving it to the later constraint simplifier to
-- sort matters out.
--
-- See Note [Refactoring hazard: checkTauTvUpdate]

metaTyVarUpdateOK :: DynFlags -> Var -> TcType -> Maybe TcType
metaTyVarUpdateOK DynFlags
dflags Var
tv TcType
ty
  = case DynFlags -> Bool -> Var -> TcType -> MetaTyVarUpdateResult ()
preCheck DynFlags
dflags Bool
False Var
tv TcType
ty of
         -- False <=> type families not ok
         -- See Note [Prevent unification with type families]
      MTVU_OK ()
_   -> TcType -> Maybe TcType
forall a. a -> Maybe a
Just TcType
ty
      MetaTyVarUpdateResult ()
MTVU_Bad    -> Maybe TcType
forall a. Maybe a
Nothing  -- forall, predicate, or type function
      MetaTyVarUpdateResult ()
MTVU_Occurs -> [Var] -> TcType -> Maybe TcType
occCheckExpand [Var
tv] TcType
ty

preCheck :: DynFlags -> Bool -> TcTyVar -> TcType -> MetaTyVarUpdateResult ()
-- A quick check for
--   (a) a forall type (unless -XImpredicativeTypes)
--   (b) a predicate type (unless -XImpredicativeTypes)
--   (c) a type family
--   (d) an occurrence of the type variable (occurs check)
--
-- For (a), (b), and (c) we check only the top level of the type, NOT
-- inside the kinds of variables it mentions.  But for (c) we do
-- look in the kinds of course.

preCheck :: DynFlags -> Bool -> Var -> TcType -> MetaTyVarUpdateResult ()
preCheck DynFlags
dflags Bool
ty_fam_ok Var
tv TcType
ty
  = TcType -> MetaTyVarUpdateResult ()
fast_check TcType
ty
  where
    details :: TcTyVarDetails
details          = Var -> TcTyVarDetails
tcTyVarDetails Var
tv
    impredicative_ok :: Bool
impredicative_ok = DynFlags -> TcTyVarDetails -> Bool
canUnifyWithPolyType DynFlags
dflags TcTyVarDetails
details

    ok :: MetaTyVarUpdateResult ()
    ok :: MetaTyVarUpdateResult ()
ok = () -> MetaTyVarUpdateResult ()
forall a. a -> MetaTyVarUpdateResult a
MTVU_OK ()

    fast_check :: TcType -> MetaTyVarUpdateResult ()
    fast_check :: TcType -> MetaTyVarUpdateResult ()
fast_check (TyVarTy Var
tv')
      | Var
tv Var -> Var -> Bool
forall a. Eq a => a -> a -> Bool
== Var
tv' = MetaTyVarUpdateResult ()
forall a. MetaTyVarUpdateResult a
MTVU_Occurs
      | Bool
otherwise = TcType -> MetaTyVarUpdateResult ()
fast_check_occ (Var -> TcType
tyVarKind Var
tv')
           -- See Note [Occurrence checking: look inside kinds]

    fast_check (TyConApp TyCon
tc [TcType]
tys)
      | TyCon -> Bool
bad_tc TyCon
tc              = MetaTyVarUpdateResult ()
forall a. MetaTyVarUpdateResult a
MTVU_Bad
      | Bool
otherwise              = (TcType -> MetaTyVarUpdateResult ())
-> [TcType] -> MetaTyVarUpdateResult [()]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM TcType -> MetaTyVarUpdateResult ()
fast_check [TcType]
tys MetaTyVarUpdateResult [()]
-> MetaTyVarUpdateResult () -> MetaTyVarUpdateResult ()
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> MetaTyVarUpdateResult ()
ok
    fast_check (LitTy {})      = MetaTyVarUpdateResult ()
ok
    fast_check (FunTy{ft_af :: TcType -> AnonArgFlag
ft_af = AnonArgFlag
af, ft_arg :: TcType -> TcType
ft_arg = TcType
a, ft_res :: TcType -> TcType
ft_res = TcType
r})
      | AnonArgFlag
InvisArg <- AnonArgFlag
af
      , Bool -> Bool
not Bool
impredicative_ok   = MetaTyVarUpdateResult ()
forall a. MetaTyVarUpdateResult a
MTVU_Bad
      | Bool
otherwise              = TcType -> MetaTyVarUpdateResult ()
fast_check TcType
a   MetaTyVarUpdateResult ()
-> MetaTyVarUpdateResult () -> MetaTyVarUpdateResult ()
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> TcType -> MetaTyVarUpdateResult ()
fast_check TcType
r
    fast_check (AppTy TcType
fun TcType
arg) = TcType -> MetaTyVarUpdateResult ()
fast_check TcType
fun MetaTyVarUpdateResult ()
-> MetaTyVarUpdateResult () -> MetaTyVarUpdateResult ()
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> TcType -> MetaTyVarUpdateResult ()
fast_check TcType
arg
    fast_check (CastTy TcType
ty TcCoercionN
co)  = TcType -> MetaTyVarUpdateResult ()
fast_check TcType
ty  MetaTyVarUpdateResult ()
-> MetaTyVarUpdateResult () -> MetaTyVarUpdateResult ()
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> TcCoercionN -> MetaTyVarUpdateResult ()
fast_check_co TcCoercionN
co
    fast_check (CoercionTy TcCoercionN
co) = TcCoercionN -> MetaTyVarUpdateResult ()
fast_check_co TcCoercionN
co
    fast_check (ForAllTy (Bndr Var
tv' ArgFlag
_) TcType
ty)
       | Bool -> Bool
not Bool
impredicative_ok = MetaTyVarUpdateResult ()
forall a. MetaTyVarUpdateResult a
MTVU_Bad
       | Var
tv Var -> Var -> Bool
forall a. Eq a => a -> a -> Bool
== Var
tv'            = MetaTyVarUpdateResult ()
ok
       | Bool
otherwise = do { TcType -> MetaTyVarUpdateResult ()
fast_check_occ (Var -> TcType
tyVarKind Var
tv')
                        ; TcType -> MetaTyVarUpdateResult ()
fast_check_occ TcType
ty }
       -- Under a forall we look only for occurrences of
       -- the type variable

     -- For kinds, we only do an occurs check; we do not worry
     -- about type families or foralls
     -- See Note [Checking for foralls]
    fast_check_occ :: TcType -> MetaTyVarUpdateResult ()
fast_check_occ TcType
k | Var
tv Var -> VarSet -> Bool
`elemVarSet` TcType -> VarSet
tyCoVarsOfType TcType
k = MetaTyVarUpdateResult ()
forall a. MetaTyVarUpdateResult a
MTVU_Occurs
                     | Bool
otherwise                        = MetaTyVarUpdateResult ()
ok

     -- For coercions, we are only doing an occurs check here;
     -- no bother about impredicativity in coercions, as they're
     -- inferred
    fast_check_co :: TcCoercionN -> MetaTyVarUpdateResult ()
fast_check_co TcCoercionN
co | Var
tv Var -> VarSet -> Bool
`elemVarSet` TcCoercionN -> VarSet
tyCoVarsOfCo TcCoercionN
co = MetaTyVarUpdateResult ()
forall a. MetaTyVarUpdateResult a
MTVU_Occurs
                     | Bool
otherwise                       = MetaTyVarUpdateResult ()
ok

    bad_tc :: TyCon -> Bool
    bad_tc :: TyCon -> Bool
bad_tc TyCon
tc
      | Bool -> Bool
not (Bool
impredicative_ok Bool -> Bool -> Bool
|| TyCon -> Bool
isTauTyCon TyCon
tc)     = Bool
True
      | Bool -> Bool
not (Bool
ty_fam_ok        Bool -> Bool -> Bool
|| TyCon -> Bool
isFamFreeTyCon TyCon
tc) = Bool
True
      | Bool
otherwise                                   = Bool
False

canUnifyWithPolyType :: DynFlags -> TcTyVarDetails -> Bool
canUnifyWithPolyType :: DynFlags -> TcTyVarDetails -> Bool
canUnifyWithPolyType DynFlags
dflags TcTyVarDetails
details
  = case TcTyVarDetails
details of
      MetaTv { mtv_info :: TcTyVarDetails -> MetaInfo
mtv_info = MetaInfo
TyVarTv }    -> Bool
False
      MetaTv { mtv_info :: TcTyVarDetails -> MetaInfo
mtv_info = MetaInfo
TauTv }      -> Extension -> DynFlags -> Bool
xopt Extension
LangExt.ImpredicativeTypes DynFlags
dflags
      TcTyVarDetails
_other                           -> Bool
True
          -- We can have non-meta tyvars in given constraints