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

{-# OPTIONS_GHC -Wno-incomplete-uni-patterns   #-}
{-# OPTIONS_GHC -Wno-incomplete-record-updates #-}

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

-- | Type subsumption and unification
module GHC.Tc.Utils.Unify (
  -- Full-blown subsumption
  tcWrapResult, tcWrapResultO, tcWrapResultMono,
  tcSkolemise, tcSkolemiseScoped, tcSkolemiseET,
  tcSubType, tcSubTypeSigma, tcSubTypePat,
  tcSubMult,
  checkConstraints, checkTvConstraints,
  buildImplicationFor, buildTvImplication, emitResidualTvConstraint,

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

  --------------------------------
  -- Holes
  tcInfer,
  matchExpectedListTy,
  matchExpectedTyConApp,
  matchExpectedAppTy,
  matchExpectedFunTys,
  matchExpectedFunKind,
  matchActualFunTySigma, matchActualFunTysRho,

  occCheckForErrors, CheckTyEqResult(..),
  checkTyVarEq, checkTyFamEq, checkTypeEq, AreTypeFamiliesOK(..)

  ) where

#include "GhclibHsVersions.h"

import GHC.Prelude

import GHC.Hs
import GHC.Core.TyCo.Rep
import GHC.Core.TyCo.Ppr( debugPprType )
import GHC.Tc.Utils.TcMType
import GHC.Tc.Utils.Monad
import GHC.Tc.Utils.TcType
import GHC.Tc.Utils.Env
import GHC.Core.Type
import GHC.Core.Coercion
import GHC.Core.Multiplicity
import GHC.Tc.Types.Evidence
import GHC.Tc.Types.Constraint
import GHC.Core.Predicate
import GHC.Tc.Types.Origin
import GHC.Types.Name( isSystemName )
import GHC.Tc.Utils.Instantiate
import GHC.Core.TyCon
import GHC.Builtin.Types
import GHC.Types.Var as Var
import GHC.Types.Var.Set
import GHC.Types.Var.Env
import GHC.Utils.Error
import GHC.Driver.Session
import GHC.Types.Basic
import GHC.Data.Bag
import GHC.Utils.Misc
import GHC.Utils.Outputable as Outputable
import GHC.Utils.Panic

import GHC.Exts      ( inline )
import Control.Monad
import Control.Arrow ( second )
import qualified Data.Semigroup as S


{- *********************************************************************
*                                                                      *
              matchActualFunTys
*                                                                      *
********************************************************************* -}

-- | matchActualFunTySigma does looks for just one function arrow
--   returning an uninstantiated sigma-type
matchActualFunTySigma
  :: SDoc -- See Note [Herald for matchExpectedFunTys]
  -> Maybe SDoc                    -- The thing with type TcSigmaType
  -> (Arity, [Scaled TcSigmaType]) -- Total number of value args in the call, and
                                   -- types of values args to which function has
                                   --   been applied already (reversed)
                                   -- Both are used only for error messages)
  -> TcRhoType                     -- Type to analyse: a TcRhoType
  -> TcM (HsWrapper, Scaled TcSigmaType, TcSigmaType)
-- The /argument/ is a RhoType
-- The /result/   is an (uninstantiated) SigmaType
--
-- See Note [matchActualFunTy error handling] for the first three arguments

-- If   (wrap, arg_ty, res_ty) = matchActualFunTySigma ... fun_ty
-- then wrap :: fun_ty ~> (arg_ty -> res_ty)
-- and NB: res_ty is an (uninstantiated) SigmaType

matchActualFunTySigma :: SDoc
-> Maybe SDoc
-> (Arity, [Scaled TcSigmaType])
-> TcSigmaType
-> TcM (HsWrapper, Scaled TcSigmaType, TcSigmaType)
matchActualFunTySigma SDoc
herald Maybe SDoc
mb_thing (Arity, [Scaled TcSigmaType])
err_info TcSigmaType
fun_ty
  = ASSERT2( isRhoTy fun_ty, ppr fun_ty )
    TcSigmaType -> TcM (HsWrapper, Scaled TcSigmaType, TcSigmaType)
go TcSigmaType
fun_ty
  where
    -- 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
    go :: TcRhoType   -- The type we're processing, perhaps after
                      -- expanding any type synonym
       -> TcM (HsWrapper, Scaled TcSigmaType, TcSigmaType)
    go :: TcSigmaType -> TcM (HsWrapper, Scaled TcSigmaType, TcSigmaType)
go TcSigmaType
ty | Just TcSigmaType
ty' <- TcSigmaType -> Maybe TcSigmaType
tcView TcSigmaType
ty = TcSigmaType -> TcM (HsWrapper, Scaled TcSigmaType, TcSigmaType)
go TcSigmaType
ty'

    go (FunTy { ft_af :: TcSigmaType -> AnonArgFlag
ft_af = AnonArgFlag
af, ft_mult :: TcSigmaType -> TcSigmaType
ft_mult = TcSigmaType
w, ft_arg :: TcSigmaType -> TcSigmaType
ft_arg = TcSigmaType
arg_ty, ft_res :: TcSigmaType -> TcSigmaType
ft_res = TcSigmaType
res_ty })
      = ASSERT( af == VisArg )
        (HsWrapper, Scaled TcSigmaType, TcSigmaType)
-> TcM (HsWrapper, Scaled TcSigmaType, TcSigmaType)
forall (m :: * -> *) a. Monad m => a -> m a
return (HsWrapper
idHsWrapper, TcSigmaType -> TcSigmaType -> Scaled TcSigmaType
forall a. TcSigmaType -> a -> Scaled a
Scaled TcSigmaType
w TcSigmaType
arg_ty, TcSigmaType
res_ty)

    go ty :: TcSigmaType
ty@(TyVarTy Var
tv)
      | Var -> Bool
isMetaTyVar Var
tv
      = do { MetaDetails
cts <- Var -> TcM MetaDetails
readMetaTyVar Var
tv
           ; case MetaDetails
cts of
               Indirect TcSigmaType
ty' -> TcSigmaType -> TcM (HsWrapper, Scaled TcSigmaType, TcSigmaType)
go TcSigmaType
ty'
               MetaDetails
Flexi        -> TcSigmaType -> TcM (HsWrapper, Scaled TcSigmaType, TcSigmaType)
defer TcSigmaType
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 TcSigmaType
ty = (TidyEnv -> TcM (TidyEnv, SDoc))
-> TcM (HsWrapper, Scaled TcSigmaType, TcSigmaType)
-> TcM (HsWrapper, Scaled TcSigmaType, TcSigmaType)
forall a. (TidyEnv -> TcM (TidyEnv, SDoc)) -> TcM a -> TcM a
addErrCtxtM (TcSigmaType -> TidyEnv -> TcM (TidyEnv, SDoc)
mk_ctxt TcSigmaType
ty) (TcSigmaType -> TcM (HsWrapper, Scaled TcSigmaType, TcSigmaType)
defer TcSigmaType
ty)

    ------------
    defer :: TcSigmaType -> TcM (HsWrapper, Scaled TcSigmaType, TcSigmaType)
defer TcSigmaType
fun_ty
      = do { TcSigmaType
arg_ty <- TcM TcSigmaType
newOpenFlexiTyVarTy
           ; TcSigmaType
res_ty <- TcM TcSigmaType
newOpenFlexiTyVarTy
           ; TcSigmaType
mult <- TcSigmaType -> TcM TcSigmaType
newFlexiTyVarTy TcSigmaType
multiplicityTy
           ; let unif_fun_ty :: TcSigmaType
unif_fun_ty = TcSigmaType -> TcSigmaType -> TcSigmaType -> TcSigmaType
mkVisFunTy TcSigmaType
mult TcSigmaType
arg_ty TcSigmaType
res_ty
           ; TcCoercionN
co <- Maybe SDoc -> TcSigmaType -> TcSigmaType -> TcM TcCoercionN
unifyType Maybe SDoc
mb_thing TcSigmaType
fun_ty TcSigmaType
unif_fun_ty
           ; (HsWrapper, Scaled TcSigmaType, TcSigmaType)
-> TcM (HsWrapper, Scaled TcSigmaType, TcSigmaType)
forall (m :: * -> *) a. Monad m => a -> m a
return (TcCoercionN -> HsWrapper
mkWpCastN TcCoercionN
co, TcSigmaType -> TcSigmaType -> Scaled TcSigmaType
forall a. TcSigmaType -> a -> Scaled a
Scaled TcSigmaType
mult TcSigmaType
arg_ty, TcSigmaType
res_ty) }

    ------------
    mk_ctxt :: TcType -> TidyEnv -> TcM (TidyEnv, SDoc)
    mk_ctxt :: TcSigmaType -> TidyEnv -> TcM (TidyEnv, SDoc)
mk_ctxt TcSigmaType
res_ty TidyEnv
env = TidyEnv
-> SDoc
-> [Scaled TcSigmaType]
-> TcSigmaType
-> Arity
-> TcM (TidyEnv, SDoc)
mkFunTysMsg TidyEnv
env SDoc
herald ([Scaled TcSigmaType] -> [Scaled TcSigmaType]
forall a. [a] -> [a]
reverse [Scaled TcSigmaType]
arg_tys_so_far)
                                     TcSigmaType
res_ty Arity
n_val_args_in_call
    (Arity
n_val_args_in_call, [Scaled TcSigmaType]
arg_tys_so_far) = (Arity, [Scaled TcSigmaType])
err_info

{- Note [matchActualFunTy error handling]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
matchActualFunTySigma is made much more complicated by the
desire to produce good error messages. Consider the application
    f @Int x y
In GHC.Tc.Gen.Expr.tcArgs we deal with visible type arguments,
and then call matchActualFunTysPart for each individual value
argument. It, in turn, must instantiate any type/dictionary args,
before looking for an arrow type.

But if it doesn't find an arrow type, it wants to generate a message
like "f is applied to two arguments but its type only has one".
To do that, it needs to know about the args that tcArgs has already
munched up -- hence passing in n_val_args_in_call and arg_tys_so_far;
and hence also the accumulating so_far arg to 'go'.

This allows us (in mk_ctxt) to construct f's /instantiated/ type,
with just the values-arg arrows, which is what we really want
in the error message.

Ugh!
-}

-- Like 'matchExpectedFunTys', but used when you have an "actual" type,
-- for example in function application
matchActualFunTysRho :: SDoc   -- See Note [Herald for matchExpectedFunTys]
                     -> CtOrigin
                     -> Maybe SDoc  -- the thing with type TcSigmaType
                     -> Arity
                     -> TcSigmaType
                     -> TcM (HsWrapper, [Scaled TcSigmaType], TcRhoType)
-- If    matchActualFunTysRho n ty = (wrap, [t1,..,tn], res_ty)
-- then  wrap : ty ~> (t1 -> ... -> tn -> res_ty)
--       and res_ty is a RhoType
-- NB: the returned type is top-instantiated; it's a RhoType
matchActualFunTysRho :: SDoc
-> CtOrigin
-> Maybe SDoc
-> Arity
-> TcSigmaType
-> TcM (HsWrapper, [Scaled TcSigmaType], TcSigmaType)
matchActualFunTysRho SDoc
herald CtOrigin
ct_orig Maybe SDoc
mb_thing Arity
n_val_args_wanted TcSigmaType
fun_ty
  = Arity
-> [Scaled TcSigmaType]
-> TcSigmaType
-> TcM (HsWrapper, [Scaled TcSigmaType], TcSigmaType)
go Arity
n_val_args_wanted [] TcSigmaType
fun_ty
  where
    go :: Arity
-> [Scaled TcSigmaType]
-> TcSigmaType
-> TcM (HsWrapper, [Scaled TcSigmaType], TcSigmaType)
go Arity
n [Scaled TcSigmaType]
so_far TcSigmaType
fun_ty
      | Bool -> Bool
not (TcSigmaType -> Bool
isRhoTy TcSigmaType
fun_ty)
      = do { (HsWrapper
wrap1, TcSigmaType
rho) <- CtOrigin -> TcSigmaType -> TcM (HsWrapper, TcSigmaType)
topInstantiate CtOrigin
ct_orig TcSigmaType
fun_ty
           ; (HsWrapper
wrap2, [Scaled TcSigmaType]
arg_tys, TcSigmaType
res_ty) <- Arity
-> [Scaled TcSigmaType]
-> TcSigmaType
-> TcM (HsWrapper, [Scaled TcSigmaType], TcSigmaType)
go Arity
n [Scaled TcSigmaType]
so_far TcSigmaType
rho
           ; (HsWrapper, [Scaled TcSigmaType], TcSigmaType)
-> TcM (HsWrapper, [Scaled TcSigmaType], TcSigmaType)
forall (m :: * -> *) a. Monad m => a -> m a
return (HsWrapper
wrap2 HsWrapper -> HsWrapper -> HsWrapper
<.> HsWrapper
wrap1, [Scaled TcSigmaType]
arg_tys, TcSigmaType
res_ty) }

    go Arity
0 [Scaled TcSigmaType]
_ TcSigmaType
fun_ty = (HsWrapper, [Scaled TcSigmaType], TcSigmaType)
-> TcM (HsWrapper, [Scaled TcSigmaType], TcSigmaType)
forall (m :: * -> *) a. Monad m => a -> m a
return (HsWrapper
idHsWrapper, [], TcSigmaType
fun_ty)

    go Arity
n [Scaled TcSigmaType]
so_far TcSigmaType
fun_ty
      = do { (HsWrapper
wrap_fun1, Scaled TcSigmaType
arg_ty1, TcSigmaType
res_ty1) <- SDoc
-> Maybe SDoc
-> (Arity, [Scaled TcSigmaType])
-> TcSigmaType
-> TcM (HsWrapper, Scaled TcSigmaType, TcSigmaType)
matchActualFunTySigma
                                                 SDoc
herald Maybe SDoc
mb_thing
                                                 (Arity
n_val_args_wanted, [Scaled TcSigmaType]
so_far)
                                                 TcSigmaType
fun_ty
           ; (HsWrapper
wrap_res, [Scaled TcSigmaType]
arg_tys, TcSigmaType
res_ty)   <- Arity
-> [Scaled TcSigmaType]
-> TcSigmaType
-> TcM (HsWrapper, [Scaled TcSigmaType], TcSigmaType)
go (Arity
nArity -> Arity -> Arity
forall a. Num a => a -> a -> a
-Arity
1) (Scaled TcSigmaType
arg_ty1Scaled TcSigmaType -> [Scaled TcSigmaType] -> [Scaled TcSigmaType]
forall a. a -> [a] -> [a]
:[Scaled TcSigmaType]
so_far) TcSigmaType
res_ty1
           ; let wrap_fun2 :: HsWrapper
wrap_fun2 = HsWrapper
-> HsWrapper
-> Scaled TcSigmaType
-> TcSigmaType
-> SDoc
-> HsWrapper
mkWpFun HsWrapper
idHsWrapper HsWrapper
wrap_res Scaled TcSigmaType
arg_ty1 TcSigmaType
res_ty SDoc
doc
           ; (HsWrapper, [Scaled TcSigmaType], TcSigmaType)
-> TcM (HsWrapper, [Scaled TcSigmaType], TcSigmaType)
forall (m :: * -> *) a. Monad m => a -> m a
return (HsWrapper
wrap_fun2 HsWrapper -> HsWrapper -> HsWrapper
<.> HsWrapper
wrap_fun1, Scaled TcSigmaType
arg_ty1Scaled TcSigmaType -> [Scaled TcSigmaType] -> [Scaled TcSigmaType]
forall a. a -> [a] -> [a]
:[Scaled TcSigmaType]
arg_tys, TcSigmaType
res_ty) }
      where
        doc :: SDoc
doc = String -> SDoc
text String
"When inferring the argument type of a function with type" SDoc -> SDoc -> SDoc
<+>
              SDoc -> SDoc
quotes (TcSigmaType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcSigmaType
fun_ty)


{-
************************************************************************
*                                                                      *
             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.
-- This function skolemises at each polytype.
matchExpectedFunTys :: forall a.
                       SDoc   -- See Note [Herald for matchExpectedFunTys]
                    -> UserTypeCtxt
                    -> Arity
                    -> ExpRhoType      -- Skolemised
                    -> ([Scaled ExpSigmaType] -> ExpRhoType -> TcM a)
                    -> TcM (HsWrapper, a)
-- 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
-> UserTypeCtxt
-> Arity
-> ExpRhoType
-> ([Scaled ExpRhoType] -> ExpRhoType -> TcM a)
-> TcM (HsWrapper, a)
matchExpectedFunTys SDoc
herald UserTypeCtxt
ctx Arity
arity ExpRhoType
orig_ty [Scaled ExpRhoType] -> ExpRhoType -> TcM a
thing_inside
  = case ExpRhoType
orig_ty of
      Check TcSigmaType
ty -> [Scaled ExpRhoType] -> Arity -> TcSigmaType -> TcM (HsWrapper, a)
go [] Arity
arity TcSigmaType
ty
      ExpRhoType
_        -> [Scaled ExpRhoType] -> Arity -> ExpRhoType -> TcM (HsWrapper, a)
defer [] Arity
arity ExpRhoType
orig_ty
  where
    -- Skolemise any foralls /before/ the zero-arg case
    -- so that we guarantee to return a rho-type
    go :: [Scaled ExpRhoType] -> Arity -> TcSigmaType -> TcM (HsWrapper, a)
go [Scaled ExpRhoType]
acc_arg_tys Arity
n TcSigmaType
ty
      | ([Var]
tvs, ThetaType
theta, TcSigmaType
_) <- TcSigmaType -> ([Var], ThetaType, TcSigmaType)
tcSplitSigmaTy TcSigmaType
ty
      , Bool -> Bool
not ([Var] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Var]
tvs Bool -> Bool -> Bool
&& ThetaType -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null ThetaType
theta)
      = do { (HsWrapper
wrap_gen, (HsWrapper
wrap_res, a
result)) <- UserTypeCtxt
-> TcSigmaType
-> (TcSigmaType -> TcM (HsWrapper, a))
-> TcM (HsWrapper, (HsWrapper, a))
forall result.
UserTypeCtxt
-> TcSigmaType
-> (TcSigmaType -> TcM result)
-> TcM (HsWrapper, result)
tcSkolemise UserTypeCtxt
ctx TcSigmaType
ty ((TcSigmaType -> TcM (HsWrapper, a))
 -> TcM (HsWrapper, (HsWrapper, a)))
-> (TcSigmaType -> TcM (HsWrapper, a))
-> TcM (HsWrapper, (HsWrapper, a))
forall a b. (a -> b) -> a -> b
$ \TcSigmaType
ty' ->
                                               [Scaled ExpRhoType] -> Arity -> TcSigmaType -> TcM (HsWrapper, a)
go [Scaled ExpRhoType]
acc_arg_tys Arity
n TcSigmaType
ty'
           ; (HsWrapper, a) -> TcM (HsWrapper, a)
forall (m :: * -> *) a. Monad m => a -> m a
return (HsWrapper
wrap_gen HsWrapper -> HsWrapper -> HsWrapper
<.> HsWrapper
wrap_res, a
result) }

    -- No more args; do this /before/ tcView, so
    -- that we do not unnecessarily unwrap synonyms
    go [Scaled ExpRhoType]
acc_arg_tys Arity
0 TcSigmaType
rho_ty
      = do { a
result <- [Scaled ExpRhoType] -> ExpRhoType -> TcM a
thing_inside ([Scaled ExpRhoType] -> [Scaled ExpRhoType]
forall a. [a] -> [a]
reverse [Scaled ExpRhoType]
acc_arg_tys) (TcSigmaType -> ExpRhoType
mkCheckExpType TcSigmaType
rho_ty)
           ; (HsWrapper, a) -> TcM (HsWrapper, a)
forall (m :: * -> *) a. Monad m => a -> m a
return (HsWrapper
idHsWrapper, a
result) }

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

    go [Scaled ExpRhoType]
acc_arg_tys Arity
n (FunTy { ft_mult :: TcSigmaType -> TcSigmaType
ft_mult = TcSigmaType
mult, ft_af :: TcSigmaType -> AnonArgFlag
ft_af = AnonArgFlag
af, ft_arg :: TcSigmaType -> TcSigmaType
ft_arg = TcSigmaType
arg_ty, ft_res :: TcSigmaType -> TcSigmaType
ft_res = TcSigmaType
res_ty })
      = ASSERT( af == VisArg )
        do { (HsWrapper
wrap_res, a
result) <- [Scaled ExpRhoType] -> Arity -> TcSigmaType -> TcM (HsWrapper, a)
go ((TcSigmaType -> ExpRhoType -> Scaled ExpRhoType
forall a. TcSigmaType -> a -> Scaled a
Scaled TcSigmaType
mult (ExpRhoType -> Scaled ExpRhoType)
-> ExpRhoType -> Scaled ExpRhoType
forall a b. (a -> b) -> a -> b
$ TcSigmaType -> ExpRhoType
mkCheckExpType TcSigmaType
arg_ty) Scaled ExpRhoType -> [Scaled ExpRhoType] -> [Scaled ExpRhoType]
forall a. a -> [a] -> [a]
: [Scaled ExpRhoType]
acc_arg_tys)
                                      (Arity
nArity -> Arity -> Arity
forall a. Num a => a -> a -> a
-Arity
1) TcSigmaType
res_ty
           ; let fun_wrap :: HsWrapper
fun_wrap = HsWrapper
-> HsWrapper
-> Scaled TcSigmaType
-> TcSigmaType
-> SDoc
-> HsWrapper
mkWpFun HsWrapper
idHsWrapper HsWrapper
wrap_res (TcSigmaType -> TcSigmaType -> Scaled TcSigmaType
forall a. TcSigmaType -> a -> Scaled a
Scaled TcSigmaType
mult TcSigmaType
arg_ty) TcSigmaType
res_ty SDoc
doc
           ; (HsWrapper, a) -> TcM (HsWrapper, a)
forall (m :: * -> *) a. Monad m => a -> m a
return ( HsWrapper
fun_wrap, a
result ) }
      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 [Scaled ExpRhoType]
acc_arg_tys Arity
n ty :: TcSigmaType
ty@(TyVarTy Var
tv)
      | Var -> Bool
isMetaTyVar Var
tv
      = do { MetaDetails
cts <- Var -> TcM MetaDetails
readMetaTyVar Var
tv
           ; case MetaDetails
cts of
               Indirect TcSigmaType
ty' -> [Scaled ExpRhoType] -> Arity -> TcSigmaType -> TcM (HsWrapper, a)
go [Scaled ExpRhoType]
acc_arg_tys Arity
n TcSigmaType
ty'
               MetaDetails
Flexi        -> [Scaled ExpRhoType] -> Arity -> ExpRhoType -> TcM (HsWrapper, a)
defer [Scaled ExpRhoType]
acc_arg_tys Arity
n (TcSigmaType -> ExpRhoType
mkCheckExpType TcSigmaType
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 [Scaled ExpRhoType]
acc_arg_tys Arity
n TcSigmaType
ty = (TidyEnv -> TcM (TidyEnv, SDoc))
-> TcM (HsWrapper, a) -> TcM (HsWrapper, a)
forall a. (TidyEnv -> TcM (TidyEnv, SDoc)) -> TcM a -> TcM a
addErrCtxtM ([Scaled ExpRhoType]
-> TcSigmaType -> TidyEnv -> TcM (TidyEnv, SDoc)
mk_ctxt [Scaled ExpRhoType]
acc_arg_tys TcSigmaType
ty) (TcM (HsWrapper, a) -> TcM (HsWrapper, a))
-> TcM (HsWrapper, a) -> TcM (HsWrapper, a)
forall a b. (a -> b) -> a -> b
$
                          [Scaled ExpRhoType] -> Arity -> ExpRhoType -> TcM (HsWrapper, a)
defer [Scaled ExpRhoType]
acc_arg_tys Arity
n (TcSigmaType -> ExpRhoType
mkCheckExpType TcSigmaType
ty)

    ------------
    defer :: [Scaled ExpSigmaType] -> Arity -> ExpRhoType -> TcM (HsWrapper, a)
    defer :: [Scaled ExpRhoType] -> Arity -> ExpRhoType -> TcM (HsWrapper, a)
defer [Scaled ExpRhoType]
acc_arg_tys Arity
n ExpRhoType
fun_ty
      = do { [Scaled ExpRhoType]
more_arg_tys <- Arity
-> IOEnv (Env TcGblEnv TcLclEnv) (Scaled ExpRhoType)
-> IOEnv (Env TcGblEnv TcLclEnv) [Scaled ExpRhoType]
forall (m :: * -> *) a. Applicative m => Arity -> m a -> m [a]
replicateM Arity
n (TcSigmaType -> ExpRhoType -> Scaled ExpRhoType
forall a. TcSigmaType -> a -> Scaled a
mkScaled (TcSigmaType -> ExpRhoType -> Scaled ExpRhoType)
-> TcM TcSigmaType
-> IOEnv (Env TcGblEnv TcLclEnv) (ExpRhoType -> Scaled ExpRhoType)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> TcSigmaType -> TcM TcSigmaType
newFlexiTyVarTy TcSigmaType
multiplicityTy IOEnv (Env TcGblEnv TcLclEnv) (ExpRhoType -> Scaled ExpRhoType)
-> IOEnv (Env TcGblEnv TcLclEnv) ExpRhoType
-> IOEnv (Env TcGblEnv TcLclEnv) (Scaled ExpRhoType)
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> IOEnv (Env TcGblEnv TcLclEnv) ExpRhoType
newInferExpType)
           ; ExpRhoType
res_ty       <- IOEnv (Env TcGblEnv TcLclEnv) ExpRhoType
newInferExpType
           ; a
result       <- [Scaled ExpRhoType] -> ExpRhoType -> TcM a
thing_inside ([Scaled ExpRhoType] -> [Scaled ExpRhoType]
forall a. [a] -> [a]
reverse [Scaled ExpRhoType]
acc_arg_tys [Scaled ExpRhoType] -> [Scaled ExpRhoType] -> [Scaled ExpRhoType]
forall a. [a] -> [a] -> [a]
++ [Scaled ExpRhoType]
more_arg_tys) ExpRhoType
res_ty
           ; [Scaled TcSigmaType]
more_arg_tys <- (Scaled ExpRhoType
 -> IOEnv (Env TcGblEnv TcLclEnv) (Scaled TcSigmaType))
-> [Scaled ExpRhoType]
-> IOEnv (Env TcGblEnv TcLclEnv) [Scaled TcSigmaType]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM (\(Scaled TcSigmaType
m ExpRhoType
t) -> TcSigmaType -> TcSigmaType -> Scaled TcSigmaType
forall a. TcSigmaType -> a -> Scaled a
Scaled TcSigmaType
m (TcSigmaType -> Scaled TcSigmaType)
-> TcM TcSigmaType
-> IOEnv (Env TcGblEnv TcLclEnv) (Scaled TcSigmaType)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ExpRhoType -> TcM TcSigmaType
readExpType ExpRhoType
t) [Scaled ExpRhoType]
more_arg_tys
           ; TcSigmaType
res_ty       <- ExpRhoType -> TcM TcSigmaType
readExpType ExpRhoType
res_ty
           ; let unif_fun_ty :: TcSigmaType
unif_fun_ty = [Scaled TcSigmaType] -> TcSigmaType -> TcSigmaType
mkVisFunTys [Scaled TcSigmaType]
more_arg_tys TcSigmaType
res_ty
           ; HsWrapper
wrap <- CtOrigin
-> UserTypeCtxt -> TcSigmaType -> ExpRhoType -> TcM HsWrapper
tcSubType CtOrigin
AppOrigin UserTypeCtxt
ctx TcSigmaType
unif_fun_ty ExpRhoType
fun_ty
                         -- Not a good origin at all :-(
           ; (HsWrapper, a) -> TcM (HsWrapper, a)
forall (m :: * -> *) a. Monad m => a -> m a
return (HsWrapper
wrap, a
result) }

    ------------
    mk_ctxt :: [Scaled ExpSigmaType] -> TcType -> TidyEnv -> TcM (TidyEnv, SDoc)
    mk_ctxt :: [Scaled ExpRhoType]
-> TcSigmaType -> TidyEnv -> TcM (TidyEnv, SDoc)
mk_ctxt [Scaled ExpRhoType]
arg_tys TcSigmaType
res_ty TidyEnv
env
      = TidyEnv
-> SDoc
-> [Scaled TcSigmaType]
-> TcSigmaType
-> Arity
-> TcM (TidyEnv, SDoc)
mkFunTysMsg TidyEnv
env SDoc
herald [Scaled TcSigmaType]
arg_tys' TcSigmaType
res_ty Arity
arity
      where
        arg_tys' :: [Scaled TcSigmaType]
arg_tys' = (Scaled ExpRhoType -> Scaled TcSigmaType)
-> [Scaled ExpRhoType] -> [Scaled TcSigmaType]
forall a b. (a -> b) -> [a] -> [b]
map (\(Scaled TcSigmaType
u ExpRhoType
v) -> TcSigmaType -> TcSigmaType -> Scaled TcSigmaType
forall a. TcSigmaType -> a -> Scaled a
Scaled TcSigmaType
u (String -> ExpRhoType -> TcSigmaType
checkingExpType String
"matchExpectedFunTys" ExpRhoType
v)) ([Scaled ExpRhoType] -> [Scaled TcSigmaType])
-> [Scaled ExpRhoType] -> [Scaled TcSigmaType]
forall a b. (a -> b) -> a -> b
$
                   [Scaled ExpRhoType] -> [Scaled ExpRhoType]
forall a. [a] -> [a]
reverse [Scaled ExpRhoType]
arg_tys
            -- this is safe b/c we're called from "go"

mkFunTysMsg :: TidyEnv -> SDoc -> [Scaled TcType] -> TcType -> Arity
            -> TcM (TidyEnv, SDoc)
mkFunTysMsg :: TidyEnv
-> SDoc
-> [Scaled TcSigmaType]
-> TcSigmaType
-> Arity
-> TcM (TidyEnv, SDoc)
mkFunTysMsg TidyEnv
env SDoc
herald [Scaled TcSigmaType]
arg_tys TcSigmaType
res_ty Arity
n_val_args_in_call
  = do { (TidyEnv
env', TcSigmaType
fun_rho) <- TidyEnv -> TcSigmaType -> TcM (TidyEnv, TcSigmaType)
zonkTidyTcType TidyEnv
env (TcSigmaType -> TcM (TidyEnv, TcSigmaType))
-> TcSigmaType -> TcM (TidyEnv, TcSigmaType)
forall a b. (a -> b) -> a -> b
$
                            [Scaled TcSigmaType] -> TcSigmaType -> TcSigmaType
mkVisFunTys [Scaled TcSigmaType]
arg_tys TcSigmaType
res_ty

       ; let ([Scaled TcSigmaType]
all_arg_tys, TcSigmaType
_) = TcSigmaType -> ([Scaled TcSigmaType], TcSigmaType)
splitFunTys TcSigmaType
fun_rho
             n_fun_args :: Arity
n_fun_args = [Scaled TcSigmaType] -> Arity
forall (t :: * -> *) a. Foldable t => t a -> Arity
length [Scaled TcSigmaType]
all_arg_tys

             msg :: SDoc
msg | Arity
n_val_args_in_call Arity -> Arity -> Bool
forall a. Ord a => a -> a -> Bool
<= Arity
n_fun_args  -- Enough args, in the end
                 = String -> SDoc
text String
"In the result of a function call"
                 | Bool
otherwise
                 = SDoc -> Arity -> SDoc -> SDoc
hang (SDoc
full_herald SDoc -> SDoc -> SDoc
<> SDoc
comma)
                      Arity
2 ([SDoc] -> SDoc
sep [ String -> SDoc
text String
"but its type" SDoc -> SDoc -> SDoc
<+> SDoc -> SDoc
quotes (TcSigmaType -> SDoc
pprType TcSigmaType
fun_rho)
                             , if Arity
n_fun_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_fun_args])

       ; (TidyEnv, SDoc) -> TcM (TidyEnv, SDoc)
forall (m :: * -> *) a. Monad m => a -> m a
return (TidyEnv
env', SDoc
msg) }
 where
  full_herald :: SDoc
full_herald = SDoc
herald SDoc -> SDoc -> SDoc
<+> Arity -> SDoc -> SDoc
speakNOf Arity
n_val_args_in_call (String -> SDoc
text String
"value argument")

----------------------
matchExpectedListTy :: TcRhoType -> TcM (TcCoercionN, TcRhoType)
-- Special case for lists
matchExpectedListTy :: TcSigmaType -> TcM (TcCoercionN, TcSigmaType)
matchExpectedListTy TcSigmaType
exp_ty
 = do { (TcCoercionN
co, [TcSigmaType
elt_ty]) <- TyCon -> TcSigmaType -> TcM (TcCoercionN, ThetaType)
matchExpectedTyConApp TyCon
listTyCon TcSigmaType
exp_ty
      ; (TcCoercionN, TcSigmaType) -> TcM (TcCoercionN, TcSigmaType)
forall (m :: * -> *) a. Monad m => a -> m a
return (TcCoercionN
co, TcSigmaType
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 -> TcSigmaType -> TcM (TcCoercionN, ThetaType)
matchExpectedTyConApp TyCon
tc TcSigmaType
orig_ty
  = ASSERT(not $ isFunTyCon tc) go orig_ty
  where
    go :: TcSigmaType -> TcM (TcCoercionN, ThetaType)
go TcSigmaType
ty
       | Just TcSigmaType
ty' <- TcSigmaType -> Maybe TcSigmaType
tcView TcSigmaType
ty
       = TcSigmaType -> TcM (TcCoercionN, ThetaType)
go TcSigmaType
ty'

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

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

    go TcSigmaType
_ = TcM (TcCoercionN, ThetaType)
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, ThetaType)
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 :: ThetaType
args = [Var] -> ThetaType
mkTyVarTys [Var]
arg_tvs
                 tc_template :: TcSigmaType
tc_template = TyCon -> ThetaType -> TcSigmaType
mkTyConApp TyCon
tc ThetaType
args
           ; TcCoercionN
co <- Maybe SDoc -> TcSigmaType -> TcSigmaType -> TcM TcCoercionN
unifyType Maybe SDoc
forall a. Maybe a
Nothing TcSigmaType
tc_template TcSigmaType
orig_ty
           ; (TcCoercionN, ThetaType) -> TcM (TcCoercionN, ThetaType)
forall (m :: * -> *) a. Monad m => a -> m a
return (TcCoercionN
co, ThetaType
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 :: TcSigmaType -> TcM (TcCoercionN, (TcSigmaType, TcSigmaType))
matchExpectedAppTy TcSigmaType
orig_ty
  = TcSigmaType -> TcM (TcCoercionN, (TcSigmaType, TcSigmaType))
go TcSigmaType
orig_ty
  where
    go :: TcSigmaType -> TcM (TcCoercionN, (TcSigmaType, TcSigmaType))
go TcSigmaType
ty
      | Just TcSigmaType
ty' <- TcSigmaType -> Maybe TcSigmaType
tcView TcSigmaType
ty = TcSigmaType -> TcM (TcCoercionN, (TcSigmaType, TcSigmaType))
go TcSigmaType
ty'

      | Just (TcSigmaType
fun_ty, TcSigmaType
arg_ty) <- TcSigmaType -> Maybe (TcSigmaType, TcSigmaType)
tcSplitAppTy_maybe TcSigmaType
ty
      = (TcCoercionN, (TcSigmaType, TcSigmaType))
-> TcM (TcCoercionN, (TcSigmaType, TcSigmaType))
forall (m :: * -> *) a. Monad m => a -> m a
return (TcSigmaType -> TcCoercionN
mkTcNomReflCo TcSigmaType
orig_ty, (TcSigmaType
fun_ty, TcSigmaType
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 TcSigmaType
ty -> TcSigmaType -> TcM (TcCoercionN, (TcSigmaType, TcSigmaType))
go TcSigmaType
ty
               MetaDetails
Flexi       -> TcM (TcCoercionN, (TcSigmaType, TcSigmaType))
defer }

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

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

    orig_kind :: TcSigmaType
orig_kind = HasDebugCallStack => TcSigmaType -> TcSigmaType
TcSigmaType -> TcSigmaType
tcTypeKind TcSigmaType
orig_ty
    kind1 :: TcSigmaType
kind1 = TcSigmaType -> TcSigmaType -> TcSigmaType
mkVisFunTyMany TcSigmaType
liftedTypeKind TcSigmaType
orig_kind
    kind2 :: TcSigmaType
kind2 = TcSigmaType
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 wrapper function
        co_fn :: actual_ty ~ expected_ty
which takes an HsExpr of type actual_ty into one of type
expected_ty.
-}


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

tcWrapResultO :: CtOrigin -> HsExpr GhcRn -> HsExpr GhcTc -> TcSigmaType -> ExpRhoType
               -> TcM (HsExpr GhcTc)
tcWrapResultO :: CtOrigin
-> HsExpr GhcRn
-> HsExpr GhcTc
-> TcSigmaType
-> ExpRhoType
-> TcM (HsExpr GhcTc)
tcWrapResultO CtOrigin
orig HsExpr GhcRn
rn_expr HsExpr GhcTc
expr TcSigmaType
actual_ty ExpRhoType
res_ty
  = do { String -> SDoc -> TcRn ()
traceTc String
"tcWrapResult" ([SDoc] -> SDoc
vcat [ String -> SDoc
text String
"Actual:  " SDoc -> SDoc -> SDoc
<+> TcSigmaType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcSigmaType
actual_ty
                                      , String -> SDoc
text String
"Expected:" SDoc -> SDoc -> SDoc
<+> ExpRhoType -> SDoc
forall a. Outputable a => a -> SDoc
ppr ExpRhoType
res_ty ])
       ; HsWrapper
wrap <- CtOrigin
-> UserTypeCtxt
-> Maybe SDoc
-> TcSigmaType
-> ExpRhoType
-> TcM HsWrapper
tcSubTypeNC CtOrigin
orig UserTypeCtxt
GenSigCtxt (SDoc -> Maybe SDoc
forall a. a -> Maybe a
Just (HsExpr GhcRn -> SDoc
forall a. Outputable a => a -> SDoc
ppr HsExpr GhcRn
rn_expr)) TcSigmaType
actual_ty ExpRhoType
res_ty
       ; HsExpr GhcTc -> TcM (HsExpr GhcTc)
forall (m :: * -> *) a. Monad m => a -> m a
return (HsWrapper -> HsExpr GhcTc -> HsExpr GhcTc
mkHsWrap HsWrapper
wrap HsExpr GhcTc
expr) }

tcWrapResultMono :: HsExpr GhcRn -> HsExpr GhcTc
                 -> TcRhoType   -- Actual -- a rho-type not a sigma-type
                 -> ExpRhoType  -- Expected
                 -> TcM (HsExpr GhcTc)
-- A version of tcWrapResult to use when the actual type is a
-- rho-type, so nothing to instantiate; just go straight to unify.
-- It means we don't need to pass in a CtOrigin
tcWrapResultMono :: HsExpr GhcRn
-> HsExpr GhcTc -> TcSigmaType -> ExpRhoType -> TcM (HsExpr GhcTc)
tcWrapResultMono HsExpr GhcRn
rn_expr HsExpr GhcTc
expr TcSigmaType
act_ty ExpRhoType
res_ty
  = ASSERT2( isRhoTy act_ty, ppr act_ty $$ ppr rn_expr )
    do { TcCoercionN
co <- case ExpRhoType
res_ty of
                  Infer InferResult
inf_res -> TcSigmaType -> InferResult -> TcM TcCoercionN
fillInferResult TcSigmaType
act_ty InferResult
inf_res
                  Check TcSigmaType
exp_ty  -> Maybe SDoc -> TcSigmaType -> TcSigmaType -> TcM TcCoercionN
unifyType (SDoc -> Maybe SDoc
forall a. a -> Maybe a
Just (HsExpr GhcRn -> SDoc
forall a. Outputable a => a -> SDoc
ppr HsExpr GhcRn
rn_expr)) TcSigmaType
act_ty TcSigmaType
exp_ty
       ; HsExpr GhcTc -> TcM (HsExpr GhcTc)
forall (m :: * -> *) a. Monad m => a -> m a
return (TcCoercionN -> HsExpr GhcTc -> HsExpr GhcTc
mkHsWrapCo TcCoercionN
co HsExpr GhcTc
expr) }

------------------------
tcSubTypePat :: CtOrigin -> UserTypeCtxt
            -> ExpSigmaType -> TcSigmaType -> TcM HsWrapper
-- Used in patterns; polarity is backwards compared
--   to tcSubType
-- If wrap = tc_sub_type_et t1 t2
--    => wrap :: t1 ~> t2
tcSubTypePat :: CtOrigin
-> UserTypeCtxt -> ExpRhoType -> TcSigmaType -> TcM HsWrapper
tcSubTypePat CtOrigin
inst_orig UserTypeCtxt
ctxt (Check TcSigmaType
ty_actual) TcSigmaType
ty_expected
  = (TcSigmaType -> TcSigmaType -> TcM TcCoercionN)
-> CtOrigin
-> UserTypeCtxt
-> TcSigmaType
-> TcSigmaType
-> TcM HsWrapper
tc_sub_type TcSigmaType -> TcSigmaType -> TcM TcCoercionN
unifyTypeET CtOrigin
inst_orig UserTypeCtxt
ctxt TcSigmaType
ty_actual TcSigmaType
ty_expected

tcSubTypePat CtOrigin
_ UserTypeCtxt
_ (Infer InferResult
inf_res) TcSigmaType
ty_expected
  = do { TcCoercionN
co <- TcSigmaType -> InferResult -> TcM TcCoercionN
fillInferResult TcSigmaType
ty_expected InferResult
inf_res
               -- In patterns we do not instantatiate

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

---------------
tcSubType :: CtOrigin -> UserTypeCtxt
          -> TcSigmaType  -- Actual
          -> ExpRhoType   -- Expected
          -> TcM HsWrapper
-- Checks that 'actual' is more polymorphic than 'expected'
tcSubType :: CtOrigin
-> UserTypeCtxt -> TcSigmaType -> ExpRhoType -> TcM HsWrapper
tcSubType CtOrigin
orig UserTypeCtxt
ctxt TcSigmaType
ty_actual ExpRhoType
ty_expected
  = TcSigmaType -> ExpRhoType -> TcM HsWrapper -> TcM HsWrapper
forall a. TcSigmaType -> ExpRhoType -> TcM a -> TcM a
addSubTypeCtxt TcSigmaType
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
"tcSubType" ([SDoc] -> SDoc
vcat [UserTypeCtxt -> SDoc
pprUserTypeCtxt UserTypeCtxt
ctxt, TcSigmaType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcSigmaType
ty_actual, ExpRhoType -> SDoc
forall a. Outputable a => a -> SDoc
ppr ExpRhoType
ty_expected])
       ; CtOrigin
-> UserTypeCtxt
-> Maybe SDoc
-> TcSigmaType
-> ExpRhoType
-> TcM HsWrapper
tcSubTypeNC CtOrigin
orig UserTypeCtxt
ctxt Maybe SDoc
forall a. Maybe a
Nothing TcSigmaType
ty_actual ExpRhoType
ty_expected }

tcSubTypeNC :: CtOrigin       -- Used when instantiating
            -> UserTypeCtxt   -- Used when skolemising
            -> Maybe SDoc     -- The expression that has type 'actual' (if known)
            -> TcSigmaType            -- Actual type
            -> ExpRhoType             -- Expected type
            -> TcM HsWrapper
tcSubTypeNC :: CtOrigin
-> UserTypeCtxt
-> Maybe SDoc
-> TcSigmaType
-> ExpRhoType
-> TcM HsWrapper
tcSubTypeNC CtOrigin
inst_orig UserTypeCtxt
ctxt Maybe SDoc
m_thing TcSigmaType
ty_actual ExpRhoType
res_ty
  = case ExpRhoType
res_ty of
      Check TcSigmaType
ty_expected -> (TcSigmaType -> TcSigmaType -> TcM TcCoercionN)
-> CtOrigin
-> UserTypeCtxt
-> TcSigmaType
-> TcSigmaType
-> TcM HsWrapper
tc_sub_type (Maybe SDoc -> TcSigmaType -> TcSigmaType -> TcM TcCoercionN
unifyType Maybe SDoc
m_thing) CtOrigin
inst_orig UserTypeCtxt
ctxt
                                       TcSigmaType
ty_actual TcSigmaType
ty_expected

      Infer InferResult
inf_res -> do { (HsWrapper
wrap, TcSigmaType
rho) <- CtOrigin -> TcSigmaType -> TcM (HsWrapper, TcSigmaType)
topInstantiate CtOrigin
inst_orig TcSigmaType
ty_actual
                                   -- See Note [Instantiation of InferResult]
                          ; TcCoercionN
co <- TcSigmaType -> InferResult -> TcM TcCoercionN
fillInferResult TcSigmaType
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) }

{- Note [Instantiation of InferResult]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We now always instantiate before filling in InferResult, so that
the result is a TcRhoType: see #17173 for discussion.

For example:

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.

3. Suppose one defines plus = (+). If we instantiate lazily, we will
   infer plus :: forall a. Num a => a -> a -> a. However, the monomorphism
   restriction compels us to infer
      plus :: Integer -> Integer -> Integer
   (or similar monotype). Indeed, the only way to know whether to apply
   the monomorphism restriction at all is to instantiate

There is one place where we don't want to instantiate eagerly,
namely in GHC.Tc.Module.tcRnExpr, which implements GHCi's :type
command. See Note [Implementing :type] in GHC.Tc.Module.
-}

---------------
tcSubTypeSigma :: UserTypeCtxt -> TcSigmaType -> TcSigmaType -> TcM HsWrapper
-- External entry point, but no ExpTypes on either side
-- Checks that actual <= expected
-- Returns HsWrapper :: actual ~ expected
tcSubTypeSigma :: UserTypeCtxt -> TcSigmaType -> TcSigmaType -> TcM HsWrapper
tcSubTypeSigma UserTypeCtxt
ctxt TcSigmaType
ty_actual TcSigmaType
ty_expected
  = (TcSigmaType -> TcSigmaType -> TcM TcCoercionN)
-> CtOrigin
-> UserTypeCtxt
-> TcSigmaType
-> TcSigmaType
-> TcM HsWrapper
tc_sub_type (Maybe SDoc -> TcSigmaType -> TcSigmaType -> TcM TcCoercionN
unifyType Maybe SDoc
forall a. Maybe a
Nothing) CtOrigin
eq_orig UserTypeCtxt
ctxt TcSigmaType
ty_actual TcSigmaType
ty_expected
  where
    eq_orig :: CtOrigin
eq_orig = TypeEqOrigin :: TcSigmaType -> TcSigmaType -> Maybe SDoc -> Bool -> CtOrigin
TypeEqOrigin { uo_actual :: TcSigmaType
uo_actual   = TcSigmaType
ty_actual
                           , uo_expected :: TcSigmaType
uo_expected = TcSigmaType
ty_expected
                           , uo_thing :: Maybe SDoc
uo_thing    = Maybe SDoc
forall a. Maybe a
Nothing
                           , uo_visible :: Bool
uo_visible  = Bool
True }

---------------
tc_sub_type :: (TcType -> TcType -> TcM TcCoercionN)  -- How to unify
            -> CtOrigin       -- Used when instantiating
            -> UserTypeCtxt   -- Used when skolemising
            -> TcSigmaType    -- Actual; a sigma-type
            -> TcSigmaType    -- Expected; also a sigma-type
            -> TcM HsWrapper
-- Checks that actual_ty is more polymorphic than expected_ty
-- If wrap = tc_sub_type t1 t2
--    => wrap :: t1 ~> t2
tc_sub_type :: (TcSigmaType -> TcSigmaType -> TcM TcCoercionN)
-> CtOrigin
-> UserTypeCtxt
-> TcSigmaType
-> TcSigmaType
-> TcM HsWrapper
tc_sub_type TcSigmaType -> TcSigmaType -> TcM TcCoercionN
unify CtOrigin
inst_orig UserTypeCtxt
ctxt TcSigmaType
ty_actual TcSigmaType
ty_expected
  | TcSigmaType -> Bool
definitely_poly TcSigmaType
ty_expected      -- See Note [Don't skolemise unnecessarily]
  , Bool -> Bool
not (TcSigmaType -> Bool
possibly_poly TcSigmaType
ty_actual)
  = do { String -> SDoc -> TcRn ()
traceTc String
"tc_sub_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
<+> TcSigmaType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcSigmaType
ty_actual
              , String -> SDoc
text String
"ty_expected =" SDoc -> SDoc -> SDoc
<+> TcSigmaType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcSigmaType
ty_expected ]
       ; TcCoercionN -> HsWrapper
mkWpCastN (TcCoercionN -> HsWrapper) -> TcM TcCoercionN -> TcM HsWrapper
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$>
         TcSigmaType -> TcSigmaType -> TcM TcCoercionN
unify TcSigmaType
ty_actual TcSigmaType
ty_expected }

  | Bool
otherwise   -- This is the general case
  = do { String -> SDoc -> TcRn ()
traceTc String
"tc_sub_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
<+> TcSigmaType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcSigmaType
ty_actual
              , String -> SDoc
text String
"ty_expected =" SDoc -> SDoc -> SDoc
<+> TcSigmaType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcSigmaType
ty_expected ]

       ; (HsWrapper
sk_wrap, HsWrapper
inner_wrap)
           <- UserTypeCtxt
-> TcSigmaType
-> (TcSigmaType -> TcM HsWrapper)
-> TcM (HsWrapper, HsWrapper)
forall result.
UserTypeCtxt
-> TcSigmaType
-> (TcSigmaType -> TcM result)
-> TcM (HsWrapper, result)
tcSkolemise UserTypeCtxt
ctxt TcSigmaType
ty_expected ((TcSigmaType -> TcM HsWrapper) -> TcM (HsWrapper, HsWrapper))
-> (TcSigmaType -> TcM HsWrapper) -> TcM (HsWrapper, HsWrapper)
forall a b. (a -> b) -> a -> b
$ \ TcSigmaType
sk_rho ->
              do { (HsWrapper
wrap, TcSigmaType
rho_a) <- CtOrigin -> TcSigmaType -> TcM (HsWrapper, TcSigmaType)
topInstantiate CtOrigin
inst_orig TcSigmaType
ty_actual
                 ; TcCoercionN
cow           <- TcSigmaType -> TcSigmaType -> TcM TcCoercionN
unify TcSigmaType
rho_a TcSigmaType
sk_rho
                 ; HsWrapper -> TcM HsWrapper
forall (m :: * -> *) a. Monad m => a -> m a
return (TcCoercionN -> HsWrapper
mkWpCastN TcCoercionN
cow HsWrapper -> HsWrapper -> HsWrapper
<.> HsWrapper
wrap) }

       ; HsWrapper -> TcM HsWrapper
forall (m :: * -> *) a. Monad m => a -> m a
return (HsWrapper
sk_wrap HsWrapper -> HsWrapper -> HsWrapper
<.> HsWrapper
inner_wrap) }
  where
    possibly_poly :: TcSigmaType -> Bool
possibly_poly TcSigmaType
ty = Bool -> Bool
not (TcSigmaType -> Bool
isRhoTy TcSigmaType
ty)

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

------------------------
addSubTypeCtxt :: TcType -> ExpType -> TcM a -> TcM a
addSubTypeCtxt :: TcSigmaType -> ExpRhoType -> TcM a -> TcM a
addSubTypeCtxt TcSigmaType
ty_actual ExpRhoType
ty_expected TcM a
thing_inside
 | TcSigmaType -> Bool
isRhoTy TcSigmaType
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, TcSigmaType
ty_actual)   <- TidyEnv -> TcSigmaType -> TcM (TidyEnv, TcSigmaType)
zonkTidyTcType TidyEnv
tidy_env TcSigmaType
ty_actual
                   -- might not be filled if we're debugging. ugh.
           ; Maybe TcSigmaType
mb_ty_expected          <- ExpRhoType -> TcM (Maybe TcSigmaType)
readExpType_maybe ExpRhoType
ty_expected
           ; (TidyEnv
tidy_env, ExpRhoType
ty_expected) <- case Maybe TcSigmaType
mb_ty_expected of
                                          Just TcSigmaType
ty -> (TcSigmaType -> ExpRhoType)
-> (TidyEnv, TcSigmaType) -> (TidyEnv, ExpRhoType)
forall (a :: * -> * -> *) b c d.
Arrow a =>
a b c -> a (d, b) (d, c)
second TcSigmaType -> ExpRhoType
mkCheckExpType ((TidyEnv, TcSigmaType) -> (TidyEnv, ExpRhoType))
-> TcM (TidyEnv, TcSigmaType)
-> IOEnv (Env TcGblEnv TcLclEnv) (TidyEnv, ExpRhoType)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$>
                                                     TidyEnv -> TcSigmaType -> TcM (TidyEnv, TcSigmaType)
zonkTidyTcType TidyEnv
tidy_env TcSigmaType
ty
                                          Maybe TcSigmaType
Nothing -> (TidyEnv, ExpRhoType)
-> IOEnv (Env TcGblEnv TcLclEnv) (TidyEnv, ExpRhoType)
forall (m :: * -> *) a. Monad m => a -> m a
return (TidyEnv
tidy_env, ExpRhoType
ty_expected)
           ; TcSigmaType
ty_expected             <- ExpRhoType -> TcM TcSigmaType
readExpType ExpRhoType
ty_expected
           ; (TidyEnv
tidy_env, TcSigmaType
ty_expected) <- TidyEnv -> TcSigmaType -> TcM (TidyEnv, TcSigmaType)
zonkTidyTcType TidyEnv
tidy_env TcSigmaType
ty_expected
           ; let msg :: SDoc
msg = [SDoc] -> SDoc
vcat [ SDoc -> Arity -> SDoc -> SDoc
hang (String -> SDoc
text String
"When checking that:")
                                 Arity
4 (TcSigmaType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcSigmaType
ty_actual)
                            , Arity -> SDoc -> SDoc
nest Arity
2 (SDoc -> Arity -> SDoc -> SDoc
hang (String -> SDoc
text String
"is more polymorphic than:")
                                         Arity
2 (TcSigmaType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcSigmaType
ty_expected)) ]
           ; (TidyEnv, SDoc) -> TcM (TidyEnv, SDoc)
forall (m :: * -> *) a. Monad m => a -> m a
return (TidyEnv
tidy_env, SDoc
msg) }

{- 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->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

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 GHC.Tc.Utils.Unify.alwaysBuildImplication checks the UserTypeCtxt.
  See Note [When to build an implication]

Note [Wrapper returned from tcSubMult]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
There is no notion of multiplicity coercion in Core, therefore the wrapper
returned by tcSubMult (and derived functions such as tcCheckUsage and
checkManyPattern) is quite unlike any other wrapper: it checks whether the
coercion produced by the constraint solver is trivial, producing a type error
is it is not. This is implemented via the WpMultCoercion wrapper, as desugared
by GHC.HsToCore.Binds.dsHsWrapper, which does the reflexivity check.

This wrapper needs to be placed in the term; otherwise, checking of the
eventual coercion won't be triggered during desugaring. But it can be put
anywhere, since it doesn't affect the desugared code.

Why do we check this in the desugarer? It's a convenient place, since it's
right after all the constraints are solved. We need the constraints to be
solved to check whether they are trivial or not. Plus there is precedent for
type errors during desuraging (such as the levity polymorphism
restriction). An alternative would be to have a kind of constraint which can
only produce trivial evidence, then this check would happen in the constraint
solver.
-}

tcSubMult :: CtOrigin -> Mult -> Mult -> TcM HsWrapper
tcSubMult :: CtOrigin -> TcSigmaType -> TcSigmaType -> TcM HsWrapper
tcSubMult CtOrigin
origin TcSigmaType
w_actual TcSigmaType
w_expected
  | Just (TcSigmaType
w1, TcSigmaType
w2) <- TcSigmaType -> Maybe (TcSigmaType, TcSigmaType)
isMultMul TcSigmaType
w_actual =
  do { HsWrapper
w1 <- CtOrigin -> TcSigmaType -> TcSigmaType -> TcM HsWrapper
tcSubMult CtOrigin
origin TcSigmaType
w1 TcSigmaType
w_expected
     ; HsWrapper
w2 <- CtOrigin -> TcSigmaType -> TcSigmaType -> TcM HsWrapper
tcSubMult CtOrigin
origin TcSigmaType
w2 TcSigmaType
w_expected
     ; HsWrapper -> TcM HsWrapper
forall (m :: * -> *) a. Monad m => a -> m a
return (HsWrapper
w1 HsWrapper -> HsWrapper -> HsWrapper
<.> HsWrapper
w2) }
  -- Currently, we consider p*q and sup p q to be equal.  Therefore, p*q <= r is
  -- equivalent to p <= r and q <= r.  For other cases, we approximate p <= q by p
  -- ~ q.  This is not complete, but it's sound. See also Note [Overapproximating
  -- multiplicities] in Multiplicity.
tcSubMult CtOrigin
origin TcSigmaType
w_actual TcSigmaType
w_expected =
  case TcSigmaType -> TcSigmaType -> IsSubmult
submult TcSigmaType
w_actual TcSigmaType
w_expected of
    IsSubmult
Submult -> HsWrapper -> TcM HsWrapper
forall (m :: * -> *) a. Monad m => a -> m a
return HsWrapper
WpHole
    IsSubmult
Unknown -> CtOrigin -> TcSigmaType -> TcSigmaType -> TcM HsWrapper
tcEqMult CtOrigin
origin TcSigmaType
w_actual TcSigmaType
w_expected

tcEqMult :: CtOrigin -> Mult -> Mult -> TcM HsWrapper
tcEqMult :: CtOrigin -> TcSigmaType -> TcSigmaType -> TcM HsWrapper
tcEqMult CtOrigin
origin TcSigmaType
w_actual TcSigmaType
w_expected = do
  {
  -- Note that here we do not call to `submult`, so we check
  -- for strict equality.
  ; TcCoercionN
coercion <- TypeOrKind
-> CtOrigin -> TcSigmaType -> TcSigmaType -> TcM TcCoercionN
uType TypeOrKind
TypeLevel CtOrigin
origin TcSigmaType
w_actual TcSigmaType
w_expected
  ; HsWrapper -> TcM HsWrapper
forall (m :: * -> *) a. Monad m => a -> m a
return (HsWrapper -> TcM HsWrapper) -> HsWrapper -> TcM HsWrapper
forall a b. (a -> b) -> a -> b
$ if TcCoercionN -> Bool
isReflCo TcCoercionN
coercion then HsWrapper
WpHole else TcCoercionN -> HsWrapper
WpMultCoercion TcCoercionN
coercion }


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

{- Note [Skolemisation]
~~~~~~~~~~~~~~~~~~~~~~~
tcSkolemise takes "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).

Note that for a nested type like
   forall a. Eq a => forall b. Ord b => blah
we still only build one implication constraint
   forall a b. (Eq a, Ord b) => <constraints>
This is just an optimisation, but it's why we use topSkolemise to
build the pieces from all the layers, before making a single call
to checkConstraints.

tcSkolemiseScoped is very similar, but differs in two ways:

* It deals specially with just the outer forall, bringing those type
  variables into lexical scope.  To my surprise, I found that doing
  this unconditionally in tcSkolemise (i.e. doing it even if we don't
  need to bring the variables into lexical scope, which is harmless)
  caused a non-trivial (1%-ish) perf hit on the compiler.

* It always calls checkConstraints, even if there are no skolem
  variables at all.  Reason: there might be nested deferred errors
  that must not be allowed to float to top level.
  See Note [When to build an implication] below.
-}

tcSkolemise, tcSkolemiseScoped
    :: UserTypeCtxt -> TcSigmaType
    -> (TcType -> TcM result)
    -> TcM (HsWrapper, result)
        -- ^ The wrapper has type: spec_ty ~> expected_ty
-- See Note [Skolemisation] for the differences between
-- tcSkolemiseScoped and tcSkolemise

tcSkolemiseScoped :: UserTypeCtxt
-> TcSigmaType
-> (TcSigmaType -> TcM result)
-> TcM (HsWrapper, result)
tcSkolemiseScoped UserTypeCtxt
ctxt TcSigmaType
expected_ty TcSigmaType -> TcM result
thing_inside
  = do { (HsWrapper
wrap, [(Name, Var)]
tv_prs, [Var]
given, TcSigmaType
rho_ty) <- TcSigmaType -> TcM (HsWrapper, [(Name, Var)], [Var], TcSigmaType)
topSkolemise TcSigmaType
expected_ty
       ; let skol_tvs :: [Var]
skol_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 -> TcSigmaType -> [(Name, Var)] -> SkolemInfo
SigSkol UserTypeCtxt
ctxt TcSigmaType
expected_ty [(Name, Var)]
tv_prs

       ; (TcEvBinds
ev_binds, result
res)
             <- SkolemInfo
-> [Var] -> [Var] -> TcM result -> TcM (TcEvBinds, result)
forall result.
SkolemInfo
-> [Var] -> [Var] -> TcM result -> TcM (TcEvBinds, result)
checkConstraints SkolemInfo
skol_info [Var]
skol_tvs [Var]
given (TcM result -> TcM (TcEvBinds, result))
-> TcM result -> TcM (TcEvBinds, result)
forall a b. (a -> b) -> a -> b
$
                [(Name, Var)] -> TcM result -> TcM result
forall r. [(Name, Var)] -> TcM r -> TcM r
tcExtendNameTyVarEnv [(Name, Var)]
tv_prs               (TcM result -> TcM result) -> TcM result -> TcM result
forall a b. (a -> b) -> a -> b
$
                TcSigmaType -> TcM result
thing_inside TcSigmaType
rho_ty

       ; (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
res) }

tcSkolemise :: UserTypeCtxt
-> TcSigmaType
-> (TcSigmaType -> TcM result)
-> TcM (HsWrapper, result)
tcSkolemise UserTypeCtxt
ctxt TcSigmaType
expected_ty TcSigmaType -> TcM result
thing_inside
  | TcSigmaType -> Bool
isRhoTy TcSigmaType
expected_ty  -- Short cut for common case
  = do { result
res <- TcSigmaType -> TcM result
thing_inside TcSigmaType
expected_ty
       ; (HsWrapper, result) -> TcM (HsWrapper, result)
forall (m :: * -> *) a. Monad m => a -> m a
return (HsWrapper
idHsWrapper, result
res) }
  | Bool
otherwise
  = do  { (HsWrapper
wrap, [(Name, Var)]
tv_prs, [Var]
given, TcSigmaType
rho_ty) <- TcSigmaType -> TcM (HsWrapper, [(Name, Var)], [Var], TcSigmaType)
topSkolemise TcSigmaType
expected_ty

        ; let skol_tvs :: [Var]
skol_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 -> TcSigmaType -> [(Name, Var)] -> SkolemInfo
SigSkol UserTypeCtxt
ctxt TcSigmaType
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]
skol_tvs [Var]
given (TcM result -> TcM (TcEvBinds, result))
-> TcM result -> TcM (TcEvBinds, result)
forall a b. (a -> b) -> a -> b
$
                 TcSigmaType -> TcM result
thing_inside TcSigmaType
rho_ty

        ; (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 TcSigmaType
ty) ExpRhoType -> TcM result
thing_inside
  = UserTypeCtxt
-> TcSigmaType
-> (TcSigmaType -> TcM result)
-> TcM (HsWrapper, result)
forall result.
UserTypeCtxt
-> TcSigmaType
-> (TcSigmaType -> TcM result)
-> TcM (HsWrapper, result)
tcSkolemise UserTypeCtxt
ctxt TcSigmaType
ty ((TcSigmaType -> TcM result) -> TcM (HsWrapper, result))
-> (TcSigmaType -> TcM result) -> TcM (HsWrapper, result)
forall a b. (a -> b) -> a -> b
$ \TcSigmaType
rho_ty ->
    ExpRhoType -> TcM result
thing_inside (TcSigmaType -> ExpRhoType
mkCheckExpType TcSigmaType
rho_ty)

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 tcCheckPolyExpr,
              -- 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 -> [Var] -> TcLevel -> WantedConstraints -> TcRn ()
emitResidualTvConstraint SkolemInfo
skol_info [Var]
skol_tvs TcLevel
tclvl WantedConstraints
wanted
       ; result -> TcM result
forall (m :: * -> *) a. Monad m => a -> m a
return result
result }

emitResidualTvConstraint :: SkolemInfo -> [TcTyVar]
                         -> TcLevel -> WantedConstraints -> TcM ()
emitResidualTvConstraint :: SkolemInfo -> [Var] -> TcLevel -> WantedConstraints -> TcRn ()
emitResidualTvConstraint SkolemInfo
skol_info [Var]
skol_tvs TcLevel
tclvl WantedConstraints
wanted
  | Bool -> Bool
not (WantedConstraints -> Bool
isEmptyWC WantedConstraints
wanted) Bool -> Bool -> Bool
||
    SkolemInfo -> Bool
checkTelescopeSkol SkolemInfo
skol_info
  = -- checkTelescopeSkol: in this case, /always/ emit this implication
    -- even if 'wanted' is empty. We need the implication so that we check
    -- for a bad telescope. See Note [Skolem escape and forall-types] in
    -- GHC.Tc.Gen.HsType
    do { Implication
implic <- SkolemInfo
-> [Var] -> TcLevel -> WantedConstraints -> TcM Implication
buildTvImplication SkolemInfo
skol_info [Var]
skol_tvs TcLevel
tclvl WantedConstraints
wanted
       ; Implication -> TcRn ()
emitImplication Implication
implic }

  | Bool
otherwise  -- Empty 'wanted', emit nothing
  = () -> TcRn ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()

buildTvImplication :: SkolemInfo -> [TcTyVar]
                   -> TcLevel -> WantedConstraints -> TcM Implication
buildTvImplication :: SkolemInfo
-> [Var] -> TcLevel -> WantedConstraints -> TcM Implication
buildTvImplication SkolemInfo
skol_info [Var]
skol_tvs TcLevel
tclvl WantedConstraints
wanted
  = do { EvBindsVar
ev_binds <- TcM EvBindsVar
newNoTcEvBinds  -- Used for equalities only, so all the constraints
                                     -- are solved by filling in coercion holes, not
                                     -- by creating a value-level evidence binding
       ; Implication
implic   <- TcM Implication
newImplication

       ; Implication -> TcM Implication
forall (m :: * -> *) a. Monad m => a -> m a
return (Implication
implic { ic_tclvl :: TcLevel
ic_tclvl     = TcLevel
tclvl
                        , ic_skols :: [Var]
ic_skols     = [Var]
skol_tvs
                        , ic_given_eqs :: HasGivenEqs
ic_given_eqs = HasGivenEqs
NoGivenEqs
                        , 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 GHC.Tc.Errors.
  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 separate.
-}

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

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

unifyType :: Maybe SDoc  -- ^ If present, the thing that has type ty1
          -> TcTauType -> TcTauType    -- ty1, ty2
          -> TcM TcCoercionN           -- :: ty1 ~# ty2
-- Actual and expected types
-- Returns a coercion : ty1 ~ ty2
unifyType :: Maybe SDoc -> TcSigmaType -> TcSigmaType -> TcM TcCoercionN
unifyType Maybe SDoc
thing TcSigmaType
ty1 TcSigmaType
ty2
  = TypeOrKind
-> CtOrigin -> TcSigmaType -> TcSigmaType -> TcM TcCoercionN
uType TypeOrKind
TypeLevel CtOrigin
origin TcSigmaType
ty1 TcSigmaType
ty2
  where
    origin :: CtOrigin
origin = TypeEqOrigin :: TcSigmaType -> TcSigmaType -> Maybe SDoc -> Bool -> CtOrigin
TypeEqOrigin { uo_actual :: TcSigmaType
uo_actual   = TcSigmaType
ty1
                          , uo_expected :: TcSigmaType
uo_expected = TcSigmaType
ty2
                          , uo_thing :: Maybe SDoc
uo_thing    = SDoc -> SDoc
forall a. Outputable a => a -> SDoc
ppr (SDoc -> SDoc) -> Maybe SDoc -> Maybe SDoc
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Maybe SDoc
thing
                          , uo_visible :: Bool
uo_visible  = Bool
True }

unifyTypeET :: TcTauType -> TcTauType -> TcM CoercionN
-- Like unifyType, but swap expected and actual in error messages
-- This is used when typechecking patterns
unifyTypeET :: TcSigmaType -> TcSigmaType -> TcM TcCoercionN
unifyTypeET TcSigmaType
ty1 TcSigmaType
ty2
  = TypeOrKind
-> CtOrigin -> TcSigmaType -> TcSigmaType -> TcM TcCoercionN
uType TypeOrKind
TypeLevel CtOrigin
origin TcSigmaType
ty1 TcSigmaType
ty2
  where
    origin :: CtOrigin
origin = TypeEqOrigin :: TcSigmaType -> TcSigmaType -> Maybe SDoc -> Bool -> CtOrigin
TypeEqOrigin { uo_actual :: TcSigmaType
uo_actual   = TcSigmaType
ty2   -- NB swapped
                          , uo_expected :: TcSigmaType
uo_expected = TcSigmaType
ty1   -- NB swapped
                          , uo_thing :: Maybe SDoc
uo_thing    = Maybe SDoc
forall a. Maybe a
Nothing
                          , uo_visible :: Bool
uo_visible  = Bool
True }


unifyKind :: Maybe SDoc -> TcKind -> TcKind -> TcM CoercionN
unifyKind :: Maybe SDoc -> TcSigmaType -> TcSigmaType -> TcM TcCoercionN
unifyKind Maybe SDoc
mb_thing TcSigmaType
ty1 TcSigmaType
ty2
  = TypeOrKind
-> CtOrigin -> TcSigmaType -> TcSigmaType -> TcM TcCoercionN
uType TypeOrKind
KindLevel CtOrigin
origin TcSigmaType
ty1 TcSigmaType
ty2
  where
    origin :: CtOrigin
origin = TypeEqOrigin :: TcSigmaType -> TcSigmaType -> Maybe SDoc -> Bool -> CtOrigin
TypeEqOrigin { uo_actual :: TcSigmaType
uo_actual   = TcSigmaType
ty1
                          , uo_expected :: TcSigmaType
uo_expected = TcSigmaType
ty2
                          , uo_thing :: Maybe SDoc
uo_thing    = Maybe SDoc
mb_thing
                          , uo_visible :: Bool
uo_visible  = Bool
True }


{-
%************************************************************************
%*                                                                      *
                 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 -> TcSigmaType -> TcSigmaType -> TcM TcCoercionN
uType_defer TypeOrKind
t_or_k CtOrigin
origin TcSigmaType
ty1 TcSigmaType
ty2
  = do { TcCoercionN
co <- CtOrigin
-> TypeOrKind
-> Role
-> TcSigmaType
-> TcSigmaType
-> TcM TcCoercionN
emitWantedEq CtOrigin
origin TypeOrKind
t_or_k Role
Nominal TcSigmaType
ty1 TcSigmaType
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 [ TcSigmaType -> SDoc
debugPprType TcSigmaType
ty1
                                          , TcSigmaType -> SDoc
debugPprType TcSigmaType
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 -> TcSigmaType -> TcSigmaType -> TcM TcCoercionN
uType TypeOrKind
t_or_k CtOrigin
origin TcSigmaType
orig_ty1 TcSigmaType
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 [ TcSigmaType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcSigmaType
orig_ty1, String -> SDoc
text String
"~", TcSigmaType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcSigmaType
orig_ty2]
              , CtOrigin -> SDoc
pprCtOrigin CtOrigin
origin]
       ; TcCoercionN
co <- TcSigmaType -> TcSigmaType -> TcM TcCoercionN
go TcSigmaType
orig_ty1 TcSigmaType
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 :: TcSigmaType -> TcSigmaType -> TcM TcCoercionN
go (CastTy TcSigmaType
t1 TcCoercionN
co1) TcSigmaType
t2
      = do { TcCoercionN
co_tys <- TypeOrKind
-> CtOrigin -> TcSigmaType -> TcSigmaType -> TcM TcCoercionN
uType TypeOrKind
t_or_k CtOrigin
origin TcSigmaType
t1 TcSigmaType
t2
           ; TcCoercionN -> TcM TcCoercionN
forall (m :: * -> *) a. Monad m => a -> m a
return (Role -> TcSigmaType -> TcCoercionN -> TcCoercionN -> TcCoercionN
mkCoherenceLeftCo Role
Nominal TcSigmaType
t1 TcCoercionN
co1 TcCoercionN
co_tys) }

    go TcSigmaType
t1 (CastTy TcSigmaType
t2 TcCoercionN
co2)
      = do { TcCoercionN
co_tys <- TypeOrKind
-> CtOrigin -> TcSigmaType -> TcSigmaType -> TcM TcCoercionN
uType TypeOrKind
t_or_k CtOrigin
origin TcSigmaType
t1 TcSigmaType
t2
           ; TcCoercionN -> TcM TcCoercionN
forall (m :: * -> *) a. Monad m => a -> m a
return (Role -> TcSigmaType -> TcCoercionN -> TcCoercionN -> TcCoercionN
mkCoherenceRightCo Role
Nominal TcSigmaType
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) TcSigmaType
ty2
      = do { Maybe TcSigmaType
lookup_res <- Var -> TcM (Maybe TcSigmaType)
isFilledMetaTyVar_maybe Var
tv1
           ; case Maybe TcSigmaType
lookup_res of
               Just TcSigmaType
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
<+> TcSigmaType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcSigmaType
ty1)
                                ; TcSigmaType -> TcSigmaType -> TcM TcCoercionN
go TcSigmaType
ty1 TcSigmaType
ty2 }
               Maybe TcSigmaType
Nothing  -> CtOrigin
-> TypeOrKind -> SwapFlag -> Var -> TcSigmaType -> TcM TcCoercionN
uUnfilledVar CtOrigin
origin TypeOrKind
t_or_k SwapFlag
NotSwapped Var
tv1 TcSigmaType
ty2 }
    go TcSigmaType
ty1 (TyVarTy Var
tv2)
      = do { Maybe TcSigmaType
lookup_res <- Var -> TcM (Maybe TcSigmaType)
isFilledMetaTyVar_maybe Var
tv2
           ; case Maybe TcSigmaType
lookup_res of
               Just TcSigmaType
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
<+> TcSigmaType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcSigmaType
ty2)
                              ; TcSigmaType -> TcSigmaType -> TcM TcCoercionN
go TcSigmaType
ty1 TcSigmaType
ty2 }
               Maybe TcSigmaType
Nothing  -> CtOrigin
-> TypeOrKind -> SwapFlag -> Var -> TcSigmaType -> TcM TcCoercionN
uUnfilledVar CtOrigin
origin TypeOrKind
t_or_k SwapFlag
IsSwapped Var
tv2 TcSigmaType
ty1 }

      -- See Note [Expanding synonyms during unification]
    go ty1 :: TcSigmaType
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
$ TcSigmaType -> TcCoercionN
mkNomReflCo TcSigmaType
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 TcSigmaType
ty1 TcSigmaType
ty2
      | Just TcSigmaType
ty1' <- TcSigmaType -> Maybe TcSigmaType
tcView TcSigmaType
ty1 = TcSigmaType -> TcSigmaType -> TcM TcCoercionN
go TcSigmaType
ty1' TcSigmaType
ty2
      | Just TcSigmaType
ty2' <- TcSigmaType -> Maybe TcSigmaType
tcView TcSigmaType
ty2 = TcSigmaType -> TcSigmaType -> TcM TcCoercionN
go TcSigmaType
ty1  TcSigmaType
ty2'

    -- Functions (t1 -> t2) just check the two parts
    -- Do not attempt (c => t); just defer
    go (FunTy { ft_af :: TcSigmaType -> AnonArgFlag
ft_af = AnonArgFlag
VisArg, ft_mult :: TcSigmaType -> TcSigmaType
ft_mult = TcSigmaType
w1, ft_arg :: TcSigmaType -> TcSigmaType
ft_arg = TcSigmaType
arg1, ft_res :: TcSigmaType -> TcSigmaType
ft_res = TcSigmaType
res1 })
       (FunTy { ft_af :: TcSigmaType -> AnonArgFlag
ft_af = AnonArgFlag
VisArg, ft_mult :: TcSigmaType -> TcSigmaType
ft_mult = TcSigmaType
w2, ft_arg :: TcSigmaType -> TcSigmaType
ft_arg = TcSigmaType
arg2, ft_res :: TcSigmaType -> TcSigmaType
ft_res = TcSigmaType
res2 })
      = do { TcCoercionN
co_l <- TypeOrKind
-> CtOrigin -> TcSigmaType -> TcSigmaType -> TcM TcCoercionN
uType TypeOrKind
t_or_k CtOrigin
origin TcSigmaType
arg1 TcSigmaType
arg2
           ; TcCoercionN
co_r <- TypeOrKind
-> CtOrigin -> TcSigmaType -> TcSigmaType -> TcM TcCoercionN
uType TypeOrKind
t_or_k CtOrigin
origin TcSigmaType
res1 TcSigmaType
res2
           ; TcCoercionN
co_w <- TypeOrKind
-> CtOrigin -> TcSigmaType -> TcSigmaType -> TcM TcCoercionN
uType TypeOrKind
t_or_k CtOrigin
origin TcSigmaType
w1 TcSigmaType
w2
           ; 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
mkFunCo Role
Nominal TcCoercionN
co_w TcCoercionN
co_l TcCoercionN
co_r }

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

    go (TyConApp TyCon
tc1 ThetaType
tys1) (TyConApp TyCon
tc2 ThetaType
tys2)
      -- See Note [Mismatched type lists and application decomposition]
      | TyCon
tc1 TyCon -> TyCon -> Bool
forall a. Eq a => a -> a -> Bool
== TyCon
tc2, ThetaType -> ThetaType -> Bool
forall a b. [a] -> [b] -> Bool
equalLength ThetaType
tys1 ThetaType
tys2
      = ASSERT2( isGenerativeTyCon tc1 Nominal, ppr tc1 )
        do { [TcCoercionN]
cos <- (CtOrigin -> TcSigmaType -> TcSigmaType -> TcM TcCoercionN)
-> [CtOrigin]
-> ThetaType
-> ThetaType
-> 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 -> TcSigmaType -> TcSigmaType -> TcM TcCoercionN
uType TypeOrKind
t_or_k) [CtOrigin]
origins' ThetaType
tys1 ThetaType
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 :: TcSigmaType
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
$ TcSigmaType -> TcCoercionN
mkNomReflCo TcSigmaType
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 TcSigmaType
s1 TcSigmaType
t1) (AppTy TcSigmaType
s2 TcSigmaType
t2)
      = Bool
-> TcSigmaType
-> TcSigmaType
-> TcSigmaType
-> TcSigmaType
-> TcM TcCoercionN
go_app (TcSigmaType -> Bool
isNextArgVisible TcSigmaType
s1) TcSigmaType
s1 TcSigmaType
t1 TcSigmaType
s2 TcSigmaType
t2

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

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

    go (CoercionTy TcCoercionN
co1) (CoercionTy TcCoercionN
co2)
      = do { let ty1 :: TcSigmaType
ty1 = TcCoercionN -> TcSigmaType
coercionType TcCoercionN
co1
                 ty2 :: TcSigmaType
ty2 = TcCoercionN -> TcSigmaType
coercionType TcCoercionN
co2
           ; TcCoercionN
kco <- TypeOrKind
-> CtOrigin -> TcSigmaType -> TcSigmaType -> TcM TcCoercionN
uType TypeOrKind
KindLevel
                          (TcSigmaType
-> Maybe TcSigmaType -> CtOrigin -> Maybe TypeOrKind -> CtOrigin
KindEqOrigin TcSigmaType
orig_ty1 (TcSigmaType -> Maybe TcSigmaType
forall a. a -> Maybe a
Just TcSigmaType
orig_ty2) CtOrigin
origin
                                        (TypeOrKind -> Maybe TypeOrKind
forall a. a -> Maybe a
Just TypeOrKind
t_or_k))
                          TcSigmaType
ty1 TcSigmaType
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 TcSigmaType
ty1 TcSigmaType
ty2 = TcSigmaType -> TcSigmaType -> TcM TcCoercionN
defer TcSigmaType
ty1 TcSigmaType
ty2

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

    ------------------
    go_app :: Bool
-> TcSigmaType
-> TcSigmaType
-> TcSigmaType
-> TcSigmaType
-> TcM TcCoercionN
go_app Bool
vis TcSigmaType
s1 TcSigmaType
t1 TcSigmaType
s2 TcSigmaType
t2
      = do { TcCoercionN
co_s <- TypeOrKind
-> CtOrigin -> TcSigmaType -> TcSigmaType -> TcM TcCoercionN
uType TypeOrKind
t_or_k CtOrigin
origin TcSigmaType
s1 TcSigmaType
s2
           ; let arg_origin :: CtOrigin
arg_origin
                   | Bool
vis       = CtOrigin
origin
                   | Bool
otherwise = CtOrigin -> CtOrigin
toInvisibleOrigin CtOrigin
origin
           ; TcCoercionN
co_t <- TypeOrKind
-> CtOrigin -> TcSigmaType -> TcSigmaType -> TcM TcCoercionN
uType TypeOrKind
t_or_k CtOrigin
arg_origin TcSigmaType
t1 TcSigmaType
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 -> TcSigmaType -> TcM TcCoercionN
uUnfilledVar CtOrigin
origin TypeOrKind
t_or_k SwapFlag
swapped Var
tv1 TcSigmaType
ty2
  = do { TcSigmaType
ty2 <- TcSigmaType -> TcM TcSigmaType
zonkTcType TcSigmaType
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 -> TcSigmaType -> TcM TcCoercionN
uUnfilledVar1 CtOrigin
origin TypeOrKind
t_or_k SwapFlag
swapped Var
tv1 TcSigmaType
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 -> TcSigmaType -> TcM TcCoercionN
uUnfilledVar1 CtOrigin
origin TypeOrKind
t_or_k SwapFlag
swapped Var
tv1 TcSigmaType
ty2
  | Just Var
tv2 <- TcSigmaType -> Maybe Var
tcGetTyVar_maybe TcSigmaType
ty2
  = Var -> TcM TcCoercionN
go Var
tv2

  | Bool
otherwise
  = CtOrigin
-> TypeOrKind -> SwapFlag -> Var -> TcSigmaType -> TcM TcCoercionN
uUnfilledVar2 CtOrigin
origin TypeOrKind
t_or_k SwapFlag
swapped Var
tv1 TcSigmaType
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 (TcSigmaType -> TcCoercionN
mkNomReflCo (Var -> TcSigmaType
mkTyVarTy Var
tv1))

           | Bool -> Var -> Var -> Bool
swapOverTyVars Bool
False 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 -> TcSigmaType -> TcM TcCoercionN
uUnfilledVar2 CtOrigin
origin TypeOrKind
t_or_k (SwapFlag -> SwapFlag
flipSwap SwapFlag
swapped)
                           Var
tv2 (Var -> TcSigmaType
mkTyVarTy Var
tv1) }

           | Bool
otherwise
           = CtOrigin
-> TypeOrKind -> SwapFlag -> Var -> TcSigmaType -> TcM TcCoercionN
uUnfilledVar2 CtOrigin
origin TypeOrKind
t_or_k SwapFlag
swapped Var
tv1 TcSigmaType
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 -> TcSigmaType -> TcM TcCoercionN
uUnfilledVar2 CtOrigin
origin TypeOrKind
t_or_k SwapFlag
swapped Var
tv1 TcSigmaType
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 -> Bool
isTouchableMetaTyVar TcLevel
cur_lvl Var
tv1
           -- See Note [Unification preconditions], (UNTOUCHABLE) wrinkles
      , MetaInfo -> TcSigmaType -> Bool
canSolveByUnification (Var -> MetaInfo
metaTyVarInfo Var
tv1) TcSigmaType
ty2
      , CheckTyEqResult
CTE_OK <- DynFlags
-> AreTypeFamiliesOK -> Var -> TcSigmaType -> CheckTyEqResult
checkTyVarEq DynFlags
dflags AreTypeFamiliesOK
NoTypeFamilies Var
tv1 TcSigmaType
ty2
           -- See Note [Prevent unification with type families] about the NoTypeFamilies:
      = do { TcCoercionN
co_k <- TypeOrKind
-> CtOrigin -> TcSigmaType -> TcSigmaType -> TcM TcCoercionN
uType TypeOrKind
KindLevel CtOrigin
kind_origin (HasDebugCallStack => TcSigmaType -> TcSigmaType
TcSigmaType -> TcSigmaType
tcTypeKind TcSigmaType
ty2) (Var -> TcSigmaType
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
<+> TcSigmaType -> SDoc
forall a. Outputable a => a -> SDoc
ppr (Var -> TcSigmaType
tyVarKind Var
tv1)
                  , TcSigmaType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcSigmaType
ty2 SDoc -> SDoc -> SDoc
<+> SDoc
dcolon SDoc -> SDoc -> SDoc
<+> TcSigmaType -> SDoc
forall a. Outputable a => a -> SDoc
ppr (HasDebugCallStack => TcSigmaType -> TcSigmaType
TcSigmaType -> TcSigmaType
tcTypeKind  TcSigmaType
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 -> TcSigmaType -> TcRn ()
writeMetaTyVar Var
tv1 TcSigmaType
ty2
                     ; TcCoercionN -> TcM TcCoercionN
forall (m :: * -> *) a. Monad m => a -> m a
return (TcSigmaType -> TcCoercionN
mkTcNomReflCo TcSigmaType
ty2) }

             else TcM TcCoercionN
defer } -- This cannot be solved now.  See GHC.Tc.Solver.Canonical
                          -- 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
$$ TcSigmaType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcSigmaType
ty2)
               -- Occurs check or an untouchable: just defer
               -- NB: occurs check isn't necessarily fatal:
               --     eg tv1 occurred in type family parameter
            ; TcM TcCoercionN
defer }

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

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

canSolveByUnification :: MetaInfo -> TcType -> Bool
-- See Note [Unification preconditions, (TYVAR-TV)]
canSolveByUnification :: MetaInfo -> TcSigmaType -> Bool
canSolveByUnification MetaInfo
info TcSigmaType
xi
  = case MetaInfo
info of
      MetaInfo
CycleBreakerTv -> Bool
False
      MetaInfo
TyVarTv -> case TcSigmaType -> Maybe Var
tcGetTyVar_maybe TcSigmaType
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
      MetaInfo
_ -> Bool
True

swapOverTyVars :: Bool -> TcTyVar -> TcTyVar -> Bool
swapOverTyVars :: Bool -> Var -> Var -> Bool
swapOverTyVars Bool
is_given Var
tv1 Var
tv2
  -- See Note [Unification variables on the left]
  | Bool -> Bool
not Bool
is_given, Arity
pri1 Arity -> Arity -> Bool
forall a. Eq a => a -> a -> Bool
== Arity
0, Arity
pri2 Arity -> Arity -> Bool
forall a. Ord a => a -> a -> Bool
> Arity
0 = Bool
True
  | Bool -> Bool
not Bool
is_given, Arity
pri2 Arity -> Arity -> Bool
forall a. Eq a => a -> a -> Bool
== Arity
0, Arity
pri1 Arity -> Arity -> Bool
forall a. Ord a => a -> a -> Bool
> Arity
0 = Bool
False

  -- 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
--        => more likely to be eliminated
-- 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
CycleBreakerTv -> Arity
0
                                     MetaInfo
TyVarTv        -> Arity
1
                                     MetaInfo
TauTv          -> Arity
2
                                     MetaInfo
RuntimeUnkTv   -> Arity
3

{- Note [Unification preconditions]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Question: given a homogeneous equality (alpha ~# ty), when is it OK to
unify alpha := ty?

This note only applied to /homogeneous/ equalities, in which both
sides have the same kind.

There are three reasons not to unify:

1. (SKOL-ESC) Skolem-escape
   Consider the constraint
        forall[2] a[2]. alpha[1] ~ Maybe a[2]
   If we unify alpha := Maybe a, the skolem 'a' may escape its scope.
   The level alpha[1] says that alpha may be used outside this constraint,
   where 'a' is not in scope at all.  So we must not unify.

   Bottom line: when looking at a constraint alpha[n] := ty, do not unify
   if any free variable of 'ty' has level deeper (greater) than n

2. (UNTOUCHABLE) Untouchable unification variables
   Consider the constraint
        forall[2] a[2]. b[1] ~ Int => alpha[1] ~ Int
   There is no (SKOL-ESC) problem with unifying alpha := Int, but it might
   not be the principal solution. Perhaps the "right" solution is alpha := b.
   We simply can't tell.  See "OutsideIn(X): modular type inference with local
   assumptions", section 2.2.  We say that alpha[1] is "untouchable" inside
   this implication.

   Bottom line: at amibient level 'l', when looking at a constraint
   alpha[n] ~ ty, do not unify alpha := ty if there are any given equalities
   between levels 'n' and 'l'.

   Exactly what is a "given equality" for the purpose of (UNTOUCHABLE)?
   Answer: see Note [Tracking Given equalities] in GHC.Tc.Solver.Monad

3. (TYVAR-TV) Unifying TyVarTvs and CycleBreakerTvs
   This precondition looks at the MetaInfo of the unification variable:

   * TyVarTv: When considering alpha{tyv} ~ ty, if alpha{tyv} is a
     TyVarTv it can only unify with a type variable, not with a
     structured type.  So if 'ty' is a structured type, such as (Maybe x),
     don't unify.

   * CycleBreakerTv: never unified, except by restoreTyVarCycles.


Needless to say, all three have wrinkles:

* (SKOL-ESC) Promotion.  Given alpha[n] ~ ty, what if beta[k] is free
  in 'ty', where beta is a unification variable, and k>n?  'beta'
  stands for a monotype, and since it is part of a level-n type
  (equal to alpha[n]), we must /promote/ beta to level n.  Just make
  up a fresh gamma[n], and unify beta[k] := gamma[n].

* (TYVAR-TV) Unification variables.  Suppose alpha[tyv,n] is a level-n
  TyVarTv (see Note [TyVarTv] in GHC.Tc.Types.TcMType)? Now
  consider alpha[tyv,n] ~ Bool.  We don't want to unify because that
  would break the TyVarTv invariant.

  What about alpha[tyv,n] ~ beta[tau,n], where beta is an ordinary
  TauTv?  Again, don't unify, because beta might later be unified
  with, say Bool.  (If levels permit, we reverse the orientation here;
  see Note [TyVar/TyVar orientation].)

* (UNTOUCHABLE) Untouchability.  When considering (alpha[n] ~ ty), how
  do we know whether there are any given equalities between level n
  and the ambient level?  We answer in two ways:

  * In the eager unifier, we only unify if l=n.  If not, alpha may be
    untouchable, and defer to the constraint solver.  This check is
    made in GHC.Tc.Utils.uUnifilledVar2, in the guard
    isTouchableMetaTyVar.

  * In the constraint solver, we track where Given equalities occur
    and use that to guard unification in GHC.Tc.Solver.Canonical.unifyTest
    More details in Note [Tracking Given equalities] in GHC.Tc.Solver.Monad

    Historical note: in the olden days (pre 2021) the constraint solver
    also used to unify only if l=n.  Equalities were "floated" out of the
    implication in a separate step, so that they would become touchable.
    But the float/don't-float question turned out to be very delicate,
    as you can see if you look at the long series of Notes associated with
    GHC.Tc.Solver.floatEqualities, around Nov 2020.  It's much easier
    to unify in-place, with no floating.

Note [TyVar/TyVar orientation]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Given (a ~ b), should we orient the CEqCan as (a~b) or (b~a)?
This is a surprisingly tricky question! This is invariant (TyEq:TV).

The question is answered by swapOverTyVars, which is used
  - in the eager unifier, in GHC.Tc.Utils.Unify.uUnfilledVar1
  - in the constraint solver, in GHC.Tc.Solver.Canonical.canEqCanLHS2

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

  Generally speaking we always try to put a MetaTv on the left
  in preference to SkolemTv or RuntimeUnkTv:
     a) Because the MetaTv may be touchable and can be unified
     b) Even if it's not touchable, GHC.Tc.Solver.floatEqualities
        looks for meta tyvars on the left

  Tie-breaking rules for MetaTvs:
  - CycleBreakerTv: This is essentially a stand-in for another type;
       it's untouchable and should have the same priority as a skolem: 0.

  - TyVarTv: These can unify only with another tyvar, but we can't unify
       a TyVarTv with a TauTv, because then the TyVarTv could (transitively)
       get a non-tyvar type. So give these a low priority: 1.

  - TauTv: This is the common case; we want these on the left so that they
       can be written to: 2.

  - RuntimeUnkTv: These aren't really meta-variables used in type inference,
       but just a convenience in the implementation of the GHCi debugger.
       Eagerly write to these: 3. See Note [RuntimeUnkTv] in
       GHC.Runtime.Heap.Inspect.

* Names. If the level and priority comparisons are all
  equal, try to eliminate a TyVar 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 [Unification variables on the left]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For wanteds, but not givens, swap (skolem ~ meta-tv) regardless of
level, so that the unification variable is on the left.

* We /don't/ want this for Givens because if we ave
    [G] a[2] ~ alpha[1]
    [W] Bool ~ a[2]
  we want to rewrite the wanted to Bool ~ alpha[1],
  so we can float the constraint and solve it.

* But for Wanteds putting the unification variable on
  the left means an easier job when floating, and when
  reporting errors -- just fewer cases to consider.

  In particular, we get better skolem-escape messages:
  see #18114

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 GHC.Tc.Solver.Monad 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 [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

Historical 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 too nice to discard altogether, so I'm leaving these
notes.  SLPJ Jan 18.

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

Revisited in Nov '20, along with removing flattening variables. Problem
is still present, and the solution (NoTypeFamilies) is still the same.

Note [Refactoring hazard: metaTyVarUpdateOK]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
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 GHC.Tc.Solver.Interact,
function @occ_check_ok@.

Note [Non-TcTyVars in GHC.Tc.Utils.Unify]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
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 GHC.Tc.TyCl"). 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.
-}

-- | 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 -> TcSigmaType -> TcM TcCoercionN
matchExpectedFunKind fun
hs_ty Arity
n TcSigmaType
k = Arity -> TcSigmaType -> TcM TcCoercionN
go Arity
n TcSigmaType
k
  where
    go :: Arity -> TcSigmaType -> TcM TcCoercionN
go Arity
0 TcSigmaType
k = TcCoercionN -> TcM TcCoercionN
forall (m :: * -> *) a. Monad m => a -> m a
return (TcSigmaType -> TcCoercionN
mkNomReflCo TcSigmaType
k)

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

    go Arity
n k :: TcSigmaType
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 TcSigmaType
fun_kind -> Arity -> TcSigmaType -> TcM TcCoercionN
go Arity
n TcSigmaType
fun_kind
                MetaDetails
Flexi ->             Arity -> TcSigmaType -> TcM TcCoercionN
defer Arity
n TcSigmaType
k }

    go Arity
n (FunTy { ft_mult :: TcSigmaType -> TcSigmaType
ft_mult = TcSigmaType
w, ft_arg :: TcSigmaType -> TcSigmaType
ft_arg = TcSigmaType
arg, ft_res :: TcSigmaType -> TcSigmaType
ft_res = TcSigmaType
res })
      = do { TcCoercionN
co <- Arity -> TcSigmaType -> TcM TcCoercionN
go (Arity
nArity -> Arity -> Arity
forall a. Num a => a -> a -> a
-Arity
1) TcSigmaType
res
           ; TcCoercionN -> TcM TcCoercionN
forall (m :: * -> *) a. Monad m => a -> m a
return (Role -> TcCoercionN -> TcCoercionN -> TcCoercionN -> TcCoercionN
mkTcFunCo Role
Nominal (TcSigmaType -> TcCoercionN
mkTcNomReflCo TcSigmaType
w) (TcSigmaType -> TcCoercionN
mkTcNomReflCo TcSigmaType
arg) TcCoercionN
co) }

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

    defer :: Arity -> TcSigmaType -> TcM TcCoercionN
defer Arity
n TcSigmaType
k
      = do { ThetaType
arg_kinds <- Arity -> TcM ThetaType
newMetaKindVars Arity
n
           ; TcSigmaType
res_kind  <- TcM TcSigmaType
newMetaKindVar
           ; let new_fun :: TcSigmaType
new_fun = ThetaType -> TcSigmaType -> TcSigmaType
mkVisFunTysMany ThetaType
arg_kinds TcSigmaType
res_kind
                 origin :: CtOrigin
origin  = TypeEqOrigin :: TcSigmaType -> TcSigmaType -> Maybe SDoc -> Bool -> CtOrigin
TypeEqOrigin { uo_actual :: TcSigmaType
uo_actual   = TcSigmaType
k
                                        , uo_expected :: TcSigmaType
uo_expected = TcSigmaType
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 -> TcSigmaType -> TcSigmaType -> TcM TcCoercionN
uType TypeOrKind
KindLevel CtOrigin
origin TcSigmaType
k TcSigmaType
new_fun }

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


{-  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] in GHC.Core.Type)
we do need to look in beta's kind.  So we carry a flag saying if a
'forall' is OK, and switch 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 CheckTyEqResult
  = CTE_OK
  | CTE_Bad          -- Forall, predicate, or type family
  | CTE_HoleBlocker  -- Blocking coercion hole
        -- See Note [Equalities with incompatible kinds] in "GHC.Tc.Solver.Canonical"
  | CTE_Occurs

instance S.Semigroup CheckTyEqResult where
  CheckTyEqResult
CTE_OK <> :: CheckTyEqResult -> CheckTyEqResult -> CheckTyEqResult
<> CheckTyEqResult
x = CheckTyEqResult
x
  CheckTyEqResult
x      <> CheckTyEqResult
_ = CheckTyEqResult
x

instance Monoid CheckTyEqResult where
  mempty :: CheckTyEqResult
mempty = CheckTyEqResult
CTE_OK

instance Outputable CheckTyEqResult where
  ppr :: CheckTyEqResult -> SDoc
ppr CheckTyEqResult
CTE_OK          = String -> SDoc
text String
"CTE_OK"
  ppr CheckTyEqResult
CTE_Bad         = String -> SDoc
text String
"CTE_Bad"
  ppr CheckTyEqResult
CTE_HoleBlocker = String -> SDoc
text String
"CTE_HoleBlocker"
  ppr CheckTyEqResult
CTE_Occurs      = String -> SDoc
text String
"CTE_Occurs"

occCheckForErrors :: DynFlags -> TcTyVar -> Type -> CheckTyEqResult
-- Just for error-message generation; so we return CheckTyEqResult
-- 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 -> TcSigmaType -> CheckTyEqResult
occCheckForErrors DynFlags
dflags Var
tv TcSigmaType
ty
  = case DynFlags
-> AreTypeFamiliesOK -> Var -> TcSigmaType -> CheckTyEqResult
checkTyVarEq DynFlags
dflags AreTypeFamiliesOK
YesTypeFamilies Var
tv TcSigmaType
ty of
      CheckTyEqResult
CTE_Occurs -> case [Var] -> TcSigmaType -> Maybe TcSigmaType
occCheckExpand [Var
tv] TcSigmaType
ty of
                        Maybe TcSigmaType
Nothing -> CheckTyEqResult
CTE_Occurs
                        Just TcSigmaType
_  -> CheckTyEqResult
CTE_OK
      CheckTyEqResult
other       -> CheckTyEqResult
other

----------------
data AreTypeFamiliesOK = YesTypeFamilies
                       | NoTypeFamilies
                       deriving AreTypeFamiliesOK -> AreTypeFamiliesOK -> Bool
(AreTypeFamiliesOK -> AreTypeFamiliesOK -> Bool)
-> (AreTypeFamiliesOK -> AreTypeFamiliesOK -> Bool)
-> Eq AreTypeFamiliesOK
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: AreTypeFamiliesOK -> AreTypeFamiliesOK -> Bool
$c/= :: AreTypeFamiliesOK -> AreTypeFamiliesOK -> Bool
== :: AreTypeFamiliesOK -> AreTypeFamiliesOK -> Bool
$c== :: AreTypeFamiliesOK -> AreTypeFamiliesOK -> Bool
Eq

instance Outputable AreTypeFamiliesOK where
  ppr :: AreTypeFamiliesOK -> SDoc
ppr AreTypeFamiliesOK
YesTypeFamilies = String -> SDoc
text String
"YesTypeFamilies"
  ppr AreTypeFamiliesOK
NoTypeFamilies  = String -> SDoc
text String
"NoTypeFamilies"

checkTyVarEq :: DynFlags -> AreTypeFamiliesOK -> TcTyVar -> TcType -> CheckTyEqResult
checkTyVarEq :: DynFlags
-> AreTypeFamiliesOK -> Var -> TcSigmaType -> CheckTyEqResult
checkTyVarEq DynFlags
dflags AreTypeFamiliesOK
ty_fam_ok Var
tv TcSigmaType
ty
  = (DynFlags
 -> AreTypeFamiliesOK -> CanEqLHS -> TcSigmaType -> CheckTyEqResult)
-> DynFlags
-> AreTypeFamiliesOK
-> CanEqLHS
-> TcSigmaType
-> CheckTyEqResult
forall a. a -> a
inline DynFlags
-> AreTypeFamiliesOK -> CanEqLHS -> TcSigmaType -> CheckTyEqResult
checkTypeEq DynFlags
dflags AreTypeFamiliesOK
ty_fam_ok (Var -> CanEqLHS
TyVarLHS Var
tv) TcSigmaType
ty
    -- inline checkTypeEq so that the `case`s over the CanEqLHS get blasted away

checkTyFamEq :: DynFlags
             -> TyCon     -- type function
             -> [TcType]  -- args, exactly saturated
             -> TcType    -- RHS
             -> CheckTyEqResult
checkTyFamEq :: DynFlags -> TyCon -> ThetaType -> TcSigmaType -> CheckTyEqResult
checkTyFamEq DynFlags
dflags TyCon
fun_tc ThetaType
fun_args TcSigmaType
ty
  = (DynFlags
 -> AreTypeFamiliesOK -> CanEqLHS -> TcSigmaType -> CheckTyEqResult)
-> DynFlags
-> AreTypeFamiliesOK
-> CanEqLHS
-> TcSigmaType
-> CheckTyEqResult
forall a. a -> a
inline DynFlags
-> AreTypeFamiliesOK -> CanEqLHS -> TcSigmaType -> CheckTyEqResult
checkTypeEq DynFlags
dflags AreTypeFamiliesOK
YesTypeFamilies (TyCon -> ThetaType -> CanEqLHS
TyFamLHS TyCon
fun_tc ThetaType
fun_args) TcSigmaType
ty
    -- inline checkTypeEq so that the `case`s over the CanEqLHS get blasted away

checkTypeEq :: DynFlags -> AreTypeFamiliesOK -> CanEqLHS -> TcType
            -> CheckTyEqResult
-- Checks the invariants for CEqCan.   In particular:
--   (a) a forall type (forall a. blah)
--   (b) a predicate type (c => ty)
--   (c) a type family; see Note [Prevent unification with type families]
--   (d) a blocking coercion hole
--   (e) an occurrence of the LHS (occurs check)
--
-- Note that an occurs-check does not mean "definite error".  For example
--   type family F a
--   type instance F Int = Int
-- consider
--   b0 ~ F b0
-- This is perfectly reasonable, if we later get b0 ~ Int.  But we
-- certainly can't unify b0 := F b0
--
-- For (a), (b), and (c) we check only the top level of the type, NOT
-- inside the kinds of variables it mentions.  For (d) we look deeply
-- in coercions when the LHS is a tyvar (but skip coercions for type family
-- LHSs), and for (e) see Note [CEqCan occurs check] in GHC.Tc.Types.Constraint.
--
-- checkTypeEq is called from
--    * checkTyFamEq, checkTyVarEq (which inline it to specialise away the
--      case-analysis on 'lhs')
--    * checkEqCanLHSFinish, which does not know the form of 'lhs'
checkTypeEq :: DynFlags
-> AreTypeFamiliesOK -> CanEqLHS -> TcSigmaType -> CheckTyEqResult
checkTypeEq DynFlags
dflags AreTypeFamiliesOK
ty_fam_ok CanEqLHS
lhs TcSigmaType
ty
  = TcSigmaType -> CheckTyEqResult
go TcSigmaType
ty
  where
    -- The GHCi runtime debugger does its type-matching with
    -- unification variables that can unify with a polytype
    -- or a TyCon that would usually be disallowed by bad_tc
    -- See Note [RuntimeUnkTv] in GHC.Runtime.Heap.Inspect
    ghci_tv :: Bool
ghci_tv
      | TyVarLHS Var
tv <- CanEqLHS
lhs
      , MetaTv { mtv_info :: TcTyVarDetails -> MetaInfo
mtv_info = MetaInfo
RuntimeUnkTv } <- Var -> TcTyVarDetails
tcTyVarDetails Var
tv
      = Bool
True

      | Bool
otherwise
      = Bool
False

    go :: TcType -> CheckTyEqResult
    go :: TcSigmaType -> CheckTyEqResult
go (TyVarTy Var
tv')           = Var -> CheckTyEqResult
go_tv Var
tv'
    go (TyConApp TyCon
tc ThetaType
tys)       = TyCon -> ThetaType -> CheckTyEqResult
go_tc TyCon
tc ThetaType
tys
    go (LitTy {})              = CheckTyEqResult
CTE_OK
    go (FunTy{ft_af :: TcSigmaType -> AnonArgFlag
ft_af = AnonArgFlag
af, ft_mult :: TcSigmaType -> TcSigmaType
ft_mult = TcSigmaType
w, ft_arg :: TcSigmaType -> TcSigmaType
ft_arg = TcSigmaType
a, ft_res :: TcSigmaType -> TcSigmaType
ft_res = TcSigmaType
r})
      | AnonArgFlag
InvisArg <- AnonArgFlag
af
      , Bool -> Bool
not Bool
ghci_tv            = CheckTyEqResult
CTE_Bad
      | Bool
otherwise              = TcSigmaType -> CheckTyEqResult
go TcSigmaType
w CheckTyEqResult -> CheckTyEqResult -> CheckTyEqResult
forall a. Semigroup a => a -> a -> a
S.<> TcSigmaType -> CheckTyEqResult
go TcSigmaType
a CheckTyEqResult -> CheckTyEqResult -> CheckTyEqResult
forall a. Semigroup a => a -> a -> a
S.<> TcSigmaType -> CheckTyEqResult
go TcSigmaType
r
    go (AppTy TcSigmaType
fun TcSigmaType
arg) = TcSigmaType -> CheckTyEqResult
go TcSigmaType
fun CheckTyEqResult -> CheckTyEqResult -> CheckTyEqResult
forall a. Semigroup a => a -> a -> a
S.<> TcSigmaType -> CheckTyEqResult
go TcSigmaType
arg
    go (CastTy TcSigmaType
ty TcCoercionN
co)  = TcSigmaType -> CheckTyEqResult
go TcSigmaType
ty  CheckTyEqResult -> CheckTyEqResult -> CheckTyEqResult
forall a. Semigroup a => a -> a -> a
S.<> TcCoercionN -> CheckTyEqResult
go_co TcCoercionN
co
    go (CoercionTy TcCoercionN
co) = TcCoercionN -> CheckTyEqResult
go_co TcCoercionN
co
    go (ForAllTy (Bndr Var
tv' ArgFlag
_) TcSigmaType
ty)
       | Bool -> Bool
not Bool
ghci_tv = CheckTyEqResult
CTE_Bad
       | Bool
otherwise   = case CanEqLHS
lhs of
           TyVarLHS Var
tv | Var
tv Var -> Var -> Bool
forall a. Eq a => a -> a -> Bool
== Var
tv' -> CheckTyEqResult
CTE_OK
                       | Bool
otherwise -> Var -> TcSigmaType -> CheckTyEqResult
go_occ Var
tv (Var -> TcSigmaType
tyVarKind Var
tv') CheckTyEqResult -> CheckTyEqResult -> CheckTyEqResult
forall a. Semigroup a => a -> a -> a
S.<> TcSigmaType -> CheckTyEqResult
go TcSigmaType
ty
           CanEqLHS
_                       -> TcSigmaType -> CheckTyEqResult
go TcSigmaType
ty

    go_tv :: TcTyVar -> CheckTyEqResult
      -- this slightly peculiar way of defining this means
      -- we don't have to evaluate this `case` at every variable
      -- occurrence
    go_tv :: Var -> CheckTyEqResult
go_tv = case CanEqLHS
lhs of
      TyVarLHS Var
tv -> \ Var
tv' -> if Var
tv Var -> Var -> Bool
forall a. Eq a => a -> a -> Bool
== Var
tv'
                              then CheckTyEqResult
CTE_Occurs
                              else Var -> TcSigmaType -> CheckTyEqResult
go_occ Var
tv (Var -> TcSigmaType
tyVarKind Var
tv')
      TyFamLHS {} -> \ Var
_tv' -> CheckTyEqResult
CTE_OK
           -- See Note [Occurrence checking: look inside kinds] in GHC.Core.Type

     -- For kinds, we only do an occurs check; we do not worry
     -- about type families or foralls
     -- See Note [Checking for foralls]
    go_occ :: Var -> TcSigmaType -> CheckTyEqResult
go_occ Var
tv TcSigmaType
k | Var
tv Var -> VarSet -> Bool
`elemVarSet` TcSigmaType -> VarSet
tyCoVarsOfType TcSigmaType
k = CheckTyEqResult
CTE_Occurs
                | Bool
otherwise                        = CheckTyEqResult
CTE_OK

    go_tc :: TyCon -> [TcType] -> CheckTyEqResult
      -- this slightly peculiar way of defining this means
      -- we don't have to evaluate this `case` at every tyconapp
    go_tc :: TyCon -> ThetaType -> CheckTyEqResult
go_tc = case CanEqLHS
lhs of
      TyVarLHS {} -> \ TyCon
tc ThetaType
tys ->
        if | TyCon -> Bool
good_tc TyCon
tc -> [CheckTyEqResult] -> CheckTyEqResult
forall a. Monoid a => [a] -> a
mconcat ((TcSigmaType -> CheckTyEqResult) -> ThetaType -> [CheckTyEqResult]
forall a b. (a -> b) -> [a] -> [b]
map TcSigmaType -> CheckTyEqResult
go ThetaType
tys)
           | Bool
otherwise  -> CheckTyEqResult
CTE_Bad
      TyFamLHS TyCon
fam_tc ThetaType
fam_args -> \ TyCon
tc ThetaType
tys ->
        if | TyCon -> ThetaType -> TyCon -> ThetaType -> Bool
tcEqTyConApps TyCon
fam_tc ThetaType
fam_args TyCon
tc ThetaType
tys -> CheckTyEqResult
CTE_Occurs
           | TyCon -> Bool
good_tc TyCon
tc                           -> [CheckTyEqResult] -> CheckTyEqResult
forall a. Monoid a => [a] -> a
mconcat ((TcSigmaType -> CheckTyEqResult) -> ThetaType -> [CheckTyEqResult]
forall a b. (a -> b) -> [a] -> [b]
map TcSigmaType -> CheckTyEqResult
go ThetaType
tys)
           | Bool
otherwise                            -> CheckTyEqResult
CTE_Bad


     -- no bother about impredicativity in coercions, as they're
     -- inferred
    go_co :: TcCoercionN -> CheckTyEqResult
go_co TcCoercionN
co | Bool -> Bool
not (GeneralFlag -> DynFlags -> Bool
gopt GeneralFlag
Opt_DeferTypeErrors DynFlags
dflags)
             , TcCoercionN -> Bool
hasCoercionHoleCo TcCoercionN
co
             = CheckTyEqResult
CTE_HoleBlocker  -- Wrinkle (2) in GHC.Tc.Solver.Canonical
        -- See GHC.Tc.Solver.Canonical Note [Equalities with incompatible kinds]
        -- Wrinkle (2) about this case in general, Wrinkle (4b) about the check for
        -- deferred type errors.

             | TyVarLHS Var
tv <- CanEqLHS
lhs
             , Var
tv Var -> VarSet -> Bool
`elemVarSet` TcCoercionN -> VarSet
tyCoVarsOfCo TcCoercionN
co
             = CheckTyEqResult
CTE_Occurs

        -- Don't check coercions for type families; see commentary at top of function
             | Bool
otherwise
             = CheckTyEqResult
CTE_OK

    good_tc :: TyCon -> Bool
    good_tc :: TyCon -> Bool
good_tc
      | Bool
ghci_tv   = \ TyCon
_tc -> Bool
True
      | Bool
otherwise = \ TyCon
tc  -> TyCon -> Bool
isTauTyCon TyCon
tc Bool -> Bool -> Bool
&&
                             (AreTypeFamiliesOK
ty_fam_ok AreTypeFamiliesOK -> AreTypeFamiliesOK -> Bool
forall a. Eq a => a -> a -> Bool
== AreTypeFamiliesOK
YesTypeFamilies Bool -> Bool -> Bool
|| TyCon -> Bool
isFamFreeTyCon TyCon
tc)