{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections       #-}
{-# LANGUAGE RecursiveDo         #-}
{-# LANGUAGE MultiWayIf          #-}
{-# LANGUAGE RecordWildCards     #-}

{-
(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,
  tcTopSkolemise, tcSkolemiseScoped, tcSkolemiseExpType,
  tcSubType, tcSubTypeSigma, tcSubTypePat, tcSubTypeDS,
  tcSubTypeAmbiguity, tcSubMult,
  checkConstraints, checkTvConstraints,
  buildImplicationFor, buildTvImplication, emitResidualTvConstraint,

  -- Various unifications
  unifyType, unifyKind, unifyInvisibleType, unifyExpectedType,
  unifyTypeAndEmit, promoteTcType,
  swapOverTyVars, touchabilityAndShapeTest,
  UnifyEnv(..), updUEnvLoc, setUEnvRole,
  uType,

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

  checkTyEqRhs, recurseIntoTyConApp,
  PuResult(..), failCheckWith, okCheckRefl, mapCheck,
  TyEqFlags(..), TyEqFamApp(..), AreUnifying(..), LevelCheck(..), FamAppBreaker,
  famAppArgFlags, simpleUnifyCheck, checkPromoteFreeVars,
  ) where

import GHC.Prelude

import GHC.Hs

import GHC.Tc.Utils.Concrete ( hasFixedRuntimeRep, hasFixedRuntimeRep_syntactic )
import GHC.Tc.Utils.Env
import GHC.Tc.Utils.Instantiate
import GHC.Tc.Utils.Monad
import GHC.Tc.Utils.TcMType
import GHC.Tc.Utils.TcType
import GHC.Tc.Types.Evidence
import GHC.Tc.Types.Constraint
import GHC.Tc.Types.Origin
import GHC.Tc.Zonk.TcType

import GHC.Core.Type
import GHC.Core.TyCo.Rep
import GHC.Core.TyCo.FVs( isInjectiveInType )
import GHC.Core.TyCo.Ppr( debugPprType {- pprTyVar -} )
import GHC.Core.TyCon
import GHC.Core.Coercion
import GHC.Core.Multiplicity
import GHC.Core.Reduction

import qualified GHC.LanguageExtensions as LangExt

import GHC.Builtin.Types
import GHC.Types.Name
import GHC.Types.Var as Var
import GHC.Types.Var.Set
import GHC.Types.Var.Env
import GHC.Types.Basic
import GHC.Types.Unique.Set (nonDetEltsUniqSet)

import GHC.Utils.Error
import GHC.Utils.Misc
import GHC.Utils.Outputable as Outputable
import GHC.Utils.Panic
import GHC.Utils.Panic.Plain

import GHC.Driver.DynFlags
import GHC.Data.Bag
import GHC.Data.FastString( fsLit )

import Control.Monad
import Data.Monoid as DM ( Any(..) )
import qualified Data.Semigroup as S ( (<>) )

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

-- | 'matchActualFunTySigma' looks for just one function arrow,
-- returning an uninstantiated sigma-type.
--
-- Invariant: the returned argument type has a syntactically fixed
-- RuntimeRep in the sense of Note [Fixed RuntimeRep]
-- in GHC.Tc.Utils.Concrete.
--
-- See Note [Return arguments with a fixed RuntimeRep].
matchActualFunTySigma
  :: ExpectedFunTyOrigin
      -- ^ See Note [Herald for matchExpectedFunTys]
  -> Maybe TypedThing
      -- ^ 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 TcSigmaTypeFRR, TcSigmaType)
-- This function takes in a type to analyse (a RhoType) and returns
-- an argument type and a result type (splitting apart a function arrow).
-- The returned argument type is a SigmaType with a fixed RuntimeRep;
-- as explained in Note [Return arguments with a fixed RuntimeRep].
--
-- 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 :: ExpectedFunTyOrigin
-> Maybe TypedThing
-> (Int, [Scaled Type])
-> Type
-> TcM (HsWrapper, Scaled Type, Type)
matchActualFunTySigma ExpectedFunTyOrigin
herald Maybe TypedThing
mb_thing (Int, [Scaled Type])
err_info Type
fun_ty
  = Bool
-> SDoc
-> TcM (HsWrapper, Scaled Type, Type)
-> TcM (HsWrapper, Scaled Type, Type)
forall a. HasCallStack => Bool -> SDoc -> a -> a
assertPpr (Type -> Bool
isRhoTy Type
fun_ty) (Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
fun_ty) (TcM (HsWrapper, Scaled Type, Type)
 -> TcM (HsWrapper, Scaled Type, Type))
-> TcM (HsWrapper, Scaled Type, Type)
-> TcM (HsWrapper, Scaled Type, Type)
forall a b. (a -> b) -> a -> b
$
    Type -> TcM (HsWrapper, Scaled Type, Type)
go Type
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 type synonyms
       -> TcM (HsWrapper, Scaled TcSigmaTypeFRR, TcSigmaType)
    go :: Type -> TcM (HsWrapper, Scaled Type, Type)
go Type
ty | Just Type
ty' <- Type -> Maybe Type
coreView Type
ty = Type -> TcM (HsWrapper, Scaled Type, Type)
go Type
ty'

    go (FunTy { ft_af :: Type -> FunTyFlag
ft_af = FunTyFlag
af, ft_mult :: Type -> Type
ft_mult = Type
w, ft_arg :: Type -> Type
ft_arg = Type
arg_ty, ft_res :: Type -> Type
ft_res = Type
res_ty })
      = Bool
-> TcM (HsWrapper, Scaled Type, Type)
-> TcM (HsWrapper, Scaled Type, Type)
forall a. HasCallStack => Bool -> a -> a
assert (FunTyFlag -> Bool
isVisibleFunArg FunTyFlag
af) (TcM (HsWrapper, Scaled Type, Type)
 -> TcM (HsWrapper, Scaled Type, Type))
-> TcM (HsWrapper, Scaled Type, Type)
-> TcM (HsWrapper, Scaled Type, Type)
forall a b. (a -> b) -> a -> b
$
      do { HasDebugCallStack => FixedRuntimeRepContext -> Type -> TcM ()
FixedRuntimeRepContext -> Type -> TcM ()
hasFixedRuntimeRep_syntactic (ExpectedFunTyOrigin -> Int -> FixedRuntimeRepContext
FRRExpectedFunTy ExpectedFunTyOrigin
herald Int
1) Type
arg_ty
         ; (HsWrapper, Scaled Type, Type)
-> TcM (HsWrapper, Scaled Type, Type)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (HsWrapper
idHsWrapper, Type -> Type -> Scaled Type
forall a. Type -> a -> Scaled a
Scaled Type
w Type
arg_ty, Type
res_ty) }

    go ty :: Type
ty@(TyVarTy TcTyVar
tv)
      | TcTyVar -> Bool
isMetaTyVar TcTyVar
tv
      = do { MetaDetails
cts <- TcTyVar -> IOEnv (Env TcGblEnv TcLclEnv) MetaDetails
forall (m :: * -> *). MonadIO m => TcTyVar -> m MetaDetails
readMetaTyVar TcTyVar
tv
           ; case MetaDetails
cts of
               Indirect Type
ty' -> Type -> TcM (HsWrapper, Scaled Type, Type)
go Type
ty'
               MetaDetails
Flexi        -> Type -> TcM (HsWrapper, Scaled Type, Type)
defer Type
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 Type
ty = (TidyEnv -> ZonkM (TidyEnv, SDoc))
-> TcM (HsWrapper, Scaled Type, Type)
-> TcM (HsWrapper, Scaled Type, Type)
forall a. (TidyEnv -> ZonkM (TidyEnv, SDoc)) -> TcM a -> TcM a
addErrCtxtM (Type -> TidyEnv -> ZonkM (TidyEnv, SDoc)
mk_ctxt Type
ty) (Type -> TcM (HsWrapper, Scaled Type, Type)
defer Type
ty)

    ------------
    defer :: Type -> TcM (HsWrapper, Scaled Type, Type)
defer Type
fun_ty
      = do { Type
arg_ty <- TcM Type
newOpenFlexiTyVarTy
           ; Type
res_ty <- TcM Type
newOpenFlexiTyVarTy
           ; Type
mult <- Type -> TcM Type
newFlexiTyVarTy Type
multiplicityTy
           ; let unif_fun_ty :: Type
unif_fun_ty = Type -> Type -> Type -> Type
tcMkVisFunTy Type
mult Type
arg_ty Type
res_ty
           ; Coercion
co <- Maybe TypedThing -> Type -> Type -> TcM Coercion
unifyType Maybe TypedThing
mb_thing Type
fun_ty Type
unif_fun_ty
           ; HasDebugCallStack => FixedRuntimeRepContext -> Type -> TcM ()
FixedRuntimeRepContext -> Type -> TcM ()
hasFixedRuntimeRep_syntactic (ExpectedFunTyOrigin -> Int -> FixedRuntimeRepContext
FRRExpectedFunTy ExpectedFunTyOrigin
herald Int
1) Type
arg_ty
           ; (HsWrapper, Scaled Type, Type)
-> TcM (HsWrapper, Scaled Type, Type)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Coercion -> HsWrapper
mkWpCastN Coercion
co, Type -> Type -> Scaled Type
forall a. Type -> a -> Scaled a
Scaled Type
mult Type
arg_ty, Type
res_ty) }

    ------------
    mk_ctxt :: TcType -> TidyEnv -> ZonkM (TidyEnv, SDoc)
    mk_ctxt :: Type -> TidyEnv -> ZonkM (TidyEnv, SDoc)
mk_ctxt Type
res_ty TidyEnv
env = TidyEnv
-> ExpectedFunTyOrigin
-> [Scaled Type]
-> Type
-> Int
-> ZonkM (TidyEnv, SDoc)
mkFunTysMsg TidyEnv
env ExpectedFunTyOrigin
herald ([Scaled Type] -> [Scaled Type]
forall a. [a] -> [a]
reverse [Scaled Type]
arg_tys_so_far)
                                     Type
res_ty Int
n_val_args_in_call
    (Int
n_val_args_in_call, [Scaled Type]
arg_tys_so_far) = (Int, [Scaled Type])
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.
--
-- INVARIANT: the returned argument types all have a syntactically fixed RuntimeRep
-- in the sense of Note [Fixed RuntimeRep] in GHC.Tc.Utils.Concrete.
-- See Note [Return arguments with a fixed RuntimeRep].
matchActualFunTysRho :: ExpectedFunTyOrigin -- ^ See Note [Herald for matchExpectedFunTys]
                     -> CtOrigin
                     -> Maybe TypedThing -- ^ the thing with type TcSigmaType
                     -> Arity
                     -> TcSigmaType
                     -> TcM (HsWrapper, [Scaled TcSigmaTypeFRR], 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 :: ExpectedFunTyOrigin
-> CtOrigin
-> Maybe TypedThing
-> Int
-> Type
-> TcM (HsWrapper, [Scaled Type], Type)
matchActualFunTysRho ExpectedFunTyOrigin
herald CtOrigin
ct_orig Maybe TypedThing
mb_thing Int
n_val_args_wanted Type
fun_ty
  = Int
-> [Scaled Type] -> Type -> TcM (HsWrapper, [Scaled Type], Type)
go Int
n_val_args_wanted [] Type
fun_ty
  where
    go :: Int
-> [Scaled Type] -> Type -> TcM (HsWrapper, [Scaled Type], Type)
go Int
n [Scaled Type]
so_far Type
fun_ty
      | Bool -> Bool
not (Type -> Bool
isRhoTy Type
fun_ty)
      = do { (HsWrapper
wrap1, Type
rho) <- CtOrigin -> Type -> TcM (HsWrapper, Type)
topInstantiate CtOrigin
ct_orig Type
fun_ty
           ; (HsWrapper
wrap2, [Scaled Type]
arg_tys, Type
res_ty) <- Int
-> [Scaled Type] -> Type -> TcM (HsWrapper, [Scaled Type], Type)
go Int
n [Scaled Type]
so_far Type
rho
           ; (HsWrapper, [Scaled Type], Type)
-> TcM (HsWrapper, [Scaled Type], Type)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (HsWrapper
wrap2 HsWrapper -> HsWrapper -> HsWrapper
<.> HsWrapper
wrap1, [Scaled Type]
arg_tys, Type
res_ty) }

    go Int
0 [Scaled Type]
_ Type
fun_ty = (HsWrapper, [Scaled Type], Type)
-> TcM (HsWrapper, [Scaled Type], Type)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (HsWrapper
idHsWrapper, [], Type
fun_ty)

    go Int
n [Scaled Type]
so_far Type
fun_ty
      = do { (HsWrapper
wrap_fun1, Scaled Type
arg_ty1, Type
res_ty1) <- ExpectedFunTyOrigin
-> Maybe TypedThing
-> (Int, [Scaled Type])
-> Type
-> TcM (HsWrapper, Scaled Type, Type)
matchActualFunTySigma
                                                 ExpectedFunTyOrigin
herald Maybe TypedThing
mb_thing
                                                 (Int
n_val_args_wanted, [Scaled Type]
so_far)
                                                 Type
fun_ty
           ; (HsWrapper
wrap_res, [Scaled Type]
arg_tys, Type
res_ty)   <- Int
-> [Scaled Type] -> Type -> TcM (HsWrapper, [Scaled Type], Type)
go (Int
nInt -> Int -> Int
forall a. Num a => a -> a -> a
-Int
1) (Scaled Type
arg_ty1Scaled Type -> [Scaled Type] -> [Scaled Type]
forall a. a -> [a] -> [a]
:[Scaled Type]
so_far) Type
res_ty1
           ; let wrap_fun2 :: HsWrapper
wrap_fun2 = HsWrapper -> HsWrapper -> Scaled Type -> Type -> HsWrapper
mkWpFun HsWrapper
idHsWrapper HsWrapper
wrap_res Scaled Type
arg_ty1 Type
res_ty
           -- NB: arg_ty1 comes from matchActualFunTySigma, so it has
           -- a syntactically fixed RuntimeRep as needed to call mkWpFun.
           ; (HsWrapper, [Scaled Type], Type)
-> TcM (HsWrapper, [Scaled Type], Type)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (HsWrapper
wrap_fun2 HsWrapper -> HsWrapper -> HsWrapper
<.> HsWrapper
wrap_fun1, Scaled Type
arg_ty1Scaled Type -> [Scaled Type] -> [Scaled Type]
forall a. a -> [a] -> [a]
:[Scaled Type]
arg_tys, Type
res_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.

Note [Return arguments with a fixed RuntimeRep]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The functions

  - matchExpectedFunTys,
  - matchActualFunTySigma,
  - matchActualFunTysRho,

peel off argument types, as explained in Note [matchExpectedFunTys].
It's important that these functions return argument types that have
a fixed runtime representation, otherwise we would be in violation
of the representation-polymorphism invariants of
Note [Representation polymorphism invariants] in GHC.Core.

This is why all these functions have an additional invariant,
that the argument types they return all have a syntactically fixed RuntimeRep,
in the sense of Note [Fixed RuntimeRep] in GHC.Tc.Utils.Concrete.

Example:

  Suppose we have

    type F :: Type -> RuntimeRep
    type family F a where { F Int = LiftedRep }

    type Dual :: Type -> Type
    type family Dual a where
      Dual a = a -> ()

    f :: forall (a :: TYPE (F Int)). Dual a
    f = \ x -> ()

  The body of `f` is a lambda abstraction, so we must be able to split off
  one argument type from its type. This is handled by `matchExpectedFunTys`
  (see 'GHC.Tc.Gen.Match.tcMatchLambda'). We end up with desugared Core that
  looks like this:

    f :: forall (a :: TYPE (F Int)). Dual (a |> (TYPE F[0]))
    f = \ @(a :: TYPE (F Int)) ->
          (\ (x :: (a |> (TYPE F[0]))) -> ())
          `cast`
          (Sub (Sym (Dual[0] <(a |> (TYPE F[0]))>)))

  Two important transformations took place:

    1. We inserted casts around the argument type to ensure that it has
       a fixed runtime representation, as required by invariant (I1) from
       Note [Representation polymorphism invariants] in GHC.Core.
    2. We inserted a cast around the whole lambda to make everything line up
       with the type signature.
-}

-- | Use this function to split off arguments types when you have an
-- \"expected\" type.
--
-- This function skolemises at each polytype.
--
-- Invariant: this function only applies the provided function
-- to a list of argument types which all have a syntactically fixed RuntimeRep
-- in the sense of Note [Fixed RuntimeRep] in GHC.Tc.Utils.Concrete.
-- See Note [Return arguments with a fixed RuntimeRep].
matchExpectedFunTys :: forall a.
                       ExpectedFunTyOrigin -- See Note [Herald for matchExpectedFunTys]
                    -> UserTypeCtxt
                    -> Arity
                    -> ExpRhoType      -- Skolemised
                    -> ([Scaled ExpSigmaTypeFRR] -> 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 :: forall a.
ExpectedFunTyOrigin
-> UserTypeCtxt
-> Int
-> ExpRhoType
-> ([Scaled ExpRhoType] -> ExpRhoType -> TcM a)
-> TcM (HsWrapper, a)
matchExpectedFunTys ExpectedFunTyOrigin
herald UserTypeCtxt
ctx Int
arity ExpRhoType
orig_ty [Scaled ExpRhoType] -> ExpRhoType -> TcM a
thing_inside
  = case ExpRhoType
orig_ty of
      Check Type
ty -> [Scaled ExpRhoType] -> Int -> Type -> TcM (HsWrapper, a)
go [] Int
arity Type
ty
      ExpRhoType
_        -> [Scaled ExpRhoType] -> Int -> ExpRhoType -> TcM (HsWrapper, a)
defer [] Int
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] -> Int -> Type -> TcM (HsWrapper, a)
go [Scaled ExpRhoType]
acc_arg_tys Int
n Type
ty
      | ([TcTyVar]
tvs, [Type]
theta, Type
_) <- Type -> ([TcTyVar], [Type], Type)
tcSplitSigmaTy Type
ty
      , Bool -> Bool
not ([TcTyVar] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [TcTyVar]
tvs Bool -> Bool -> Bool
&& [Type] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Type]
theta)
      = do { (HsWrapper
wrap_gen, (HsWrapper
wrap_res, a
result)) <- UserTypeCtxt
-> Type
-> (Type -> TcM (HsWrapper, a))
-> TcM (HsWrapper, (HsWrapper, a))
forall result.
UserTypeCtxt
-> Type -> (Type -> TcM result) -> TcM (HsWrapper, result)
tcTopSkolemise UserTypeCtxt
ctx Type
ty ((Type -> TcM (HsWrapper, a)) -> TcM (HsWrapper, (HsWrapper, a)))
-> (Type -> TcM (HsWrapper, a)) -> TcM (HsWrapper, (HsWrapper, a))
forall a b. (a -> b) -> a -> b
$ \Type
ty' ->
                                               [Scaled ExpRhoType] -> Int -> Type -> TcM (HsWrapper, a)
go [Scaled ExpRhoType]
acc_arg_tys Int
n Type
ty'
           ; (HsWrapper, a) -> TcM (HsWrapper, a)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) 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/ coreView, so
    -- that we do not unnecessarily unwrap synonyms
    go [Scaled ExpRhoType]
acc_arg_tys Int
0 Type
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) (Type -> ExpRhoType
mkCheckExpType Type
rho_ty)
           ; (HsWrapper, a) -> TcM (HsWrapper, a)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (HsWrapper
idHsWrapper, a
result) }

    go [Scaled ExpRhoType]
acc_arg_tys Int
n Type
ty
      | Just Type
ty' <- Type -> Maybe Type
coreView Type
ty = [Scaled ExpRhoType] -> Int -> Type -> TcM (HsWrapper, a)
go [Scaled ExpRhoType]
acc_arg_tys Int
n Type
ty'

    go [Scaled ExpRhoType]
acc_arg_tys Int
n (FunTy { ft_af :: Type -> FunTyFlag
ft_af = FunTyFlag
af, ft_mult :: Type -> Type
ft_mult = Type
mult, ft_arg :: Type -> Type
ft_arg = Type
arg_ty, ft_res :: Type -> Type
ft_res = Type
res_ty })
      = Bool -> TcM (HsWrapper, a) -> TcM (HsWrapper, a)
forall a. HasCallStack => Bool -> a -> a
assert (FunTyFlag -> Bool
isVisibleFunArg FunTyFlag
af) (TcM (HsWrapper, a) -> TcM (HsWrapper, a))
-> TcM (HsWrapper, a) -> TcM (HsWrapper, a)
forall a b. (a -> b) -> a -> b
$
        do { let arg_pos :: Int
arg_pos = Int
1 Int -> Int -> Int
forall a. Num a => a -> a -> a
+ [Scaled ExpRhoType] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Scaled ExpRhoType]
acc_arg_tys -- for error messages only
           ; (Coercion
arg_co, Type
arg_ty) <- HasDebugCallStack =>
FixedRuntimeRepContext -> Type -> TcM (Coercion, Type)
FixedRuntimeRepContext -> Type -> TcM (Coercion, Type)
hasFixedRuntimeRep (ExpectedFunTyOrigin -> Int -> FixedRuntimeRepContext
FRRExpectedFunTy ExpectedFunTyOrigin
herald Int
arg_pos) Type
arg_ty
           ; (HsWrapper
wrap_res, a
result) <- [Scaled ExpRhoType] -> Int -> Type -> TcM (HsWrapper, a)
go ((Type -> ExpRhoType -> Scaled ExpRhoType
forall a. Type -> a -> Scaled a
Scaled Type
mult (ExpRhoType -> Scaled ExpRhoType)
-> ExpRhoType -> Scaled ExpRhoType
forall a b. (a -> b) -> a -> b
$ Type -> ExpRhoType
mkCheckExpType Type
arg_ty) Scaled ExpRhoType -> [Scaled ExpRhoType] -> [Scaled ExpRhoType]
forall a. a -> [a] -> [a]
: [Scaled ExpRhoType]
acc_arg_tys)
                                      (Int
nInt -> Int -> Int
forall a. Num a => a -> a -> a
-Int
1) Type
res_ty
           ; let wrap_arg :: HsWrapper
wrap_arg = Coercion -> HsWrapper
mkWpCastN Coercion
arg_co
                 fun_wrap :: HsWrapper
fun_wrap = HsWrapper -> HsWrapper -> Scaled Type -> Type -> HsWrapper
mkWpFun HsWrapper
wrap_arg HsWrapper
wrap_res (Type -> Type -> Scaled Type
forall a. Type -> a -> Scaled a
Scaled Type
mult Type
arg_ty) Type
res_ty
           ; (HsWrapper, a) -> TcM (HsWrapper, a)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (HsWrapper
fun_wrap, a
result) }

    go [Scaled ExpRhoType]
acc_arg_tys Int
n ty :: Type
ty@(TyVarTy TcTyVar
tv)
      | TcTyVar -> Bool
isMetaTyVar TcTyVar
tv
      = do { MetaDetails
cts <- TcTyVar -> IOEnv (Env TcGblEnv TcLclEnv) MetaDetails
forall (m :: * -> *). MonadIO m => TcTyVar -> m MetaDetails
readMetaTyVar TcTyVar
tv
           ; case MetaDetails
cts of
               Indirect Type
ty' -> [Scaled ExpRhoType] -> Int -> Type -> TcM (HsWrapper, a)
go [Scaled ExpRhoType]
acc_arg_tys Int
n Type
ty'
               MetaDetails
Flexi        -> [Scaled ExpRhoType] -> Int -> ExpRhoType -> TcM (HsWrapper, a)
defer [Scaled ExpRhoType]
acc_arg_tys Int
n (Type -> ExpRhoType
mkCheckExpType Type
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 Int
n Type
ty = (TidyEnv -> ZonkM (TidyEnv, SDoc))
-> TcM (HsWrapper, a) -> TcM (HsWrapper, a)
forall a. (TidyEnv -> ZonkM (TidyEnv, SDoc)) -> TcM a -> TcM a
addErrCtxtM ([Scaled ExpRhoType] -> Type -> TidyEnv -> ZonkM (TidyEnv, SDoc)
mk_ctxt [Scaled ExpRhoType]
acc_arg_tys Type
ty) (TcM (HsWrapper, a) -> TcM (HsWrapper, a))
-> TcM (HsWrapper, a) -> TcM (HsWrapper, a)
forall a b. (a -> b) -> a -> b
$
                          [Scaled ExpRhoType] -> Int -> ExpRhoType -> TcM (HsWrapper, a)
defer [Scaled ExpRhoType]
acc_arg_tys Int
n (Type -> ExpRhoType
mkCheckExpType Type
ty)

    ------------
    defer :: [Scaled ExpSigmaTypeFRR] -> Arity -> ExpRhoType -> TcM (HsWrapper, a)
    defer :: [Scaled ExpRhoType] -> Int -> ExpRhoType -> TcM (HsWrapper, a)
defer [Scaled ExpRhoType]
acc_arg_tys Int
n ExpRhoType
fun_ty
      = do { let last_acc_arg_pos :: Int
last_acc_arg_pos = [Scaled ExpRhoType] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Scaled ExpRhoType]
acc_arg_tys
           ; [Scaled ExpRhoType]
more_arg_tys <- (Int -> IOEnv (Env TcGblEnv TcLclEnv) (Scaled ExpRhoType))
-> [Int] -> IOEnv (Env TcGblEnv TcLclEnv) [Scaled ExpRhoType]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
forall (m :: * -> *) a b. Monad m => (a -> m b) -> [a] -> m [b]
mapM Int -> IOEnv (Env TcGblEnv TcLclEnv) (Scaled ExpRhoType)
new_exp_arg_ty [Int
last_acc_arg_pos Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1 .. Int
last_acc_arg_pos Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
n]
           ; ExpRhoType
res_ty       <- TcM 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 Type]
more_arg_tys <- (Scaled ExpRhoType -> IOEnv (Env TcGblEnv TcLclEnv) (Scaled Type))
-> [Scaled ExpRhoType]
-> IOEnv (Env TcGblEnv TcLclEnv) [Scaled Type]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
forall (m :: * -> *) a b. Monad m => (a -> m b) -> [a] -> m [b]
mapM (\(Scaled Type
m ExpRhoType
t) -> Type -> Type -> Scaled Type
forall a. Type -> a -> Scaled a
Scaled Type
m (Type -> Scaled Type)
-> TcM Type -> IOEnv (Env TcGblEnv TcLclEnv) (Scaled Type)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ExpRhoType -> TcM Type
forall (m :: * -> *). MonadIO m => ExpRhoType -> m Type
readExpType ExpRhoType
t) [Scaled ExpRhoType]
more_arg_tys
           ; Type
res_ty       <- ExpRhoType -> TcM Type
forall (m :: * -> *). MonadIO m => ExpRhoType -> m Type
readExpType ExpRhoType
res_ty
           ; let unif_fun_ty :: Type
unif_fun_ty = [Scaled Type] -> Type -> Type
HasDebugCallStack => [Scaled Type] -> Type -> Type
mkScaledFunTys [Scaled Type]
more_arg_tys Type
res_ty
           ; HsWrapper
wrap <- CtOrigin -> UserTypeCtxt -> Type -> ExpRhoType -> TcM HsWrapper
tcSubType CtOrigin
AppOrigin UserTypeCtxt
ctx Type
unif_fun_ty ExpRhoType
fun_ty
                         -- Not a good origin at all :-(
           ; (HsWrapper, a) -> TcM (HsWrapper, a)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (HsWrapper
wrap, a
result) }

    new_exp_arg_ty :: Int -> TcM (Scaled ExpSigmaTypeFRR)
    new_exp_arg_ty :: Int -> IOEnv (Env TcGblEnv TcLclEnv) (Scaled ExpRhoType)
new_exp_arg_ty Int
arg_pos -- position for error messages only
      = Type -> ExpRhoType -> Scaled ExpRhoType
forall a. Type -> a -> Scaled a
mkScaled (Type -> ExpRhoType -> Scaled ExpRhoType)
-> TcM Type
-> IOEnv (Env TcGblEnv TcLclEnv) (ExpRhoType -> Scaled ExpRhoType)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Type -> TcM Type
newFlexiTyVarTy Type
multiplicityTy
                 IOEnv (Env TcGblEnv TcLclEnv) (ExpRhoType -> Scaled ExpRhoType)
-> TcM ExpRhoType
-> IOEnv (Env TcGblEnv TcLclEnv) (Scaled ExpRhoType)
forall a b.
IOEnv (Env TcGblEnv TcLclEnv) (a -> b)
-> IOEnv (Env TcGblEnv TcLclEnv) a
-> IOEnv (Env TcGblEnv TcLclEnv) b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> FixedRuntimeRepContext -> TcM ExpRhoType
newInferExpTypeFRR (ExpectedFunTyOrigin -> Int -> FixedRuntimeRepContext
FRRExpectedFunTy ExpectedFunTyOrigin
herald Int
arg_pos)

    ------------
    mk_ctxt :: [Scaled ExpSigmaTypeFRR] -> TcType -> TidyEnv -> ZonkM (TidyEnv, SDoc)
    mk_ctxt :: [Scaled ExpRhoType] -> Type -> TidyEnv -> ZonkM (TidyEnv, SDoc)
mk_ctxt [Scaled ExpRhoType]
arg_tys Type
res_ty TidyEnv
env
      = TidyEnv
-> ExpectedFunTyOrigin
-> [Scaled Type]
-> Type
-> Int
-> ZonkM (TidyEnv, SDoc)
mkFunTysMsg TidyEnv
env ExpectedFunTyOrigin
herald [Scaled Type]
arg_tys' Type
res_ty Int
arity
      where
        arg_tys' :: [Scaled Type]
arg_tys' = (Scaled ExpRhoType -> Scaled Type)
-> [Scaled ExpRhoType] -> [Scaled Type]
forall a b. (a -> b) -> [a] -> [b]
map (\(Scaled Type
u ExpRhoType
v) -> Type -> Type -> Scaled Type
forall a. Type -> a -> Scaled a
Scaled Type
u (String -> ExpRhoType -> Type
checkingExpType String
"matchExpectedFunTys" ExpRhoType
v)) ([Scaled ExpRhoType] -> [Scaled Type])
-> [Scaled ExpRhoType] -> [Scaled Type]
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
            -> ExpectedFunTyOrigin
            -> [Scaled TcType] -> TcType -> Arity
            -> ZonkM (TidyEnv, SDoc)
mkFunTysMsg :: TidyEnv
-> ExpectedFunTyOrigin
-> [Scaled Type]
-> Type
-> Int
-> ZonkM (TidyEnv, SDoc)
mkFunTysMsg TidyEnv
env ExpectedFunTyOrigin
herald [Scaled Type]
arg_tys Type
res_ty Int
n_val_args_in_call
  = do { (TidyEnv
env', Type
fun_rho) <- TidyEnv -> Type -> ZonkM (TidyEnv, Type)
zonkTidyTcType TidyEnv
env (Type -> ZonkM (TidyEnv, Type)) -> Type -> ZonkM (TidyEnv, Type)
forall a b. (a -> b) -> a -> b
$
                            [Scaled Type] -> Type -> Type
HasDebugCallStack => [Scaled Type] -> Type -> Type
mkScaledFunTys [Scaled Type]
arg_tys Type
res_ty

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

             msg :: SDoc
msg | Int
n_val_args_in_call Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
n_fun_args  -- Enough args, in the end
                 = String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"In the result of a function call"
                 | Bool
otherwise
                 = SDoc -> Int -> SDoc -> SDoc
hang (SDoc
full_herald SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<> SDoc
forall doc. IsLine doc => doc
comma)
                      Int
2 ([SDoc] -> SDoc
forall doc. IsLine doc => [doc] -> doc
sep [ String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"but its type" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> SDoc -> SDoc
quotes (Type -> SDoc
pprType Type
fun_rho)
                             , if Int
n_fun_args Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
0 then String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"has none"
                               else String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"has only" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> Int -> SDoc
speakN Int
n_fun_args])

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

----------------------
matchExpectedListTy :: TcRhoType -> TcM (TcCoercionN, TcRhoType)
-- Special case for lists
matchExpectedListTy :: Type -> TcM (Coercion, Type)
matchExpectedListTy Type
exp_ty
 = do { (Coercion
co, [Type
elt_ty]) <- TyCon -> Type -> TcM (Coercion, [Type])
matchExpectedTyConApp TyCon
listTyCon Type
exp_ty
      ; (Coercion, Type) -> TcM (Coercion, Type)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Coercion
co, Type
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 -> Type -> TcM (Coercion, [Type])
matchExpectedTyConApp TyCon
tc Type
orig_ty
  = Bool -> SDoc -> TcM (Coercion, [Type]) -> TcM (Coercion, [Type])
forall a. HasCallStack => Bool -> SDoc -> a -> a
assertPpr (TyCon -> Bool
isAlgTyCon TyCon
tc) (TyCon -> SDoc
forall a. Outputable a => a -> SDoc
ppr TyCon
tc) (TcM (Coercion, [Type]) -> TcM (Coercion, [Type]))
-> TcM (Coercion, [Type]) -> TcM (Coercion, [Type])
forall a b. (a -> b) -> a -> b
$
    Type -> TcM (Coercion, [Type])
go Type
orig_ty
  where
    go :: Type -> TcM (Coercion, [Type])
go Type
ty
       | Just Type
ty' <- Type -> Maybe Type
coreView Type
ty
       = Type -> TcM (Coercion, [Type])
go Type
ty'

    go ty :: Type
ty@(TyConApp TyCon
tycon [Type]
args)
       | TyCon
tc TyCon -> TyCon -> Bool
forall a. Eq a => a -> a -> Bool
== TyCon
tycon  -- Common case
       = (Coercion, [Type]) -> TcM (Coercion, [Type])
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Type -> Coercion
mkNomReflCo Type
ty, [Type]
args)

    go (TyVarTy TcTyVar
tv)
       | TcTyVar -> Bool
isMetaTyVar TcTyVar
tv
       = do { MetaDetails
cts <- TcTyVar -> IOEnv (Env TcGblEnv TcLclEnv) MetaDetails
forall (m :: * -> *). MonadIO m => TcTyVar -> m MetaDetails
readMetaTyVar TcTyVar
tv
            ; case MetaDetails
cts of
                Indirect Type
ty -> Type -> TcM (Coercion, [Type])
go Type
ty
                MetaDetails
Flexi       -> TcM (Coercion, [Type])
defer }

    go Type
_ = TcM (Coercion, [Type])
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 (Coercion, [Type])
defer
      = do { (Subst
_, [TcTyVar]
arg_tvs) <- [TcTyVar] -> TcM (Subst, [TcTyVar])
newMetaTyVars (TyCon -> [TcTyVar]
tyConTyVars TyCon
tc)
           ; String -> SDoc -> TcM ()
traceTc String
"matchExpectedTyConApp" (TyCon -> SDoc
forall a. Outputable a => a -> SDoc
ppr TyCon
tc SDoc -> SDoc -> SDoc
forall doc. IsDoc doc => doc -> doc -> doc
$$ [TcTyVar] -> SDoc
forall a. Outputable a => a -> SDoc
ppr (TyCon -> [TcTyVar]
tyConTyVars TyCon
tc) SDoc -> SDoc -> SDoc
forall doc. IsDoc doc => doc -> doc -> doc
$$ [TcTyVar] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [TcTyVar]
arg_tvs)
           ; let args :: [Type]
args = [TcTyVar] -> [Type]
mkTyVarTys [TcTyVar]
arg_tvs
                 tc_template :: Type
tc_template = TyCon -> [Type] -> Type
mkTyConApp TyCon
tc [Type]
args
           ; Coercion
co <- Maybe TypedThing -> Type -> Type -> TcM Coercion
unifyType Maybe TypedThing
forall a. Maybe a
Nothing Type
tc_template Type
orig_ty
           ; (Coercion, [Type]) -> TcM (Coercion, [Type])
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Coercion
co, [Type]
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 :: Type -> TcM (Coercion, (Type, Type))
matchExpectedAppTy Type
orig_ty
  = Type -> TcM (Coercion, (Type, Type))
go Type
orig_ty
  where
    go :: Type -> TcM (Coercion, (Type, Type))
go Type
ty
      | Just Type
ty' <- Type -> Maybe Type
coreView Type
ty = Type -> TcM (Coercion, (Type, Type))
go Type
ty'

      | Just (Type
fun_ty, Type
arg_ty) <- Type -> Maybe (Type, Type)
tcSplitAppTy_maybe Type
ty
      = (Coercion, (Type, Type)) -> TcM (Coercion, (Type, Type))
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Type -> Coercion
mkNomReflCo Type
orig_ty, (Type
fun_ty, Type
arg_ty))

    go (TyVarTy TcTyVar
tv)
      | TcTyVar -> Bool
isMetaTyVar TcTyVar
tv
      = do { MetaDetails
cts <- TcTyVar -> IOEnv (Env TcGblEnv TcLclEnv) MetaDetails
forall (m :: * -> *). MonadIO m => TcTyVar -> m MetaDetails
readMetaTyVar TcTyVar
tv
           ; case MetaDetails
cts of
               Indirect Type
ty -> Type -> TcM (Coercion, (Type, Type))
go Type
ty
               MetaDetails
Flexi       -> TcM (Coercion, (Type, Type))
defer }

    go Type
_ = TcM (Coercion, (Type, Type))
defer

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

    orig_kind :: Type
orig_kind = HasDebugCallStack => Type -> Type
Type -> Type
typeKind Type
orig_ty
    kind1 :: Type
kind1 = HasDebugCallStack => Type -> Type -> Type
Type -> Type -> Type
mkVisFunTyMany Type
liftedTypeKind Type
orig_kind
    kind2 :: Type
kind2 = Type
liftedTypeKind    -- m :: * -> k
                              -- arg type :: *

{- **********************************************************************
*
                      fillInferResult
*
********************************************************************** -}

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

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

-- | Fill an 'InferResult' with the given type.
--
-- If @co = fillInferResult t1 infer_res@, then @co :: t1 ~# t2@,
-- where @t2@ is the type stored in the 'ir_ref' field of @infer_res@.
--
-- This function enforces the following invariants:
--
--  - Level invariant.
--    The stored type @t2@ is at the same level as given by the
--    'ir_lvl' field.
--  - FRR invariant.
--    Whenever the 'ir_frr' field is not @Nothing@, @t2@ is guaranteed
--    to have a syntactically fixed RuntimeRep, in the sense of
--    Note [Fixed RuntimeRep] in GHC.Tc.Utils.Concrete.
fillInferResult :: TcType -> InferResult -> TcM TcCoercionN
fillInferResult :: Type -> InferResult -> TcM Coercion
fillInferResult Type
act_res_ty (IR { ir_uniq :: InferResult -> Unique
ir_uniq = Unique
u
                               , ir_lvl :: InferResult -> TcLevel
ir_lvl  = TcLevel
res_lvl
                               , ir_frr :: InferResult -> Maybe FixedRuntimeRepContext
ir_frr  = Maybe FixedRuntimeRepContext
mb_frr
                               , ir_ref :: InferResult -> IORef (Maybe Type)
ir_ref  = IORef (Maybe Type)
ref })
  = do { Maybe Type
mb_exp_res_ty <- IORef (Maybe Type) -> IOEnv (Env TcGblEnv TcLclEnv) (Maybe Type)
forall (m :: * -> *) a. MonadIO m => TcRef a -> m a
readTcRef IORef (Maybe Type)
ref
       ; case Maybe Type
mb_exp_res_ty of
            Just Type
exp_res_ty
               -- We progressively refine the type stored in 'ref',
               -- for example when inferring types across multiple equations.
               --
               -- Example:
               --
               --  \ x -> case y of { True -> x ; False -> 3 :: Int }
               --
               -- When inferring the return type of this function, we will create
               -- an 'Infer' 'ExpType', which will first be filled by the type of 'x'
               -- after typechecking the first equation, and then filled again with
               -- the type 'Int', at which point we want to ensure that we unify
               -- the type of 'x' with 'Int'. This is what is happening below when
               -- we are "joining" several inferred 'ExpType's.
               -> do { String -> SDoc -> TcM ()
traceTc String
"Joining inferred ExpType" (SDoc -> TcM ()) -> SDoc -> TcM ()
forall a b. (a -> b) -> a -> b
$
                       Unique -> SDoc
forall a. Outputable a => a -> SDoc
ppr Unique
u SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<> SDoc
forall doc. IsLine doc => doc
colon SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
act_res_ty SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> Char -> SDoc
forall doc. IsLine doc => Char -> doc
char Char
'~' SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
exp_res_ty
                     ; TcLevel
cur_lvl <- TcM TcLevel
getTcLevel
                     ; Bool -> TcM () -> TcM ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (TcLevel
cur_lvl TcLevel -> TcLevel -> Bool
`sameDepthAs` TcLevel
res_lvl) (TcM () -> TcM ()) -> TcM () -> TcM ()
forall a b. (a -> b) -> a -> b
$
                       Type -> TcM ()
ensureMonoType Type
act_res_ty
                     ; Maybe TypedThing -> Type -> Type -> TcM Coercion
unifyType Maybe TypedThing
forall a. Maybe a
Nothing Type
act_res_ty Type
exp_res_ty }
            Maybe Type
Nothing
               -> do { String -> SDoc -> TcM ()
traceTc String
"Filling inferred ExpType" (SDoc -> TcM ()) -> SDoc -> TcM ()
forall a b. (a -> b) -> a -> b
$
                       Unique -> SDoc
forall a. Outputable a => a -> SDoc
ppr Unique
u SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> String -> SDoc
forall doc. IsLine doc => String -> doc
text String
":=" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
act_res_ty

                     -- Enforce the level invariant: ensure the TcLevel of
                     -- the type we are writing to 'ref' matches 'ir_lvl'.
                     ; (Coercion
prom_co, Type
act_res_ty) <- TcLevel -> Type -> TcM (Coercion, Type)
promoteTcType TcLevel
res_lvl Type
act_res_ty

                     -- Enforce the FRR invariant: ensure the type has a syntactically
                     -- fixed RuntimeRep (if necessary, i.e. 'mb_frr' is not 'Nothing').
                     ; (Coercion
frr_co, Type
act_res_ty) <-
                         case Maybe FixedRuntimeRepContext
mb_frr of
                           Maybe FixedRuntimeRepContext
Nothing       -> (Coercion, Type) -> TcM (Coercion, Type)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Type -> Coercion
mkNomReflCo Type
act_res_ty, Type
act_res_ty)
                           Just FixedRuntimeRepContext
frr_orig -> HasDebugCallStack =>
FixedRuntimeRepContext -> Type -> TcM (Coercion, Type)
FixedRuntimeRepContext -> Type -> TcM (Coercion, Type)
hasFixedRuntimeRep FixedRuntimeRepContext
frr_orig Type
act_res_ty

                     -- Compose the two coercions.
                     ; let final_co :: Coercion
final_co = Coercion
prom_co Coercion -> Coercion -> Coercion
`mkTransCo` Coercion
frr_co

                     ; IORef (Maybe Type) -> Maybe Type -> TcM ()
forall (m :: * -> *) a. MonadIO m => TcRef a -> a -> m ()
writeTcRef IORef (Maybe Type)
ref (Type -> Maybe Type
forall a. a -> Maybe a
Just Type
act_res_ty)

                     ; Coercion -> TcM Coercion
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return Coercion
final_co }
     }

{- Note [fillInferResult]
~~~~~~~~~~~~~~~~~~~~~~~~~
When inferring, we use fillInferResult to "fill in" the hole in InferResult
   data InferResult = IR { ir_uniq :: Unique
                         , ir_lvl  :: TcLevel
                         , ir_ref  :: IORef (Maybe TcType) }

There are two things to worry about:

1. What if it is under a GADT or existential pattern match?
   - GADTs: a unification variable (and Infer's hole is similar) is untouchable
   - Existentials: be careful about skolem-escape

2. What if it is filled in more than once?  E.g. multiple branches of a case
     case e of
        T1 -> e1
        T2 -> e2

Our typing rules are:

* The RHS of a existential or GADT alternative must always be a
  monotype, regardless of the number of alternatives.

* Multiple non-existential/GADT branches can have (the same)
  higher rank type (#18412).  E.g. this is OK:
      case e of
        True  -> hr
        False -> hr
  where hr:: (forall a. a->a) -> Int
  c.f. Section 7.1 of "Practical type inference for arbitrary-rank types"
       We use choice (2) in that Section.
       (GHC 8.10 and earlier used choice (1).)

  But note that
      case e of
        True  -> hr
        False -> \x -> hr x
  will fail, because we still /infer/ both branches, so the \x will get
  a (monotype) unification variable, which will fail to unify with
  (forall a. a->a)

For (1) we can detect the GADT/existential situation by seeing that
the current TcLevel is greater than that stored in ir_lvl of the Infer
ExpType.  We bump the level whenever we go past a GADT/existential match.

Then, before filling the hole use promoteTcType to promote the type
to the outer ir_lvl.  promoteTcType does this
  - create a fresh unification variable alpha at level ir_lvl
  - emits an equality alpha[ir_lvl] ~ ty
  - fills the hole with alpha
That forces the type to be a monotype (since unification variables can
only unify with monotypes); and catches skolem-escapes because the
alpha is untouchable until the equality floats out.

For (2), we simply look to see if the hole is filled already.
  - if not, we promote (as above) and fill the hole
  - if it is filled, we simply unify with the type that is
    already there

There is one wrinkle.  Suppose we have
   case e of
      T1 -> e1 :: (forall a. a->a) -> Int
      G2 -> e2
where T1 is not GADT or existential, but G2 is a GADT.  Then suppose the
T1 alternative fills the hole with (forall a. a->a) -> Int, which is fine.
But now the G2 alternative must not *just* unify with that else we'd risk
allowing through (e2 :: (forall a. a->a) -> Int).  If we'd checked G2 first
we'd have filled the hole with a unification variable, which enforces a
monotype.

So if we check G2 second, we still want to emit a constraint that restricts
the RHS to be a monotype. This is done by ensureMonoType, and it works
by simply generating a constraint (alpha ~ ty), where alpha is a fresh
unification variable.  We discard the evidence.

-}



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

Note [Ambiguity check and deep subsumption]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
   f :: (forall b. Eq b => a -> a) -> Int

Does `f` have an ambiguous type?   The ambiguity check usually checks
that this definition of f' would typecheck, where f' has the exact same
type as f:
   f' :: (forall b. Eq b => a -> a) -> Intp
   f' = f

This will be /rejected/ with DeepSubsumption but /accepted/ with
ShallowSubsumption.  On the other hand, this eta-expanded version f''
would be rejected both ways:
   f'' :: (forall b. Eq b => a -> a) -> Intp
   f'' x = f x

This is squishy in the same way as other examples in GHC.Tc.Validity
Note [The squishiness of the ambiguity check]

The situation in June 2022.  Since we have SimpleSubsumption at the moment,
we don't want introduce new breakage if you add -XDeepSubsumption, by
rejecting types as ambiguous that weren't ambiguous before.  So, as a
holding decision, we /always/ use SimpleSubsumption for the ambiguity check
(erring on the side accepting more programs). Hence tcSubTypeAmbiguity.
-}



-----------------
-- 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 -> Type -> ExpRhoType -> TcM (HsExpr GhcTc)
tcWrapResult HsExpr GhcRn
rn_expr = CtOrigin
-> HsExpr GhcRn
-> HsExpr GhcTc
-> Type
-> 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
-> Type
-> ExpRhoType
-> TcM (HsExpr GhcTc)
tcWrapResultO CtOrigin
orig HsExpr GhcRn
rn_expr HsExpr GhcTc
expr Type
actual_ty ExpRhoType
res_ty
  = do { String -> SDoc -> TcM ()
traceTc String
"tcWrapResult" ([SDoc] -> SDoc
forall doc. IsDoc doc => [doc] -> doc
vcat [ String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"Actual:  " SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
actual_ty
                                      , String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"Expected:" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> ExpRhoType -> SDoc
forall a. Outputable a => a -> SDoc
ppr ExpRhoType
res_ty ])
       ; HsWrapper
wrap <- CtOrigin
-> UserTypeCtxt
-> Maybe TypedThing
-> Type
-> ExpRhoType
-> TcM HsWrapper
tcSubTypeNC CtOrigin
orig UserTypeCtxt
GenSigCtxt (TypedThing -> Maybe TypedThing
forall a. a -> Maybe a
Just (TypedThing -> Maybe TypedThing) -> TypedThing -> Maybe TypedThing
forall a b. (a -> b) -> a -> b
$ HsExpr GhcRn -> TypedThing
HsExprRnThing HsExpr GhcRn
rn_expr) Type
actual_ty ExpRhoType
res_ty
       ; HsExpr GhcTc -> TcM (HsExpr GhcTc)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
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 -> Type -> ExpRhoType -> TcM (HsExpr GhcTc)
tcWrapResultMono HsExpr GhcRn
rn_expr HsExpr GhcTc
expr Type
act_ty ExpRhoType
res_ty
  = Bool -> SDoc -> TcM (HsExpr GhcTc) -> TcM (HsExpr GhcTc)
forall a. HasCallStack => Bool -> SDoc -> a -> a
assertPpr (Type -> Bool
isRhoTy Type
act_ty) (Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
act_ty SDoc -> SDoc -> SDoc
forall doc. IsDoc doc => doc -> doc -> doc
$$ HsExpr GhcRn -> SDoc
forall a. Outputable a => a -> SDoc
ppr HsExpr GhcRn
rn_expr) (TcM (HsExpr GhcTc) -> TcM (HsExpr GhcTc))
-> TcM (HsExpr GhcTc) -> TcM (HsExpr GhcTc)
forall a b. (a -> b) -> a -> b
$
    do { Coercion
co <- HsExpr GhcRn -> Type -> ExpRhoType -> TcM Coercion
unifyExpectedType HsExpr GhcRn
rn_expr Type
act_ty ExpRhoType
res_ty
       ; HsExpr GhcTc -> TcM (HsExpr GhcTc)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Coercion -> HsExpr GhcTc -> HsExpr GhcTc
mkHsWrapCo Coercion
co HsExpr GhcTc
expr) }

unifyExpectedType :: HsExpr GhcRn
                  -> TcRhoType   -- Actual -- a rho-type not a sigma-type
                  -> ExpRhoType  -- Expected
                  -> TcM TcCoercionN
unifyExpectedType :: HsExpr GhcRn -> Type -> ExpRhoType -> TcM Coercion
unifyExpectedType HsExpr GhcRn
rn_expr Type
act_ty ExpRhoType
exp_ty
  = case ExpRhoType
exp_ty of
      Infer InferResult
inf_res -> Type -> InferResult -> TcM Coercion
fillInferResult Type
act_ty InferResult
inf_res
      Check Type
exp_ty  -> Maybe TypedThing -> Type -> Type -> TcM Coercion
unifyType (TypedThing -> Maybe TypedThing
forall a. a -> Maybe a
Just (TypedThing -> Maybe TypedThing) -> TypedThing -> Maybe TypedThing
forall a b. (a -> b) -> a -> b
$ HsExpr GhcRn -> TypedThing
HsExprRnThing HsExpr GhcRn
rn_expr) Type
act_ty Type
exp_ty

------------------------
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 -> Type -> TcM HsWrapper
tcSubTypePat CtOrigin
inst_orig UserTypeCtxt
ctxt (Check Type
ty_actual) Type
ty_expected
  = (Type -> Type -> TcM Coercion)
-> CtOrigin -> UserTypeCtxt -> Type -> Type -> TcM HsWrapper
tc_sub_type Type -> Type -> TcM Coercion
unifyTypeET CtOrigin
inst_orig UserTypeCtxt
ctxt Type
ty_actual Type
ty_expected

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

       ; HsWrapper -> TcM HsWrapper
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Coercion -> HsWrapper
mkWpCastN (Coercion -> Coercion
mkSymCo Coercion
co)) }

---------------
tcSubType :: CtOrigin -> UserTypeCtxt
          -> TcSigmaType  -- ^ Actual
          -> ExpRhoType   -- ^ Expected
          -> TcM HsWrapper
-- Checks that 'actual' is more polymorphic than 'expected'
tcSubType :: CtOrigin -> UserTypeCtxt -> Type -> ExpRhoType -> TcM HsWrapper
tcSubType CtOrigin
orig UserTypeCtxt
ctxt Type
ty_actual ExpRhoType
ty_expected
  = Type -> ExpRhoType -> TcM HsWrapper -> TcM HsWrapper
forall a. Type -> ExpRhoType -> TcM a -> TcM a
addSubTypeCtxt Type
ty_actual ExpRhoType
ty_expected (TcM HsWrapper -> TcM HsWrapper) -> TcM HsWrapper -> TcM HsWrapper
forall a b. (a -> b) -> a -> b
$
    do { String -> SDoc -> TcM ()
traceTc String
"tcSubType" ([SDoc] -> SDoc
forall doc. IsDoc doc => [doc] -> doc
vcat [UserTypeCtxt -> SDoc
pprUserTypeCtxt UserTypeCtxt
ctxt, Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
ty_actual, ExpRhoType -> SDoc
forall a. Outputable a => a -> SDoc
ppr ExpRhoType
ty_expected])
       ; CtOrigin
-> UserTypeCtxt
-> Maybe TypedThing
-> Type
-> ExpRhoType
-> TcM HsWrapper
tcSubTypeNC CtOrigin
orig UserTypeCtxt
ctxt Maybe TypedThing
forall a. Maybe a
Nothing Type
ty_actual ExpRhoType
ty_expected }

---------------
tcSubTypeDS :: HsExpr GhcRn
            -> TcRhoType   -- Actual -- a rho-type not a sigma-type
            -> ExpRhoType  -- Expected
            -> TcM HsWrapper
-- Similar signature to unifyExpectedType; does deep subsumption
-- Only one call site, in GHC.Tc.Gen.App.tcApp
tcSubTypeDS :: HsExpr GhcRn -> Type -> ExpRhoType -> TcM HsWrapper
tcSubTypeDS HsExpr GhcRn
rn_expr Type
act_rho ExpRhoType
res_ty
  = case ExpRhoType
res_ty of
      Check Type
exp_rho -> (Type -> Type -> TcM Coercion)
-> CtOrigin -> UserTypeCtxt -> Type -> Type -> TcM HsWrapper
tc_sub_type_deep (Maybe TypedThing -> Type -> Type -> TcM Coercion
unifyType Maybe TypedThing
m_thing) CtOrigin
orig
                                        UserTypeCtxt
GenSigCtxt Type
act_rho Type
exp_rho

      Infer InferResult
inf_res -> do { Coercion
co <- Type -> InferResult -> TcM Coercion
fillInferResult Type
act_rho InferResult
inf_res
                          ; HsWrapper -> TcM HsWrapper
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Coercion -> HsWrapper
mkWpCastN Coercion
co) }
  where
    orig :: CtOrigin
orig    = HsExpr GhcRn -> CtOrigin
exprCtOrigin HsExpr GhcRn
rn_expr
    m_thing :: Maybe TypedThing
m_thing = TypedThing -> Maybe TypedThing
forall a. a -> Maybe a
Just (HsExpr GhcRn -> TypedThing
HsExprRnThing HsExpr GhcRn
rn_expr)

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

      Infer InferResult
inf_res -> do { (HsWrapper
wrap, Type
rho) <- CtOrigin -> Type -> TcM (HsWrapper, Type)
topInstantiate CtOrigin
inst_orig Type
ty_actual
                                   -- See Note [Instantiation of InferResult]
                          ; Coercion
co <- Type -> InferResult -> TcM Coercion
fillInferResult Type
rho InferResult
inf_res
                          ; HsWrapper -> TcM HsWrapper
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Coercion -> HsWrapper
mkWpCastN Coercion
co HsWrapper -> HsWrapper -> HsWrapper
<.> HsWrapper
wrap) }

---------------
tcSubTypeSigma :: CtOrigin       -- where did the actual type arise / why are we
                                 -- doing this subtype check?
               -> UserTypeCtxt   -- where did the expected type arise?
               -> TcSigmaType -> TcSigmaType -> TcM HsWrapper
-- External entry point, but no ExpTypes on either side
-- Checks that actual <= expected
-- Returns HsWrapper :: actual ~ expected
tcSubTypeSigma :: CtOrigin -> UserTypeCtxt -> Type -> Type -> TcM HsWrapper
tcSubTypeSigma CtOrigin
orig UserTypeCtxt
ctxt Type
ty_actual Type
ty_expected
  = (Type -> Type -> TcM Coercion)
-> CtOrigin -> UserTypeCtxt -> Type -> Type -> TcM HsWrapper
tc_sub_type (Maybe TypedThing -> Type -> Type -> TcM Coercion
unifyType Maybe TypedThing
forall a. Maybe a
Nothing) CtOrigin
orig UserTypeCtxt
ctxt Type
ty_actual Type
ty_expected

---------------
tcSubTypeAmbiguity :: UserTypeCtxt   -- Where did this type arise
                   -> TcSigmaType -> TcSigmaType -> TcM HsWrapper
-- See Note [Ambiguity check and deep subsumption]
tcSubTypeAmbiguity :: UserTypeCtxt -> Type -> Type -> TcM HsWrapper
tcSubTypeAmbiguity UserTypeCtxt
ctxt Type
ty_actual Type
ty_expected
  = (Type -> Type -> TcM Coercion)
-> CtOrigin -> UserTypeCtxt -> Type -> Type -> TcM HsWrapper
tc_sub_type_shallow (Maybe TypedThing -> Type -> Type -> TcM Coercion
unifyType Maybe TypedThing
forall a. Maybe a
Nothing)
                        (UserTypeCtxt -> CtOrigin
AmbiguityCheckOrigin UserTypeCtxt
ctxt)
                        UserTypeCtxt
ctxt Type
ty_actual Type
ty_expected

---------------
addSubTypeCtxt :: TcType -> ExpType -> TcM a -> TcM a
addSubTypeCtxt :: forall a. Type -> ExpRhoType -> TcM a -> TcM a
addSubTypeCtxt Type
ty_actual ExpRhoType
ty_expected TcM a
thing_inside
 | Type -> Bool
isRhoTy Type
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 -> ZonkM (TidyEnv, SDoc)) -> TcM a -> TcM a
forall a. (TidyEnv -> ZonkM (TidyEnv, SDoc)) -> TcM a -> TcM a
addErrCtxtM TidyEnv -> ZonkM (TidyEnv, SDoc)
mk_msg TcM a
thing_inside
  where
    mk_msg :: TidyEnv -> ZonkM (TidyEnv, SDoc)
mk_msg TidyEnv
tidy_env
      = do { (TidyEnv
tidy_env, Type
ty_actual)   <- TidyEnv -> Type -> ZonkM (TidyEnv, Type)
zonkTidyTcType TidyEnv
tidy_env Type
ty_actual
           ; Type
ty_expected             <- ExpRhoType -> ZonkM Type
forall (m :: * -> *). MonadIO m => ExpRhoType -> m Type
readExpType ExpRhoType
ty_expected
                   -- A worry: might not be filled if we're debugging. Ugh.
           ; (TidyEnv
tidy_env, Type
ty_expected) <- TidyEnv -> Type -> ZonkM (TidyEnv, Type)
zonkTidyTcType TidyEnv
tidy_env Type
ty_expected
           ; let msg :: SDoc
msg = [SDoc] -> SDoc
forall doc. IsDoc doc => [doc] -> doc
vcat [ SDoc -> Int -> SDoc -> SDoc
hang (String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"When checking that:")
                                 Int
4 (Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
ty_actual)
                            , Int -> SDoc -> SDoc
nest Int
2 (SDoc -> Int -> SDoc -> SDoc
hang (String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"is more polymorphic than:")
                                         Int
2 (Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
ty_expected)) ]
           ; (TidyEnv, SDoc) -> ZonkM (TidyEnv, SDoc)
forall a. a -> ZonkM a
forall (m :: * -> *) a. Monad m => a -> m a
return (TidyEnv
tidy_env, SDoc
msg) }


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

---------------
tc_sub_type, tc_sub_type_deep, tc_sub_type_shallow
    :: (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
--
-- The "how to unify argument" is always a call to `uType TypeLevel orig`,
-- but with different ways of constructing the CtOrigin `orig` from
-- the argument types and context.

----------------------
tc_sub_type :: (Type -> Type -> TcM Coercion)
-> CtOrigin -> UserTypeCtxt -> Type -> Type -> TcM HsWrapper
tc_sub_type Type -> Type -> TcM Coercion
unify CtOrigin
inst_orig UserTypeCtxt
ctxt Type
ty_actual Type
ty_expected
  = do { Bool
deep_subsumption <- Extension -> TcRnIf TcGblEnv TcLclEnv Bool
forall gbl lcl. Extension -> TcRnIf gbl lcl Bool
xoptM Extension
LangExt.DeepSubsumption
       ; if Bool
deep_subsumption
         then (Type -> Type -> TcM Coercion)
-> CtOrigin -> UserTypeCtxt -> Type -> Type -> TcM HsWrapper
tc_sub_type_deep    Type -> Type -> TcM Coercion
unify CtOrigin
inst_orig UserTypeCtxt
ctxt Type
ty_actual Type
ty_expected
         else (Type -> Type -> TcM Coercion)
-> CtOrigin -> UserTypeCtxt -> Type -> Type -> TcM HsWrapper
tc_sub_type_shallow Type -> Type -> TcM Coercion
unify CtOrigin
inst_orig UserTypeCtxt
ctxt Type
ty_actual Type
ty_expected
  }

----------------------
tc_sub_type_shallow :: (Type -> Type -> TcM Coercion)
-> CtOrigin -> UserTypeCtxt -> Type -> Type -> TcM HsWrapper
tc_sub_type_shallow Type -> Type -> TcM Coercion
unify CtOrigin
inst_orig UserTypeCtxt
ctxt Type
ty_actual Type
ty_expected
  | Type -> Bool
definitely_poly Type
ty_expected   -- See Note [Don't skolemise unnecessarily]
  , Type -> Bool
definitely_mono_shallow Type
ty_actual
  = do { String -> SDoc -> TcM ()
traceTc String
"tc_sub_type (drop to equality)" (SDoc -> TcM ()) -> SDoc -> TcM ()
forall a b. (a -> b) -> a -> b
$
         [SDoc] -> SDoc
forall doc. IsDoc doc => [doc] -> doc
vcat [ String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"ty_actual   =" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
ty_actual
              , String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"ty_expected =" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
ty_expected ]
       ; Coercion -> HsWrapper
mkWpCastN (Coercion -> HsWrapper) -> TcM Coercion -> TcM HsWrapper
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$>
         Type -> Type -> TcM Coercion
unify Type
ty_actual Type
ty_expected }

  | Bool
otherwise   -- This is the general case
  = do { String -> SDoc -> TcM ()
traceTc String
"tc_sub_type (general case)" (SDoc -> TcM ()) -> SDoc -> TcM ()
forall a b. (a -> b) -> a -> b
$
         [SDoc] -> SDoc
forall doc. IsDoc doc => [doc] -> doc
vcat [ String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"ty_actual   =" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
ty_actual
              , String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"ty_expected =" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
ty_expected ]

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

       ; HsWrapper -> TcM HsWrapper
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (HsWrapper
sk_wrap HsWrapper -> HsWrapper -> HsWrapper
<.> HsWrapper
inner_wrap) }

----------------------
tc_sub_type_deep :: (Type -> Type -> TcM Coercion)
-> CtOrigin -> UserTypeCtxt -> Type -> Type -> TcM HsWrapper
tc_sub_type_deep Type -> Type -> TcM Coercion
unify CtOrigin
inst_orig UserTypeCtxt
ctxt Type
ty_actual Type
ty_expected
  | Type -> Bool
definitely_poly Type
ty_expected      -- See Note [Don't skolemise unnecessarily]
  , Type -> Bool
definitely_mono_deep Type
ty_actual
  = do { String -> SDoc -> TcM ()
traceTc String
"tc_sub_type_deep (drop to equality)" (SDoc -> TcM ()) -> SDoc -> TcM ()
forall a b. (a -> b) -> a -> b
$
         [SDoc] -> SDoc
forall doc. IsDoc doc => [doc] -> doc
vcat [ String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"ty_actual   =" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
ty_actual
              , String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"ty_expected =" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
ty_expected ]
       ; Coercion -> HsWrapper
mkWpCastN (Coercion -> HsWrapper) -> TcM Coercion -> TcM HsWrapper
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$>
         Type -> Type -> TcM Coercion
unify Type
ty_actual Type
ty_expected }

  | Bool
otherwise   -- This is the general case
  = do { String -> SDoc -> TcM ()
traceTc String
"tc_sub_type_deep (general case)" (SDoc -> TcM ()) -> SDoc -> TcM ()
forall a b. (a -> b) -> a -> b
$
         [SDoc] -> SDoc
forall doc. IsDoc doc => [doc] -> doc
vcat [ String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"ty_actual   =" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
ty_actual
              , String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"ty_expected =" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
ty_expected ]

       ; (HsWrapper
sk_wrap, HsWrapper
inner_wrap)
           <- UserTypeCtxt
-> Type -> (Type -> TcM HsWrapper) -> TcM (HsWrapper, HsWrapper)
forall result.
UserTypeCtxt
-> Type -> (Type -> TcM result) -> TcM (HsWrapper, result)
tcDeeplySkolemise UserTypeCtxt
ctxt Type
ty_expected ((Type -> TcM HsWrapper) -> TcM (HsWrapper, HsWrapper))
-> (Type -> TcM HsWrapper) -> TcM (HsWrapper, HsWrapper)
forall a b. (a -> b) -> a -> b
$ \ Type
sk_rho ->
              -- See Note [Deep subsumption]
              (Type -> Type -> TcM Coercion)
-> CtOrigin -> UserTypeCtxt -> Type -> Type -> TcM HsWrapper
tc_sub_type_ds Type -> Type -> TcM Coercion
unify CtOrigin
inst_orig UserTypeCtxt
ctxt Type
ty_actual Type
sk_rho

       ; HsWrapper -> TcM HsWrapper
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (HsWrapper
sk_wrap HsWrapper -> HsWrapper -> HsWrapper
<.> HsWrapper
inner_wrap) }

definitely_mono_shallow :: TcType -> Bool
definitely_mono_shallow :: Type -> Bool
definitely_mono_shallow Type
ty = Type -> Bool
isRhoTy Type
ty
    -- isRhoTy: no top level forall or (=>)

definitely_mono_deep :: TcType -> Bool
definitely_mono_deep :: Type -> Bool
definitely_mono_deep Type
ty
  | Bool -> Bool
not (Type -> Bool
definitely_mono_shallow Type
ty)     = Bool
False
    -- isRhoTy: False means top level forall or (=>)
  | Just (Scaled Type
_, Type
res) <- Type -> Maybe (Scaled Type, Type)
tcSplitFunTy_maybe Type
ty = Type -> Bool
definitely_mono_deep Type
res
    -- Top level (->)
  | Bool
otherwise                              = Bool
True

definitely_poly :: TcType -> Bool
-- A very conservative test:
-- see Note [Don't skolemise unnecessarily]
definitely_poly :: Type -> Bool
definitely_poly Type
ty
  | ([TcTyVar]
tvs, [Type]
theta, Type
tau) <- Type -> ([TcTyVar], [Type], Type)
tcSplitSigmaTy Type
ty
  , (TcTyVar
tv:[TcTyVar]
_) <- [TcTyVar]
tvs   -- At least one tyvar
  , [Type] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Type]
theta      -- No constraints; see (DP1)
  , TcTyVar
tv TcTyVar -> Type -> Bool
`isInjectiveInType` Type
tau
       -- The tyvar actually occurs (DP2),
       -- and occurs in an injective position (DP3).
  = Bool
True
  | Bool
otherwise
  = Bool
False

{- Note [Don't skolemise unnecessarily]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose we are trying to solve
     ty_actual   <= ty_expected
    (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.

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: see `definitely_mono`
   This definitely_mono test comes in "shallow" and "deep" variants

 * ty_expected is /definitely/ polymorphic: see `definitely_poly`
   This definitely_poly test is more subtle than you might think.
   Here are three cases where expected_ty looks polymorphic, but
   isn't, and where it would be /wrong/ to switch to equality:

   (DP1)  (Char->Char) <= (forall a. (a~Char) => a -> a)

   (DP2)  (Char->Char) <= (forall a. Char -> Char)

   (DP3)  (Char->Char) <= (forall a. F [a] Char -> Char)
                          where type instance F [x] t = t


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

An alternative would be to have a kind of constraint which can
only produce trivial evidence. This would allow such checks to happen
in the constraint solver (#18756).
This would be similar to the existing setup for Concrete, see
  Note [The Concrete mechanism] in GHC.Tc.Utils.Concrete
    (PHASE 1 in particular).
-}

tcSubMult :: CtOrigin -> Mult -> Mult -> TcM HsWrapper
tcSubMult :: CtOrigin -> Type -> Type -> TcM HsWrapper
tcSubMult CtOrigin
origin Type
w_actual Type
w_expected
  | Just (Type
w1, Type
w2) <- Type -> Maybe (Type, Type)
isMultMul Type
w_actual =
  do { HsWrapper
w1 <- CtOrigin -> Type -> Type -> TcM HsWrapper
tcSubMult CtOrigin
origin Type
w1 Type
w_expected
     ; HsWrapper
w2 <- CtOrigin -> Type -> Type -> TcM HsWrapper
tcSubMult CtOrigin
origin Type
w2 Type
w_expected
     ; HsWrapper -> TcM HsWrapper
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
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 Type
w_actual Type
w_expected =
  case Type -> Type -> IsSubmult
submult Type
w_actual Type
w_expected of
    IsSubmult
Submult -> HsWrapper -> TcM HsWrapper
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return HsWrapper
WpHole
    IsSubmult
Unknown -> CtOrigin -> Type -> Type -> TcM HsWrapper
tcEqMult CtOrigin
origin Type
w_actual Type
w_expected

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


{- *********************************************************************
*                                                                      *
                    Deep subsumption
*                                                                      *
********************************************************************* -}

{- Note [Deep subsumption]
~~~~~~~~~~~~~~~~~~~~~~~~~~
The DeepSubsumption extension, documented here

    https://github.com/ghc-proposals/ghc-proposals/pull/511.

makes a best-efforts attempt implement deep subsumption as it was
prior to the Simplify Subsumption proposal:

    https://github.com/ghc-proposals/ghc-proposals/pull/287

The effects are in these main places:

1. In the subsumption check, tcSubType, we must do deep skolemisation:
   see the call to tcDeeplySkolemise in tc_sub_type_deep

2. In tcPolyExpr we must do deep skolemisation:
   see the call to tcDeeplySkolemise in tcSkolemiseExpType

3. for expression type signatures (e :: ty), and functions with type
   signatures (e.g. f :: ty; f = e), we must deeply skolemise the type;
   see the call to tcDeeplySkolemise in tcSkolemiseScoped.

4. In GHC.Tc.Gen.App.tcApp we call tcSubTypeDS to match the result
   type. Without deep subsumption, unifyExpectedType would be sufficent.

In all these cases note that the deep skolemisation must be done /first/.
Consider (1)
     (forall a. Int -> a -> a)  <=  Int -> (forall b. b -> b)
We must skolemise the `forall b` before instantiating the `forall a`.
See also Note [Deep skolemisation].

Note that we /always/ use shallow subsumption in the ambiguity check.
See Note [Ambiguity check and deep subsumption].

Note [Deep skolemisation]
~~~~~~~~~~~~~~~~~~~~~~~~~
deeplySkolemise decomposes and skolemises a type, returning a type
with all its arrows visible (ie not buried under foralls)

Examples:

  deeplySkolemise (Int -> forall a. Ord a => blah)
    =  ( wp, [a], [d:Ord a], Int -> blah )
    where wp = \x:Int. /\a. \(d:Ord a). <hole> x

  deeplySkolemise  (forall a. Ord a => Maybe a -> forall b. Eq b => blah)
    =  ( wp, [a,b], [d1:Ord a,d2:Eq b], Maybe a -> blah )
    where wp = /\a.\(d1:Ord a).\(x:Maybe a)./\b.\(d2:Ord b). <hole> x

In general,
  if      deeplySkolemise ty = (wrap, tvs, evs, rho)
    and   e :: rho
  then    wrap e :: ty
    and   'wrap' binds tvs, evs

ToDo: this eta-abstraction plays fast and loose with termination,
      because it can introduce extra lambdas.  Maybe add a `seq` to
      fix this

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

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

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

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

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

Note [Multiplicity in deep subsumption]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
   t1 ->{mt} t2  <=   s1 ->{ms} s2

At the moment we /unify/ ms~mt, via tcEqMult.

Arguably we should use `tcSubMult`. But then if mt=m0 (a unification
variable) and ms=Many, `tcSubMult` is a no-op (since anything is a
sub-multiplicty of Many).  But then `m0` may never get unified with
anything.  It is then skolemised by the zonker; see GHC.HsToCore.Binds
Note [Free tyvars on rule LHS].  So we in RULE foldr/app in GHC.Base
we get this

 "foldr/app"     [1] forall ys m1 m2. foldr (\x{m1} \xs{m2}. (:) x xs) ys
                                       = \xs -> xs ++ ys

where we eta-expanded that (:).  But now foldr expects an argument
with ->{Many} and gets an argument with ->{m1} or ->{m2}, and Lint
complains.

The easiest solution was to use tcEqMult in tc_sub_type_ds, and
insist on equality. This is only in the DeepSubsumption code anyway.
-}

tc_sub_type_ds :: (TcType -> TcType -> TcM TcCoercionN)  -- How to unify
               -> CtOrigin       -- Used when instantiating
               -> UserTypeCtxt   -- Used when skolemising
               -> TcSigmaType    -- Actual; a sigma-type
               -> TcRhoType      -- Expected; deeply skolemised
               -> TcM HsWrapper

-- If wrap = tc_sub_type_ds t1 t2
--    => wrap :: t1 ~> t2
-- Here is where the work actually happens!
-- Precondition: ty_expected is deeply skolemised

tc_sub_type_ds :: (Type -> Type -> TcM Coercion)
-> CtOrigin -> UserTypeCtxt -> Type -> Type -> TcM HsWrapper
tc_sub_type_ds Type -> Type -> TcM Coercion
unify CtOrigin
inst_orig UserTypeCtxt
ctxt Type
ty_actual Type
ty_expected
  = do { String -> SDoc -> TcM ()
traceTc String
"tc_sub_type_ds" (SDoc -> TcM ()) -> SDoc -> TcM ()
forall a b. (a -> b) -> a -> b
$
         [SDoc] -> SDoc
forall doc. IsDoc doc => [doc] -> doc
vcat [ String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"ty_actual   =" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
ty_actual
              , String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"ty_expected =" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
ty_expected ]
       ; Type -> Type -> TcM HsWrapper
go Type
ty_actual Type
ty_expected }
  where
    -- NB: 'go' is not recursive, except for doing coreView
    go :: Type -> Type -> TcM HsWrapper
go Type
ty_a Type
ty_e | Just Type
ty_a' <- Type -> Maybe Type
coreView Type
ty_a = Type -> Type -> TcM HsWrapper
go Type
ty_a' Type
ty_e
                 | Just Type
ty_e' <- Type -> Maybe Type
coreView Type
ty_e = Type -> Type -> TcM HsWrapper
go Type
ty_a  Type
ty_e'

    go (TyVarTy TcTyVar
tv_a) Type
ty_e
      = do { Maybe Type
lookup_res <- TcTyVar -> IOEnv (Env TcGblEnv TcLclEnv) (Maybe Type)
isFilledMetaTyVar_maybe TcTyVar
tv_a
           ; case Maybe Type
lookup_res of
               Just Type
ty_a' ->
                 do { String -> SDoc -> TcM ()
traceTc String
"tc_sub_type_ds following filled meta-tyvar:"
                        (TcTyVar -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcTyVar
tv_a SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"-->" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
ty_a')
                    ; (Type -> Type -> TcM Coercion)
-> CtOrigin -> UserTypeCtxt -> Type -> Type -> TcM HsWrapper
tc_sub_type_ds Type -> Type -> TcM Coercion
unify CtOrigin
inst_orig UserTypeCtxt
ctxt Type
ty_a' Type
ty_e }
               Maybe Type
Nothing -> Type -> Type -> TcM HsWrapper
just_unify Type
ty_actual Type
ty_expected }

    go ty_a :: Type
ty_a@(FunTy { ft_af :: Type -> FunTyFlag
ft_af = FunTyFlag
af1, ft_mult :: Type -> Type
ft_mult = Type
act_mult, ft_arg :: Type -> Type
ft_arg = Type
act_arg, ft_res :: Type -> Type
ft_res = Type
act_res })
       ty_e :: Type
ty_e@(FunTy { ft_af :: Type -> FunTyFlag
ft_af = FunTyFlag
af2, ft_mult :: Type -> Type
ft_mult = Type
exp_mult, ft_arg :: Type -> Type
ft_arg = Type
exp_arg, ft_res :: Type -> Type
ft_res = Type
exp_res })
      | FunTyFlag -> Bool
isVisibleFunArg FunTyFlag
af1, FunTyFlag -> Bool
isVisibleFunArg FunTyFlag
af2
      = if (Type -> Bool
isTauTy Type
ty_a Bool -> Bool -> Bool
&& Type -> Bool
isTauTy Type
ty_e)       -- Short cut common case to avoid
        then Type -> Type -> TcM HsWrapper
just_unify Type
ty_actual Type
ty_expected   -- unnecessary eta expansion
        else
        -- This is where we do the co/contra thing, and generate a WpFun, which in turn
        -- causes eta-expansion, which we don't like; hence encouraging NoDeepSubsumption
        do { HsWrapper
arg_wrap  <- (Type -> Type -> TcM Coercion)
-> CtOrigin -> UserTypeCtxt -> Type -> Type -> TcM HsWrapper
tc_sub_type_deep Type -> Type -> TcM Coercion
unify CtOrigin
given_orig UserTypeCtxt
GenSigCtxt Type
exp_arg Type
act_arg
                          -- GenSigCtxt: See Note [Setting the argument context]
           ; HsWrapper
res_wrap  <- (Type -> Type -> TcM Coercion)
-> CtOrigin -> UserTypeCtxt -> Type -> Type -> TcM HsWrapper
tc_sub_type_ds   Type -> Type -> TcM Coercion
unify CtOrigin
inst_orig  UserTypeCtxt
ctxt       Type
act_res Type
exp_res
           ; HsWrapper
mult_wrap <- CtOrigin -> Type -> Type -> TcM HsWrapper
tcEqMult CtOrigin
inst_orig Type
act_mult Type
exp_mult
                          -- See Note [Multiplicity in deep subsumption]
           ; HsWrapper -> TcM HsWrapper
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (HsWrapper
mult_wrap HsWrapper -> HsWrapper -> HsWrapper
<.>
                     HsWrapper -> HsWrapper -> Scaled Type -> Type -> HsWrapper
mkWpFun HsWrapper
arg_wrap HsWrapper
res_wrap (Type -> Type -> Scaled Type
forall a. Type -> a -> Scaled a
Scaled Type
exp_mult Type
exp_arg) Type
exp_res) }
                     -- arg_wrap :: exp_arg ~> act_arg
                     -- res_wrap :: act-res ~> exp_res
      where
        given_orig :: CtOrigin
given_orig = SkolemInfoAnon -> CtOrigin
GivenOrigin (UserTypeCtxt -> Type -> [(Name, TcTyVar)] -> SkolemInfoAnon
SigSkol UserTypeCtxt
GenSigCtxt Type
exp_arg [])

    go Type
ty_a Type
ty_e
      | let ([TcTyVar]
tvs, [Type]
theta, Type
_) = Type -> ([TcTyVar], [Type], Type)
tcSplitSigmaTy Type
ty_a
      , Bool -> Bool
not ([TcTyVar] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [TcTyVar]
tvs Bool -> Bool -> Bool
&& [Type] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Type]
theta)
      = do { (HsWrapper
in_wrap, Type
in_rho) <- CtOrigin -> Type -> TcM (HsWrapper, Type)
topInstantiate CtOrigin
inst_orig Type
ty_a
           ; HsWrapper
body_wrap <- (Type -> Type -> TcM Coercion)
-> CtOrigin -> UserTypeCtxt -> Type -> Type -> TcM HsWrapper
tc_sub_type_ds Type -> Type -> TcM Coercion
unify CtOrigin
inst_orig UserTypeCtxt
ctxt Type
in_rho Type
ty_e
           ; HsWrapper -> TcM HsWrapper
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (HsWrapper
body_wrap HsWrapper -> HsWrapper -> HsWrapper
<.> HsWrapper
in_wrap) }

      | Bool
otherwise   -- Revert to unification
      = do { -- It's still possible that ty_actual has nested foralls. Instantiate
             -- these, as there's no way unification will succeed with them in.
             -- See typecheck/should_compile/T11305 for an example of when this
             -- is important. The problem is that we're checking something like
             --  a -> forall b. b -> b     <=   alpha beta gamma
             -- where we end up with alpha := (->)
             (HsWrapper
inst_wrap, Type
rho_a) <- CtOrigin -> Type -> TcM (HsWrapper, Type)
deeplyInstantiate CtOrigin
inst_orig Type
ty_actual
           ; HsWrapper
unify_wrap         <- Type -> Type -> TcM HsWrapper
just_unify Type
rho_a Type
ty_expected
           ; HsWrapper -> TcM HsWrapper
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (HsWrapper
unify_wrap HsWrapper -> HsWrapper -> HsWrapper
<.> HsWrapper
inst_wrap) }

    just_unify :: Type -> Type -> TcM HsWrapper
just_unify Type
ty_a Type
ty_e = do { Coercion
cow <- Type -> Type -> TcM Coercion
unify Type
ty_a Type
ty_e
                              ; HsWrapper -> TcM HsWrapper
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Coercion -> HsWrapper
mkWpCastN Coercion
cow) }

tcDeeplySkolemise
    :: UserTypeCtxt -> TcSigmaType
    -> (TcType -> TcM result)
    -> TcM (HsWrapper, result)
        -- ^ The wrapper has type: spec_ty ~> expected_ty
-- Just like tcTopSkolemise, but calls
-- deeplySkolemise instead of topSkolemise
-- See Note [Deep skolemisation]
tcDeeplySkolemise :: forall result.
UserTypeCtxt
-> Type -> (Type -> TcM result) -> TcM (HsWrapper, result)
tcDeeplySkolemise UserTypeCtxt
ctxt Type
expected_ty Type -> TcM result
thing_inside
  | Type -> Bool
isTauTy Type
expected_ty  -- Short cut for common case
  = do { result
res <- Type -> TcM result
thing_inside Type
expected_ty
       ; (HsWrapper, result) -> TcM (HsWrapper, result)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (HsWrapper
idHsWrapper, result
res) }
  | Bool
otherwise
  = do  { -- This (unpleasant) rec block allows us to pass skol_info to deeplySkolemise;
          -- but skol_info can't be built until we have tv_prs
          rec { (HsWrapper
wrap, [(Name, TcTyVar)]
tv_prs, [TcTyVar]
given, Type
rho_ty) <- SkolemInfo
-> Type -> TcM (HsWrapper, [(Name, TcTyVar)], [TcTyVar], Type)
deeplySkolemise SkolemInfo
skol_info Type
expected_ty
              ; SkolemInfo
skol_info <- SkolemInfoAnon -> IOEnv (Env TcGblEnv TcLclEnv) SkolemInfo
forall (m :: * -> *). MonadIO m => SkolemInfoAnon -> m SkolemInfo
mkSkolemInfo (UserTypeCtxt -> Type -> [(Name, TcTyVar)] -> SkolemInfoAnon
SigSkol UserTypeCtxt
ctxt Type
expected_ty [(Name, TcTyVar)]
tv_prs) }

        ; String -> SDoc -> TcM ()
traceTc String
"tcDeeplySkolemise" (Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
expected_ty SDoc -> SDoc -> SDoc
forall doc. IsDoc doc => doc -> doc -> doc
$$ Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
rho_ty SDoc -> SDoc -> SDoc
forall doc. IsDoc doc => doc -> doc -> doc
$$ [(Name, TcTyVar)] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [(Name, TcTyVar)]
tv_prs)

        ; let skol_tvs :: [TcTyVar]
skol_tvs  = ((Name, TcTyVar) -> TcTyVar) -> [(Name, TcTyVar)] -> [TcTyVar]
forall a b. (a -> b) -> [a] -> [b]
map (Name, TcTyVar) -> TcTyVar
forall a b. (a, b) -> b
snd [(Name, TcTyVar)]
tv_prs
        ; (TcEvBinds
ev_binds, result
result)
              <- SkolemInfoAnon
-> [TcTyVar] -> [TcTyVar] -> TcM result -> TcM (TcEvBinds, result)
forall result.
SkolemInfoAnon
-> [TcTyVar] -> [TcTyVar] -> TcM result -> TcM (TcEvBinds, result)
checkConstraints (SkolemInfo -> SkolemInfoAnon
getSkolemInfo SkolemInfo
skol_info) [TcTyVar]
skol_tvs [TcTyVar]
given (TcM result -> TcM (TcEvBinds, result))
-> TcM result -> TcM (TcEvBinds, result)
forall a b. (a -> b) -> a -> b
$
                 Type -> TcM result
thing_inside Type
rho_ty

        ; (HsWrapper, result) -> TcM (HsWrapper, result)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
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

deeplySkolemise :: SkolemInfo -> TcSigmaType
                -> TcM ( HsWrapper
                       , [(Name,TyVar)]     -- All skolemised variables
                       , [EvVar]            -- All "given"s
                       , TcRhoType )
-- See Note [Deep skolemisation]
deeplySkolemise :: SkolemInfo
-> Type -> TcM (HsWrapper, [(Name, TcTyVar)], [TcTyVar], Type)
deeplySkolemise SkolemInfo
skol_info Type
ty
  = Subst
-> Type -> TcM (HsWrapper, [(Name, TcTyVar)], [TcTyVar], Type)
go Subst
init_subst Type
ty
  where
    init_subst :: Subst
init_subst = InScopeSet -> Subst
mkEmptySubst (VarSet -> InScopeSet
mkInScopeSet (Type -> VarSet
tyCoVarsOfType Type
ty))

    go :: Subst
-> Type -> TcM (HsWrapper, [(Name, TcTyVar)], [TcTyVar], Type)
go Subst
subst Type
ty
      | Just ([Scaled Type]
arg_tys, [TcTyVar]
tvs, [Type]
theta, Type
ty') <- Type -> Maybe ([Scaled Type], [TcTyVar], [Type], Type)
tcDeepSplitSigmaTy_maybe Type
ty
      = do { let arg_tys' :: [Scaled Type]
arg_tys' = HasDebugCallStack => Subst -> [Scaled Type] -> [Scaled Type]
Subst -> [Scaled Type] -> [Scaled Type]
substScaledTys Subst
subst [Scaled Type]
arg_tys
           ; [TcTyVar]
ids1           <- FastString -> [Scaled Type] -> TcRnIf TcGblEnv TcLclEnv [TcTyVar]
forall gbl lcl.
FastString -> [Scaled Type] -> TcRnIf gbl lcl [TcTyVar]
newSysLocalIds (String -> FastString
fsLit String
"dk") [Scaled Type]
arg_tys'
           ; (Subst
subst', [TcTyVar]
tvs1) <- SkolemInfo -> Subst -> [TcTyVar] -> TcM (Subst, [TcTyVar])
tcInstSkolTyVarsX SkolemInfo
skol_info Subst
subst [TcTyVar]
tvs
           ; [TcTyVar]
ev_vars1       <- [Type] -> TcRnIf TcGblEnv TcLclEnv [TcTyVar]
newEvVars (HasDebugCallStack => Subst -> [Type] -> [Type]
Subst -> [Type] -> [Type]
substTheta Subst
subst' [Type]
theta)
           ; (HsWrapper
wrap, [(Name, TcTyVar)]
tvs_prs2, [TcTyVar]
ev_vars2, Type
rho) <- Subst
-> Type -> TcM (HsWrapper, [(Name, TcTyVar)], [TcTyVar], Type)
go Subst
subst' Type
ty'
           ; let tv_prs1 :: [(Name, TcTyVar)]
tv_prs1 = (TcTyVar -> Name) -> [TcTyVar] -> [Name]
forall a b. (a -> b) -> [a] -> [b]
map TcTyVar -> Name
tyVarName [TcTyVar]
tvs [Name] -> [TcTyVar] -> [(Name, TcTyVar)]
forall a b. [a] -> [b] -> [(a, b)]
`zip` [TcTyVar]
tvs1
           ; (HsWrapper, [(Name, TcTyVar)], [TcTyVar], Type)
-> TcM (HsWrapper, [(Name, TcTyVar)], [TcTyVar], Type)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return ( [TcTyVar] -> HsWrapper -> HsWrapper
mkWpEta [TcTyVar]
ids1 ([TcTyVar] -> HsWrapper
mkWpTyLams [TcTyVar]
tvs1
                                    HsWrapper -> HsWrapper -> HsWrapper
<.> [TcTyVar] -> HsWrapper
mkWpEvLams [TcTyVar]
ev_vars1
                                    HsWrapper -> HsWrapper -> HsWrapper
<.> HsWrapper
wrap)
                    , [(Name, TcTyVar)]
tv_prs1  [(Name, TcTyVar)] -> [(Name, TcTyVar)] -> [(Name, TcTyVar)]
forall a. [a] -> [a] -> [a]
++ [(Name, TcTyVar)]
tvs_prs2
                    , [TcTyVar]
ev_vars1 [TcTyVar] -> [TcTyVar] -> [TcTyVar]
forall a. [a] -> [a] -> [a]
++ [TcTyVar]
ev_vars2
                    , [Scaled Type] -> Type -> Type
HasDebugCallStack => [Scaled Type] -> Type -> Type
mkScaledFunTys [Scaled Type]
arg_tys' Type
rho ) }

      | Bool
otherwise
      = (HsWrapper, [(Name, TcTyVar)], [TcTyVar], Type)
-> TcM (HsWrapper, [(Name, TcTyVar)], [TcTyVar], Type)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (HsWrapper
idHsWrapper, [], [], HasDebugCallStack => Subst -> Type -> Type
Subst -> Type -> Type
substTy Subst
subst Type
ty)
        -- substTy is a quick no-op on an empty substitution

deeplyInstantiate :: CtOrigin -> TcType -> TcM (HsWrapper, Type)
deeplyInstantiate :: CtOrigin -> Type -> TcM (HsWrapper, Type)
deeplyInstantiate CtOrigin
orig Type
ty
  = Subst -> Type -> TcM (HsWrapper, Type)
go Subst
init_subst Type
ty
  where
    init_subst :: Subst
init_subst = InScopeSet -> Subst
mkEmptySubst (VarSet -> InScopeSet
mkInScopeSet (Type -> VarSet
tyCoVarsOfType Type
ty))

    go :: Subst -> Type -> TcM (HsWrapper, Type)
go Subst
subst Type
ty
      | Just ([Scaled Type]
arg_tys, [TcTyVar]
tvs, [Type]
theta, Type
rho) <- Type -> Maybe ([Scaled Type], [TcTyVar], [Type], Type)
tcDeepSplitSigmaTy_maybe Type
ty
      = do { (Subst
subst', [TcTyVar]
tvs') <- Subst -> [TcTyVar] -> TcM (Subst, [TcTyVar])
newMetaTyVarsX Subst
subst [TcTyVar]
tvs
           ; let arg_tys' :: [Scaled Type]
arg_tys' = HasDebugCallStack => Subst -> [Scaled Type] -> [Scaled Type]
Subst -> [Scaled Type] -> [Scaled Type]
substScaledTys   Subst
subst' [Scaled Type]
arg_tys
                 theta' :: [Type]
theta'   = HasDebugCallStack => Subst -> [Type] -> [Type]
Subst -> [Type] -> [Type]
substTheta Subst
subst' [Type]
theta
           ; [TcTyVar]
ids1  <- FastString -> [Scaled Type] -> TcRnIf TcGblEnv TcLclEnv [TcTyVar]
forall gbl lcl.
FastString -> [Scaled Type] -> TcRnIf gbl lcl [TcTyVar]
newSysLocalIds (String -> FastString
fsLit String
"di") [Scaled Type]
arg_tys'
           ; HsWrapper
wrap1 <- CtOrigin -> [Type] -> [Type] -> TcM HsWrapper
instCall CtOrigin
orig ([TcTyVar] -> [Type]
mkTyVarTys [TcTyVar]
tvs') [Type]
theta'
           ; (HsWrapper
wrap2, Type
rho2) <- Subst -> Type -> TcM (HsWrapper, Type)
go Subst
subst' Type
rho
           ; (HsWrapper, Type) -> TcM (HsWrapper, Type)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return ([TcTyVar] -> HsWrapper -> HsWrapper
mkWpEta [TcTyVar]
ids1 (HsWrapper
wrap2 HsWrapper -> HsWrapper -> HsWrapper
<.> HsWrapper
wrap1),
                     [Scaled Type] -> Type -> Type
HasDebugCallStack => [Scaled Type] -> Type -> Type
mkScaledFunTys [Scaled Type]
arg_tys' Type
rho2) }

      | Bool
otherwise
      = do { let ty' :: Type
ty' = HasDebugCallStack => Subst -> Type -> Type
Subst -> Type -> Type
substTy Subst
subst Type
ty
           ; (HsWrapper, Type) -> TcM (HsWrapper, Type)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (HsWrapper
idHsWrapper, Type
ty') }

tcDeepSplitSigmaTy_maybe
  :: TcSigmaType -> Maybe ([Scaled TcType], [TyVar], ThetaType, TcSigmaType)
-- Looks for a *non-trivial* quantified type, under zero or more function arrows
-- By "non-trivial" we mean either tyvars or constraints are non-empty

tcDeepSplitSigmaTy_maybe :: Type -> Maybe ([Scaled Type], [TcTyVar], [Type], Type)
tcDeepSplitSigmaTy_maybe Type
ty
  | Just (Scaled Type
arg_ty, Type
res_ty)           <- Type -> Maybe (Scaled Type, Type)
tcSplitFunTy_maybe Type
ty
  , Just ([Scaled Type]
arg_tys, [TcTyVar]
tvs, [Type]
theta, Type
rho) <- Type -> Maybe ([Scaled Type], [TcTyVar], [Type], Type)
tcDeepSplitSigmaTy_maybe Type
res_ty
  = ([Scaled Type], [TcTyVar], [Type], Type)
-> Maybe ([Scaled Type], [TcTyVar], [Type], Type)
forall a. a -> Maybe a
Just (Scaled Type
arg_tyScaled Type -> [Scaled Type] -> [Scaled Type]
forall a. a -> [a] -> [a]
:[Scaled Type]
arg_tys, [TcTyVar]
tvs, [Type]
theta, Type
rho)

  | ([TcTyVar]
tvs, [Type]
theta, Type
rho) <- Type -> ([TcTyVar], [Type], Type)
tcSplitSigmaTy Type
ty
  , Bool -> Bool
not ([TcTyVar] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [TcTyVar]
tvs Bool -> Bool -> Bool
&& [Type] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Type]
theta)
  = ([Scaled Type], [TcTyVar], [Type], Type)
-> Maybe ([Scaled Type], [TcTyVar], [Type], Type)
forall a. a -> Maybe a
Just ([], [TcTyVar]
tvs, [Type]
theta, Type
rho)

  | Bool
otherwise = Maybe ([Scaled Type], [TcTyVar], [Type], Type)
forall a. Maybe a
Nothing


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

{- Note [Skolemisation]
~~~~~~~~~~~~~~~~~~~~~~~
tcTopSkolemise 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 tcTopSkolemise (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 handles deep subumption, wheres tcTopSkolemise never looks under
  function arrows.

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

tcTopSkolemise, 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 tcTopSkolemise

tcSkolemiseScoped :: forall result.
UserTypeCtxt
-> Type -> (Type -> TcM result) -> TcM (HsWrapper, result)
tcSkolemiseScoped UserTypeCtxt
ctxt Type
expected_ty Type -> TcM result
thing_inside
  = do { Bool
deep_subsumption <- Extension -> TcRnIf TcGblEnv TcLclEnv Bool
forall gbl lcl. Extension -> TcRnIf gbl lcl Bool
xoptM Extension
LangExt.DeepSubsumption
       ; let skolemise :: SkolemInfo
-> Type -> TcM (HsWrapper, [(Name, TcTyVar)], [TcTyVar], Type)
skolemise | Bool
deep_subsumption = SkolemInfo
-> Type -> TcM (HsWrapper, [(Name, TcTyVar)], [TcTyVar], Type)
deeplySkolemise
                       | Bool
otherwise        = SkolemInfo
-> Type -> TcM (HsWrapper, [(Name, TcTyVar)], [TcTyVar], Type)
topSkolemise
       ; -- rec {..}: see Note [Keeping SkolemInfo inside a SkolemTv]
         --           in GHC.Tc.Utils.TcType
         rec { (HsWrapper
wrap, [(Name, TcTyVar)]
tv_prs, [TcTyVar]
given, Type
rho_ty) <- SkolemInfo
-> Type -> TcM (HsWrapper, [(Name, TcTyVar)], [TcTyVar], Type)
skolemise SkolemInfo
skol_info Type
expected_ty
             ; SkolemInfo
skol_info <- SkolemInfoAnon -> IOEnv (Env TcGblEnv TcLclEnv) SkolemInfo
forall (m :: * -> *). MonadIO m => SkolemInfoAnon -> m SkolemInfo
mkSkolemInfo (UserTypeCtxt -> Type -> [(Name, TcTyVar)] -> SkolemInfoAnon
SigSkol UserTypeCtxt
ctxt Type
expected_ty [(Name, TcTyVar)]
tv_prs) }

       ; let skol_tvs :: [TcTyVar]
skol_tvs = ((Name, TcTyVar) -> TcTyVar) -> [(Name, TcTyVar)] -> [TcTyVar]
forall a b. (a -> b) -> [a] -> [b]
map (Name, TcTyVar) -> TcTyVar
forall a b. (a, b) -> b
snd [(Name, TcTyVar)]
tv_prs
       ; (TcEvBinds
ev_binds, result
res)
             <- SkolemInfoAnon
-> [TcTyVar] -> [TcTyVar] -> TcM result -> TcM (TcEvBinds, result)
forall result.
SkolemInfoAnon
-> [TcTyVar] -> [TcTyVar] -> TcM result -> TcM (TcEvBinds, result)
checkConstraints (SkolemInfo -> SkolemInfoAnon
getSkolemInfo SkolemInfo
skol_info) [TcTyVar]
skol_tvs [TcTyVar]
given (TcM result -> TcM (TcEvBinds, result))
-> TcM result -> TcM (TcEvBinds, result)
forall a b. (a -> b) -> a -> b
$
                [(Name, TcTyVar)] -> TcM result -> TcM result
forall r. [(Name, TcTyVar)] -> TcM r -> TcM r
tcExtendNameTyVarEnv [(Name, TcTyVar)]
tv_prs               (TcM result -> TcM result) -> TcM result -> TcM result
forall a b. (a -> b) -> a -> b
$
                Type -> TcM result
thing_inside Type
rho_ty

       ; (HsWrapper, result) -> TcM (HsWrapper, result)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (HsWrapper
wrap HsWrapper -> HsWrapper -> HsWrapper
<.> TcEvBinds -> HsWrapper
mkWpLet TcEvBinds
ev_binds, result
res) }

tcTopSkolemise :: forall result.
UserTypeCtxt
-> Type -> (Type -> TcM result) -> TcM (HsWrapper, result)
tcTopSkolemise UserTypeCtxt
ctxt Type
expected_ty Type -> TcM result
thing_inside
  | Type -> Bool
isRhoTy Type
expected_ty  -- Short cut for common case
  = do { result
res <- Type -> TcM result
thing_inside Type
expected_ty
       ; (HsWrapper, result) -> TcM (HsWrapper, result)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (HsWrapper
idHsWrapper, result
res) }
  | Bool
otherwise
  = do { -- rec {..}: see Note [Keeping SkolemInfo inside a SkolemTv]
         --           in GHC.Tc.Utils.TcType
         rec { (HsWrapper
wrap, [(Name, TcTyVar)]
tv_prs, [TcTyVar]
given, Type
rho_ty) <- SkolemInfo
-> Type -> TcM (HsWrapper, [(Name, TcTyVar)], [TcTyVar], Type)
topSkolemise SkolemInfo
skol_info Type
expected_ty
             ; SkolemInfo
skol_info <- SkolemInfoAnon -> IOEnv (Env TcGblEnv TcLclEnv) SkolemInfo
forall (m :: * -> *). MonadIO m => SkolemInfoAnon -> m SkolemInfo
mkSkolemInfo (UserTypeCtxt -> Type -> [(Name, TcTyVar)] -> SkolemInfoAnon
SigSkol UserTypeCtxt
ctxt Type
expected_ty [(Name, TcTyVar)]
tv_prs) }

       ; let skol_tvs :: [TcTyVar]
skol_tvs = ((Name, TcTyVar) -> TcTyVar) -> [(Name, TcTyVar)] -> [TcTyVar]
forall a b. (a -> b) -> [a] -> [b]
map (Name, TcTyVar) -> TcTyVar
forall a b. (a, b) -> b
snd [(Name, TcTyVar)]
tv_prs
       ; (TcEvBinds
ev_binds, result
result)
             <- SkolemInfoAnon
-> [TcTyVar] -> [TcTyVar] -> TcM result -> TcM (TcEvBinds, result)
forall result.
SkolemInfoAnon
-> [TcTyVar] -> [TcTyVar] -> TcM result -> TcM (TcEvBinds, result)
checkConstraints (SkolemInfo -> SkolemInfoAnon
getSkolemInfo SkolemInfo
skol_info) [TcTyVar]
skol_tvs [TcTyVar]
given (TcM result -> TcM (TcEvBinds, result))
-> TcM result -> TcM (TcEvBinds, result)
forall a b. (a -> b) -> a -> b
$
                Type -> TcM result
thing_inside Type
rho_ty

       ; (HsWrapper, result) -> TcM (HsWrapper, result)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
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 'tcTopSkolemise' that takes an ExpType
tcSkolemiseExpType :: UserTypeCtxt -> ExpSigmaType
                   -> (ExpRhoType -> TcM result)
                   -> TcM (HsWrapper, result)
tcSkolemiseExpType :: forall result.
UserTypeCtxt
-> ExpRhoType
-> (ExpRhoType -> TcM result)
-> TcM (HsWrapper, result)
tcSkolemiseExpType UserTypeCtxt
_ et :: ExpRhoType
et@(Infer {}) ExpRhoType -> TcM result
thing_inside
  = (HsWrapper
idHsWrapper, ) (result -> (HsWrapper, result))
-> TcM result -> IOEnv (Env TcGblEnv TcLclEnv) (HsWrapper, result)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ExpRhoType -> TcM result
thing_inside ExpRhoType
et
tcSkolemiseExpType UserTypeCtxt
ctxt (Check Type
ty) ExpRhoType -> TcM result
thing_inside
  = do { Bool
deep_subsumption <- Extension -> TcRnIf TcGblEnv TcLclEnv Bool
forall gbl lcl. Extension -> TcRnIf gbl lcl Bool
xoptM Extension
LangExt.DeepSubsumption
       ; let skolemise :: UserTypeCtxt
-> Type
-> (Type -> TcM result)
-> IOEnv (Env TcGblEnv TcLclEnv) (HsWrapper, result)
skolemise | Bool
deep_subsumption = UserTypeCtxt
-> Type
-> (Type -> TcM result)
-> IOEnv (Env TcGblEnv TcLclEnv) (HsWrapper, result)
forall result.
UserTypeCtxt
-> Type -> (Type -> TcM result) -> TcM (HsWrapper, result)
tcDeeplySkolemise
                       | Bool
otherwise        = UserTypeCtxt
-> Type
-> (Type -> TcM result)
-> IOEnv (Env TcGblEnv TcLclEnv) (HsWrapper, result)
forall result.
UserTypeCtxt
-> Type -> (Type -> TcM result) -> TcM (HsWrapper, result)
tcTopSkolemise
       ; UserTypeCtxt
-> Type
-> (Type -> TcM result)
-> IOEnv (Env TcGblEnv TcLclEnv) (HsWrapper, result)
skolemise UserTypeCtxt
ctxt Type
ty ((Type -> TcM result)
 -> IOEnv (Env TcGblEnv TcLclEnv) (HsWrapper, result))
-> (Type -> TcM result)
-> IOEnv (Env TcGblEnv TcLclEnv) (HsWrapper, result)
forall a b. (a -> b) -> a -> b
$ \Type
rho_ty ->
         ExpRhoType -> TcM result
thing_inside (Type -> ExpRhoType
mkCheckExpType Type
rho_ty) }

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

checkConstraints :: forall result.
SkolemInfoAnon
-> [TcTyVar] -> [TcTyVar] -> TcM result -> TcM (TcEvBinds, result)
checkConstraints SkolemInfoAnon
skol_info [TcTyVar]
skol_tvs [TcTyVar]
given TcM result
thing_inside
  = do { Bool
implication_needed <- SkolemInfoAnon
-> [TcTyVar] -> [TcTyVar] -> TcRnIf TcGblEnv TcLclEnv Bool
implicationNeeded SkolemInfoAnon
skol_info [TcTyVar]
skol_tvs [TcTyVar]
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
-> SkolemInfoAnon
-> [TcTyVar]
-> [TcTyVar]
-> WantedConstraints
-> TcM (Bag Implication, TcEvBinds)
buildImplicationFor TcLevel
tclvl SkolemInfoAnon
skol_info [TcTyVar]
skol_tvs [TcTyVar]
given WantedConstraints
wanted
                 ; String -> SDoc -> TcM ()
traceTc String
"checkConstraints" (TcLevel -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcLevel
tclvl SDoc -> SDoc -> SDoc
forall doc. IsDoc doc => doc -> doc -> doc
$$ [TcTyVar] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [TcTyVar]
skol_tvs)
                 ; Bag Implication -> TcM ()
emitImplications Bag Implication
implics
                 ; (TcEvBinds, result) -> TcM (TcEvBinds, result)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
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 tcTopSkolemise and hence checkConstraints.
              -- So this fast path is well-exercised
              do { result
res <- TcM result
thing_inside
                 ; (TcEvBinds, result) -> TcM (TcEvBinds, result)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (TcEvBinds
emptyTcEvBinds, result
res) } }

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

checkTvConstraints :: forall result. SkolemInfo -> [TcTyVar] -> TcM result -> TcM result
checkTvConstraints SkolemInfo
skol_info [TcTyVar]
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 -> [TcTyVar] -> TcLevel -> WantedConstraints -> TcM ()
emitResidualTvConstraint SkolemInfo
skol_info [TcTyVar]
skol_tvs TcLevel
tclvl WantedConstraints
wanted
       ; result -> TcM result
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return result
result }

emitResidualTvConstraint :: SkolemInfo -> [TcTyVar]
                         -> TcLevel -> WantedConstraints -> TcM ()
emitResidualTvConstraint :: SkolemInfo -> [TcTyVar] -> TcLevel -> WantedConstraints -> TcM ()
emitResidualTvConstraint SkolemInfo
skol_info [TcTyVar]
skol_tvs TcLevel
tclvl WantedConstraints
wanted
  | Bool -> Bool
not (WantedConstraints -> Bool
isEmptyWC WantedConstraints
wanted) Bool -> Bool -> Bool
||
    SkolemInfoAnon -> Bool
checkTelescopeSkol SkolemInfoAnon
skol_info_anon
  = -- 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 <- SkolemInfoAnon
-> [TcTyVar] -> TcLevel -> WantedConstraints -> TcM Implication
buildTvImplication SkolemInfoAnon
skol_info_anon [TcTyVar]
skol_tvs TcLevel
tclvl WantedConstraints
wanted
       ; Implication -> TcM ()
emitImplication Implication
implic }

  | Bool
otherwise  -- Empty 'wanted', emit nothing
  = () -> TcM ()
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return ()
  where
     skol_info_anon :: SkolemInfoAnon
skol_info_anon = SkolemInfo -> SkolemInfoAnon
getSkolemInfo SkolemInfo
skol_info

buildTvImplication :: SkolemInfoAnon -> [TcTyVar]
                   -> TcLevel -> WantedConstraints -> TcM Implication
buildTvImplication :: SkolemInfoAnon
-> [TcTyVar] -> TcLevel -> WantedConstraints -> TcM Implication
buildTvImplication SkolemInfoAnon
skol_info [TcTyVar]
skol_tvs TcLevel
tclvl WantedConstraints
wanted
  = Bool -> SDoc -> TcM Implication -> TcM Implication
forall a. HasCallStack => Bool -> SDoc -> a -> a
assertPpr ((TcTyVar -> Bool) -> [TcTyVar] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all (TcTyVar -> Bool
isSkolemTyVar (TcTyVar -> Bool) -> (TcTyVar -> Bool) -> TcTyVar -> Bool
forall (f :: * -> *). Applicative f => f Bool -> f Bool -> f Bool
<||> TcTyVar -> Bool
isTyVarTyVar) [TcTyVar]
skol_tvs) ([TcTyVar] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [TcTyVar]
skol_tvs) (TcM Implication -> TcM Implication)
-> TcM Implication -> TcM Implication
forall a b. (a -> b) -> a -> b
$
    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

       ; let implic' :: Implication
implic' = Implication
implic { ic_tclvl     = tclvl
                              , ic_skols     = skol_tvs
                              , ic_given_eqs = NoGivenEqs
                              , ic_wanted    = wanted
                              , ic_binds     = ev_binds
                              , ic_info      = skol_info }

       ; Implication -> TcM ()
forall (m :: * -> *).
(HasCallStack, Applicative m) =>
Implication -> m ()
checkImplicationInvariants Implication
implic'
       ; Implication -> TcM Implication
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return Implication
implic' }

implicationNeeded :: SkolemInfoAnon -> [TcTyVar] -> [EvVar] -> TcM Bool
-- See Note [When to build an implication]
implicationNeeded :: SkolemInfoAnon
-> [TcTyVar] -> [TcTyVar] -> TcRnIf TcGblEnv TcLclEnv Bool
implicationNeeded SkolemInfoAnon
skol_info [TcTyVar]
skol_tvs [TcTyVar]
given
  | [TcTyVar] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [TcTyVar]
skol_tvs
  , [TcTyVar] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [TcTyVar]
given
  , Bool -> Bool
not (SkolemInfoAnon -> Bool
alwaysBuildImplication SkolemInfoAnon
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 -> TcRnIf TcGblEnv TcLclEnv Bool
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
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 -> TcRnIf TcGblEnv TcLclEnv Bool
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
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 -> TcRnIf TcGblEnv TcLclEnv Bool
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
True   -- Definitely need an implication

alwaysBuildImplication :: SkolemInfoAnon -> Bool
-- See Note [When to build an implication]
alwaysBuildImplication :: SkolemInfoAnon -> Bool
alwaysBuildImplication SkolemInfoAnon
_ = 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 -> SkolemInfoAnon -> [TcTyVar]
                   -> [EvVar] -> WantedConstraints
                   -> TcM (Bag Implication, TcEvBinds)
buildImplicationFor :: TcLevel
-> SkolemInfoAnon
-> [TcTyVar]
-> [TcTyVar]
-> WantedConstraints
-> TcM (Bag Implication, TcEvBinds)
buildImplicationFor TcLevel
tclvl SkolemInfoAnon
skol_info [TcTyVar]
skol_tvs [TcTyVar]
given WantedConstraints
wanted
  | WantedConstraints -> Bool
isEmptyWC WantedConstraints
wanted Bool -> Bool -> Bool
&& [TcTyVar] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [TcTyVar]
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 a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Bag Implication
forall a. Bag a
emptyBag, TcEvBinds
emptyTcEvBinds)

  | Bool
otherwise
  = Bool
-> SDoc
-> TcM (Bag Implication, TcEvBinds)
-> TcM (Bag Implication, TcEvBinds)
forall a. HasCallStack => Bool -> SDoc -> a -> a
assertPpr ((TcTyVar -> Bool) -> [TcTyVar] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all (TcTyVar -> Bool
isSkolemTyVar (TcTyVar -> Bool) -> (TcTyVar -> Bool) -> TcTyVar -> Bool
forall (f :: * -> *). Applicative f => f Bool -> f Bool -> f Bool
<||> TcTyVar -> Bool
isTyVarTyVar) [TcTyVar]
skol_tvs) ([TcTyVar] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [TcTyVar]
skol_tvs) (TcM (Bag Implication, TcEvBinds)
 -> TcM (Bag Implication, TcEvBinds))
-> TcM (Bag Implication, TcEvBinds)
-> TcM (Bag Implication, TcEvBinds)
forall a b. (a -> b) -> a -> b
$
      -- 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  = tclvl
                              , ic_skols  = skol_tvs
                              , ic_given  = given
                              , ic_wanted = wanted
                              , ic_binds  = ev_binds_var
                              , ic_info   = skol_info }
       ; Implication -> TcM ()
forall (m :: * -> *).
(HasCallStack, Applicative m) =>
Implication -> m ()
checkImplicationInvariants Implication
implic'

       ; (Bag Implication, TcEvBinds) -> TcM (Bag Implication, TcEvBinds)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
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 [W] 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 TypedThing  -- ^ If present, the thing that has type ty1
          -> TcTauType -> TcTauType    -- ty1 (actual), ty2 (expected)
          -> TcM TcCoercionN           -- :: ty1 ~# ty2
-- Actual and expected types
-- Returns a coercion : ty1 ~ ty2
unifyType :: Maybe TypedThing -> Type -> Type -> TcM Coercion
unifyType Maybe TypedThing
thing Type
ty1 Type
ty2
  = TypeOrKind -> CtOrigin -> Type -> Type -> TcM Coercion
unifyTypeAndEmit TypeOrKind
TypeLevel CtOrigin
origin Type
ty1 Type
ty2
  where
    origin :: CtOrigin
origin = TypeEqOrigin { uo_actual :: Type
uo_actual   = Type
ty1
                          , uo_expected :: Type
uo_expected = Type
ty2
                          , uo_thing :: Maybe TypedThing
uo_thing    = Maybe TypedThing
thing
                          , uo_visible :: Bool
uo_visible  = Bool
True }

unifyInvisibleType :: TcTauType -> TcTauType    -- ty1 (actual), ty2 (expected)
                   -> TcM TcCoercionN           -- :: ty1 ~# ty2
-- Actual and expected types
-- Returns a coercion : ty1 ~ ty2
unifyInvisibleType :: Type -> Type -> TcM Coercion
unifyInvisibleType Type
ty1 Type
ty2
  = TypeOrKind -> CtOrigin -> Type -> Type -> TcM Coercion
unifyTypeAndEmit TypeOrKind
TypeLevel CtOrigin
origin Type
ty1 Type
ty2
  where
    origin :: CtOrigin
origin = TypeEqOrigin { uo_actual :: Type
uo_actual   = Type
ty1
                          , uo_expected :: Type
uo_expected = Type
ty2
                          , uo_thing :: Maybe TypedThing
uo_thing    = Maybe TypedThing
forall a. Maybe a
Nothing
                          , uo_visible :: Bool
uo_visible  = Bool
False }  -- This is the "invisible" bit

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


unifyKind :: Maybe TypedThing -> TcKind -> TcKind -> TcM CoercionN
unifyKind :: Maybe TypedThing -> Type -> Type -> TcM Coercion
unifyKind Maybe TypedThing
mb_thing Type
ty1 Type
ty2
  = TypeOrKind -> CtOrigin -> Type -> Type -> TcM Coercion
unifyTypeAndEmit TypeOrKind
KindLevel CtOrigin
origin Type
ty1 Type
ty2
  where
    origin :: CtOrigin
origin = TypeEqOrigin { uo_actual :: Type
uo_actual   = Type
ty1
                          , uo_expected :: Type
uo_expected = Type
ty2
                          , uo_thing :: Maybe TypedThing
uo_thing    = Maybe TypedThing
mb_thing
                          , uo_visible :: Bool
uo_visible  = Bool
True }

unifyTypeAndEmit :: TypeOrKind -> CtOrigin -> TcType -> TcType -> TcM CoercionN
-- Make a ref-cell, unify, emit the collected constraints
unifyTypeAndEmit :: TypeOrKind -> CtOrigin -> Type -> Type -> TcM Coercion
unifyTypeAndEmit TypeOrKind
t_or_k CtOrigin
orig Type
ty1 Type
ty2
  = do { TcRef (Bag Ct)
ref <- Bag Ct -> IOEnv (Env TcGblEnv TcLclEnv) (TcRef (Bag Ct))
forall (m :: * -> *) a. MonadIO m => a -> m (TcRef a)
newTcRef Bag Ct
forall a. Bag a
emptyBag
       ; CtLoc
loc <- CtOrigin -> Maybe TypeOrKind -> TcM CtLoc
getCtLocM CtOrigin
orig (TypeOrKind -> Maybe TypeOrKind
forall a. a -> Maybe a
Just TypeOrKind
t_or_k)
       ; let env :: UnifyEnv
env = UE { u_loc :: CtLoc
u_loc = CtLoc
loc, u_role :: Role
u_role = Role
Nominal
                      , u_rewriters :: RewriterSet
u_rewriters = RewriterSet
emptyRewriterSet  -- ToDo: check this
                      , u_defer :: TcRef (Bag Ct)
u_defer = TcRef (Bag Ct)
ref, u_unified :: Maybe (TcRef [TcTyVar])
u_unified = Maybe (TcRef [TcTyVar])
forall a. Maybe a
Nothing }

       -- The hard work happens here
       ; Coercion
co <- UnifyEnv -> Type -> Type -> TcM Coercion
uType UnifyEnv
env Type
ty1 Type
ty2

       ; Bag Ct
cts <- TcRef (Bag Ct) -> IOEnv (Env TcGblEnv TcLclEnv) (Bag Ct)
forall (m :: * -> *) a. MonadIO m => TcRef a -> m a
readTcRef TcRef (Bag Ct)
ref
       ; Bool -> TcM () -> TcM ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (Bag Ct -> Bool
forall a. Bag a -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null Bag Ct
cts) (Bag Ct -> TcM ()
emitSimples Bag Ct
cts)
       ; Coercion -> TcM Coercion
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return Coercion
co }

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

Note [The eager unifier]
~~~~~~~~~~~~~~~~~~~~~~~~
The eager unifier, `uType`, is called by

  * The constraint generator (e.g. in GHC.Tc.Gen.Expr),
    via the wrappers `unifyType`, `unifyKind` etc

  * The constraint solver (e.g. in GHC.Tc.Solver.Equality),
    via `GHC.Tc.Solver.Monad.wrapUnifierTcS`.

`uType` runs in the TcM monad, but it carries a UnifyEnv that tells it
what to do when unifying a variable or deferring a constraint. Specifically,
  * it collects deferred constraints in `u_defer`, and
  * it records which unification variables it has unified in `u_unified`
Then it is up to the wrappers (one for the constraint generator, one for
the constraint solver) to deal with these collected sets.

Although `uType` runs in the TcM monad for convenience, really it could
operate just with the ability to
  * write to the accumulators of deferred constraints
    and unification variables in UnifyEnv.
  * read and update existing unification variables
  * zonk types befire unifying (`zonkTcType` in `uUnfilledVar`, and
    `zonkTyCoVarKind` in `uUnfilledVar1`
  * create fresh coercion holes (`newCoercionHole`)
  * emit tracing info for debugging
  * look at the ambient TcLevel: `getTcLevel`
A job for the future.
-}

data UnifyEnv
  = UE { UnifyEnv -> Role
u_role      :: Role
       , UnifyEnv -> CtLoc
u_loc       :: CtLoc
       , UnifyEnv -> RewriterSet
u_rewriters :: RewriterSet

         -- Deferred constraints
       , UnifyEnv -> TcRef (Bag Ct)
u_defer     :: TcRef (Bag Ct)

         -- Which variables are unified;
         -- if Nothing, we don't care
       , UnifyEnv -> Maybe (TcRef [TcTyVar])
u_unified :: Maybe (TcRef [TcTyVar])
    }

setUEnvRole :: UnifyEnv -> Role -> UnifyEnv
setUEnvRole :: UnifyEnv -> Role -> UnifyEnv
setUEnvRole UnifyEnv
uenv Role
role = UnifyEnv
uenv { u_role = role }

updUEnvLoc :: UnifyEnv -> (CtLoc -> CtLoc) -> UnifyEnv
updUEnvLoc :: UnifyEnv -> (CtLoc -> CtLoc) -> UnifyEnv
updUEnvLoc uenv :: UnifyEnv
uenv@(UE { u_loc :: UnifyEnv -> CtLoc
u_loc = CtLoc
loc }) CtLoc -> CtLoc
upd = UnifyEnv
uenv { u_loc = upd loc }

mkKindEnv :: UnifyEnv -> TcType -> TcType -> UnifyEnv
-- Modify the UnifyEnv to be right for unifing
-- the kinds of these two types
mkKindEnv :: UnifyEnv -> Type -> Type -> UnifyEnv
mkKindEnv env :: UnifyEnv
env@(UE { u_loc :: UnifyEnv -> CtLoc
u_loc = CtLoc
ctloc }) Type
ty1 Type
ty2
  = UnifyEnv
env { u_role = Nominal, u_loc = mkKindEqLoc ty1 ty2 ctloc }

uType, uType_defer
  :: UnifyEnv
  -> 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 :: UnifyEnv -> Type -> Type -> TcM Coercion
uType_defer (UE { u_loc :: UnifyEnv -> CtLoc
u_loc = CtLoc
loc, u_defer :: UnifyEnv -> TcRef (Bag Ct)
u_defer = TcRef (Bag Ct)
ref
                , u_role :: UnifyEnv -> Role
u_role = Role
role, u_rewriters :: UnifyEnv -> RewriterSet
u_rewriters = RewriterSet
rewriters })
            Type
ty1 Type
ty2  -- ty1 is "actual", ty2 is "expected"
  = do { let pred_ty :: Type
pred_ty = Role -> Type -> Type -> Type
mkPrimEqPredRole Role
role Type
ty1 Type
ty2
       ; CoercionHole
hole <- CtLoc -> Type -> TcM CoercionHole
newCoercionHole CtLoc
loc Type
pred_ty
       ; let ct :: Ct
ct = CtEvidence -> Ct
mkNonCanonical (CtEvidence -> Ct) -> CtEvidence -> Ct
forall a b. (a -> b) -> a -> b
$
                  CtWanted { ctev_pred :: Type
ctev_pred      = Type
pred_ty
                           , ctev_dest :: TcEvDest
ctev_dest      = CoercionHole -> TcEvDest
HoleDest CoercionHole
hole
                           , ctev_loc :: CtLoc
ctev_loc       = CtLoc
loc
                           , ctev_rewriters :: RewriterSet
ctev_rewriters = RewriterSet
rewriters }
             co :: Coercion
co = CoercionHole -> Coercion
HoleCo CoercionHole
hole
       ; TcRef (Bag Ct) -> (Bag Ct -> Bag Ct) -> TcM ()
forall (m :: * -> *) a. MonadIO m => TcRef a -> (a -> a) -> m ()
updTcRef TcRef (Bag Ct)
ref (Bag Ct -> Ct -> Bag Ct
forall a. Bag a -> a -> Bag a
`snocBag` Ct
ct)
         -- snocBag: see Note [Work-list ordering] in GHC.Tc.Solver.Equality

       -- Error trace only
       -- NB. do *not* call mkErrInfo unless tracing is on,
       --     because it is hugely expensive (#5631)
       ; DumpFlag -> TcM () -> TcM ()
forall gbl lcl. DumpFlag -> TcRnIf gbl lcl () -> TcRnIf gbl lcl ()
whenDOptM DumpFlag
Opt_D_dump_tc_trace (TcM () -> TcM ()) -> TcM () -> TcM ()
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 -> TcM ()
traceTc String
"utype_defer" ([SDoc] -> SDoc
forall doc. IsDoc doc => [doc] -> doc
vcat [ Role -> SDoc
forall a. Outputable a => a -> SDoc
ppr Role
role
                                          , Type -> SDoc
debugPprType Type
ty1
                                          , Type -> SDoc
debugPprType Type
ty2
                                          , SDoc
doc])
            ; String -> SDoc -> TcM ()
traceTc String
"utype_defer2" (Coercion -> SDoc
forall a. Outputable a => a -> SDoc
ppr Coercion
co) }

       ; Coercion -> TcM Coercion
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return Coercion
co }


--------------
uType :: UnifyEnv -> Type -> Type -> TcM Coercion
uType env :: UnifyEnv
env@(UE { u_role :: UnifyEnv -> Role
u_role = Role
role }) Type
orig_ty1 Type
orig_ty2
  | Role
Phantom <- Role
role
  = do { Coercion
kind_co <- UnifyEnv -> Type -> Type -> TcM Coercion
uType (UnifyEnv -> Type -> Type -> UnifyEnv
mkKindEnv UnifyEnv
env Type
orig_ty1 Type
orig_ty2)
                          (HasDebugCallStack => Type -> Type
Type -> Type
typeKind Type
orig_ty1) (HasDebugCallStack => Type -> Type
Type -> Type
typeKind Type
orig_ty2)
       ; Coercion -> TcM Coercion
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Coercion -> Type -> Type -> Coercion
mkPhantomCo Coercion
kind_co Type
orig_ty1 Type
orig_ty2) }

  | Bool
otherwise
  = do { TcLevel
tclvl <- TcM TcLevel
getTcLevel
       ; String -> SDoc -> TcM ()
traceTc String
"u_tys" (SDoc -> TcM ()) -> SDoc -> TcM ()
forall a b. (a -> b) -> a -> b
$ [SDoc] -> SDoc
forall doc. IsDoc doc => [doc] -> doc
vcat
              [ String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"tclvl" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> TcLevel -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcLevel
tclvl
              , [SDoc] -> SDoc
forall doc. IsLine doc => [doc] -> doc
sep [ Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
orig_ty1, String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"~" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<> Role -> SDoc
forall a. Outputable a => a -> SDoc
ppr Role
role, Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
orig_ty2] ]
       ; Coercion
co <- Type -> Type -> TcM Coercion
go Type
orig_ty1 Type
orig_ty2
       ; if Coercion -> Bool
isReflCo Coercion
co
            then String -> SDoc -> TcM ()
traceTc String
"u_tys yields no coercion" SDoc
forall doc. IsOutput doc => doc
Outputable.empty
            else String -> SDoc -> TcM ()
traceTc String
"u_tys yields coercion:" (Coercion -> SDoc
forall a. Outputable a => a -> SDoc
ppr Coercion
co)
       ; Coercion -> TcM Coercion
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return Coercion
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 :: Type -> Type -> TcM Coercion
go (CastTy Type
t1 Coercion
co1) Type
t2
      = do { Coercion
co_tys <- UnifyEnv -> Type -> Type -> TcM Coercion
uType UnifyEnv
env Type
t1 Type
t2
           ; Coercion -> TcM Coercion
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Role -> Type -> Coercion -> Coercion -> Coercion
mkCoherenceLeftCo Role
role Type
t1 Coercion
co1 Coercion
co_tys) }

    go Type
t1 (CastTy Type
t2 Coercion
co2)
      = do { Coercion
co_tys <- UnifyEnv -> Type -> Type -> TcM Coercion
uType UnifyEnv
env Type
t1 Type
t2
           ; Coercion -> TcM Coercion
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Role -> Type -> Coercion -> Coercion -> Coercion
mkCoherenceRightCo Role
role Type
t2 Coercion
co2 Coercion
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 TcTyVar
tv1) Type
ty2
      = do { Maybe Type
lookup_res <- TcTyVar -> IOEnv (Env TcGblEnv TcLclEnv) (Maybe Type)
isFilledMetaTyVar_maybe TcTyVar
tv1
           ; case Maybe Type
lookup_res of
               Just Type
ty1 -> do { String -> SDoc -> TcM ()
traceTc String
"found filled tyvar" (TcTyVar -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcTyVar
tv1 SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> String -> SDoc
forall doc. IsLine doc => String -> doc
text String
":->" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
ty1)
                              ; UnifyEnv -> Type -> Type -> TcM Coercion
uType UnifyEnv
env Type
ty1 Type
orig_ty2 }
               Maybe Type
Nothing -> UnifyEnv -> SwapFlag -> TcTyVar -> Type -> TcM Coercion
uUnfilledVar UnifyEnv
env SwapFlag
NotSwapped TcTyVar
tv1 Type
ty2 }

    go Type
ty1 (TyVarTy TcTyVar
tv2)
      = do { Maybe Type
lookup_res <- TcTyVar -> IOEnv (Env TcGblEnv TcLclEnv) (Maybe Type)
isFilledMetaTyVar_maybe TcTyVar
tv2
           ; case Maybe Type
lookup_res of
               Just Type
ty2 -> do { String -> SDoc -> TcM ()
traceTc String
"found filled tyvar" (TcTyVar -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcTyVar
tv2 SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> String -> SDoc
forall doc. IsLine doc => String -> doc
text String
":->" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
ty2)
                              ; UnifyEnv -> Type -> Type -> TcM Coercion
uType UnifyEnv
env Type
orig_ty1 Type
ty2 }
               Maybe Type
Nothing -> UnifyEnv -> SwapFlag -> TcTyVar -> Type -> TcM Coercion
uUnfilledVar UnifyEnv
env SwapFlag
IsSwapped TcTyVar
tv2 Type
ty1 }

      -- See Note [Expanding synonyms during unification]
    go ty1 :: Type
ty1@(TyConApp TyCon
tc1 []) (TyConApp TyCon
tc2 [])
      | TyCon
tc1 TyCon -> TyCon -> Bool
forall a. Eq a => a -> a -> Bool
== TyCon
tc2
      = Coercion -> TcM Coercion
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Coercion -> TcM Coercion) -> Coercion -> TcM Coercion
forall a b. (a -> b) -> a -> b
$ Role -> Type -> Coercion
mkReflCo Role
role Type
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 Type
ty1 Type
ty2
      | Just Type
ty1' <- Type -> Maybe Type
coreView Type
ty1 = Type -> Type -> TcM Coercion
go Type
ty1' Type
ty2
      | Just Type
ty2' <- Type -> Maybe Type
coreView Type
ty2 = Type -> Type -> TcM Coercion
go Type
ty1  Type
ty2'

    -- Functions (t1 -> t2) just check the two parts
    go (FunTy { ft_af :: Type -> FunTyFlag
ft_af = FunTyFlag
af1, ft_mult :: Type -> Type
ft_mult = Type
w1, ft_arg :: Type -> Type
ft_arg = Type
arg1, ft_res :: Type -> Type
ft_res = Type
res1 })
       (FunTy { ft_af :: Type -> FunTyFlag
ft_af = FunTyFlag
af2, ft_mult :: Type -> Type
ft_mult = Type
w2, ft_arg :: Type -> Type
ft_arg = Type
arg2, ft_res :: Type -> Type
ft_res = Type
res2 })
      | FunTyFlag -> Bool
isVisibleFunArg FunTyFlag
af1  -- Do not attempt (c => t); just defer
      , FunTyFlag
af1 FunTyFlag -> FunTyFlag -> Bool
forall a. Eq a => a -> a -> Bool
== FunTyFlag
af2           -- Important!  See #21530
      = do { Coercion
co_w <- UnifyEnv -> Type -> Type -> TcM Coercion
uType (UnifyEnv
env { u_role = funRole role SelMult }) Type
w1   Type
w2
           ; Coercion
co_l <- UnifyEnv -> Type -> Type -> TcM Coercion
uType (UnifyEnv
env { u_role = funRole role SelArg })  Type
arg1 Type
arg2
           ; Coercion
co_r <- UnifyEnv -> Type -> Type -> TcM Coercion
uType (UnifyEnv
env { u_role = funRole role SelRes })  Type
res1 Type
res2
           ; Coercion -> TcM Coercion
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Coercion -> TcM Coercion) -> Coercion -> TcM Coercion
forall a b. (a -> b) -> a -> b
$ Role -> FunTyFlag -> Coercion -> Coercion -> Coercion -> Coercion
mkNakedFunCo Role
role FunTyFlag
af1 Coercion
co_w Coercion
co_l Coercion
co_r }

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

    go (TyConApp TyCon
tc1 [Type]
tys1) (TyConApp TyCon
tc2 [Type]
tys2)
      -- See Note [Mismatched type lists and application decomposition]
      | TyCon
tc1 TyCon -> TyCon -> Bool
forall a. Eq a => a -> a -> Bool
== TyCon
tc2, [Type] -> [Type] -> Bool
forall a b. [a] -> [b] -> Bool
equalLength [Type]
tys1 [Type]
tys2
      , TyCon -> Role -> Bool
isInjectiveTyCon TyCon
tc1 Role
role -- don't look under newtypes at Rep equality
      = Bool -> SDoc -> TcM Coercion -> TcM Coercion
forall a. HasCallStack => Bool -> SDoc -> a -> a
assertPpr (TyCon -> Role -> Bool
isGenerativeTyCon TyCon
tc1 Role
role) (TyCon -> SDoc
forall a. Outputable a => a -> SDoc
ppr TyCon
tc1) (TcM Coercion -> TcM Coercion) -> TcM Coercion -> TcM Coercion
forall a b. (a -> b) -> a -> b
$
        do { String -> SDoc -> TcM ()
traceTc String
"go-tycon" (TyCon -> SDoc
forall a. Outputable a => a -> SDoc
ppr TyCon
tc1 SDoc -> SDoc -> SDoc
forall doc. IsDoc doc => doc -> doc -> doc
$$ [Type] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [Type]
tys1 SDoc -> SDoc -> SDoc
forall doc. IsDoc doc => doc -> doc -> doc
$$ [Type] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [Type]
tys2 SDoc -> SDoc -> SDoc
forall doc. IsDoc doc => doc -> doc -> doc
$$ [Role] -> SDoc
forall a. Outputable a => a -> SDoc
ppr (Int -> [Role] -> [Role]
forall a. Int -> [a] -> [a]
take Int
10 (Role -> TyCon -> [Role]
tyConRoleListX Role
role TyCon
tc1)))
           ; [Coercion]
cos <- (Bool -> Role -> Type -> Type -> TcM Coercion)
-> [Bool]
-> [Role]
-> [Type]
-> [Type]
-> IOEnv (Env TcGblEnv TcLclEnv) [Coercion]
forall (m :: * -> *) a b c d e.
Monad m =>
(a -> b -> c -> d -> m e) -> [a] -> [b] -> [c] -> [d] -> m [e]
zipWith4M Bool -> Role -> Type -> Type -> TcM Coercion
u_tc_arg (TyCon -> [Bool]
tyConVisibilities TyCon
tc1)   -- Infinite
                                       (Role -> TyCon -> [Role]
tyConRoleListX Role
role TyCon
tc1) -- Infinite
                                       [Type]
tys1 [Type]
tys2
           ; Coercion -> TcM Coercion
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Coercion -> TcM Coercion) -> Coercion -> TcM Coercion
forall a b. (a -> b) -> a -> b
$ HasDebugCallStack => Role -> TyCon -> [Coercion] -> Coercion
Role -> TyCon -> [Coercion] -> Coercion
mkTyConAppCo Role
role TyCon
tc1 [Coercion]
cos }

    go (LitTy TyLit
m) ty :: Type
ty@(LitTy TyLit
n)
      | TyLit
m TyLit -> TyLit -> Bool
forall a. Eq a => a -> a -> Bool
== TyLit
n
      = Coercion -> TcM Coercion
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Coercion -> TcM Coercion) -> Coercion -> TcM Coercion
forall a b. (a -> b) -> a -> b
$ Role -> Type -> Coercion
mkReflCo Role
role Type
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 ty1 :: Type
ty1@(AppTy Type
s1 Type
t1) ty2 :: Type
ty2@(AppTy Type
s2 Type
t2)
      = Bool
-> Type -> Type -> Type -> Type -> Type -> Type -> TcM Coercion
go_app (Type -> Bool
isNextArgVisible Type
s1) Type
ty1 Type
s1 Type
t1 Type
ty2 Type
s2 Type
t2

    go ty1 :: Type
ty1@(AppTy Type
s1 Type
t1) ty2 :: Type
ty2@(TyConApp TyCon
tc2 [Type]
ts2)
      | Just ([Type]
ts2', Type
t2') <- [Type] -> Maybe ([Type], Type)
forall a. [a] -> Maybe ([a], a)
snocView [Type]
ts2
      = Bool -> TcM Coercion -> TcM Coercion
forall a. HasCallStack => Bool -> a -> a
assert (Bool -> Bool
not (TyCon -> Bool
tyConMustBeSaturated TyCon
tc2)) (TcM Coercion -> TcM Coercion) -> TcM Coercion -> TcM Coercion
forall a b. (a -> b) -> a -> b
$
        Bool
-> Type -> Type -> Type -> Type -> Type -> Type -> TcM Coercion
go_app (TyCon -> [Type] -> Bool
isNextTyConArgVisible TyCon
tc2 [Type]
ts2')
               Type
ty1 Type
s1 Type
t1 Type
ty2 (TyCon -> [Type] -> Type
TyConApp TyCon
tc2 [Type]
ts2') Type
t2'

    go ty1 :: Type
ty1@(TyConApp TyCon
tc1 [Type]
ts1) ty2 :: Type
ty2@(AppTy Type
s2 Type
t2)
      | Just ([Type]
ts1', Type
t1') <- [Type] -> Maybe ([Type], Type)
forall a. [a] -> Maybe ([a], a)
snocView [Type]
ts1
      = Bool -> TcM Coercion -> TcM Coercion
forall a. HasCallStack => Bool -> a -> a
assert (Bool -> Bool
not (TyCon -> Bool
tyConMustBeSaturated TyCon
tc1)) (TcM Coercion -> TcM Coercion) -> TcM Coercion -> TcM Coercion
forall a b. (a -> b) -> a -> b
$
        Bool
-> Type -> Type -> Type -> Type -> Type -> Type -> TcM Coercion
go_app (TyCon -> [Type] -> Bool
isNextTyConArgVisible TyCon
tc1 [Type]
ts1')
               Type
ty1 (TyCon -> [Type] -> Type
TyConApp TyCon
tc1 [Type]
ts1') Type
t1' Type
ty2 Type
s2 Type
t2

    go ty1 :: Type
ty1@(CoercionTy Coercion
co1) ty2 :: Type
ty2@(CoercionTy Coercion
co2)
      = do { Coercion
kco <- UnifyEnv -> Type -> Type -> TcM Coercion
uType (UnifyEnv -> Type -> Type -> UnifyEnv
mkKindEnv UnifyEnv
env Type
ty1 Type
ty2)
                          (Coercion -> Type
coercionType Coercion
co1) (Coercion -> Type
coercionType Coercion
co2)
           ; Coercion -> TcM Coercion
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Coercion -> TcM Coercion) -> Coercion -> TcM Coercion
forall a b. (a -> b) -> a -> b
$ Role -> Coercion -> Coercion -> Coercion -> Coercion
mkProofIrrelCo Role
role Coercion
kco Coercion
co1 Coercion
co2 }

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

    ------------------
    defer :: Type -> Type -> TcM Coercion
defer Type
ty1 Type
ty2   -- See Note [Check for equality before deferring]
      | Type
ty1 HasDebugCallStack => Type -> Type -> Bool
Type -> Type -> Bool
`tcEqType` Type
ty2 = Coercion -> TcM Coercion
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Role -> Type -> Coercion
mkReflCo Role
role Type
ty1)
      | Bool
otherwise          = UnifyEnv -> Type -> Type -> TcM Coercion
uType_defer UnifyEnv
env Type
orig_ty1 Type
orig_ty2


    ------------------
    u_tc_arg :: Bool -> Role -> Type -> Type -> TcM Coercion
u_tc_arg Bool
is_vis Role
role Type
ty1 Type
ty2
      = do { String -> SDoc -> TcM ()
traceTc String
"u_tc_arg" (Role -> SDoc
forall a. Outputable a => a -> SDoc
ppr Role
role SDoc -> SDoc -> SDoc
forall doc. IsDoc doc => doc -> doc -> doc
$$ Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
ty1 SDoc -> SDoc -> SDoc
forall doc. IsDoc doc => doc -> doc -> doc
$$ Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
ty2)
           ; UnifyEnv -> Type -> Type -> TcM Coercion
uType UnifyEnv
env_arg Type
ty1 Type
ty2 }
      where
        env_arg :: UnifyEnv
env_arg = UnifyEnv
env { u_loc = adjustCtLoc is_vis False (u_loc env)
                      , u_role = role }

    ------------------
    -- For AppTy, decompose only nominal equalities
    -- See Note [Decomposing AppTy equalities] in GHC.Tc.Solver.Equality
    go_app :: Bool
-> Type -> Type -> Type -> Type -> Type -> Type -> TcM Coercion
go_app Bool
vis Type
ty1 Type
s1 Type
t1 Type
ty2 Type
s2 Type
t2
      | Role
Nominal <- Role
role
      = -- Unify arguments t1/t2 before function s1/s2, because
        -- the former have smaller kinds, and hence simpler error messages
        -- c.f. GHC.Tc.Solver.Equality.can_eq_app
        -- Example: test T8603
        do { let env_arg :: UnifyEnv
env_arg = UnifyEnv
env { u_loc = adjustCtLoc vis False (u_loc env) }
           ; Coercion
co_t <- UnifyEnv -> Type -> Type -> TcM Coercion
uType UnifyEnv
env_arg Type
t1 Type
t2
           ; Coercion
co_s <- UnifyEnv -> Type -> Type -> TcM Coercion
uType UnifyEnv
env Type
s1 Type
s2
           ; Coercion -> TcM Coercion
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Coercion -> TcM Coercion) -> Coercion -> TcM Coercion
forall a b. (a -> b) -> a -> b
$ Coercion -> Coercion -> Coercion
mkAppCo Coercion
co_s Coercion
co_t }
      | Bool
otherwise
      = Type -> Type -> TcM Coercion
defer Type
ty1 Type
ty2

{- 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, uUnfilledVar1
    :: UnifyEnv
    -> SwapFlag
    -> TcTyVar        -- Tyvar 1: not necessarily a meta-tyvar
                      --    definitely not a /filled/ meta-tyvar
    -> TcTauType      -- Type 2
    -> TcM CoercionN
-- "Unfilled" means that the variable is definitely not a filled-in meta tyvar
--            It might be a skolem, or untouchable, or meta
uUnfilledVar :: UnifyEnv -> SwapFlag -> TcTyVar -> Type -> TcM Coercion
uUnfilledVar UnifyEnv
env SwapFlag
swapped TcTyVar
tv1 Type
ty2
  | Role
Nominal <- UnifyEnv -> Role
u_role UnifyEnv
env
  = do { Type
ty2 <- ZonkM Type -> TcM Type
forall a. ZonkM a -> TcM a
liftZonkM (ZonkM Type -> TcM Type) -> ZonkM Type -> TcM Type
forall a b. (a -> b) -> a -> b
$ Type -> ZonkM Type
zonkTcType Type
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
       ; UnifyEnv -> SwapFlag -> TcTyVar -> Type -> TcM Coercion
uUnfilledVar1 UnifyEnv
env SwapFlag
swapped TcTyVar
tv1 Type
ty2 }

  | Bool
otherwise  -- See Note [Do not unify representational equalities]
               -- in GHC.Tc.Solver.Equality
  = SwapFlag
-> (Type -> Type -> TcM Coercion) -> Type -> Type -> TcM Coercion
forall a b. SwapFlag -> (a -> a -> b) -> a -> a -> b
unSwap SwapFlag
swapped (UnifyEnv -> Type -> Type -> TcM Coercion
uType_defer UnifyEnv
env) (TcTyVar -> Type
mkTyVarTy TcTyVar
tv1) Type
ty2

uUnfilledVar1 :: UnifyEnv -> SwapFlag -> TcTyVar -> Type -> TcM Coercion
uUnfilledVar1 UnifyEnv
env       -- Precondition: u_role==Nominal
              SwapFlag
swapped
              TcTyVar
tv1
              Type
ty2       -- ty2 is zonked
  | Just TcTyVar
tv2 <- Type -> Maybe TcTyVar
getTyVar_maybe Type
ty2
  = TcTyVar -> TcM Coercion
go TcTyVar
tv2

  | Bool
otherwise
  = UnifyEnv -> SwapFlag -> TcTyVar -> Type -> TcM Coercion
uUnfilledVar2 UnifyEnv
env SwapFlag
swapped TcTyVar
tv1 Type
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 :: TcTyVar -> TcM Coercion
go TcTyVar
tv2 | TcTyVar
tv1 TcTyVar -> TcTyVar -> Bool
forall a. Eq a => a -> a -> Bool
== TcTyVar
tv2  -- Same type variable => no-op
           = Coercion -> TcM Coercion
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Type -> Coercion
mkNomReflCo (TcTyVar -> Type
mkTyVarTy TcTyVar
tv1))

           | Bool -> TcTyVar -> TcTyVar -> Bool
swapOverTyVars Bool
False TcTyVar
tv1 TcTyVar
tv2   -- Distinct type variables
               -- Swap meta tyvar to the left if poss
           = do { TcTyVar
tv1 <- ZonkM TcTyVar -> TcM TcTyVar
forall a. ZonkM a -> TcM a
liftZonkM (ZonkM TcTyVar -> TcM TcTyVar) -> ZonkM TcTyVar -> TcM TcTyVar
forall a b. (a -> b) -> a -> b
$ TcTyVar -> ZonkM TcTyVar
zonkTyCoVarKind TcTyVar
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
                ; UnifyEnv -> SwapFlag -> TcTyVar -> Type -> TcM Coercion
uUnfilledVar2 UnifyEnv
env (SwapFlag -> SwapFlag
flipSwap SwapFlag
swapped) TcTyVar
tv2 (TcTyVar -> Type
mkTyVarTy TcTyVar
tv1) }

           | Bool
otherwise
           = UnifyEnv -> SwapFlag -> TcTyVar -> Type -> TcM Coercion
uUnfilledVar2 UnifyEnv
env SwapFlag
swapped TcTyVar
tv1 Type
ty2

----------
uUnfilledVar2 :: UnifyEnv       -- Precondition: u_role==Nominal
              -> SwapFlag
              -> TcTyVar        -- Tyvar 1: not necessarily a meta-tyvar
                                --    definitely not a /filled/ meta-tyvar
              -> TcTauType      -- Type 2, zonked
              -> TcM CoercionN
uUnfilledVar2 :: UnifyEnv -> SwapFlag -> TcTyVar -> Type -> TcM Coercion
uUnfilledVar2 env :: UnifyEnv
env@(UE { u_defer :: UnifyEnv -> TcRef (Bag Ct)
u_defer = TcRef (Bag Ct)
def_eq_ref }) SwapFlag
swapped TcTyVar
tv1 Type
ty2
  = do { TcLevel
cur_lvl <- TcM TcLevel
getTcLevel
           -- See Note [Unification preconditions], (UNTOUCHABLE) wrinkles
           -- Here we don't know about given equalities here; so we treat
           -- /any/ level outside this one as untouchable.  Hence cur_lvl.
       ; if Bool -> Bool
not (TcLevel -> TcTyVar -> Type -> Bool
touchabilityAndShapeTest TcLevel
cur_lvl TcTyVar
tv1 Type
ty2
                 Bool -> Bool -> Bool
&& Bool -> TcTyVar -> Type -> Bool
simpleUnifyCheck Bool
False TcTyVar
tv1 Type
ty2)
         then TcM Coercion
not_ok_so_defer
         else
    do { Bag Ct
def_eqs <- TcRef (Bag Ct) -> IOEnv (Env TcGblEnv TcLclEnv) (Bag Ct)
forall (m :: * -> *) a. MonadIO m => TcRef a -> m a
readTcRef TcRef (Bag Ct)
def_eq_ref  -- Capture current state of def_eqs

       -- Attempt to unify kinds
       ; Coercion
co_k <- UnifyEnv -> Type -> Type -> TcM Coercion
uType (UnifyEnv -> Type -> Type -> UnifyEnv
mkKindEnv UnifyEnv
env Type
ty1 Type
ty2) (HasDebugCallStack => Type -> Type
Type -> Type
typeKind Type
ty2) (TcTyVar -> Type
tyVarKind TcTyVar
tv1)
       ; String -> SDoc -> TcM ()
traceTc String
"uUnfilledVar2 ok" (SDoc -> TcM ()) -> SDoc -> TcM ()
forall a b. (a -> b) -> a -> b
$
         [SDoc] -> SDoc
forall doc. IsDoc doc => [doc] -> doc
vcat [ TcTyVar -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcTyVar
tv1 SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> SDoc
dcolon SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr (TcTyVar -> Type
tyVarKind TcTyVar
tv1)
              , Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
ty2 SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> SDoc
dcolon SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr (HasDebugCallStack => Type -> Type
Type -> Type
typeKind  Type
ty2)
              , Bool -> SDoc
forall a. Outputable a => a -> SDoc
ppr (Coercion -> Bool
isReflCo Coercion
co_k), Coercion -> SDoc
forall a. Outputable a => a -> SDoc
ppr Coercion
co_k ]

       ; if Coercion -> Bool
isReflCo Coercion
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 { ZonkM () -> TcM ()
forall a. ZonkM a -> TcM a
liftZonkM (ZonkM () -> TcM ()) -> ZonkM () -> TcM ()
forall a b. (a -> b) -> a -> b
$ HasDebugCallStack => TcTyVar -> Type -> ZonkM ()
TcTyVar -> Type -> ZonkM ()
writeMetaTyVar TcTyVar
tv1 Type
ty2
                 ; case UnifyEnv -> Maybe (TcRef [TcTyVar])
u_unified UnifyEnv
env of
                     Maybe (TcRef [TcTyVar])
Nothing -> () -> TcM ()
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return ()
                     Just TcRef [TcTyVar]
uref -> TcRef [TcTyVar] -> ([TcTyVar] -> [TcTyVar]) -> TcM ()
forall (m :: * -> *) a. MonadIO m => TcRef a -> (a -> a) -> m ()
updTcRef TcRef [TcTyVar]
uref (TcTyVar
tv1 TcTyVar -> [TcTyVar] -> [TcTyVar]
forall a. a -> [a] -> [a]
:)
                 ; Coercion -> TcM Coercion
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Type -> Coercion
mkNomReflCo Type
ty2) }  -- Unification is always Nominal

         else -- The kinds don't match yet, so defer instead.
              do { TcRef (Bag Ct) -> Bag Ct -> TcM ()
forall (m :: * -> *) a. MonadIO m => TcRef a -> a -> m ()
writeTcRef TcRef (Bag Ct)
def_eq_ref Bag Ct
def_eqs
                     -- Since we are discarding co_k, also discard any constraints
                     -- emitted by kind unification; they are just useless clutter.
                     -- Do this dicarding by simply restoring the previous state
                     -- of def_eqs; a bit imperative/yukky but works fine.
                 ; TcM Coercion
defer }
         }}
  where
    ty1 :: Type
ty1 = TcTyVar -> Type
mkTyVarTy TcTyVar
tv1
    defer :: TcM Coercion
defer = SwapFlag
-> (Type -> Type -> TcM Coercion) -> Type -> Type -> TcM Coercion
forall a b. SwapFlag -> (a -> a -> b) -> a -> a -> b
unSwap SwapFlag
swapped (UnifyEnv -> Type -> Type -> TcM Coercion
uType_defer UnifyEnv
env) Type
ty1 Type
ty2

    not_ok_so_defer :: TcM Coercion
not_ok_so_defer =
      do { String -> SDoc -> TcM ()
traceTc String
"uUnfilledVar2 not ok" (TcTyVar -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcTyVar
tv1 SDoc -> SDoc -> SDoc
forall doc. IsDoc doc => doc -> doc -> doc
$$ Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
ty2)
               -- Occurs check or an untouchable: just defer
               -- NB: occurs check isn't necessarily fatal:
               --     eg tv1 occurred in type family parameter
          ; TcM Coercion
defer }

swapOverTyVars :: Bool -> TcTyVar -> TcTyVar -> Bool
swapOverTyVars :: Bool -> TcTyVar -> TcTyVar -> Bool
swapOverTyVars Bool
is_given TcTyVar
tv1 TcTyVar
tv2
  -- See Note [Unification variables on the left]
  | Bool -> Bool
not Bool
is_given, Int
pri1 Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
0, Int
pri2 Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
0 = Bool
True
  | Bool -> Bool
not Bool
is_given, Int
pri2 Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
0, Int
pri1 Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
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]
  | Int
pri1 Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
pri2 = Bool
False
  | Int
pri2 Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
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 = TcTyVar -> TcLevel
tcTyVarLevel TcTyVar
tv1
    lvl2 :: TcLevel
lvl2 = TcTyVar -> TcLevel
tcTyVarLevel TcTyVar
tv2
    pri1 :: Int
pri1 = TcTyVar -> Int
lhsPriority TcTyVar
tv1
    pri2 :: Int
pri2 = TcTyVar -> Int
lhsPriority TcTyVar
tv2
    tv1_name :: Name
tv1_name = TcTyVar -> Name
Var.varName TcTyVar
tv1
    tv2_name :: Name
tv2_name = TcTyVar -> Name
Var.varName TcTyVar
tv2


lhsPriority :: TcTyVar -> Int
-- Higher => more important to be on the LHS
--        => more likely to be eliminated
-- See Note [TyVar/TyVar orientation]
lhsPriority :: TcTyVar -> Int
lhsPriority TcTyVar
tv
  = Bool -> SDoc -> Int -> Int
forall a. HasCallStack => Bool -> SDoc -> a -> a
assertPpr (TcTyVar -> Bool
isTyVar TcTyVar
tv) (TcTyVar -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcTyVar
tv) (Int -> Int) -> Int -> Int
forall a b. (a -> b) -> a -> b
$
    case TcTyVar -> TcTyVarDetails
tcTyVarDetails TcTyVar
tv of
      TcTyVarDetails
RuntimeUnk  -> Int
0
      SkolemTv {} -> Int
0
      MetaTv { mtv_info :: TcTyVarDetails -> MetaInfo
mtv_info = MetaInfo
info } -> case MetaInfo
info of
                                     MetaInfo
CycleBreakerTv -> Int
0
                                     MetaInfo
TyVarTv        -> Int
1
                                     ConcreteTv {}  -> Int
2
                                     MetaInfo
TauTv          -> Int
3
                                     MetaInfo
RuntimeUnkTv   -> Int
4

{- 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 five 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 ambient 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.InertSet

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.

4. (CONCRETE) A ConcreteTv can only unify with a concrete type,
    by definition.

    That is, if we have `rr[conc] ~ F Int`, we can't unify
    `rr` with `F Int`, so we hold off on unifying.
    Note however that the equality might get rewritten; for instance
    if we can rewrite `F Int` to a concrete type, say `FloatRep`,
    then we will have `rr[conc] ~ FloatRep` and we can unify `rr ~ FloatRep`.

    Note that we can still make progress on unification even if
    we can't fully solve an equality, e.g.

      alpha[conc] ~# TupleRep '[ beta[tau], F gamma[tau] ]

    we can fill beta[tau] := beta[conc]. This is why we call
    'makeTypeConcrete' in startSolvingByUnification.

5. (COERCION-HOLE) Confusing coercion holes
   Suppose our equality is
     (alpha :: k) ~ (Int |> {co})
   where co :: Type ~ k is an unsolved wanted. Note that this equality
   is homogeneous; both sides have kind k. We refrain from unifying here, because
   of the coercion hole in the RHS -- see Wrinkle (EIK2) in
   Note [Equalities with incompatible kinds] in GHC.Solver.Equality.

Needless to say, all there are 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.Utils.Unify.touchabilityAndShapeTest. More details in
    Note [Tracking Given equalities] in GHC.Tc.Solver.InertSet

    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]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
See also Note [Fundeps with instances, and equality orientation]
where the kind equality orientation is important

Given (a ~ b), should we orient the equality as (a~b) or (b~a)?
This is a surprisingly tricky question!

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.Equality.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, because the MetaTv may be
  touchable and can be unified.

  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.

  - ConcreteTv: These are like TauTv, except they can only unify with
    a concrete type. So we want to be able to write to them, but not quite
    as much as TauTvs: 2.

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

  - 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: 4. 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.InertSet 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 is still the same.

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
  :: TypedThing     -- ^ type, only for errors
  -> Arity           -- ^ n: number of desired arrows
  -> TcKind          -- ^ fun_kind
  -> TcM Coercion    -- ^ co :: fun_kind ~ (arg1 -> ... -> argn -> res)

matchExpectedFunKind :: TypedThing -> Int -> Type -> TcM Coercion
matchExpectedFunKind TypedThing
hs_ty Int
n Type
k = Int -> Type -> TcM Coercion
go Int
n Type
k
  where
    go :: Int -> Type -> TcM Coercion
go Int
0 Type
k = Coercion -> TcM Coercion
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Type -> Coercion
mkNomReflCo Type
k)

    go Int
n Type
k | Just Type
k' <- Type -> Maybe Type
coreView Type
k = Int -> Type -> TcM Coercion
go Int
n Type
k'

    go Int
n k :: Type
k@(TyVarTy TcTyVar
kvar)
      | TcTyVar -> Bool
isMetaTyVar TcTyVar
kvar
      = do { MetaDetails
maybe_kind <- TcTyVar -> IOEnv (Env TcGblEnv TcLclEnv) MetaDetails
forall (m :: * -> *). MonadIO m => TcTyVar -> m MetaDetails
readMetaTyVar TcTyVar
kvar
           ; case MetaDetails
maybe_kind of
                Indirect Type
fun_kind -> Int -> Type -> TcM Coercion
go Int
n Type
fun_kind
                MetaDetails
Flexi ->             Int -> Type -> TcM Coercion
defer Int
n Type
k }

    go Int
n (FunTy { ft_af :: Type -> FunTyFlag
ft_af = FunTyFlag
af, ft_mult :: Type -> Type
ft_mult = Type
w, ft_arg :: Type -> Type
ft_arg = Type
arg, ft_res :: Type -> Type
ft_res = Type
res })
      | FunTyFlag -> Bool
isVisibleFunArg FunTyFlag
af
      = do { Coercion
co <- Int -> Type -> TcM Coercion
go (Int
nInt -> Int -> Int
forall a. Num a => a -> a -> a
-Int
1) Type
res
           ; Coercion -> TcM Coercion
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Role -> FunTyFlag -> Coercion -> Coercion -> Coercion -> Coercion
mkNakedFunCo Role
Nominal FunTyFlag
af (Type -> Coercion
mkNomReflCo Type
w) (Type -> Coercion
mkNomReflCo Type
arg) Coercion
co) }

    go Int
n Type
other
     = Int -> Type -> TcM Coercion
defer Int
n Type
other

    defer :: Int -> Type -> TcM Coercion
defer Int
n Type
k
      = do { [Type]
arg_kinds <- Int -> TcM [Type]
newMetaKindVars Int
n
           ; Type
res_kind  <- TcM Type
newMetaKindVar
           ; let new_fun :: Type
new_fun = [Type] -> Type -> Type
mkVisFunTysMany [Type]
arg_kinds Type
res_kind
                 origin :: CtOrigin
origin  = TypeEqOrigin { uo_actual :: Type
uo_actual   = Type
k
                                        , uo_expected :: Type
uo_expected = Type
new_fun
                                        , uo_thing :: Maybe TypedThing
uo_thing    = TypedThing -> Maybe TypedThing
forall a. a -> Maybe a
Just TypedThing
hs_ty
                                        , uo_visible :: Bool
uo_visible  = Bool
True
                                        }
           ; TypeOrKind -> CtOrigin -> Type -> Type -> TcM Coercion
unifyTypeAndEmit TypeOrKind
KindLevel CtOrigin
origin Type
k Type
new_fun }

{- *********************************************************************
*                                                                      *
                 Checking alpha ~ ty
              for the on-the-fly unifier
*                                                                      *
********************************************************************* -}

simpleUnifyCheck :: Bool -> TcTyVar -> TcType -> Bool
-- A fast check: True <=> unification is OK
-- If it says 'False' then unification might still be OK, but
-- it'll take more work to do -- use the full checkTypeEq
--
-- * Always rejects foralls unless lhs_tv is RuntimeUnk
--   (used by GHCi debugger)
-- * Rejects a non-concrete type if lhs_tv is concrete
-- * Rejects type families unless fam_ok=True
-- * Does a level-check for type variables
--
-- This function is pretty heavily used, so it's optimised not to allocate
simpleUnifyCheck :: Bool -> TcTyVar -> Type -> Bool
simpleUnifyCheck Bool
fam_ok TcTyVar
lhs_tv Type
rhs
  = Type -> Bool
go Type
rhs
  where
    !(Type -> Bool
occ_in_ty, Coercion -> Bool
occ_in_co) = TcTyVar -> (Type -> Bool, Coercion -> Bool)
mkOccFolders TcTyVar
lhs_tv

    lhs_tv_lvl :: TcLevel
lhs_tv_lvl         = TcTyVar -> TcLevel
tcTyVarLevel TcTyVar
lhs_tv
    lhs_tv_is_concrete :: Bool
lhs_tv_is_concrete = TcTyVar -> Bool
isConcreteTyVar TcTyVar
lhs_tv
    forall_ok :: Bool
forall_ok          = case TcTyVar -> TcTyVarDetails
tcTyVarDetails TcTyVar
lhs_tv of
                            MetaTv { mtv_info :: TcTyVarDetails -> MetaInfo
mtv_info = MetaInfo
RuntimeUnkTv } -> Bool
True
                            TcTyVarDetails
_                                  -> Bool
False

    go :: Type -> Bool
go (TyVarTy TcTyVar
tv)
      | TcTyVar
lhs_tv TcTyVar -> TcTyVar -> Bool
forall a. Eq a => a -> a -> Bool
== TcTyVar
tv                                 = Bool
False
      | TcTyVar -> TcLevel
tcTyVarLevel TcTyVar
tv TcLevel -> TcLevel -> Bool
forall a. Ord a => a -> a -> Bool
> TcLevel
lhs_tv_lvl                 = Bool
False
      | Bool
lhs_tv_is_concrete, Bool -> Bool
not (TcTyVar -> Bool
isConcreteTyVar TcTyVar
tv) = Bool
False
      | Type -> Bool
occ_in_ty (Type -> Bool) -> Type -> Bool
forall a b. (a -> b) -> a -> b
$! (TcTyVar -> Type
tyVarKind TcTyVar
tv)                  = Bool
False
      | Bool
otherwise                                    = Bool
True

    go (FunTy {ft_af :: Type -> FunTyFlag
ft_af = FunTyFlag
af, ft_mult :: Type -> Type
ft_mult = Type
w, ft_arg :: Type -> Type
ft_arg = Type
a, ft_res :: Type -> Type
ft_res = Type
r})
      | FunTyFlag -> Bool
isInvisibleFunArg FunTyFlag
af, Bool -> Bool
not Bool
forall_ok = Bool
False
      | Bool
otherwise                           = Type -> Bool
go Type
w Bool -> Bool -> Bool
&& Type -> Bool
go Type
a Bool -> Bool -> Bool
&& Type -> Bool
go Type
r

    go (TyConApp TyCon
tc [Type]
tys)
      | Bool
lhs_tv_is_concrete, Bool -> Bool
not (TyCon -> Bool
isConcreteTyCon TyCon
tc) = Bool
False
      | Bool -> Bool
not (TyCon -> Bool
isTauTyCon TyCon
tc)                          = Bool
False
      | Bool -> Bool
not Bool
fam_ok, Bool -> Bool
not (TyCon -> Bool
isFamFreeTyCon TyCon
tc)          = Bool
False
      | Bool
otherwise                                    = (Type -> Bool) -> [Type] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all Type -> Bool
go [Type]
tys

    go (AppTy Type
t1 Type
t2)    = Type -> Bool
go Type
t1 Bool -> Bool -> Bool
&& Type -> Bool
go Type
t2
    go (ForAllTy (Bndr TcTyVar
tv ForAllTyFlag
_) Type
ty)
      | Bool
forall_ok = Type -> Bool
go (TcTyVar -> Type
tyVarKind TcTyVar
tv) Bool -> Bool -> Bool
&& (TcTyVar
tv TcTyVar -> TcTyVar -> Bool
forall a. Eq a => a -> a -> Bool
== TcTyVar
lhs_tv Bool -> Bool -> Bool
|| Type -> Bool
go Type
ty)
      | Bool
otherwise = Bool
False

    go (CastTy Type
ty Coercion
co)   = Bool -> Bool
not (Coercion -> Bool
occ_in_co Coercion
co) Bool -> Bool -> Bool
&& Type -> Bool
go Type
ty
    go (CoercionTy Coercion
co)  = Bool -> Bool
not (Coercion -> Bool
occ_in_co Coercion
co)
    go (LitTy {})       = Bool
True


mkOccFolders :: TcTyVar -> (TcType -> Bool, TcCoercion -> Bool)
-- These functions return True
--   * if lhs_tv occurs (incl deeply, in the kind of variable)
--   * if there is a coercion hole
-- No expansion of type synonyms
mkOccFolders :: TcTyVar -> (Type -> Bool, Coercion -> Bool)
mkOccFolders TcTyVar
lhs_tv = (Any -> Bool
getAny (Any -> Bool) -> (Type -> Any) -> Type -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Type -> Any
check_ty, Any -> Bool
getAny (Any -> Bool) -> (Coercion -> Any) -> Coercion -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Coercion -> Any
check_co)
  where
    !(Type -> Any
check_ty, [Type] -> Any
_, Coercion -> Any
check_co, [Coercion] -> Any
_) = TyCoFolder VarSet Any
-> VarSet
-> (Type -> Any, [Type] -> Any, Coercion -> Any, [Coercion] -> Any)
forall a env.
Monoid a =>
TyCoFolder env a
-> env -> (Type -> a, [Type] -> a, Coercion -> a, [Coercion] -> a)
foldTyCo TyCoFolder VarSet Any
occ_folder VarSet
emptyVarSet
    occ_folder :: TyCoFolder VarSet Any
occ_folder = TyCoFolder { tcf_view :: Type -> Maybe Type
tcf_view  = Type -> Maybe Type
noView  -- Don't expand synonyms
                            , tcf_tyvar :: VarSet -> TcTyVar -> Any
tcf_tyvar = VarSet -> TcTyVar -> Any
do_tcv, tcf_covar :: VarSet -> TcTyVar -> Any
tcf_covar = VarSet -> TcTyVar -> Any
do_tcv
                            , tcf_hole :: VarSet -> CoercionHole -> Any
tcf_hole  = VarSet -> CoercionHole -> Any
forall {p} {p}. p -> p -> Any
do_hole
                            , tcf_tycobinder :: VarSet -> TcTyVar -> ForAllTyFlag -> VarSet
tcf_tycobinder = VarSet -> TcTyVar -> ForAllTyFlag -> VarSet
forall {p}. VarSet -> TcTyVar -> p -> VarSet
do_bndr }

    do_tcv :: VarSet -> TcTyVar -> Any
do_tcv VarSet
is TcTyVar
v = Bool -> Any
Any (Bool -> Bool
not (TcTyVar
v TcTyVar -> VarSet -> Bool
`elemVarSet` VarSet
is) Bool -> Bool -> Bool
&& TcTyVar
v TcTyVar -> TcTyVar -> Bool
forall a. Eq a => a -> a -> Bool
== TcTyVar
lhs_tv)
                  Any -> Any -> Any
forall a. Monoid a => a -> a -> a
`mappend` Type -> Any
check_ty (TcTyVar -> Type
varType TcTyVar
v)

    do_bndr :: VarSet -> TcTyVar -> p -> VarSet
do_bndr VarSet
is TcTyVar
tcv p
_faf = VarSet -> TcTyVar -> VarSet
extendVarSet VarSet
is TcTyVar
tcv
    do_hole :: p -> p -> Any
do_hole p
_is p
_hole = Bool -> Any
DM.Any Bool
True  -- Reject coercion holes

{- *********************************************************************
*                                                                      *
                 Equality invariant checking
*                                                                      *
********************************************************************* -}


{-  Note [Checking for foralls]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We never 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->*)

Note [Forgetful synonyms in checkTyConApp]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
   type S a b = b   -- Forgets 'a'

   [W] alpha[2] ~ Maybe (S beta[4] gamma[2])

We don't want to promote beta to level 2; rather, we should
expand the synonym. (Currently, in checkTypeEqRhs promotion
is irrevocable, by side effect.)

To avoid this risk we eagerly expand forgetful synonyms.
This also means we won't get an occurs check in
   a ~ Maybe (S a b)

The annoyance is that we might expand the synonym unnecessarily,
something we generally try to avoid.  But for now, this seems
simple.

In a forgetful case like a ~ Maybe (S a b), `checkTyEqRhs` returns
a Reduction that looks
    Reduction { reductionCoercion    = Refl
              , reductionReducedType = Maybe b }
We must jolly well use that reductionReduced type, even though the
reductionCoercion is Refl.  See `canEqCanLHSFinish_no_unification`.
-}

data PuResult a b = PuFail CheckTyEqResult
                  | PuOK (Bag a) b

instance Functor (PuResult a) where
  fmap :: forall a b. (a -> b) -> PuResult a a -> PuResult a b
fmap a -> b
_ (PuFail CheckTyEqResult
prob) = CheckTyEqResult -> PuResult a b
forall a b. CheckTyEqResult -> PuResult a b
PuFail CheckTyEqResult
prob
  fmap a -> b
f (PuOK Bag a
cts a
x)  = Bag a -> b -> PuResult a b
forall a b. Bag a -> b -> PuResult a b
PuOK Bag a
cts (a -> b
f a
x)

instance Applicative (PuResult a) where
  pure :: forall a. a -> PuResult a a
pure a
x = Bag a -> a -> PuResult a a
forall a b. Bag a -> b -> PuResult a b
PuOK Bag a
forall a. Bag a
emptyBag a
x
  PuFail CheckTyEqResult
p1 <*> :: forall a b. PuResult a (a -> b) -> PuResult a a -> PuResult a b
<*> PuFail CheckTyEqResult
p2 = CheckTyEqResult -> PuResult a b
forall a b. CheckTyEqResult -> PuResult a b
PuFail (CheckTyEqResult
p1 CheckTyEqResult -> CheckTyEqResult -> CheckTyEqResult
forall a. Semigroup a => a -> a -> a
S.<> CheckTyEqResult
p2)
  PuFail CheckTyEqResult
p1 <*> PuOK {}   = CheckTyEqResult -> PuResult a b
forall a b. CheckTyEqResult -> PuResult a b
PuFail CheckTyEqResult
p1
  PuOK {}   <*> PuFail CheckTyEqResult
p2 = CheckTyEqResult -> PuResult a b
forall a b. CheckTyEqResult -> PuResult a b
PuFail CheckTyEqResult
p2
  PuOK Bag a
c1 a -> b
f <*> PuOK Bag a
c2 a
x = Bag a -> b -> PuResult a b
forall a b. Bag a -> b -> PuResult a b
PuOK (Bag a
c1 Bag a -> Bag a -> Bag a
forall a. Bag a -> Bag a -> Bag a
`unionBags` Bag a
c2) (a -> b
f a
x)

instance (Outputable a, Outputable b) => Outputable (PuResult a b) where
  ppr :: PuResult a b -> SDoc
ppr (PuFail CheckTyEqResult
prob) = String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"PuFail" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> (CheckTyEqResult -> SDoc
forall a. Outputable a => a -> SDoc
ppr CheckTyEqResult
prob)
  ppr (PuOK Bag a
cts b
x)  = String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"PuOK" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc
braces
                        ([SDoc] -> SDoc
forall doc. IsDoc doc => [doc] -> doc
vcat [ String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"redn:" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> b -> SDoc
forall a. Outputable a => a -> SDoc
ppr b
x
                              , String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"cts:" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> Bag a -> SDoc
forall a. Outputable a => a -> SDoc
ppr Bag a
cts ])

pprPur :: PuResult a b -> SDoc
-- For debugging
pprPur :: forall a b. PuResult a b -> SDoc
pprPur (PuFail CheckTyEqResult
prob) = String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"PuFail:" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<> CheckTyEqResult -> SDoc
forall a. Outputable a => a -> SDoc
ppr CheckTyEqResult
prob
pprPur (PuOK {})     = String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"PuOK"

okCheckRefl :: TcType -> TcM (PuResult a Reduction)
okCheckRefl :: forall a. Type -> TcM (PuResult a Reduction)
okCheckRefl Type
ty = PuResult a Reduction
-> IOEnv (Env TcGblEnv TcLclEnv) (PuResult a Reduction)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Bag a -> Reduction -> PuResult a Reduction
forall a b. Bag a -> b -> PuResult a b
PuOK Bag a
forall a. Bag a
emptyBag (Role -> Type -> Reduction
mkReflRedn Role
Nominal Type
ty))

failCheckWith :: CheckTyEqResult -> TcM (PuResult a b)
failCheckWith :: forall a b. CheckTyEqResult -> TcM (PuResult a b)
failCheckWith CheckTyEqResult
p = PuResult a b -> IOEnv (Env TcGblEnv TcLclEnv) (PuResult a b)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (CheckTyEqResult -> PuResult a b
forall a b. CheckTyEqResult -> PuResult a b
PuFail CheckTyEqResult
p)

mapCheck :: (x -> TcM (PuResult a Reduction))
         -> [x]
         -> TcM (PuResult a Reductions)
mapCheck :: forall x a.
(x -> TcM (PuResult a Reduction))
-> [x] -> TcM (PuResult a Reductions)
mapCheck x -> TcM (PuResult a Reduction)
f [x]
xs
  = do { ([PuResult a Reduction]
ress :: [PuResult a Reduction]) <- (x -> TcM (PuResult a Reduction))
-> [x] -> IOEnv (Env TcGblEnv TcLclEnv) [PuResult a Reduction]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
forall (m :: * -> *) a b. Monad m => (a -> m b) -> [a] -> m [b]
mapM x -> TcM (PuResult a Reduction)
f [x]
xs
       ; PuResult a Reductions -> TcM (PuResult a Reductions)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return ([Reduction] -> Reductions
unzipRedns ([Reduction] -> Reductions)
-> PuResult a [Reduction] -> PuResult a Reductions
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> [PuResult a Reduction] -> PuResult a [Reduction]
forall (t :: * -> *) (f :: * -> *) a.
(Traversable t, Applicative f) =>
t (f a) -> f (t a)
forall (f :: * -> *) a. Applicative f => [f a] -> f [a]
sequenceA [PuResult a Reduction]
ress) }
         -- sequenceA :: [PuResult a Reduction] -> PuResult a [Reduction]
         -- unzipRedns :: [Reduction] -> Reductions

-----------------------------
-- | Options describing how to deal with a type equality
-- in the pure unifier. See 'checkTyEqRhs'
data TyEqFlags a
  = TEF { forall a. TyEqFlags a -> Bool
tef_foralls  :: Bool         -- Allow foralls
        , forall a. TyEqFlags a -> CanEqLHS
tef_lhs      :: CanEqLHS     -- LHS of the constraint
        , forall a. TyEqFlags a -> AreUnifying
tef_unifying :: AreUnifying  -- Always NotUnifying if tef_lhs is TyFamLHS
        , forall a. TyEqFlags a -> TyEqFamApp a
tef_fam_app  :: TyEqFamApp a
        , forall a. TyEqFlags a -> CheckTyEqProblem
tef_occurs   :: CheckTyEqProblem }  -- Soluble or insoluble occurs check

-- | What to do when encountering a type-family application while processing
-- a type equality in the pure unifier.
--
-- See Note [Family applications in canonical constraints]
data TyEqFamApp a
  = TEFA_Fail                    -- Always fail
  | TEFA_Recurse                 -- Just recurse
  | TEFA_Break (FamAppBreaker a) -- Recurse, but replace with cycle breaker if fails,
                                 -- using the FamAppBreaker

data AreUnifying
  = Unifying
       MetaInfo         -- MetaInfo of the LHS tyvar (which is a meta-tyvar)
       TcLevel          -- Level of the LHS tyvar
       LevelCheck

  | NotUnifying         -- Not attempting to unify

data LevelCheck
  = LC_None       -- Level check not needed: we should never encounter
                  -- a tyvar at deeper level than the LHS

  | LC_Check      -- Do a level check between the LHS tyvar and the occurrence tyvar
                  -- Fail if the level check fails

  | LC_Promote    -- Do a level check between the LHS tyvar and the occurrence tyvar
                  -- If the level check fails, and the occurrence is a unification
                  -- variable, promote it

instance Outputable (TyEqFlags a) where
  ppr :: TyEqFlags a -> SDoc
ppr (TEF { Bool
CheckTyEqProblem
CanEqLHS
AreUnifying
TyEqFamApp a
tef_foralls :: forall a. TyEqFlags a -> Bool
tef_lhs :: forall a. TyEqFlags a -> CanEqLHS
tef_unifying :: forall a. TyEqFlags a -> AreUnifying
tef_fam_app :: forall a. TyEqFlags a -> TyEqFamApp a
tef_occurs :: forall a. TyEqFlags a -> CheckTyEqProblem
tef_foralls :: Bool
tef_lhs :: CanEqLHS
tef_unifying :: AreUnifying
tef_fam_app :: TyEqFamApp a
tef_occurs :: CheckTyEqProblem
.. }) = String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"TEF" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc
braces (
                        [SDoc] -> SDoc
forall doc. IsDoc doc => [doc] -> doc
vcat [ String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"tef_foralls =" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> Bool -> SDoc
forall a. Outputable a => a -> SDoc
ppr Bool
tef_foralls
                             , String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"tef_lhs =" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> CanEqLHS -> SDoc
forall a. Outputable a => a -> SDoc
ppr CanEqLHS
tef_lhs
                             , String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"tef_unifying =" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> AreUnifying -> SDoc
forall a. Outputable a => a -> SDoc
ppr AreUnifying
tef_unifying
                             , String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"tef_fam_app =" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> TyEqFamApp a -> SDoc
forall a. Outputable a => a -> SDoc
ppr TyEqFamApp a
tef_fam_app
                             , String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"tef_occurs =" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> CheckTyEqProblem -> SDoc
forall a. Outputable a => a -> SDoc
ppr CheckTyEqProblem
tef_occurs ])

instance Outputable (TyEqFamApp a) where
  ppr :: TyEqFamApp a -> SDoc
ppr TyEqFamApp a
TEFA_Fail       = String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"TEFA_Fail"
  ppr TyEqFamApp a
TEFA_Recurse    = String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"TEFA_Fail"
  ppr (TEFA_Break {}) = String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"TEFA_Break"

instance Outputable AreUnifying where
  ppr :: AreUnifying -> SDoc
ppr AreUnifying
NotUnifying = String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"NotUnifying"
  ppr (Unifying MetaInfo
mi TcLevel
lvl LevelCheck
lc) = String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"Unifying" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+>
         SDoc -> SDoc
forall doc. IsLine doc => doc -> doc
braces (MetaInfo -> SDoc
forall a. Outputable a => a -> SDoc
ppr MetaInfo
mi SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<> SDoc
forall doc. IsLine doc => doc
comma SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> TcLevel -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcLevel
lvl SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<> SDoc
forall doc. IsLine doc => doc
comma SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> LevelCheck -> SDoc
forall a. Outputable a => a -> SDoc
ppr LevelCheck
lc)

instance Outputable LevelCheck where
  ppr :: LevelCheck -> SDoc
ppr LevelCheck
LC_None    = String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"LC_None"
  ppr LevelCheck
LC_Check   = String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"LC_Check"
  ppr LevelCheck
LC_Promote = String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"LC_Promote"

famAppArgFlags :: TyEqFlags a -> TyEqFlags a
-- Adjust the flags when going undter a type family
-- Only the outer family application gets the loop-breaker treatment
-- Ditto tyvar promotion.  E.g.
--        [W] alpha[2] ~ Maybe (F beta[3])
-- Do not promote beta[3]; instead promote (F beta[3])
famAppArgFlags :: forall a. TyEqFlags a -> TyEqFlags a
famAppArgFlags flags :: TyEqFlags a
flags@(TEF { tef_unifying :: forall a. TyEqFlags a -> AreUnifying
tef_unifying = AreUnifying
unifying })
  = TyEqFlags a
flags { tef_fam_app  = TEFA_Recurse
          , tef_unifying = zap_promotion unifying
          , tef_occurs   = cteSolubleOccurs }
            -- tef_occurs: under a type family, an occurs check is not definitely-insoluble
  where
    zap_promotion :: AreUnifying -> AreUnifying
zap_promotion (Unifying MetaInfo
info TcLevel
lvl LevelCheck
LC_Promote) = MetaInfo -> TcLevel -> LevelCheck -> AreUnifying
Unifying MetaInfo
info TcLevel
lvl LevelCheck
LC_Check
    zap_promotion AreUnifying
unifying                       = AreUnifying
unifying

type FamAppBreaker a = TcType -> TcM (PuResult a Reduction)
     -- Given a family-application ty, return a Reduction :: ty ~ cvb
     -- where 'cbv' is a fresh loop-breaker tyvar (for Given), or
     -- just a fresh TauTv (for Wanted)

checkTyEqRhs :: forall a. TyEqFlags a -> TcType -> TcM (PuResult a Reduction)
checkTyEqRhs :: forall a. TyEqFlags a -> Type -> TcM (PuResult a Reduction)
checkTyEqRhs TyEqFlags a
flags Type
ty
  = case Type
ty of
      LitTy {}        -> Type -> TcM (PuResult a Reduction)
forall a. Type -> TcM (PuResult a Reduction)
okCheckRefl Type
ty
      TyConApp TyCon
tc [Type]
tys -> TyEqFlags a
-> Type -> TyCon -> [Type] -> TcM (PuResult a Reduction)
forall a.
TyEqFlags a
-> Type -> TyCon -> [Type] -> TcM (PuResult a Reduction)
checkTyConApp TyEqFlags a
flags Type
ty TyCon
tc [Type]
tys
      TyVarTy TcTyVar
tv      -> TyEqFlags a -> TcTyVar -> TcM (PuResult a Reduction)
forall a. TyEqFlags a -> TcTyVar -> TcM (PuResult a Reduction)
checkTyVar TyEqFlags a
flags TcTyVar
tv
        -- Don't worry about foralls inside the kind; see Note [Checking for foralls]
        -- Nor can we expand synonyms; see Note [Occurrence checking: look inside kinds]
        --                             in GHC.Core.FVs

      FunTy {ft_af :: Type -> FunTyFlag
ft_af = FunTyFlag
af, ft_mult :: Type -> Type
ft_mult = Type
w, ft_arg :: Type -> Type
ft_arg = Type
a, ft_res :: Type -> Type
ft_res = Type
r}
       | FunTyFlag -> Bool
isInvisibleFunArg FunTyFlag
af  -- e.g.  Num a => blah
       , Bool -> Bool
not (TyEqFlags a -> Bool
forall a. TyEqFlags a -> Bool
tef_foralls TyEqFlags a
flags)
       -> CheckTyEqResult -> TcM (PuResult a Reduction)
forall a b. CheckTyEqResult -> TcM (PuResult a b)
failCheckWith CheckTyEqResult
impredicativeProblem -- Not allowed (TyEq:F)
       | Bool
otherwise
       -> do { PuResult a Reduction
w_res <- TyEqFlags a -> Type -> TcM (PuResult a Reduction)
forall a. TyEqFlags a -> Type -> TcM (PuResult a Reduction)
checkTyEqRhs TyEqFlags a
flags Type
w
             ; PuResult a Reduction
a_res <- TyEqFlags a -> Type -> TcM (PuResult a Reduction)
forall a. TyEqFlags a -> Type -> TcM (PuResult a Reduction)
checkTyEqRhs TyEqFlags a
flags Type
a
             ; PuResult a Reduction
r_res <- TyEqFlags a -> Type -> TcM (PuResult a Reduction)
forall a. TyEqFlags a -> Type -> TcM (PuResult a Reduction)
checkTyEqRhs TyEqFlags a
flags Type
r
             ; PuResult a Reduction -> TcM (PuResult a Reduction)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Role
-> FunTyFlag -> Reduction -> Reduction -> Reduction -> Reduction
mkFunRedn Role
Nominal FunTyFlag
af (Reduction -> Reduction -> Reduction -> Reduction)
-> PuResult a Reduction
-> PuResult a (Reduction -> Reduction -> Reduction)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> PuResult a Reduction
w_res PuResult a (Reduction -> Reduction -> Reduction)
-> PuResult a Reduction -> PuResult a (Reduction -> Reduction)
forall a b. PuResult a (a -> b) -> PuResult a a -> PuResult a b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> PuResult a Reduction
a_res PuResult a (Reduction -> Reduction)
-> PuResult a Reduction -> PuResult a Reduction
forall a b. PuResult a (a -> b) -> PuResult a a -> PuResult a b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> PuResult a Reduction
r_res) }

      AppTy Type
fun Type
arg -> do { PuResult a Reduction
fun_res <- TyEqFlags a -> Type -> TcM (PuResult a Reduction)
forall a. TyEqFlags a -> Type -> TcM (PuResult a Reduction)
checkTyEqRhs TyEqFlags a
flags Type
fun
                          ; PuResult a Reduction
arg_res <- TyEqFlags a -> Type -> TcM (PuResult a Reduction)
forall a. TyEqFlags a -> Type -> TcM (PuResult a Reduction)
checkTyEqRhs TyEqFlags a
flags Type
arg
                          ; PuResult a Reduction -> TcM (PuResult a Reduction)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Reduction -> Reduction -> Reduction
mkAppRedn (Reduction -> Reduction -> Reduction)
-> PuResult a Reduction -> PuResult a (Reduction -> Reduction)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> PuResult a Reduction
fun_res PuResult a (Reduction -> Reduction)
-> PuResult a Reduction -> PuResult a Reduction
forall a b. PuResult a (a -> b) -> PuResult a a -> PuResult a b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> PuResult a Reduction
arg_res) }

      CastTy Type
ty Coercion
co  -> do { PuResult a Reduction
ty_res <- TyEqFlags a -> Type -> TcM (PuResult a Reduction)
forall a. TyEqFlags a -> Type -> TcM (PuResult a Reduction)
checkTyEqRhs TyEqFlags a
flags Type
ty
                          ; PuResult a Coercion
co_res <- TyEqFlags a -> Coercion -> TcM (PuResult a Coercion)
forall a. TyEqFlags a -> Coercion -> TcM (PuResult a Coercion)
checkCo TyEqFlags a
flags Coercion
co
                          ; PuResult a Reduction -> TcM (PuResult a Reduction)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Role -> Type -> Coercion -> Reduction -> Reduction
mkCastRedn1 Role
Nominal Type
ty (Coercion -> Reduction -> Reduction)
-> PuResult a Coercion -> PuResult a (Reduction -> Reduction)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> PuResult a Coercion
co_res PuResult a (Reduction -> Reduction)
-> PuResult a Reduction -> PuResult a Reduction
forall a b. PuResult a (a -> b) -> PuResult a a -> PuResult a b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> PuResult a Reduction
ty_res) }

      CoercionTy Coercion
co -> do { PuResult a Coercion
co_res <- TyEqFlags a -> Coercion -> TcM (PuResult a Coercion)
forall a. TyEqFlags a -> Coercion -> TcM (PuResult a Coercion)
checkCo TyEqFlags a
flags Coercion
co
                          ; PuResult a Reduction -> TcM (PuResult a Reduction)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Role -> Coercion -> Reduction
mkReflCoRedn Role
Nominal (Coercion -> Reduction)
-> PuResult a Coercion -> PuResult a Reduction
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> PuResult a Coercion
co_res) }

      ForAllTy {}
         | TyEqFlags a -> Bool
forall a. TyEqFlags a -> Bool
tef_foralls TyEqFlags a
flags -> Type -> TcM (PuResult a Reduction)
forall a. Type -> TcM (PuResult a Reduction)
okCheckRefl Type
ty
         | Bool
otherwise         -> CheckTyEqResult -> TcM (PuResult a Reduction)
forall a b. CheckTyEqResult -> TcM (PuResult a b)
failCheckWith CheckTyEqResult
impredicativeProblem  -- Not allowed (TyEq:F)


-------------------
checkCo :: TyEqFlags a -> Coercion -> TcM (PuResult a Coercion)
-- See Note [checkCo]
checkCo :: forall a. TyEqFlags a -> Coercion -> TcM (PuResult a Coercion)
checkCo (TEF { tef_lhs :: forall a. TyEqFlags a -> CanEqLHS
tef_lhs = TyFamLHS {} }) Coercion
co
  = PuResult a Coercion
-> IOEnv (Env TcGblEnv TcLclEnv) (PuResult a Coercion)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Coercion -> PuResult a Coercion
forall a. a -> PuResult a a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Coercion
co)

checkCo (TEF { tef_lhs :: forall a. TyEqFlags a -> CanEqLHS
tef_lhs = TyVarLHS TcTyVar
lhs_tv
             , tef_unifying :: forall a. TyEqFlags a -> AreUnifying
tef_unifying = AreUnifying
unifying
             , tef_occurs :: forall a. TyEqFlags a -> CheckTyEqProblem
tef_occurs = CheckTyEqProblem
occ_prob }) Coercion
co
  -- Check for coercion holes, if unifying
  -- See (COERCION-HOLE) in Note [Unification preconditions]
  | Coercion -> Bool
hasCoercionHoleCo Coercion
co
  = CheckTyEqResult
-> IOEnv (Env TcGblEnv TcLclEnv) (PuResult a Coercion)
forall a b. CheckTyEqResult -> TcM (PuResult a b)
failCheckWith (CheckTyEqProblem -> CheckTyEqResult
cteProblem CheckTyEqProblem
cteCoercionHole)

  -- Occurs check (can promote)
  | Unifying MetaInfo
_ TcLevel
lhs_tv_lvl LevelCheck
LC_Promote <- AreUnifying
unifying
  = do { CheckTyEqResult
reason <- CheckTyEqProblem
-> TcTyVar -> TcLevel -> VarSet -> TcM CheckTyEqResult
checkPromoteFreeVars CheckTyEqProblem
occ_prob TcTyVar
lhs_tv TcLevel
lhs_tv_lvl (Coercion -> VarSet
tyCoVarsOfCo Coercion
co)
       ; if CheckTyEqResult -> Bool
cterHasNoProblem CheckTyEqResult
reason
         then PuResult a Coercion
-> IOEnv (Env TcGblEnv TcLclEnv) (PuResult a Coercion)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Coercion -> PuResult a Coercion
forall a. a -> PuResult a a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Coercion
co)
         else CheckTyEqResult
-> IOEnv (Env TcGblEnv TcLclEnv) (PuResult a Coercion)
forall a b. CheckTyEqResult -> TcM (PuResult a b)
failCheckWith CheckTyEqResult
reason }

  -- Occurs check (no promotion)
  | TcTyVar
lhs_tv TcTyVar -> VarSet -> Bool
`elemVarSet` Coercion -> VarSet
tyCoVarsOfCo Coercion
co
  = CheckTyEqResult
-> IOEnv (Env TcGblEnv TcLclEnv) (PuResult a Coercion)
forall a b. CheckTyEqResult -> TcM (PuResult a b)
failCheckWith (CheckTyEqProblem -> CheckTyEqResult
cteProblem CheckTyEqProblem
occ_prob)

  | Bool
otherwise
  = PuResult a Coercion
-> IOEnv (Env TcGblEnv TcLclEnv) (PuResult a Coercion)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Coercion -> PuResult a Coercion
forall a. a -> PuResult a a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Coercion
co)

{- Note [checkCo]
~~~~~~~~~~~~~~~~~
We don't often care about the contents of coercions, so checking
coercions before making an equality constraint may be surprising.
But there are several cases we need to be wary of:

(1) When we're unifying a variable, we must make sure that the variable
    appears nowhere on the RHS -- even in a coercion. Otherwise, we'll
    create a loop.

(2) We must still make sure that no variable in a coercion is at too
    high a level. But, when unifying, we can promote any variables we encounter.

(3) We do not unify variables with a type with a free coercion hole.
    See (COERCION-HOLE) in Note [Unification preconditions].


Note [Promotion and level-checking]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"Promotion" happens when we have this:

  [W] w1: alpha[2] ~ Maybe beta[4]

Here we must NOT unify alpha := Maybe beta, because beta may turn out
to stand for a type involving some inner skolem.  Yikes!
Skolem-escape.  So instead we /promote/ beta, like this:

  beta[4] := beta'[2]
  [W] w1: alpha[2] ~ Maybe beta'[2]

Now we can unify alpha := Maybe beta', which might unlock other
constraints.  But if some other constraint wants to unify beta with a
nested skolem, it'll get stuck with a skolem-escape error.

Now consider `w2` where a type family is involved (#22194):

  [W] w2: alpha[2] ~ Maybe (F gamma beta[4])

In `w2`, it may or may not be the case that `beta` is level 2; suppose
we later discover gamma := Int, and type instance F Int _ = Int.
So, instead, we promote the entire funcion call:

  [W] w2': alpha[2] ~ Maybe gamma[2]
  [W] w3:  gamma[2] ~ F gamma beta[4]

Now we can unify alpha := Maybe gamma, which is a Good Thng.

Wrinkle (W1)

There is an important wrinkle: /all this only applies when unifying/.
For example, suppose we have
 [G] a[2] ~ Maybe b[4]
where 'a' is a skolem.  This Given might arise from a GADT match, and
we can absolutely use it to rewrite locally. In fact we must do so:
that is how we exploit local knowledge about the outer skolem a[2].
This applies equally for a Wanted [W] a[2] ~ Maybe b[4]. Using it for
local rewriting is fine. (It's not clear to me that it is /useful/,
but it's fine anyway.)

So we only do the level-check in checkTyVar when /unifying/ not for
skolems (or untouchable unification variables).

Note [Family applications in canonical constraints]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A constraint with a type family application in the RHS needs special care.

* First, occurs checks.  If we have
     [G] a ~ Maybe (F (Maybe a))
     [W] alpha ~ Maybe (F (Maybe alpha))
  it looks as if we have an occurs check.  But go read
  Note [Type equality cycles] in GHC.Tc.Solver.Equality

  The same considerations apply when the LHS is a type family:
     [G] G a ~ Maybe (F (Maybe (G a)))
     [W] G alpha ~ Maybe (F (Maybe (G alpha)))

* Second, promotion. If we have (#22194)
     [W] alpha[2] ~ Maybe (F beta[4])
  it is wrong to promote beta.  Instead we want to split to
     [W] alpha[2] ~ Maybe gamma[2]
     [W] gamma[2] ~ F beta[4]
  See Note [Promotion and level-checking] above.

* Third, concrete type variables.  If we have
     [W] alpha[conc] ~ Maybe (F tys)
  we want to add an extra variable thus:
     [W] alpha[conc] ~ Maybe gamma[conc]
     [W] gamma[conc] ~ F tys
  Now we can unify alpha, and that might unlock something else.

In all these cases we want to create a fresh type variable, and
emit a new equality connecting it to the type family application.

The `tef_fam_app` field of `TypeEqFlags` says what to do at a type
family application in the RHS of the constraint.  `TEFA_Fail` and
`TEFA_Recurse` are straightforward.  `TEFA_Break` is the clever
one. As you can see in `checkFamApp`, it
  * Checks the arguments, but using `famAppArgFlags` to record that
    we are now "under" a type-family application. It `tef_fam_app` to
    `TEFA_Recurse`.
  * If any of the arguments fail (level-check error, occurs check)
    use the `FamAppBreaker` to create the extra binding.

Note that this always cycle-breaks the /outermost/ family application.
If we have  [W] alpha ~ Maybe (F (G alpha))
* We'll use checkFamApp on `(F (G alpha))`
* It will recurse into `(G alpha)` with TEFA_Recurse, but not cycle-break it
* The occurs check will fire when we hit `alpha`
* `checkFamApp` on `(F (G alpha))` will see the failure and invoke
  the `FamAppBreaker`.
-}

-------------------
checkTyConApp :: TyEqFlags a
              -> TcType -> TyCon -> [TcType]
              -> TcM (PuResult a Reduction)
checkTyConApp :: forall a.
TyEqFlags a
-> Type -> TyCon -> [Type] -> TcM (PuResult a Reduction)
checkTyConApp flags :: TyEqFlags a
flags@(TEF { tef_unifying :: forall a. TyEqFlags a -> AreUnifying
tef_unifying = AreUnifying
unifying, tef_foralls :: forall a. TyEqFlags a -> Bool
tef_foralls = Bool
foralls_ok })
              Type
tc_app TyCon
tc [Type]
tys
  | TyCon -> Bool
isTypeFamilyTyCon TyCon
tc
  , let arity :: Int
arity = TyCon -> Int
tyConArity TyCon
tc
  = if [Type]
tys [Type] -> Int -> Bool
forall a. [a] -> Int -> Bool
`lengthIs` Int
arity
    then TyEqFlags a
-> Type -> TyCon -> [Type] -> TcM (PuResult a Reduction)
forall a.
TyEqFlags a
-> Type -> TyCon -> [Type] -> TcM (PuResult a Reduction)
checkFamApp TyEqFlags a
flags Type
tc_app TyCon
tc [Type]
tys  -- Common case
    else do { let ([Type]
fun_args, [Type]
extra_args) = Int -> [Type] -> ([Type], [Type])
forall a. Int -> [a] -> ([a], [a])
splitAt (TyCon -> Int
tyConArity TyCon
tc) [Type]
tys
                  fun_app :: Type
fun_app                = TyCon -> [Type] -> Type
mkTyConApp TyCon
tc [Type]
fun_args
            ; PuResult a Reduction
fun_res   <- TyEqFlags a
-> Type -> TyCon -> [Type] -> TcM (PuResult a Reduction)
forall a.
TyEqFlags a
-> Type -> TyCon -> [Type] -> TcM (PuResult a Reduction)
checkFamApp TyEqFlags a
flags Type
fun_app TyCon
tc [Type]
fun_args
            ; PuResult a Reductions
extra_res <- (Type -> TcM (PuResult a Reduction))
-> [Type] -> TcM (PuResult a Reductions)
forall x a.
(x -> TcM (PuResult a Reduction))
-> [x] -> TcM (PuResult a Reductions)
mapCheck (TyEqFlags a -> Type -> TcM (PuResult a Reduction)
forall a. TyEqFlags a -> Type -> TcM (PuResult a Reduction)
checkTyEqRhs TyEqFlags a
flags) [Type]
extra_args
            ; String -> SDoc -> TcM ()
traceTc String
"Over-sat" (TyCon -> SDoc
forall a. Outputable a => a -> SDoc
ppr TyCon
tc SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> [Type] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [Type]
tys SDoc -> SDoc -> SDoc
forall doc. IsDoc doc => doc -> doc -> doc
$$ Int -> SDoc
forall a. Outputable a => a -> SDoc
ppr Int
arity SDoc -> SDoc -> SDoc
forall doc. IsDoc doc => doc -> doc -> doc
$$ PuResult a Reduction -> SDoc
forall a b. PuResult a b -> SDoc
pprPur PuResult a Reduction
fun_res SDoc -> SDoc -> SDoc
forall doc. IsDoc doc => doc -> doc -> doc
$$ PuResult a Reductions -> SDoc
forall a b. PuResult a b -> SDoc
pprPur PuResult a Reductions
extra_res)
            ; PuResult a Reduction -> TcM (PuResult a Reduction)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Reduction -> Reductions -> Reduction
mkAppRedns (Reduction -> Reductions -> Reduction)
-> PuResult a Reduction -> PuResult a (Reductions -> Reduction)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> PuResult a Reduction
fun_res PuResult a (Reductions -> Reduction)
-> PuResult a Reductions -> PuResult a Reduction
forall a b. PuResult a (a -> b) -> PuResult a a -> PuResult a b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> PuResult a Reductions
extra_res) }

  | Just Type
ty' <- Type -> Maybe Type
rewriterView Type
tc_app
       -- e.g. S a  where  type S a = F [a]
       --             or   type S a = Int
       -- See Note [Forgetful synonyms in checkTyConApp]
  = TyEqFlags a -> Type -> TcM (PuResult a Reduction)
forall a. TyEqFlags a -> Type -> TcM (PuResult a Reduction)
checkTyEqRhs TyEqFlags a
flags Type
ty'

  | Bool -> Bool
not (TyCon -> Bool
isTauTyCon TyCon
tc Bool -> Bool -> Bool
|| Bool
foralls_ok)
  = CheckTyEqResult -> TcM (PuResult a Reduction)
forall a b. CheckTyEqResult -> TcM (PuResult a b)
failCheckWith CheckTyEqResult
impredicativeProblem

  | Unifying MetaInfo
info TcLevel
_ LevelCheck
_ <- AreUnifying
unifying
  , MetaInfo -> Bool
isConcreteInfo MetaInfo
info
  , Bool -> Bool
not (TyCon -> Bool
isConcreteTyCon TyCon
tc)
  = CheckTyEqResult -> TcM (PuResult a Reduction)
forall a b. CheckTyEqResult -> TcM (PuResult a b)
failCheckWith (CheckTyEqProblem -> CheckTyEqResult
cteProblem CheckTyEqProblem
cteConcrete)

  | Bool
otherwise  -- Recurse on arguments
  = TyEqFlags a -> TyCon -> [Type] -> TcM (PuResult a Reduction)
forall a.
TyEqFlags a -> TyCon -> [Type] -> TcM (PuResult a Reduction)
recurseIntoTyConApp TyEqFlags a
flags TyCon
tc [Type]
tys

recurseIntoTyConApp :: TyEqFlags a -> TyCon -> [TcType] -> TcM (PuResult a Reduction)
recurseIntoTyConApp :: forall a.
TyEqFlags a -> TyCon -> [Type] -> TcM (PuResult a Reduction)
recurseIntoTyConApp TyEqFlags a
flags TyCon
tc [Type]
tys
  = do { PuResult a Reductions
tys_res <- (Type -> TcM (PuResult a Reduction))
-> [Type] -> TcM (PuResult a Reductions)
forall x a.
(x -> TcM (PuResult a Reduction))
-> [x] -> TcM (PuResult a Reductions)
mapCheck (TyEqFlags a -> Type -> TcM (PuResult a Reduction)
forall a. TyEqFlags a -> Type -> TcM (PuResult a Reduction)
checkTyEqRhs TyEqFlags a
flags) [Type]
tys
       ; PuResult a Reduction -> TcM (PuResult a Reduction)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Role -> TyCon -> Reductions -> Reduction
mkTyConAppRedn Role
Nominal TyCon
tc (Reductions -> Reduction)
-> PuResult a Reductions -> PuResult a Reduction
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> PuResult a Reductions
tys_res) }

-------------------
checkFamApp :: TyEqFlags a
            -> TcType -> TyCon -> [TcType]  -- Saturated family application
            -> TcM (PuResult a Reduction)
-- See Note [Family applications in canonical constraints]
checkFamApp :: forall a.
TyEqFlags a
-> Type -> TyCon -> [Type] -> TcM (PuResult a Reduction)
checkFamApp flags :: TyEqFlags a
flags@(TEF { tef_unifying :: forall a. TyEqFlags a -> AreUnifying
tef_unifying = AreUnifying
unifying, tef_occurs :: forall a. TyEqFlags a -> CheckTyEqProblem
tef_occurs = CheckTyEqProblem
occ_prob
                       , tef_fam_app :: forall a. TyEqFlags a -> TyEqFamApp a
tef_fam_app = TyEqFamApp a
fam_app_flag, tef_lhs :: forall a. TyEqFlags a -> CanEqLHS
tef_lhs = CanEqLHS
lhs })
            Type
fam_app TyCon
tc [Type]
tys
  = case TyEqFamApp a
fam_app_flag of
      TyEqFamApp a
TEFA_Fail -> CheckTyEqResult -> TcM (PuResult a Reduction)
forall a b. CheckTyEqResult -> TcM (PuResult a b)
failCheckWith (CheckTyEqProblem -> CheckTyEqResult
cteProblem CheckTyEqProblem
cteTypeFamily)

      TyEqFamApp a
_ | TyFamLHS TyCon
lhs_tc [Type]
lhs_tys <- CanEqLHS
lhs
        , TyCon -> [Type] -> TyCon -> [Type] -> Bool
tcEqTyConApps TyCon
lhs_tc [Type]
lhs_tys TyCon
tc [Type]
tys   -- F ty ~ ...(F ty)...
        -> case TyEqFamApp a
fam_app_flag of
             TyEqFamApp a
TEFA_Recurse       -> CheckTyEqResult -> TcM (PuResult a Reduction)
forall a b. CheckTyEqResult -> TcM (PuResult a b)
failCheckWith (CheckTyEqProblem -> CheckTyEqResult
cteProblem CheckTyEqProblem
occ_prob)
             TEFA_Break FamAppBreaker a
breaker -> FamAppBreaker a
breaker Type
fam_app

      TyEqFamApp a
_ | Unifying MetaInfo
lhs_info TcLevel
_ LevelCheck
_ <- AreUnifying
unifying
        , MetaInfo -> Bool
isConcreteInfo MetaInfo
lhs_info
        -> case TyEqFamApp a
fam_app_flag of
             TyEqFamApp a
TEFA_Recurse       -> CheckTyEqResult -> TcM (PuResult a Reduction)
forall a b. CheckTyEqResult -> TcM (PuResult a b)
failCheckWith (CheckTyEqProblem -> CheckTyEqResult
cteProblem CheckTyEqProblem
cteConcrete)
             TEFA_Break FamAppBreaker a
breaker -> FamAppBreaker a
breaker Type
fam_app

      TyEqFamApp a
TEFA_Recurse
        -> do { PuResult a Reductions
tys_res <- FamAppBreaker a -> [Type] -> TcM (PuResult a Reductions)
forall x a.
(x -> TcM (PuResult a Reduction))
-> [x] -> TcM (PuResult a Reductions)
mapCheck (TyEqFlags a -> FamAppBreaker a
forall a. TyEqFlags a -> Type -> TcM (PuResult a Reduction)
checkTyEqRhs TyEqFlags a
arg_flags) [Type]
tys
              ; String -> SDoc -> TcM ()
traceTc String
"under" (TyCon -> SDoc
forall a. Outputable a => a -> SDoc
ppr TyCon
tc SDoc -> SDoc -> SDoc
forall doc. IsDoc doc => doc -> doc -> doc
$$ PuResult a Reductions -> SDoc
forall a b. PuResult a b -> SDoc
pprPur PuResult a Reductions
tys_res SDoc -> SDoc -> SDoc
forall doc. IsDoc doc => doc -> doc -> doc
$$ TyEqFlags a -> SDoc
forall a. Outputable a => a -> SDoc
ppr TyEqFlags a
flags)
              ; PuResult a Reduction -> TcM (PuResult a Reduction)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Role -> TyCon -> Reductions -> Reduction
mkTyConAppRedn Role
Nominal TyCon
tc (Reductions -> Reduction)
-> PuResult a Reductions -> PuResult a Reduction
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> PuResult a Reductions
tys_res) }

      TEFA_Break FamAppBreaker a
breaker    -- Recurse; and break if there is a problem
        -> do { PuResult a Reductions
tys_res <- FamAppBreaker a -> [Type] -> TcM (PuResult a Reductions)
forall x a.
(x -> TcM (PuResult a Reduction))
-> [x] -> TcM (PuResult a Reductions)
mapCheck (TyEqFlags a -> FamAppBreaker a
forall a. TyEqFlags a -> Type -> TcM (PuResult a Reduction)
checkTyEqRhs TyEqFlags a
arg_flags) [Type]
tys
              ; case PuResult a Reductions
tys_res of
                  PuOK Bag a
cts Reductions
redns -> PuResult a Reduction -> TcM (PuResult a Reduction)
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Bag a -> Reduction -> PuResult a Reduction
forall a b. Bag a -> b -> PuResult a b
PuOK Bag a
cts (Role -> TyCon -> Reductions -> Reduction
mkTyConAppRedn Role
Nominal TyCon
tc Reductions
redns))
                  PuFail {}      -> FamAppBreaker a
breaker Type
fam_app }
  where
    arg_flags :: TyEqFlags a
arg_flags = TyEqFlags a -> TyEqFlags a
forall a. TyEqFlags a -> TyEqFlags a
famAppArgFlags TyEqFlags a
flags

-------------------
checkTyVar :: forall a. TyEqFlags a -> TcTyVar -> TcM (PuResult a Reduction)
checkTyVar :: forall a. TyEqFlags a -> TcTyVar -> TcM (PuResult a Reduction)
checkTyVar (TEF { tef_lhs :: forall a. TyEqFlags a -> CanEqLHS
tef_lhs = CanEqLHS
lhs, tef_unifying :: forall a. TyEqFlags a -> AreUnifying
tef_unifying = AreUnifying
unifying, tef_occurs :: forall a. TyEqFlags a -> CheckTyEqProblem
tef_occurs = CheckTyEqProblem
occ_prob }) TcTyVar
occ_tv
  = case CanEqLHS
lhs of
      TyFamLHS {}     -> TcM (PuResult a Reduction)
success   -- Nothing to do if the LHS is a type-family
      TyVarLHS TcTyVar
lhs_tv -> AreUnifying -> TcTyVar -> TcM (PuResult a Reduction)
check_tv AreUnifying
unifying TcTyVar
lhs_tv
  where
    lvl_occ :: TcLevel
lvl_occ = TcTyVar -> TcLevel
tcTyVarLevel TcTyVar
occ_tv
    success :: TcM (PuResult a Reduction)
success = Type -> TcM (PuResult a Reduction)
forall a. Type -> TcM (PuResult a Reduction)
okCheckRefl (TcTyVar -> Type
mkTyVarTy TcTyVar
occ_tv)

    ---------------------
    check_tv :: AreUnifying -> TcTyVar -> TcM (PuResult a Reduction)
check_tv AreUnifying
NotUnifying TcTyVar
lhs_tv
      = TcTyVar -> TcM (PuResult a Reduction)
simple_occurs_check TcTyVar
lhs_tv
      -- We need an occurs-check here, but no level check
      -- See Note [Promotion and level-checking] wrinkle (W1)

    check_tv (Unifying MetaInfo
info TcLevel
lvl LevelCheck
prom) TcTyVar
lhs_tv
      = do { Maybe Type
mb_done <- TcTyVar -> IOEnv (Env TcGblEnv TcLclEnv) (Maybe Type)
isFilledMetaTyVar_maybe TcTyVar
occ_tv
           ; case Maybe Type
mb_done of
               Just {} -> TcM (PuResult a Reduction)
success
               -- Already promoted; job done
               -- Example alpha[2] ~ Maybe (beta[4], beta[4])
               -- We promote the first occurrence, and then encounter it
               -- a second time; we don't want to re-promote it!
               -- Remember, the entire process started with a fully zonked type

               Maybe Type
Nothing -> MetaInfo
-> TcLevel -> LevelCheck -> TcTyVar -> TcM (PuResult a Reduction)
check_unif MetaInfo
info TcLevel
lvl LevelCheck
prom TcTyVar
lhs_tv }

    ---------------------
    -- We are in the Unifying branch of AreUnifing
    check_unif :: MetaInfo -> TcLevel -> LevelCheck
               -> TcTyVar -> TcM (PuResult a Reduction)
    check_unif :: MetaInfo
-> TcLevel -> LevelCheck -> TcTyVar -> TcM (PuResult a Reduction)
check_unif MetaInfo
lhs_tv_info TcLevel
lhs_tv_lvl LevelCheck
prom TcTyVar
lhs_tv
      | MetaInfo -> Bool
isConcreteInfo MetaInfo
lhs_tv_info
      , Bool -> Bool
not (TcTyVar -> Bool
isConcreteTyVar TcTyVar
occ_tv)
      = if TcTyVar -> Bool
can_make_concrete TcTyVar
occ_tv
        then TcTyVar -> MetaInfo -> TcLevel -> TcM (PuResult a Reduction)
promote TcTyVar
lhs_tv MetaInfo
lhs_tv_info TcLevel
lhs_tv_lvl
        else CheckTyEqResult -> TcM (PuResult a Reduction)
forall a b. CheckTyEqResult -> TcM (PuResult a b)
failCheckWith (CheckTyEqProblem -> CheckTyEqResult
cteProblem CheckTyEqProblem
cteConcrete)

      | TcLevel
lvl_occ TcLevel -> TcLevel -> Bool
`strictlyDeeperThan` TcLevel
lhs_tv_lvl
      = case LevelCheck
prom of
           LevelCheck
LC_None    -> String -> SDoc -> TcM (PuResult a Reduction)
forall a. HasCallStack => String -> SDoc -> a
pprPanic String
"check_unif" (TcTyVar -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcTyVar
lhs_tv SDoc -> SDoc -> SDoc
forall doc. IsDoc doc => doc -> doc -> doc
$$ TcTyVar -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcTyVar
occ_tv)
           LevelCheck
LC_Check   -> CheckTyEqResult -> TcM (PuResult a Reduction)
forall a b. CheckTyEqResult -> TcM (PuResult a b)
failCheckWith (CheckTyEqProblem -> CheckTyEqResult
cteProblem CheckTyEqProblem
cteSkolemEscape)
           LevelCheck
LC_Promote
             | TcTyVar -> Bool
isSkolemTyVar TcTyVar
occ_tv  -> CheckTyEqResult -> TcM (PuResult a Reduction)
forall a b. CheckTyEqResult -> TcM (PuResult a b)
failCheckWith (CheckTyEqProblem -> CheckTyEqResult
cteProblem CheckTyEqProblem
cteSkolemEscape)
             | Bool
otherwise             -> TcTyVar -> MetaInfo -> TcLevel -> TcM (PuResult a Reduction)
promote TcTyVar
lhs_tv MetaInfo
lhs_tv_info TcLevel
lhs_tv_lvl

      | Bool
otherwise
      = TcTyVar -> TcM (PuResult a Reduction)
simple_occurs_check TcTyVar
lhs_tv

    ---------------------
    simple_occurs_check :: TcTyVar -> TcM (PuResult a Reduction)
simple_occurs_check TcTyVar
lhs_tv
      | TcTyVar
lhs_tv TcTyVar -> TcTyVar -> Bool
forall a. Eq a => a -> a -> Bool
== TcTyVar
occ_tv Bool -> Bool -> Bool
|| Type -> Bool
check_kind (TcTyVar -> Type
tyVarKind TcTyVar
occ_tv)
      = CheckTyEqResult -> TcM (PuResult a Reduction)
forall a b. CheckTyEqResult -> TcM (PuResult a b)
failCheckWith (CheckTyEqProblem -> CheckTyEqResult
cteProblem CheckTyEqProblem
occ_prob)
      | Bool
otherwise
      = TcM (PuResult a Reduction)
success
      where
        (Type -> Bool
check_kind, Coercion -> Bool
_) = TcTyVar -> (Type -> Bool, Coercion -> Bool)
mkOccFolders TcTyVar
lhs_tv

    ---------------------
    can_make_concrete :: TcTyVar -> Bool
can_make_concrete TcTyVar
occ_tv = case TcTyVar -> TcTyVarDetails
tcTyVarDetails TcTyVar
occ_tv of
      MetaTv { mtv_info :: TcTyVarDetails -> MetaInfo
mtv_info = MetaInfo
info } -> case MetaInfo
info of
                                      ConcreteTv {} -> Bool
True
                                      TauTv {}      -> Bool
True
                                      MetaInfo
_             -> Bool
False
      TcTyVarDetails
_ -> Bool
False  -- Don't attempt to make other type variables concrete
                  -- (e.g. SkolemTv, TyVarTv, CycleBreakerTv, RuntimeUnkTv).

    ---------------------
    -- occ_tv is definitely a MetaTyVar
    promote :: TcTyVar -> MetaInfo -> TcLevel -> TcM (PuResult a Reduction)
promote TcTyVar
lhs_tv MetaInfo
lhs_tv_info TcLevel
lhs_tv_lvl
      | MetaTv { mtv_info :: TcTyVarDetails -> MetaInfo
mtv_info = MetaInfo
info_occ, mtv_tclvl :: TcTyVarDetails -> TcLevel
mtv_tclvl = TcLevel
lvl_occ } <- TcTyVar -> TcTyVarDetails
tcTyVarDetails TcTyVar
occ_tv
      = do { let new_info :: MetaInfo
new_info | MetaInfo -> Bool
isConcreteInfo MetaInfo
lhs_tv_info = MetaInfo
lhs_tv_info
                          | Bool
otherwise                  = MetaInfo
info_occ
                 new_lvl :: TcLevel
new_lvl = TcLevel
lhs_tv_lvl TcLevel -> TcLevel -> TcLevel
`minTcLevel` TcLevel
lvl_occ
                           -- c[conc,3] ~ p[tau,2]: want to clone p:=p'[conc,2]
                           -- c[tau,2]  ~ p[tau,3]: want to clone p:=p'[tau,2]

           -- Check the kind of occ_tv
           ; CheckTyEqResult
reason <- CheckTyEqProblem
-> TcTyVar -> TcLevel -> VarSet -> TcM CheckTyEqResult
checkPromoteFreeVars CheckTyEqProblem
occ_prob TcTyVar
lhs_tv TcLevel
lhs_tv_lvl (Type -> VarSet
tyCoVarsOfType (TcTyVar -> Type
tyVarKind TcTyVar
occ_tv))

           ; if CheckTyEqResult -> Bool
cterHasNoProblem CheckTyEqResult
reason  -- Successfully promoted
             then do { Type
new_tv_ty <- MetaInfo -> TcLevel -> TcTyVar -> TcM Type
promote_meta_tyvar MetaInfo
new_info TcLevel
new_lvl TcTyVar
occ_tv
                     ; Type -> TcM (PuResult a Reduction)
forall a. Type -> TcM (PuResult a Reduction)
okCheckRefl Type
new_tv_ty }
             else CheckTyEqResult -> TcM (PuResult a Reduction)
forall a b. CheckTyEqResult -> TcM (PuResult a b)
failCheckWith CheckTyEqResult
reason }

      | Bool
otherwise = String -> SDoc -> TcM (PuResult a Reduction)
forall a. HasCallStack => String -> SDoc -> a
pprPanic String
"promote" (TcTyVar -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcTyVar
occ_tv)

-------------------------
checkPromoteFreeVars :: CheckTyEqProblem    -- What occurs check problem to report
                     -> TcTyVar -> TcLevel
                     -> TyCoVarSet -> TcM CheckTyEqResult
-- Check this set of TyCoVars for
--   (a) occurs check
--   (b) promote if necessary, or report skolem escape
checkPromoteFreeVars :: CheckTyEqProblem
-> TcTyVar -> TcLevel -> VarSet -> TcM CheckTyEqResult
checkPromoteFreeVars CheckTyEqProblem
occ_prob TcTyVar
lhs_tv TcLevel
lhs_tv_lvl VarSet
vs
  = do { [CheckTyEqResult]
oks <- (TcTyVar -> TcM CheckTyEqResult)
-> [TcTyVar] -> IOEnv (Env TcGblEnv TcLclEnv) [CheckTyEqResult]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
forall (m :: * -> *) a b. Monad m => (a -> m b) -> [a] -> m [b]
mapM TcTyVar -> TcM CheckTyEqResult
do_one (VarSet -> [TcTyVar]
forall elt. UniqSet elt -> [elt]
nonDetEltsUniqSet VarSet
vs)
       ; CheckTyEqResult -> TcM CheckTyEqResult
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return ([CheckTyEqResult] -> CheckTyEqResult
forall a. Monoid a => [a] -> a
mconcat [CheckTyEqResult]
oks) }
  where
    do_one :: TyCoVar -> TcM CheckTyEqResult
    do_one :: TcTyVar -> TcM CheckTyEqResult
do_one TcTyVar
v | TcTyVar -> Bool
isCoVar TcTyVar
v           = CheckTyEqResult -> TcM CheckTyEqResult
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return CheckTyEqResult
cteOK
             | TcTyVar
lhs_tv TcTyVar -> TcTyVar -> Bool
forall a. Eq a => a -> a -> Bool
== TcTyVar
v         = CheckTyEqResult -> TcM CheckTyEqResult
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (CheckTyEqProblem -> CheckTyEqResult
cteProblem CheckTyEqProblem
occ_prob)
             | Bool
no_promotion        = CheckTyEqResult -> TcM CheckTyEqResult
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return CheckTyEqResult
cteOK
             | Bool -> Bool
not (TcTyVar -> Bool
isMetaTyVar TcTyVar
v) = CheckTyEqResult -> TcM CheckTyEqResult
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (CheckTyEqProblem -> CheckTyEqResult
cteProblem CheckTyEqProblem
cteSkolemEscape)
             | Bool
otherwise           = TcTyVar -> TcM CheckTyEqResult
promote_one TcTyVar
v
      where
        no_promotion :: Bool
no_promotion = Bool -> Bool
not (TcTyVar -> TcLevel
tcTyVarLevel TcTyVar
v TcLevel -> TcLevel -> Bool
`strictlyDeeperThan` TcLevel
lhs_tv_lvl)

    -- isCoVar case: coercion variables are not an escape risk
    -- If an implication binds a coercion variable, it'll have equalities,
    -- so the "intervening given equalities" test above will catch it
    -- Coercion holes get filled with coercions, so again no problem.

    promote_one :: TcTyVar -> TcM CheckTyEqResult
promote_one TcTyVar
tv = do { Type
_ <- MetaInfo -> TcLevel -> TcTyVar -> TcM Type
promote_meta_tyvar MetaInfo
TauTv TcLevel
lhs_tv_lvl TcTyVar
tv
                        ; CheckTyEqResult -> TcM CheckTyEqResult
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return CheckTyEqResult
cteOK }

promote_meta_tyvar :: MetaInfo -> TcLevel -> TcTyVar -> TcM TcType
promote_meta_tyvar :: MetaInfo -> TcLevel -> TcTyVar -> TcM Type
promote_meta_tyvar MetaInfo
info TcLevel
dest_lvl TcTyVar
occ_tv
  = do { -- Check whether occ_tv is already unified. The rhs-type
         -- started zonked, but we may have promoted one of its type
         -- variables, and we then encounter it for the second time.
         -- But if so, it'll definitely be another already-checked TyVar
         Maybe Type
mb_filled <- TcTyVar -> IOEnv (Env TcGblEnv TcLclEnv) (Maybe Type)
isFilledMetaTyVar_maybe TcTyVar
occ_tv
       ; case Maybe Type
mb_filled of {
           Just Type
ty -> Type -> TcM Type
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return Type
ty ;
           Maybe Type
Nothing ->

    -- OK, not done already, so clone/promote it
    do { TcTyVar
new_tv <- MetaInfo -> TcLevel -> TcTyVar -> TcM TcTyVar
cloneMetaTyVarWithInfo MetaInfo
info TcLevel
dest_lvl TcTyVar
occ_tv
       ; ZonkM () -> TcM ()
forall a. ZonkM a -> TcM a
liftZonkM (ZonkM () -> TcM ()) -> ZonkM () -> TcM ()
forall a b. (a -> b) -> a -> b
$ HasDebugCallStack => TcTyVar -> Type -> ZonkM ()
TcTyVar -> Type -> ZonkM ()
writeMetaTyVar TcTyVar
occ_tv (TcTyVar -> Type
mkTyVarTy TcTyVar
new_tv)
       ; String -> SDoc -> TcM ()
traceTc String
"promoteTyVar" (TcTyVar -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcTyVar
occ_tv SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> String -> SDoc
forall doc. IsLine doc => String -> doc
text String
"-->" SDoc -> SDoc -> SDoc
forall doc. IsLine doc => doc -> doc -> doc
<+> TcTyVar -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcTyVar
new_tv)
       ; Type -> TcM Type
forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
forall (m :: * -> *) a. Monad m => a -> m a
return (TcTyVar -> Type
mkTyVarTy TcTyVar
new_tv) } } }



-------------------------
touchabilityAndShapeTest :: TcLevel -> TcTyVar -> TcType -> Bool
-- This is the key test for untouchability:
-- See Note [Unification preconditions] in GHC.Tc.Utils.Unify
-- and Note [Solve by unification] in GHC.Tc.Solver.Equality
-- True <=> touchability and shape are OK
touchabilityAndShapeTest :: TcLevel -> TcTyVar -> Type -> Bool
touchabilityAndShapeTest TcLevel
given_eq_lvl TcTyVar
tv Type
rhs
  | MetaTv { mtv_info :: TcTyVarDetails -> MetaInfo
mtv_info = MetaInfo
info, mtv_tclvl :: TcTyVarDetails -> TcLevel
mtv_tclvl = TcLevel
tv_lvl } <- TcTyVar -> TcTyVarDetails
tcTyVarDetails TcTyVar
tv
  , MetaInfo -> Type -> Bool
checkTopShape MetaInfo
info Type
rhs
  = TcLevel
tv_lvl TcLevel -> TcLevel -> Bool
`deeperThanOrSame` TcLevel
given_eq_lvl
  | Bool
otherwise
  = Bool
False

-------------------------
-- | checkTopShape checks (TYVAR-TV)
-- Note [Unification preconditions]; returns True if these conditions
-- are satisfied. But see the Note for other preconditions, too.
checkTopShape :: MetaInfo -> TcType -> Bool
checkTopShape :: MetaInfo -> Type -> Bool
checkTopShape MetaInfo
info Type
xi
  = case MetaInfo
info of
      MetaInfo
TyVarTv ->
        case Type -> Maybe TcTyVar
getTyVar_maybe Type
xi of   -- Looks through type synonyms
           Maybe TcTyVar
Nothing -> Bool
False
           Just TcTyVar
tv -> case TcTyVar -> TcTyVarDetails
tcTyVarDetails TcTyVar
tv of -- (TYVAR-TV) wrinkle
                        SkolemTv {} -> Bool
True
                        TcTyVarDetails
RuntimeUnk  -> Bool
True
                        MetaTv { mtv_info :: TcTyVarDetails -> MetaInfo
mtv_info = MetaInfo
TyVarTv } -> Bool
True
                        TcTyVarDetails
_                             -> Bool
False
      MetaInfo
CycleBreakerTv -> Bool
False  -- We never unify these
      MetaInfo
_ -> Bool
True