    {-# LANGUAGE DataKinds           #-}
    {-# LANGUAGE DeriveTraversable   #-}
    {-# LANGUAGE DerivingStrategies  #-}
    {-# LANGUAGE LambdaCase          #-}
    {-# LANGUAGE ScopedTypeVariables #-}
    {-# LANGUAGE TupleSections       #-}
    {-# LANGUAGE RecursiveDo         #-}
    {-# LANGUAGE MultiWayIf          #-}
    {-# LANGUAGE RecordWildCards     #-}
    {-# LANGUAGE TypeApplications    #-}

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

      -- Skolemisation
      DeepSubsumptionFlag(..), getDeepSubsumptionFlag, isRhoTyDS,
      tcSkolemise, tcSkolemiseCompleteSig, tcSkolemiseExpectedType,
      dsInstantiate,

      -- Various unifications
      unifyType, unifyKind, unifyInvisibleType,
      unifyExprType, unifyTypeAndEmit, promoteTcType,
      swapOverTyVars, touchabilityTest, checkTopShape, lhsPriority,
      UnifyEnv(..), updUEnvLoc, setUEnvRole,
      uType,
      mightEqualLater,
      makeTypeConcrete,

      --------------------------------
      -- Holes
      matchExpectedListTy,
      matchExpectedTyConApp,
      matchExpectedAppTy,
      matchExpectedFunTys,
      matchExpectedFunKind,
      matchActualFunTy, matchActualFunTys,

      checkTyEqRhs, recurseIntoTyConApp, recurseIntoFamTyConApp,
      PuResult(..), okCheckRefl, mapCheck,
      TyEqFlags(..),
      notUnifying_TEFTask, unifyingLHSMetaTyVar_TEFTask, defaulting_TEFTask,
      pureTyEqFlags_LHSMetaTyVar, mkTEFA_Break,

      OccursCheck(..), LevelCheck(..), ConcreteCheck(..),
      TyEqFamApp(..), FamAppBreaker(..),
      checkPromoteFreeVars,

      simpleUnifyCheck, UnifyCheckCaller(..), SimpleUnifyResult(..),

      fillInferResult, fillInferResultNoInst
      ) where

    import GHC.Prelude

    import GHC.Hs

    import GHC.Tc.Errors.Types ( ErrCtxtMsg(..) )
    import GHC.Tc.Errors.Ppr   ( pprErrCtxtMsg )
    import GHC.Tc.Utils.Concrete
    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.CtLoc( CtLoc, mkKindEqLoc, adjustCtLoc, updateCtLocOrigin, ctLocOrigin )
    import GHC.Tc.Types.Origin
    import GHC.Tc.Zonk.TcType
    import GHC.Tc.Utils.TcMType qualified as TcM

    import GHC.Tc.Solver.InertSet

    import GHC.Core.Type
    import GHC.Core.TyCo.Rep hiding (Refl)
    import GHC.Core.TyCo.FVs( isInjectiveInType )
    import GHC.Core.TyCo.Ppr( debugPprType {- pprTyVar -} )
    import GHC.Core.TyCon
    import GHC.Core.Coercion
    import GHC.Core.Unify
    import GHC.Core.Predicate( EqRel(..), mkEqPredRole, mkNomEqPred )
    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.Id( idType )
    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.Misc
    import GHC.Utils.Outputable as Outputable
    import GHC.Utils.Panic

    import GHC.Driver.DynFlags

    import GHC.Data.Bag
    import GHC.Data.FastString
    import GHC.Data.Maybe (firstJusts)

    import Control.Monad
    import Data.Functor.Identity (Identity(..))
    import qualified Data.List.NonEmpty as NE
    import Data.Monoid as DM ( Any(..) )
    import qualified Data.Semigroup as S ( (<>) )
    import Data.Traversable (for)

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

    -- | 'matchActualFunTy' 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].
    matchActualFunTy
      :: ExpectedFunTyOrigin
          -- ^ See Note [Herald for matchExpectedFunTys]
      -> Maybe TypedThing
          -- ^ The thing with type TcSigmaType
      -> (Arity, TcType)
          -- ^ Total number of value args in the call, and
          --   the original function type
          -- (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) = matchActualFunTy ... fun_ty
    -- then wrap :: fun_ty ~> (arg_ty -> res_ty)
    -- and NB: res_ty is an (uninstantiated) SigmaType

    matchActualFunTy :: ExpectedFunTyOrigin
    -> Maybe TypedThing
    -> (Int, TcType)
    -> TcType
    -> TcM (HsWrapper, Scaled TcType, TcType)
    matchActualFunTy ExpectedFunTyOrigin
    herald Maybe TypedThing
    mb_thing (Int, TcType)
    err_info TcType
    fun_ty
      = Bool
    -> SDoc
    -> TcM (HsWrapper, Scaled TcType, TcType)
    -> TcM (HsWrapper, Scaled TcType, TcType)
    forall a. HasCallStack => Bool -> SDoc -> a -> a
    assertPpr (TcType -> Bool
    isRhoTy TcType
    fun_ty) (TcType -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr TcType
    fun_ty) (TcM (HsWrapper, Scaled TcType, TcType)
     -> TcM (HsWrapper, Scaled TcType, TcType))
    -> TcM (HsWrapper, Scaled TcType, TcType)
    -> TcM (HsWrapper, Scaled TcType, TcType)
    forall a b. (a -> b) -> a -> b
    $
        TcType -> TcM (HsWrapper, Scaled TcType, TcType)
    go TcType
    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 :: TcType -> TcM (HsWrapper, Scaled TcType, TcType)
    go TcType
    ty | Just TcType
    ty' <- TcType -> Maybe TcType
    coreView TcType
    ty = TcType -> TcM (HsWrapper, Scaled TcType, TcType)
    go TcType
    ty'

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

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

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

        ------------
        defer :: TcType -> TcM (HsWrapper, Scaled TcType, TcType)
    defer TcType
    fun_ty
          = do { arg_ty <- ExpectedFunTyOrigin -> Int -> TcM (Scaled TcType)
    new_check_arg_ty ExpectedFunTyOrigin
    herald Int
    1
               ; res_ty <- newOpenFlexiTyVarTy
               ; let unif_fun_ty = [Scaled TcType] -> TcType -> TcType
    HasDebugCallStack => [Scaled TcType] -> TcType -> TcType
    mkScaledFunTys [Scaled TcType
    arg_ty] TcType
    res_ty
               ; co <- unifyType mb_thing fun_ty unif_fun_ty
               ; return (mkWpCastN co, arg_ty, res_ty) }

        ------------
        mk_ctxt :: TcType -> TidyEnv -> ZonkM (TidyEnv, ErrCtxtMsg)
        mk_ctxt :: TcType -> TidyEnv -> ZonkM (TidyEnv, ErrCtxtMsg)
    mk_ctxt TcType
    _res_ty = ExpectedFunTyOrigin
    -> (Int, TcType) -> TidyEnv -> ZonkM (TidyEnv, ErrCtxtMsg)
    mkFunTysMsg ExpectedFunTyOrigin
    herald (Int, TcType)
    err_info

    {- Note [matchActualFunTy error handling]
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    matchActualFunTy is made much more complicated by the
    desire to produce good error messages. Consider the application
        f @Int x y
    In GHC.Tc.Gen.Head.tcInstFun we instantiate the function type, one
    argument at a time.  It 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].
    matchActualFunTys :: ExpectedFunTyOrigin -- ^ See Note [Herald for matchExpectedFunTys]
                      -> CtOrigin
                      -> Arity
                      -> TcSigmaType
                      -> TcM (HsWrapper, [Scaled TcSigmaTypeFRR], TcRhoType)
    -- If    matchActualFunTys 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
    matchActualFunTys :: ExpectedFunTyOrigin
    -> CtOrigin
    -> Int
    -> TcType
    -> TcM (HsWrapper, [Scaled TcType], TcType)
    matchActualFunTys ExpectedFunTyOrigin
    herald CtOrigin
    ct_orig Int
    n_val_args_wanted TcType
    top_ty
      = Int
    -> [Scaled TcType]
    -> TcType
    -> TcM (HsWrapper, [Scaled TcType], TcType)
    go Int
    n_val_args_wanted [] TcType
    top_ty
      where
        go :: Int
    -> [Scaled TcType]
    -> TcType
    -> TcM (HsWrapper, [Scaled TcType], TcType)
    go Int
    n [Scaled TcType]
    so_far TcType
    fun_ty
          | Bool -> Bool
    not (TcType -> Bool
    isRhoTy TcType
    fun_ty)
          = do { (wrap1, rho) <- CtOrigin -> TcType -> TcM (HsWrapper, TcType)
    topInstantiate CtOrigin
    ct_orig TcType
    fun_ty
               ; (wrap2, arg_tys, res_ty) <- go n so_far rho
               ; return (wrap2 <.> wrap1, arg_tys, res_ty) }

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

        go Int
    n [Scaled TcType]
    so_far TcType
    fun_ty
          = do { (wrap_fun1, arg_ty1, res_ty1) <- ExpectedFunTyOrigin
    -> Maybe TypedThing
    -> (Int, TcType)
    -> TcType
    -> TcM (HsWrapper, Scaled TcType, TcType)
    matchActualFunTy
                                                     ExpectedFunTyOrigin
    herald Maybe TypedThing
    forall a. Maybe a
    Nothing
                                                     (Int
    n_val_args_wanted, TcType
    top_ty)
                                                     TcType
    fun_ty
               ; (wrap_res, arg_tys, res_ty)   <- go (n-1) (arg_ty1:so_far) res_ty1
               ; let wrap_fun2 = HsWrapper -> HsWrapper -> Scaled TcType -> TcType -> HsWrapper
    mkWpFun HsWrapper
    idHsWrapper HsWrapper
    wrap_res Scaled TcType
    arg_ty1 TcType
    res_ty
               -- NB: arg_ty1 comes from matchActualFunTy, so it has
               -- a syntactically fixed RuntimeRep as needed to call mkWpFun.
               ; return (wrap_fun2 <.> wrap_fun1, arg_ty1:arg_tys, res_ty) }

    {-
    ************************************************************************
    *                                                                      *
              Skolemisation and matchExpectedFunTys
    *                                                                      *
    ************************************************************************

    Note [Skolemisation overview]
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Suppose f :: (forall a. a->a) -> blah, and we have the application (f e)
    Then we want to typecheck `e` pushing in the type `forall a. a->a`. But we
    need to be careful:

    * Roughly speaking, in (tcPolyExpr e (forall a b. rho)), we skolemise `a` and `b`,
      and then call (tcExpr e rho)

    * But not quite!  We must be careful if `e` is a type lambda (\ @p @q -> blah).
      Then we want to line up the skolemised variables `a`,`b`
      with `p`,`q`, so we can't just call (tcExpr (\ @p @q -> blah) rho)

    * A very similar situation arises with
         (\ @p @q -> blah) :: forall a b. rho
      Again, we must line up `p`, `q` with the skolemised `a` and `b`.

    * Another similar situation arises with
        g :: forall a b. rho
        g @p @q x y = ....
      Here again when skolemising `a` and `b` we must be careful to match them up
      with `p` and `q`.

    OK, so how exactly do we check @p binders in lambdas?  First note that we only
    we only attempt to deal with @p binders when /checking/. We don't do inference for
    (\ @a -> blah), not yet anyway.

    For checking, there are two cases to consider:
      * Function LHS, where the function has a type signature
                      f :: forall a. a -> forall b. [b] -> blah
                      f @p x @q y = ...

      * Lambda        \ @p x @q y -> ...
                      \cases { @p x @q y -> ... }
        (\case p behaves like \cases { p -> ... }, and p is always a term pattern.)

    Both ultimately handled by matchExpectedFunTys.

    * Function LHS case is handled by `GHC.Tc.Gen.Bind.tcPolyCheck`:
      * It calls `tcSkolemiseCompleteSig`
      * Passes the skolemised variables into `tcFunBindMatches`
      * Which uses `matchExpectedFunTys` to decompose the function type to
        match the arguments
      * And then passes the (skolemised-variables ++ arg tys) on to `tcMatches`

    * For the Lambda case there are two sub-cases:
       * An expression with a type signature: (\ @a x y -> blah) :: hs_ty
         This is handled by `GHC.Tc.Gen.Head.tcExprWithSig`, which kind-checks
         the signature and hands off to `tcExprPolyCheck` via `tcPolyLExprSig`.
         Note that the foralls at the top of hs_ty scope over the expression.

       * A higher order call: h e, where h :: poly_ty -> blah
         This is handlded by `GHC.Tc.Gen.Expr.tcPolyExpr`, which (in the
         checking case) again hands off to `tcExprPolyCheck`.  Here there is
         no type-variable scoping to worry about.

      So both sub-cases end up in `GHC.Tc.Gen.Expr.tcPolyExprCheck`
      * This skolemises the /top-level/ invisible binders, but remembers
        the binders as [ExpPatType]
      * Then it looks for a lambda, and if so, calls `tcLambdaMatches` passing in
        the skolemised binders so they can be matched up with the lambda binders.
      * Otherwise it does deep-skolemisation if DeepSubsumption is on,
        and then calls tcExpr to typecheck `e`

      The outer skolemisation in tcPolyExprCheck is done using
        * tcSkolemiseCompleteSig when there is a user-written signature
        * tcSkolemiseGeneral when the polytype just comes from the context e.g. (f e)
      The former just calls the latter, so the two cases differ only slightly:
        * Both do shallow skolemisation
        * Both go via checkConstraints, which uses implicationNeeded to decide whether
          to build an implication constraint even if there /are/ no skolems.
          See Note [When to build an implication] below.

      The difference between the two cases is that `tcSkolemiseCompleteSig`
      also brings the outer type variables into scope.  It would do no
      harm to do so in both cases, but I found that (to my surprise) doing
      so caused a non-trivial (1%-ish) perf hit on the compiler.

    * `tcFunBindMatches` and `tcLambdaMatches` both use `matchExpectedFunTys`, which
      ensures that any trailing invisible binders are skolemised; and does so deeply
      if DeepSubsumption is on.

      This corresponds to the plan: "skolemise at the '=' of a function binding or
      at the '->' of a lambda binding".  (See #17594 and "Plan B2".)

    Some wrinkles

    (SK1) tcSkolemiseGeneral and tcSkolemiseCompleteSig make fresh type variables
          See Note [Instantiate sig with fresh variables]

    (SK2) All skolemisation (even without DeepSubsumption) builds just one implication
          constraint for a nested forall like:
              forall a. Eq a => forall b. Ord b => blah
          The implication constraint will look like
              forall a b. (Eq a, Ord b) => <constraints>
          See the loop in GHC.Tc.Utils.Instantiate.topSkolemise.
          and Note [Skolemisation en-bloc] in that module

    Some examples:

    *     f :: forall a b. blah
          f @p x = rhs
      `tcPolyCheck` calls `tcSkolemiseCompleteSig` to skolemise the signature, and
      then calls `tcFunBindMatches` passing in [a_sk, b_sk], the skolemsed
      variables. The latter ultimately calls `tcMatches`, and thence `tcMatchPats`.
      The latter matches up the `a_sk` with `@p`, and discards the `b_sk`.

    *     f :: forall (a::Type) (b::a). blah
          f @(p::b) x = rhs
      `tcSkolemiseCompleteSig` brings `a` and `b` into scope, bound to `a_sk` and `b_sk` resp.
      When `tcMatchPats` typechecks the pattern `@(p::b)` it'll find that `b` is in
      scope (as a result of tcSkolemiseCompleteSig) which is a bit strange.  But
      it'll then unify the kinds `Type ~ b`, which will fail as it should.

    *     f :: Int -> forall (a::Type) (b::a). blah
          f x  @p = rhs
      `matchExpectedFunTys` does shallow skolemisation eagerly, so we'll skolemise the
      forall a b.  Then `tcMatchPats` will bind [p :-> a_sk], and discard `b_sk`.
      Discarding the `b_sk` means that
          f x @p = \ @q -> blah
      or  f x @p = let .. in \ @q -> blah
      will both be rejected: this is Plan B2: skolemise at the "=".

    * Suppose DeepSubsumption is on
        f :: forall a. a -> forall b. b -> b -> forall z. z
        f @p x @q y = rhs
      The `tcSkolemiseCompleteSig` uses shallow skolemisation, so it only skolemises
      and brings into scope [a :-> a_sk]. Then `matchExpectedFunTys` skolemises the
      forall b, because it needs to expose two value arguments.  Finally
      `matchExpectedFunTys` concludes with deeply skolemising the remaining type.

      So we end up with `[p :-> a_sk, q :-> b_sk]`.  Notice that we must not
      deeply-skolemise /first/ or we'd get the tyvars [a_sk, b_sk, c_sk] which would
      not line up with the patterns [@p, x, @q, y]
    -}

    tcSkolemiseGeneral
      :: DeepSubsumptionFlag
      -> UserTypeCtxt
      -> TcType -> TcType   -- top_ty and expected_ty
            -- Here, top_ty      is the type we started to skolemise; used only in SigSkol
            -- -     expected_ty is the type we are actually skolemising
            -- matchExpectedFunTys walks down the type, skolemising as it goes,
            -- keeping the same top_ty, but successively smaller expected_tys
      -> ([(Name, TcInvisTVBinder)] -> TcType -> TcM result)
      -> TcM (HsWrapper, result)
    tcSkolemiseGeneral :: forall result.
    DeepSubsumptionFlag
    -> UserTypeCtxt
    -> TcType
    -> TcType
    -> ([(Name, TcInvisTVBinder)] -> TcType -> TcM result)
    -> TcM (HsWrapper, result)
    tcSkolemiseGeneral DeepSubsumptionFlag
    ds_flag UserTypeCtxt
    ctxt TcType
    top_ty TcType
    expected_ty [(Name, TcInvisTVBinder)] -> TcType -> TcM result
    thing_inside
      | DeepSubsumptionFlag -> TcType -> Bool
    isRhoTyDS DeepSubsumptionFlag
    ds_flag TcType
    expected_ty
        -- Fast path for a very very common case: no skolemisation to do
        -- But still call checkConstraints in case we need an implication regardless
      = do { let sig_skol :: SkolemInfoAnon
    sig_skol = UserTypeCtxt -> TcType -> [(Name, TcTyVar)] -> SkolemInfoAnon
    SigSkol UserTypeCtxt
    ctxt TcType
    top_ty []
           ; (ev_binds, result) <- SkolemInfoAnon
    -> [TcTyVar] -> [TcTyVar] -> TcM result -> TcM (TcEvBinds, result)
    forall result.
    SkolemInfoAnon
    -> [TcTyVar] -> [TcTyVar] -> TcM result -> TcM (TcEvBinds, result)
    checkConstraints SkolemInfoAnon
    sig_skol [] [] (TcM result -> TcM (TcEvBinds, result))
    -> TcM result -> TcM (TcEvBinds, result)
    forall a b. (a -> b) -> a -> b
    $
                                   [(Name, TcInvisTVBinder)] -> TcType -> TcM result
    thing_inside [] TcType
    expected_ty
           ; return (mkWpLet ev_binds, result) }

      | Bool
    otherwise
      = do { -- rec {..}: see Note [Keeping SkolemInfo inside a SkolemTv]
             --           in GHC.Tc.Utils.TcType
           ; rec { (wrap, tv_prs, given, rho_ty) <- case ds_flag of
                        DeepSubsumptionFlag
    Deep    -> SkolemInfo
    -> TcType
    -> IOEnv
         (Env TcGblEnv TcLclEnv)
         (HsWrapper, [(Name, TcInvisTVBinder)], [TcTyVar], TcType)
    deeplySkolemise SkolemInfo
    skol_info TcType
    expected_ty
                        DeepSubsumptionFlag
    Shallow -> SkolemInfo
    -> TcType
    -> IOEnv
         (Env TcGblEnv TcLclEnv)
         (HsWrapper, [(Name, TcInvisTVBinder)], [TcTyVar], TcType)
    topSkolemise SkolemInfo
    skol_info TcType
    expected_ty
                 ; let sig_skol = UserTypeCtxt -> TcType -> [(Name, TcTyVar)] -> SkolemInfoAnon
    SigSkol UserTypeCtxt
    ctxt TcType
    top_ty (((Name, TcInvisTVBinder) -> (Name, TcTyVar))
    -> [(Name, TcInvisTVBinder)] -> [(Name, TcTyVar)]
    forall a b. (a -> b) -> [a] -> [b]
    map ((TcInvisTVBinder -> TcTyVar)
    -> (Name, TcInvisTVBinder) -> (Name, TcTyVar)
    forall a b. (a -> b) -> (Name, a) -> (Name, b)
    forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
    fmap TcInvisTVBinder -> TcTyVar
    forall tv argf. VarBndr tv argf -> tv
    binderVar) [(Name, TcInvisTVBinder)]
    tv_prs)
                 ; skol_info <- mkSkolemInfo sig_skol }

           ; let skol_tvs = ((Name, TcInvisTVBinder) -> TcTyVar)
    -> [(Name, TcInvisTVBinder)] -> [TcTyVar]
    forall a b. (a -> b) -> [a] -> [b]
    map (TcInvisTVBinder -> TcTyVar
    forall tv argf. VarBndr tv argf -> tv
    binderVar (TcInvisTVBinder -> TcTyVar)
    -> ((Name, TcInvisTVBinder) -> TcInvisTVBinder)
    -> (Name, TcInvisTVBinder)
    -> TcTyVar
    forall b c a. (b -> c) -> (a -> b) -> a -> c
    . (Name, TcInvisTVBinder) -> TcInvisTVBinder
    forall a b. (a, b) -> b
    snd) [(Name, TcInvisTVBinder)]
    tv_prs
           ; traceTc "tcSkolemiseGeneral" (pprUserTypeCtxt ctxt <+> ppr skol_tvs <+> ppr given)
           ; (ev_binds, result) <- checkConstraints sig_skol skol_tvs given $
                                   thing_inside tv_prs rho_ty

           ; return (wrap <.> mkWpLet ev_binds, result) }
             -- The ev_binds returned by checkConstraints is very
             -- often empty, in which case mkWpLet is a no-op

    tcSkolemiseCompleteSig :: TcCompleteSig
                           -> ([ExpPatType] -> TcRhoType -> TcM result)
                           -> TcM (HsWrapper, result)
    -- ^ The wrapper has type: spec_ty ~> expected_ty
    -- See Note [Skolemisation] for the differences between
    -- tcSkolemiseCompleteSig and tcTopSkolemise

    tcSkolemiseCompleteSig :: forall result.
    TcCompleteSig
    -> ([ExpPatType] -> TcType -> TcM result)
    -> TcM (HsWrapper, result)
    tcSkolemiseCompleteSig (CSig { sig_bndr :: TcCompleteSig -> TcTyVar
    sig_bndr = TcTyVar
    poly_id, sig_ctxt :: TcCompleteSig -> UserTypeCtxt
    sig_ctxt = UserTypeCtxt
    ctxt, sig_loc :: TcCompleteSig -> SrcSpan
    sig_loc = SrcSpan
    loc })
                           [ExpPatType] -> TcType -> TcM result
    thing_inside
      = do { cur_loc <- TcRn SrcSpan
    getSrcSpanM
           ; let poly_ty = TcTyVar -> TcType
    idType TcTyVar
    poly_id
           ; setSrcSpan loc $   -- Sets the location for the implication constraint
             tcSkolemiseGeneral Shallow ctxt poly_ty poly_ty $ \[(Name, TcInvisTVBinder)]
    tv_prs TcType
    rho_ty ->
             SrcSpan -> TcM result -> TcM result
    forall a. SrcSpan -> TcRn a -> TcRn a
    setSrcSpan SrcSpan
    cur_loc (TcM result -> TcM result) -> TcM result -> TcM result
    forall a b. (a -> b) -> a -> b
    $ -- Revert to the original location
             [(Name, TcTyVar)] -> TcM result -> TcM result
    forall r. [(Name, TcTyVar)] -> TcM r -> TcM r
    tcExtendNameTyVarEnv (((Name, TcInvisTVBinder) -> (Name, TcTyVar))
    -> [(Name, TcInvisTVBinder)] -> [(Name, TcTyVar)]
    forall a b. (a -> b) -> [a] -> [b]
    map ((TcInvisTVBinder -> TcTyVar)
    -> (Name, TcInvisTVBinder) -> (Name, TcTyVar)
    forall a b. (a -> b) -> (Name, a) -> (Name, b)
    forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
    fmap TcInvisTVBinder -> TcTyVar
    forall tv argf. VarBndr tv argf -> tv
    binderVar) [(Name, TcInvisTVBinder)]
    tv_prs) (TcM result -> TcM result) -> TcM result -> TcM result
    forall a b. (a -> b) -> a -> b
    $
             [ExpPatType] -> TcType -> TcM result
    thing_inside (((Name, TcInvisTVBinder) -> ExpPatType)
    -> [(Name, TcInvisTVBinder)] -> [ExpPatType]
    forall a b. (a -> b) -> [a] -> [b]
    map (TcInvisTVBinder -> ExpPatType
    mkInvisExpPatType (TcInvisTVBinder -> ExpPatType)
    -> ((Name, TcInvisTVBinder) -> TcInvisTVBinder)
    -> (Name, TcInvisTVBinder)
    -> ExpPatType
    forall b c a. (b -> c) -> (a -> b) -> a -> c
    . (Name, TcInvisTVBinder) -> TcInvisTVBinder
    forall a b. (a, b) -> b
    snd) [(Name, TcInvisTVBinder)]
    tv_prs) TcType
    rho_ty }

    tcSkolemiseExpectedType :: TcSigmaType
                            -> ([ExpPatType] -> TcRhoType -> TcM result)
                            -> TcM (HsWrapper, result)
    -- Just like tcSkolemiseCompleteSig, except that we don't have a user-written
    -- type signature, we only have a type comimg from the context.
    -- Eg. f :: (forall a. blah) -> blah
    --     In the call (f e) we will call tcSkolemiseExpectedType on (forall a.blah)
    --     before typececking `e`
    tcSkolemiseExpectedType :: forall result.
    TcType
    -> ([ExpPatType] -> TcType -> TcM result)
    -> TcM (HsWrapper, result)
    tcSkolemiseExpectedType TcType
    exp_ty [ExpPatType] -> TcType -> TcM result
    thing_inside
      = DeepSubsumptionFlag
    -> UserTypeCtxt
    -> TcType
    -> TcType
    -> ([(Name, TcInvisTVBinder)] -> TcType -> TcM result)
    -> TcM (HsWrapper, result)
    forall result.
    DeepSubsumptionFlag
    -> UserTypeCtxt
    -> TcType
    -> TcType
    -> ([(Name, TcInvisTVBinder)] -> TcType -> TcM result)
    -> TcM (HsWrapper, result)
    tcSkolemiseGeneral DeepSubsumptionFlag
    Shallow UserTypeCtxt
    GenSigCtxt TcType
    exp_ty TcType
    exp_ty (([(Name, TcInvisTVBinder)] -> TcType -> TcM result)
     -> TcM (HsWrapper, result))
    -> ([(Name, TcInvisTVBinder)] -> TcType -> TcM result)
    -> TcM (HsWrapper, result)
    forall a b. (a -> b) -> a -> b
    $ \[(Name, TcInvisTVBinder)]
    tv_prs TcType
    rho_ty ->
        [ExpPatType] -> TcType -> TcM result
    thing_inside (((Name, TcInvisTVBinder) -> ExpPatType)
    -> [(Name, TcInvisTVBinder)] -> [ExpPatType]
    forall a b. (a -> b) -> [a] -> [b]
    map (TcInvisTVBinder -> ExpPatType
    mkInvisExpPatType (TcInvisTVBinder -> ExpPatType)
    -> ((Name, TcInvisTVBinder) -> TcInvisTVBinder)
    -> (Name, TcInvisTVBinder)
    -> ExpPatType
    forall b c a. (b -> c) -> (a -> b) -> a -> c
    . (Name, TcInvisTVBinder) -> TcInvisTVBinder
    forall a b. (a, b) -> b
    snd) [(Name, TcInvisTVBinder)]
    tv_prs) TcType
    rho_ty

    tcSkolemise :: DeepSubsumptionFlag -> UserTypeCtxt -> TcSigmaType
                -> (TcRhoType -> TcM result)
                -> TcM (HsWrapper, result)
    tcSkolemise :: forall result.
    DeepSubsumptionFlag
    -> UserTypeCtxt
    -> TcType
    -> (TcType -> TcM result)
    -> TcM (HsWrapper, result)
    tcSkolemise DeepSubsumptionFlag
    ds_flag UserTypeCtxt
    ctxt TcType
    expected_ty TcType -> TcM result
    thing_inside
      = DeepSubsumptionFlag
    -> UserTypeCtxt
    -> TcType
    -> TcType
    -> ([(Name, TcInvisTVBinder)] -> TcType -> TcM result)
    -> TcM (HsWrapper, result)
    forall result.
    DeepSubsumptionFlag
    -> UserTypeCtxt
    -> TcType
    -> TcType
    -> ([(Name, TcInvisTVBinder)] -> TcType -> TcM result)
    -> TcM (HsWrapper, result)
    tcSkolemiseGeneral DeepSubsumptionFlag
    ds_flag UserTypeCtxt
    ctxt TcType
    expected_ty TcType
    expected_ty (([(Name, TcInvisTVBinder)] -> TcType -> TcM result)
     -> TcM (HsWrapper, result))
    -> ([(Name, TcInvisTVBinder)] -> TcType -> TcM result)
    -> TcM (HsWrapper, result)
    forall a b. (a -> b) -> a -> b
    $ \[(Name, TcInvisTVBinder)]
    _ TcType
    rho_ty ->
        TcType -> TcM result
    thing_inside TcType
    rho_ty

    checkConstraints :: SkolemInfoAnon
                     -> [TcTyVar]           -- Skolems
                     -> [EvVar]             -- Given
                     -> TcM result
                     -> TcM (TcEvBinds, result)
    -- checkConstraints is careful to build an implication even if
    -- `skol_tvs` and `given` are both empty, under certain circumstances
    -- See Note [When to build an implication]
    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 { implication_needed <- SkolemInfoAnon -> [TcTyVar] -> [TcTyVar] -> TcM Bool
    implicationNeeded SkolemInfoAnon
    skol_info [TcTyVar]
    skol_tvs [TcTyVar]
    given

           ; if implication_needed
             then do { (tclvl, wanted, result) <- pushLevelAndCaptureConstraints thing_inside
                     ; (implics, ev_binds) <- buildImplicationFor tclvl skol_info skol_tvs given wanted
                     ; traceTc "checkConstraints" (ppr tclvl $$ ppr skol_tvs)
                     ; emitImplications implics
                     ; return (ev_binds, 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 { res <- thing_inside
                     ; return (emptyTcEvBinds, 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 { (tclvl, wanted, result) <- TcM result -> TcM (TcLevel, WantedConstraints, result)
    forall a. TcM a -> TcM (TcLevel, WantedConstraints, a)
    pushLevelAndCaptureConstraints TcM result
    thing_inside
           ; emitResidualTvConstraint skol_info skol_tvs tclvl wanted
           ; return 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 { implic <- SkolemInfoAnon
    -> [TcTyVar] -> TcLevel -> WantedConstraints -> TcM Implication
    buildTvImplication SkolemInfoAnon
    skol_info_anon [TcTyVar]
    skol_tvs TcLevel
    tclvl WantedConstraints
    wanted
           ; emitImplication 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 { 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
           ; implic   <- newImplication

           ; let 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 }

           ; checkImplicationInvariants implic'
           ; return implic' }

    implicationNeeded :: SkolemInfoAnon -> [TcTyVar] -> [EvVar] -> TcM Bool
    -- See Note [When to build an implication]
    implicationNeeded :: SkolemInfoAnon -> [TcTyVar] -> [TcTyVar] -> TcM 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 { tc_lvl <- TcM TcLevel
    getTcLevel
           ; if not (isTopTcLevel tc_lvl)  -- No implication needed if we are
             then return False             -- already inside an implication
             else
        do { dflags <- getDynFlags       -- If any deferral can happen,
                                         -- we must build an implication
           ; return (gopt Opt_DeferTypeErrors dflags ||
                     gopt Opt_DeferTypedHoles dflags ||
                     gopt Opt_DeferOutOfScopeVariables dflags) } }

      | Bool
    otherwise     -- Non-empty skolems or givens
      = Bool -> TcM 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

    Caution: we get some duplication of errors if we build more implications.
    Because we get one error for each function RHS, even if it's for
    the same class constraint.

    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 { ev_binds_var <- TcM EvBindsVar
    newTcEvBinds
           ; implic <- newImplication
           ; let 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 }
           ; checkImplicationInvariants implic'

           ; return (unitBag implic', TcEvBinds 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/ do 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.

    * This is /necessary/ for top level but may be /desirable/ even for
      nested bindings, because if the deferred coercion is bound too far
      out it will be reported even if that thunk (say) is not evaluated.

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

    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,
      - matchActualFunTy,
      - matchActualFunTys,

    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.tcLambdaMatches'). 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
                        -> VisArity
                        -> ExpSigmaType
                        -> ([ExpPatType] -> 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
    --
    -- Unconditionally concludes by skolemising any trailing invisible
    -- binders and, if DeepSubsumption is on, it does so deeply.
    --
    -- Postcondition:
    --   If exp_ty is Check {}, then [ExpPatType] and ExpRhoType results are all Check{}
    --   If exp_ty is Infer {}, then [ExpPatType] and ExpRhoType results are all Infer{}
    matchExpectedFunTys :: forall a.
    ExpectedFunTyOrigin
    -> UserTypeCtxt
    -> Int
    -> ExpRhoType
    -> ([ExpPatType] -> ExpRhoType -> TcM a)
    -> TcM (HsWrapper, a)
    matchExpectedFunTys ExpectedFunTyOrigin
    herald UserTypeCtxt
    _ctxt Int
    arity (Infer InferResult
    inf_res) [ExpPatType] -> ExpRhoType -> TcM a
    thing_inside
      = do { 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 (ExpectedFunTyOrigin
    -> Int -> IOEnv (Env TcGblEnv TcLclEnv) (Scaled ExpRhoType)
    new_infer_arg_ty ExpectedFunTyOrigin
    herald) [Int
    1 .. Int
    arity]
           ; res_ty  <- newInferExpType (ir_inst inf_res)
           ; result  <- thing_inside (map ExpFunPatTy arg_tys) res_ty
           ; arg_tys <- mapM (\(Scaled TcType
    m ExpRhoType
    t) -> TcType -> TcType -> Scaled TcType
    forall a. TcType -> a -> Scaled a
    Scaled TcType
    m (TcType -> Scaled TcType) -> TcM TcType -> TcM (Scaled TcType)
    forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
    <$> ExpRhoType -> TcM TcType
    forall (m :: * -> *). MonadIO m => ExpRhoType -> m TcType
    readExpType ExpRhoType
    t) arg_tys
           ; res_ty  <- readExpType res_ty
             -- Remarks:
             --  1. use tcMkScaledFunTys rather than mkScaledFunTys, as we might
             --     have res_ty :: kappa[tau] for a meta ty-var kappa, in which case
             --     mkScaledFunTys would crash. See #26277.
             --  2. tcMkScaledFunTys arg_tys res_ty does not contain any foralls
             --     (even nested ones), so no need to instantiate.
           ; co <- fillInferResultNoInst (tcMkScaledFunTys arg_tys res_ty) inf_res
           ; return (mkWpCastN co, result) }

    matchExpectedFunTys ExpectedFunTyOrigin
    herald UserTypeCtxt
    ctx Int
    arity (Check TcType
    top_ty) [ExpPatType] -> ExpRhoType -> TcM a
    thing_inside
      = Int
    -> [ExpPatType]
    -> TcType
    -> IOEnv (Env TcGblEnv TcLclEnv) (HsWrapper, a)
    check Int
    arity [] TcType
    top_ty
      where
        check :: VisArity -> [ExpPatType] -> TcSigmaType -> TcM (HsWrapper, a)
        -- `check` is called only in the Check{} case
        -- It collects rev_pat_tys in reversed order
        -- n_req is the number of /visible/ arguments still needed

        ----------------------------
        -- Skolemise quantifiers, both visible (up to n_req) and invisible
        -- See Note [Visible type application and abstraction] in GHC.Tc.Gen.App
        check :: Int
    -> [ExpPatType]
    -> TcType
    -> IOEnv (Env TcGblEnv TcLclEnv) (HsWrapper, a)
    check Int
    n_req [ExpPatType]
    rev_pat_tys TcType
    ty
          | TcType -> Bool
    isSigmaTy TcType
    ty                     -- An invisible quantifier at the top
            Bool -> Bool -> Bool
    || (Int
    n_req Int -> Int -> Bool
    forall a. Ord a => a -> a -> Bool
    > Int
    0 Bool -> Bool -> Bool
    && TcType -> Bool
    isForAllTy TcType
    ty)  -- A visible quantifier at top, and we need it
          = do { rec { (n_req', wrap_gen, tv_nms, bndrs, given, inner_ty) <- skolemiseRequired skol_info n_req ty
                     ; let sig_skol = UserTypeCtxt -> TcType -> [(Name, TcTyVar)] -> SkolemInfoAnon
    SigSkol UserTypeCtxt
    ctx TcType
    top_ty ([Name]
    tv_nms [Name] -> [TcTyVar] -> [(Name, TcTyVar)]
    forall a b. [a] -> [b] -> [(a, b)]
    `zip` [TcTyVar]
    skol_tvs)
                           skol_tvs = [ForAllTyBinder] -> [TcTyVar]
    forall tv argf. [VarBndr tv argf] -> [tv]
    binderVars [ForAllTyBinder]
    bndrs
                     ; skol_info <- mkSkolemInfo sig_skol }
                 -- rec {..}: see Note [Keeping SkolemInfo inside a SkolemTv]
                 --           in GHC.Tc.Utils.TcType
               ; (ev_binds, (wrap_res, result))
                      <- checkConstraints (getSkolemInfo skol_info) skol_tvs given $
                         check n_req'
                               (reverse (map ExpForAllPatTy bndrs) ++ rev_pat_tys)
                               inner_ty
               ; assertPpr (not (null bndrs && null given)) (ppr ty) $
                           -- The guard ensures that we made some progress
                 return (wrap_gen <.> mkWpLet ev_binds <.> wrap_res, result) }

        ----------------------------
        -- Base case: (n_req == 0): no more args
        --    The earlier skolemisation ensurs that rho_ty has no top-level invisible quantifiers
        --    If there is deep subsumption, do deep skolemisation now
        check Int
    n_req [ExpPatType]
    rev_pat_tys TcType
    rho_ty
          | Int
    n_req Int -> Int -> Bool
    forall a. Eq a => a -> a -> Bool
    == Int
    0
          = do { let pat_tys :: [ExpPatType]
    pat_tys = [ExpPatType] -> [ExpPatType]
    forall a. [a] -> [a]
    reverse [ExpPatType]
    rev_pat_tys
               ; ds_flag <- TcM DeepSubsumptionFlag
    getDeepSubsumptionFlag
               ; case ds_flag of
                   DeepSubsumptionFlag
    Shallow -> do { res <- [ExpPatType] -> ExpRhoType -> TcM a
    thing_inside [ExpPatType]
    pat_tys (TcType -> ExpRhoType
    mkCheckExpType TcType
    rho_ty)
                                 ; return (idHsWrapper, res) }
                   DeepSubsumptionFlag
    Deep    -> DeepSubsumptionFlag
    -> UserTypeCtxt
    -> TcType
    -> TcType
    -> ([(Name, TcInvisTVBinder)] -> TcType -> TcM a)
    -> IOEnv (Env TcGblEnv TcLclEnv) (HsWrapper, a)
    forall result.
    DeepSubsumptionFlag
    -> UserTypeCtxt
    -> TcType
    -> TcType
    -> ([(Name, TcInvisTVBinder)] -> TcType -> TcM result)
    -> TcM (HsWrapper, result)
    tcSkolemiseGeneral DeepSubsumptionFlag
    Deep UserTypeCtxt
    ctx TcType
    top_ty TcType
    rho_ty (([(Name, TcInvisTVBinder)] -> TcType -> TcM a)
     -> IOEnv (Env TcGblEnv TcLclEnv) (HsWrapper, a))
    -> ([(Name, TcInvisTVBinder)] -> TcType -> TcM a)
    -> IOEnv (Env TcGblEnv TcLclEnv) (HsWrapper, a)
    forall a b. (a -> b) -> a -> b
    $ \[(Name, TcInvisTVBinder)]
    _ TcType
    rho_ty ->
                              -- "_" drop the /deeply/-skolemise binders
                              -- They do not line up with binders in the Match
                              [ExpPatType] -> ExpRhoType -> TcM a
    thing_inside [ExpPatType]
    pat_tys (TcType -> ExpRhoType
    mkCheckExpType TcType
    rho_ty) }

        ----------------------------
        -- Function types
        check Int
    n_req [ExpPatType]
    rev_pat_tys (FunTy { ft_af :: TcType -> FunTyFlag
    ft_af = FunTyFlag
    af, ft_mult :: TcType -> TcType
    ft_mult = TcType
    mult
                                       , ft_arg :: TcType -> TcType
    ft_arg = TcType
    arg_ty, ft_res :: TcType -> TcType
    ft_res = TcType
    res_ty })
          = Bool
    -> IOEnv (Env TcGblEnv TcLclEnv) (HsWrapper, a)
    -> IOEnv (Env TcGblEnv TcLclEnv) (HsWrapper, a)
    forall a. HasCallStack => Bool -> a -> a
    assert (FunTyFlag -> Bool
    isVisibleFunArg FunTyFlag
    af) (IOEnv (Env TcGblEnv TcLclEnv) (HsWrapper, a)
     -> IOEnv (Env TcGblEnv TcLclEnv) (HsWrapper, a))
    -> IOEnv (Env TcGblEnv TcLclEnv) (HsWrapper, a)
    -> IOEnv (Env TcGblEnv TcLclEnv) (HsWrapper, a)
    forall a b. (a -> b) -> a -> b
    $
            do { let arg_pos :: Int
    arg_pos = Int
    arity Int -> Int -> Int
    forall a. Num a => a -> a -> a
    - Int
    n_req Int -> Int -> Int
    forall a. Num a => a -> a -> a
    + Int
    1   -- 1 for the first argument etc
               ; (arg_co, arg_ty) <- HasDebugCallStack =>
    FixedRuntimeRepContext -> TcType -> TcM (Coercion, TcType)
    FixedRuntimeRepContext -> TcType -> TcM (Coercion, TcType)
    hasFixedRuntimeRep (ExpectedFunTyOrigin -> Int -> FixedRuntimeRepContext
    FRRExpectedFunTy ExpectedFunTyOrigin
    herald Int
    arg_pos) TcType
    arg_ty
               ; (wrap_res, result) <- check (n_req - 1)
                                             (mkCheckExpFunPatTy (Scaled mult arg_ty) : rev_pat_tys)
                                             res_ty
               ; let wrap_arg = Coercion -> HsWrapper
    mkWpCastN Coercion
    arg_co
                     fun_wrap = HsWrapper -> HsWrapper -> Scaled TcType -> TcType -> HsWrapper
    mkWpFun HsWrapper
    wrap_arg HsWrapper
    wrap_res (TcType -> TcType -> Scaled TcType
    forall a. TcType -> a -> Scaled a
    Scaled TcType
    mult TcType
    arg_ty) TcType
    res_ty
               ; return (fun_wrap, result) }

        ----------------------------
        -- Type variables
        check Int
    n_req [ExpPatType]
    rev_pat_tys ty :: TcType
    ty@(TyVarTy TcTyVar
    tv)
          | TcTyVar -> Bool
    isMetaTyVar TcTyVar
    tv
          = do { cts <- TcTyVar -> IOEnv (Env TcGblEnv TcLclEnv) MetaDetails
    forall (m :: * -> *). MonadIO m => TcTyVar -> m MetaDetails
    readMetaTyVar TcTyVar
    tv
               ; case cts of
                   Indirect TcType
    ty' -> Int
    -> [ExpPatType]
    -> TcType
    -> IOEnv (Env TcGblEnv TcLclEnv) (HsWrapper, a)
    check Int
    n_req [ExpPatType]
    rev_pat_tys TcType
    ty'
                   MetaDetails
    Flexi        -> Int
    -> [ExpPatType]
    -> TcType
    -> IOEnv (Env TcGblEnv TcLclEnv) (HsWrapper, a)
    defer Int
    n_req [ExpPatType]
    rev_pat_tys TcType
    ty }

        ----------------------------
        -- NOW do coreView.  We didn't do it before, so that we do not unnecessarily
        -- unwrap a synonym in the returned rho_ty
        check Int
    n_req [ExpPatType]
    rev_pat_tys TcType
    ty
          | Just TcType
    ty' <- TcType -> Maybe TcType
    coreView TcType
    ty = Int
    -> [ExpPatType]
    -> TcType
    -> IOEnv (Env TcGblEnv TcLclEnv) (HsWrapper, a)
    check Int
    n_req [ExpPatType]
    rev_pat_tys TcType
    ty'

           -- In all other cases we bale out into ordinary unification
           -- However unlike the meta-tyvar case, we are sure that the
           -- number of arguments doesn't match arity of the original
           -- type, so we can add a bit more context to the error message
           -- (cf #7869).
           --
           -- It is not always an error, because specialized type may have
           -- different arity, for example:
           --
           -- > f1 = f2 'a'
           -- > f2 :: Monad m => m Bool
           -- > f2 = undefined
           --
           -- But in that case we add specialized type into error context
           -- anyway, because it may be useful. See also #9605.
        check Int
    n_req [ExpPatType]
    rev_pat_tys TcType
    res_ty
          = (TidyEnv -> ZonkM (TidyEnv, ErrCtxtMsg))
    -> IOEnv (Env TcGblEnv TcLclEnv) (HsWrapper, a)
    -> IOEnv (Env TcGblEnv TcLclEnv) (HsWrapper, a)
    forall a.
    (TidyEnv -> ZonkM (TidyEnv, ErrCtxtMsg)) -> TcM a -> TcM a
    addErrCtxtM (ExpectedFunTyOrigin
    -> (Int, TcType) -> TidyEnv -> ZonkM (TidyEnv, ErrCtxtMsg)
    mkFunTysMsg ExpectedFunTyOrigin
    herald (Int
    arity, TcType
    top_ty))  (IOEnv (Env TcGblEnv TcLclEnv) (HsWrapper, a)
     -> IOEnv (Env TcGblEnv TcLclEnv) (HsWrapper, a))
    -> IOEnv (Env TcGblEnv TcLclEnv) (HsWrapper, a)
    -> IOEnv (Env TcGblEnv TcLclEnv) (HsWrapper, a)
    forall a b. (a -> b) -> a -> b
    $
            Int
    -> [ExpPatType]
    -> TcType
    -> IOEnv (Env TcGblEnv TcLclEnv) (HsWrapper, a)
    defer Int
    n_req [ExpPatType]
    rev_pat_tys TcType
    res_ty

        ------------
        defer :: VisArity -> [ExpPatType] -> TcRhoType -> TcM (HsWrapper, a)
        defer :: Int
    -> [ExpPatType]
    -> TcType
    -> IOEnv (Env TcGblEnv TcLclEnv) (HsWrapper, a)
    defer Int
    n_req [ExpPatType]
    rev_pat_tys TcType
    fun_ty
          = do { more_arg_tys <- (Int -> TcM (Scaled TcType))
    -> [Int] -> IOEnv (Env TcGblEnv TcLclEnv) [Scaled TcType]
    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 (ExpectedFunTyOrigin -> Int -> TcM (Scaled TcType)
    new_check_arg_ty ExpectedFunTyOrigin
    herald) [Int
    arity Int -> Int -> Int
    forall a. Num a => a -> a -> a
    - Int
    n_req Int -> Int -> Int
    forall a. Num a => a -> a -> a
    + Int
    1 .. Int
    arity]
               ; let all_pats = [ExpPatType] -> [ExpPatType]
    forall a. [a] -> [a]
    reverse [ExpPatType]
    rev_pat_tys [ExpPatType] -> [ExpPatType] -> [ExpPatType]
    forall a. [a] -> [a] -> [a]
    ++ (Scaled TcType -> ExpPatType) -> [Scaled TcType] -> [ExpPatType]
    forall a b. (a -> b) -> [a] -> [b]
    map Scaled TcType -> ExpPatType
    mkCheckExpFunPatTy [Scaled TcType]
    more_arg_tys
               ; res_ty <- newOpenFlexiTyVarTy
               ; result <- thing_inside all_pats (mkCheckExpType res_ty)

               ; co <- unifyType Nothing (mkScaledFunTys more_arg_tys res_ty) fun_ty
               ; return (mkWpCastN co, result) }

    new_infer_arg_ty :: ExpectedFunTyOrigin -> Int -> TcM (Scaled ExpRhoTypeFRR)
    new_infer_arg_ty :: ExpectedFunTyOrigin
    -> Int -> IOEnv (Env TcGblEnv TcLclEnv) (Scaled ExpRhoType)
    new_infer_arg_ty ExpectedFunTyOrigin
    herald Int
    arg_pos -- position for error messages only
      = do { mult     <- TcType -> TcM TcType
    newFlexiTyVarTy TcType
    multiplicityTy
           ; inf_hole <- newInferExpTypeFRR IIF_DeepRho (FRRExpectedFunTy herald arg_pos)
           ; return (mkScaled mult inf_hole) }

    new_check_arg_ty :: ExpectedFunTyOrigin -> Int -> TcM (Scaled TcType)
    new_check_arg_ty :: ExpectedFunTyOrigin -> Int -> TcM (Scaled TcType)
    new_check_arg_ty ExpectedFunTyOrigin
    herald Int
    arg_pos -- Position for error messages only, 1 for first arg
      = do { mult   <- TcType -> TcM TcType
    newFlexiTyVarTy TcType
    multiplicityTy
           ; arg_ty <- newOpenFlexiFRRTyVarTy (FRRExpectedFunTy herald arg_pos)
           ; return (mkScaled mult arg_ty) }

    mkFunTysMsg :: ExpectedFunTyOrigin
                -> (VisArity, TcType)
                -> TidyEnv -> ZonkM (TidyEnv, ErrCtxtMsg)
    -- See Note [Reporting application arity errors]
    mkFunTysMsg :: ExpectedFunTyOrigin
    -> (Int, TcType) -> TidyEnv -> ZonkM (TidyEnv, ErrCtxtMsg)
    mkFunTysMsg ExpectedFunTyOrigin
    herald (Int
    n_vis_args_in_call, TcType
    fun_ty) TidyEnv
    env
      = do { (env', fun_ty) <- TidyEnv -> TcType -> ZonkM (TidyEnv, TcType)
    zonkTidyTcType TidyEnv
    env TcType
    fun_ty

           ; let (pi_ty_bndrs, _) = splitPiTys fun_ty
                 n_fun_args = (PiTyBinder -> Bool) -> [PiTyBinder] -> Int
    forall a. (a -> Bool) -> [a] -> Int
    count PiTyBinder -> Bool
    isVisiblePiTyBinder [PiTyBinder]
    pi_ty_bndrs

           ; return (env', FunTysCtxt herald fun_ty n_vis_args_in_call n_fun_args) }

    {- Note [Reporting application arity errors]
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Consider      f :: Int -> Int -> Int
    and the call  foo = f 3 4 5
    We'd like to get an error like:

        • Couldn't match expected type ‘t0 -> t’ with actual type ‘Int’
        • The function ‘f’ is applied to three visible arguments,           -- What are "visible" arguments?
            but its type ‘Int -> Int -> Int’ has only two                   -- See Note [Visibility and arity] in GHC.Types.Basic

    That is what `mkFunTysMsg` tries to do.  But what is the "type of the function".
    Most obviously, we can report its full, polymorphic type; that is simple and
    explicable.  But sometimes a bit odd.  Consider
        f :: Bool -> t Int Int
        foo = f True 5 10
    We get this error:
        • Couldn't match type ‘Int’ with ‘t0 -> t’
          Expected: Int -> t0 -> t
            Actual: Int -> Int
        • The function ‘f’ is applied to three visible arguments,
            but its type ‘Bool -> t Int Int’ has only one

    That's not /quite/ right beause we can instantiate `t` to an arrow and get
    two arrows (but not three!).  With that in mind, one could consider reporting
    the /instantiated/ type, and GHC used to do so.  But it's more work, and in
    some ways more confusing, especially when nested quantifiers are concerned, e.g.
        f :: Bool -> forall t. t Int Int

    So we just keep it simple and report the original function type.

    ************************************************************************
    *                                                                      *
                        Other matchExpected functions
    *                                                                      *
    ********************************************************************* -}

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

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

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

    matchExpectedTyConApp :: TyCon -> TcType -> TcM (Coercion, [TcType])
    matchExpectedTyConApp TyCon
    tc TcType
    orig_ty
      = Bool
    -> SDoc -> TcM (Coercion, [TcType]) -> TcM (Coercion, [TcType])
    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, [TcType]) -> TcM (Coercion, [TcType]))
    -> TcM (Coercion, [TcType]) -> TcM (Coercion, [TcType])
    forall a b. (a -> b) -> a -> b
    $
        TcType -> TcM (Coercion, [TcType])
    go TcType
    orig_ty
      where
        go :: TcType -> TcM (Coercion, [TcType])
    go TcType
    ty
           | Just TcType
    ty' <- TcType -> Maybe TcType
    coreView TcType
    ty
           = TcType -> TcM (Coercion, [TcType])
    go TcType
    ty'

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

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

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

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

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

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

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

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

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

        -- Defer splitting by generating an equality constraint
        defer :: TcM (Coercion, (TcType, TcType))
    defer
          = do { ty1 <- TcType -> TcM TcType
    newFlexiTyVarTy TcType
    kind1
               ; ty2 <- newFlexiTyVarTy kind2
               ; co <- unifyType Nothing (mkAppTy ty1 ty2) orig_ty
               ; return (co, (ty1, ty2)) }

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

    {- **********************************************************************
    *
                          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 `IFRR_Check`, @t2@ is guaranteed
    --    to have a syntactically fixed RuntimeRep, in the sense of
    --    Note [Fixed RuntimeRep] in GHC.Tc.Utils.Concrete.
    fillInferResultNoInst :: TcType -> InferResult -> TcM TcCoercionN
    fillInferResultNoInst :: TcType -> InferResult -> TcM Coercion
    fillInferResultNoInst TcType
    act_res_ty (IR { ir_uniq :: InferResult -> Unique
    ir_uniq = Unique
    u
                                         , ir_lvl :: InferResult -> TcLevel
    ir_lvl  = TcLevel
    res_lvl
                                         , ir_frr :: InferResult -> InferFRRFlag
    ir_frr  = InferFRRFlag
    mb_frr
                                         , ir_ref :: InferResult -> IORef (Maybe TcType)
    ir_ref  = IORef (Maybe TcType)
    ref })
      = do { mb_exp_res_ty <- IORef (Maybe TcType)
    -> IOEnv (Env TcGblEnv TcLclEnv) (Maybe TcType)
    forall (m :: * -> *) a. MonadIO m => TcRef a -> m a
    readTcRef IORef (Maybe TcType)
    ref
           ; case mb_exp_res_ty of
                Just TcType
    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
    <+> TcType -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr TcType
    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
    <+> TcType -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr TcType
    exp_res_ty
                         ; cur_lvl <- TcM TcLevel
    getTcLevel
                         ; unless (cur_lvl `sameDepthAs` res_lvl) $
                           ensureMonoType act_res_ty -- See (FIR1)
                         ; unifyType Nothing act_res_ty exp_res_ty }
                Maybe TcType
    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
    <+> TcType -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr TcType
    act_res_ty

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

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

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

                         ; writeTcRef ref (Just act_res_ty)

                         ; return final_co } }

    fillInferResult :: CtOrigin -> TcType -> InferResult -> TcM HsWrapper
    -- See Note [Instantiation of InferResult]
    fillInferResult :: CtOrigin -> TcType -> InferResult -> TcM HsWrapper
    fillInferResult CtOrigin
    ct_orig TcType
    res_ty ires :: InferResult
    ires@(IR { ir_inst :: InferResult -> InferInstFlag
    ir_inst = InferInstFlag
    iif })
      = case InferInstFlag
    iif of
           InferInstFlag
    IIF_Sigma      -> do { co <- TcType -> InferResult -> TcM Coercion
    fillInferResultNoInst TcType
    res_ty InferResult
    ires
                                ; return (mkWpCastN co) }
           InferInstFlag
    IIF_ShallowRho -> do { (wrap, res_ty') <- CtOrigin -> TcType -> TcM (HsWrapper, TcType)
    topInstantiate CtOrigin
    ct_orig TcType
    res_ty
                                ; co <- fillInferResultNoInst res_ty' ires
                                ; return (mkWpCastN co <.> wrap) }
           InferInstFlag
    IIF_DeepRho     -> do { (wrap, res_ty') <- CtOrigin -> TcType -> TcM (HsWrapper, TcType)
    dsInstantiate CtOrigin
    ct_orig TcType
    res_ty
                                 ; co <- fillInferResultNoInst res_ty' ires
                                 ; return (mkWpCastN co <.> wrap) }

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

    (FIR1) 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.

    Note [Instantiation of InferResult]
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    When typechecking expressions (not types, not patterns), we always almost
    always instantiate before filling in `InferResult`, so that the result is a
    TcRhoType. This behaviour is controlled by the `ir_inst :: InferInstFlag`
    field of `InferResult`.

    If we do instantiate (ir_inst = IIF_DeepRho), and DeepSubsumption is enabled,
    we instantiate deeply. See `tcInferResult`.

    Usually this field is `IIF_DeepRho` meaning "return a (possibly deep) rho-type".
    Why is this the common case?  See #17173 for discussion.  Here are some examples
    of why:

    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

    HOWEVER, not always! Here are places where we want `IIF_Sigma` meaning
    "return a sigma-type":

    * IIF_Sigma: In GHC.Tc.Module.tcRnExpr, which implements GHCi's :type
      command, we want to return a completely uninstantiated type.
      See Note [Implementing :type] in GHC.Tc.Module.

    * IIF_Sigma: In types we can't lambda-abstract, so we must be careful not to instantiate
      at all. See calls to `runInferHsType`

    * IIF_Sigma: in patterns we don't want to instantiate at all. See the use of
      `runInferSigmaFRR` in GHC.Tc.Gen.Pat

    * IIF_ShallowRho: in the expression part of a view pattern, we must top-instantiate
      but /not/ deeply instantiate (#26331). See Note [View patterns and polymorphism]
      in GHC.Tc.Gen.Pat.  This the only place we use IIF_ShallowRho.

    Why do we want to deeply instantiate, ever?  Why isn't top-instantiation enough?
    Answer: to accept the following program (T26225b) with -XDeepSubsumption, we
    need to deeply instantiate when inferring in checkResultTy:

      f :: Int -> (forall a. a->a)
      g :: Int -> Bool -> Bool

      test b =
        case b of
          True  -> f
          False -> g

    If we don't deeply instantiate in the branches of the case expression, we will
    try to unify the type of 'f' with that of 'g', which fails. If we instead
    deeply instantiate 'f', we will fill the 'InferResult' with 'Int -> alpha -> alpha'
    which then successfully unifies with the type of 'g' when we come to fill the
    'InferResult' hole a second time for the second case branch.
    -}

    {-
    ************************************************************************
    *                                                                      *
                    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 -> TcType -> ExpRhoType -> TcM (HsExpr GhcTc)
    tcWrapResult HsExpr GhcRn
    rn_expr = CtOrigin
    -> HsExpr GhcRn
    -> HsExpr GhcTc
    -> TcType
    -> 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
    -> TcType
    -> ExpRhoType
    -> TcM (HsExpr GhcTc)
    tcWrapResultO CtOrigin
    orig HsExpr GhcRn
    rn_expr HsExpr GhcTc
    expr TcType
    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
    <+> TcType -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr TcType
    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 ])
           ; wrap <- CtOrigin
    -> UserTypeCtxt
    -> Maybe TypedThing
    -> TcType
    -> ExpRhoType
    -> TcM HsWrapper
    tcSubType 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) TcType
    actual_ty ExpRhoType
    res_ty
           ; return (mkHsWrap wrap expr) }

    -- | 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 :: HasDebugCallStack
                     => HsExpr GhcRn -> HsExpr GhcTc
                     -> TcRhoType   -- ^ Actual; a rho-type, not a sigma-type
                     -> ExpRhoType  -- ^ Expected
                     -> TcM (HsExpr GhcTc)
    tcWrapResultMono :: HasDebugCallStack =>
    HsExpr GhcRn
    -> HsExpr GhcTc -> TcType -> ExpRhoType -> TcM (HsExpr GhcTc)
    tcWrapResultMono HsExpr GhcRn
    rn_expr HsExpr GhcTc
    expr TcType
    act_ty ExpRhoType
    res_ty
      = do { co <- HasDebugCallStack =>
    HsExpr GhcRn -> TcType -> ExpRhoType -> TcM Coercion
    HsExpr GhcRn -> TcType -> ExpRhoType -> TcM Coercion
    tcSubTypeMono HsExpr GhcRn
    rn_expr TcType
    act_ty ExpRhoType
    res_ty
           ; return (mkHsWrapCo co expr) }

    -- | A version of 'tcSubType' to use when the actual type is a rho-type,
    -- so that no instantiation is needed.
    tcSubTypeMono :: HasDebugCallStack
                  => HsExpr GhcRn
                  -> TcRhoType   -- ^ Actual; a rho-type, not a sigma-type
                  -> ExpRhoType  -- ^ Expected
                  -> TcM TcCoercionN
    tcSubTypeMono :: HasDebugCallStack =>
    HsExpr GhcRn -> TcType -> ExpRhoType -> TcM Coercion
    tcSubTypeMono HsExpr GhcRn
    rn_expr TcType
    act_ty ExpRhoType
    exp_ty
      = Bool -> SDoc -> TcM Coercion -> TcM Coercion
    forall a. HasCallStack => Bool -> SDoc -> a -> a
    assertPpr (TcType -> Bool
    isDeepRhoTy TcType
    act_ty)
          ([SDoc] -> SDoc
    forall doc. IsDoc doc => [doc] -> doc
    vcat [ String -> SDoc
    forall doc. IsLine doc => String -> doc
    text String
    "Actual type is not a (deep) rho-type."
                , String -> SDoc
    forall doc. IsLine doc => String -> doc
    text String
    "act_ty:" SDoc -> SDoc -> SDoc
    forall doc. IsLine doc => doc -> doc -> doc
    <+> TcType -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr TcType
    act_ty
                , String -> SDoc
    forall doc. IsLine doc => String -> doc
    text String
    "rn_expr:" SDoc -> SDoc -> SDoc
    forall doc. IsLine doc => doc -> doc -> doc
    <+> HsExpr GhcRn -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr HsExpr GhcRn
    rn_expr]) (TcM Coercion -> TcM Coercion) -> TcM Coercion -> TcM Coercion
    forall a b. (a -> b) -> a -> b
    $
        case ExpRhoType
    exp_ty of
          Infer InferResult
    inf_res -> TcType -> InferResult -> TcM Coercion
    fillInferResultNoInst TcType
    act_ty InferResult
    inf_res
          Check TcType
    exp_ty  -> Maybe TypedThing -> TcType -> TcType -> 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) TcType
    act_ty TcType
    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 -> TcType -> TcM HsWrapper
    tcSubTypePat CtOrigin
    inst_orig UserTypeCtxt
    ctxt (Check TcType
    ty_actual) TcType
    ty_expected
      = (TcType -> TcType -> TcM Coercion)
    -> CtOrigin -> UserTypeCtxt -> TcType -> TcType -> TcM HsWrapper
    tc_sub_type TcType -> TcType -> TcM Coercion
    unifyTypeET CtOrigin
    inst_orig UserTypeCtxt
    ctxt TcType
    ty_actual TcType
    ty_expected

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

           ; return (mkWpCastN (mkSymCo co)) }

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

    -- | A subtype check that performs deep subsumption.
    -- See also 'tcSubTypeMono', for when no instantiation is required.
    tcSubTypeDS :: HsExpr GhcRn
                -> TcRhoType   -- Actual type -- a rho-type not a sigma-type
                -> TcRhoType   -- Expected type
                               -- DeepSubsumption <=> when checking, this type
                               --                     is deeply skolemised
                -> TcM HsWrapper
    -- Only one call site, in GHC.Tc.Gen.App.tcApp
    tcSubTypeDS :: HsExpr GhcRn -> TcType -> TcType -> TcM HsWrapper
    tcSubTypeDS HsExpr GhcRn
    rn_expr TcType
    act_rho TcType
    exp_rho
      = Position 'Pos
    -> (TcType -> TcType -> TcM Coercion)
    -> CtOrigin
    -> UserTypeCtxt
    -> TcType
    -> TcType
    -> TcM HsWrapper
    forall (p :: Polarity).
    HasDebugCallStack =>
    Position p
    -> (TcType -> TcType -> TcM Coercion)
    -> CtOrigin
    -> UserTypeCtxt
    -> TcType
    -> TcType
    -> TcM HsWrapper
    tc_sub_type_deep Position 'Pos
    Top (HsExpr GhcRn -> TcType -> TcType -> TcM Coercion
    unifyExprType HsExpr GhcRn
    rn_expr) CtOrigin
    orig UserTypeCtxt
    GenSigCtxt TcType
    act_rho TcType
    exp_rho
      where
        orig :: CtOrigin
    orig = HsExpr GhcRn -> CtOrigin
    exprCtOrigin HsExpr GhcRn
    rn_expr

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

    -- | Checks that the 'actual' type is more polymorphic than the 'expected' type.
    tcSubType :: 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
    tcSubType :: CtOrigin
    -> UserTypeCtxt
    -> Maybe TypedThing
    -> TcType
    -> ExpRhoType
    -> TcM HsWrapper
    tcSubType CtOrigin
    inst_orig UserTypeCtxt
    ctxt Maybe TypedThing
    m_thing TcType
    ty_actual ExpRhoType
    res_ty
      = case ExpRhoType
    res_ty of
          Check TcType
    ty_expected -> (TcType -> TcType -> TcM Coercion)
    -> CtOrigin -> UserTypeCtxt -> TcType -> TcType -> TcM HsWrapper
    tc_sub_type (Maybe TypedThing -> TcType -> TcType -> TcM Coercion
    unifyType Maybe TypedThing
    m_thing) CtOrigin
    inst_orig UserTypeCtxt
    ctxt
                                           TcType
    ty_actual TcType
    ty_expected

          Infer InferResult
    inf_res -> CtOrigin -> TcType -> InferResult -> TcM HsWrapper
    fillInferResult CtOrigin
    inst_orig TcType
    ty_actual InferResult
    inf_res

    ---------------
    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 -> TcType -> TcType -> TcM HsWrapper
    tcSubTypeSigma CtOrigin
    orig UserTypeCtxt
    ctxt TcType
    ty_actual TcType
    ty_expected
      = (TcType -> TcType -> TcM Coercion)
    -> CtOrigin -> UserTypeCtxt -> TcType -> TcType -> TcM HsWrapper
    tc_sub_type (Maybe TypedThing -> TcType -> TcType -> TcM Coercion
    unifyType Maybe TypedThing
    forall a. Maybe a
    Nothing) CtOrigin
    orig UserTypeCtxt
    ctxt TcType
    ty_actual TcType
    ty_expected

    ---------------
    tcSubTypeAmbiguity :: UserTypeCtxt   -- Where did this type arise
                       -> TcSigmaType -> TcSigmaType -> TcM HsWrapper
    -- See Note [Ambiguity check and deep subsumption]
    tcSubTypeAmbiguity :: UserTypeCtxt -> TcType -> TcType -> TcM HsWrapper
    tcSubTypeAmbiguity UserTypeCtxt
    ctxt TcType
    ty_actual TcType
    ty_expected
      = Position 'Pos
    -> DeepSubsumptionFlag
    -> (TcType -> TcType -> TcM Coercion)
    -> CtOrigin
    -> UserTypeCtxt
    -> TcType
    -> TcType
    -> TcM HsWrapper
    forall (p :: Polarity).
    Position p
    -> DeepSubsumptionFlag
    -> (TcType -> TcType -> TcM Coercion)
    -> CtOrigin
    -> UserTypeCtxt
    -> TcType
    -> TcType
    -> TcM HsWrapper
    tc_sub_type_ds Position 'Pos
    Top DeepSubsumptionFlag
    Shallow (Maybe TypedThing -> TcType -> TcType -> TcM Coercion
    unifyType Maybe TypedThing
    forall a. Maybe a
    Nothing)
                                 (UserTypeCtxt -> CtOrigin
    AmbiguityCheckOrigin UserTypeCtxt
    ctxt)
                                 UserTypeCtxt
    ctxt TcType
    ty_actual TcType
    ty_expected

    ---------------
    addSubTypeCtxt :: TcType -> ExpType -> TcM a -> TcM a
    addSubTypeCtxt :: forall a. TcType -> ExpRhoType -> TcM a -> TcM a
    addSubTypeCtxt TcType
    ty_actual ExpRhoType
    ty_expected TcM a
    thing_inside
     | TcType -> Bool
    isRhoTy TcType
    ty_actual        -- If there is no polymorphism involved, the
     , ExpRhoType -> Bool
    isRhoExpTy ExpRhoType
    ty_expected   -- TypeEqOrigin stuff (added by the _NC functions)
     = TcM a
    thing_inside             -- gives enough context by itself
     | Bool
    otherwise
     = (TidyEnv -> ZonkM (TidyEnv, ErrCtxtMsg)) -> TcM a -> TcM a
    forall a.
    (TidyEnv -> ZonkM (TidyEnv, ErrCtxtMsg)) -> TcM a -> TcM a
    addErrCtxtM TidyEnv -> ZonkM (TidyEnv, ErrCtxtMsg)
    mk_msg TcM a
    thing_inside
      where
        mk_msg :: TidyEnv -> ZonkM (TidyEnv, ErrCtxtMsg)
    mk_msg TidyEnv
    tidy_env
          = do { (tidy_env, ty_actual)   <- TidyEnv -> TcType -> ZonkM (TidyEnv, TcType)
    zonkTidyTcType TidyEnv
    tidy_env TcType
    ty_actual
               ; ty_expected             <- readExpType ty_expected
                       -- A worry: might not be filled if we're debugging. Ugh.
               ; (tidy_env, ty_expected) <- zonkTidyTcType tidy_env ty_expected
               ; return (tidy_env, SubTypeCtxt ty_expected ty_actual) }

    ---------------
    tc_sub_type :: (TcType -> TcType -> TcM TcCoercionN)  -- How to unify
                -> CtOrigin       -- Used when instantiating
                -> UserTypeCtxt   -- Used when skolemising
                -> TcSigmaType    -- Actual; a sigma-type
                -> TcSigmaType    -- Expected; also a sigma-type
                -> TcM HsWrapper
    -- Checks that actual_ty is more polymorphic than expected_ty
    -- If wrap = tc_sub_type t1 t2
    --    => wrap :: t1 ~> t2
    --
    -- 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 :: (TcType -> TcType -> TcM Coercion)
    -> CtOrigin -> UserTypeCtxt -> TcType -> TcType -> TcM HsWrapper
    tc_sub_type TcType -> TcType -> TcM Coercion
    unify CtOrigin
    inst_orig UserTypeCtxt
    ctxt TcType
    ty_actual TcType
    ty_expected
      = do { ds_flag <- TcM DeepSubsumptionFlag
    getDeepSubsumptionFlag
           ; tc_sub_type_ds Top ds_flag unify inst_orig ctxt ty_actual ty_expected }

    ----------------------
    tc_sub_type_ds :: Position p -- ^ position in the type (for error messages only)
                   -> DeepSubsumptionFlag
                   -> (TcType -> TcType -> TcM TcCoercionN)
                   -> CtOrigin -> UserTypeCtxt -> TcSigmaType
                   -> TcSigmaType -> TcM HsWrapper
    -- tc_sub_type_ds is the main subsumption worker function
    -- It takes an explicit DeepSubsumptionFlag
    tc_sub_type_ds :: forall (p :: Polarity).
    Position p
    -> DeepSubsumptionFlag
    -> (TcType -> TcType -> TcM Coercion)
    -> CtOrigin
    -> UserTypeCtxt
    -> TcType
    -> TcType
    -> TcM HsWrapper
    tc_sub_type_ds Position p
    pos DeepSubsumptionFlag
    ds_flag TcType -> TcType -> TcM Coercion
    unify CtOrigin
    inst_orig UserTypeCtxt
    ctxt TcType
    ty_actual TcType
    ty_expected
      | TcType -> Bool
    definitely_poly TcType
    ty_expected   -- See Note [Don't skolemise unnecessarily]
      , DeepSubsumptionFlag -> TcType -> Bool
    isRhoTyDS DeepSubsumptionFlag
    ds_flag TcType
    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
    <+> TcType -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr TcType
    ty_actual
                  , String -> SDoc
    forall doc. IsLine doc => String -> doc
    text String
    "ty_expected =" SDoc -> SDoc -> SDoc
    forall doc. IsLine doc => doc -> doc -> doc
    <+> TcType -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr TcType
    ty_expected ]
           ; Coercion -> HsWrapper
    mkWpCastN (Coercion -> HsWrapper) -> TcM Coercion -> TcM HsWrapper
    forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
    <$>
             TcType -> TcType -> TcM Coercion
    unify TcType
    ty_actual TcType
    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
    <+> TcType -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr TcType
    ty_actual
                  , String -> SDoc
    forall doc. IsLine doc => String -> doc
    text String
    "ty_expected =" SDoc -> SDoc -> SDoc
    forall doc. IsLine doc => doc -> doc -> doc
    <+> TcType -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr TcType
    ty_expected ]

           ; (sk_wrap, inner_wrap)
                <- DeepSubsumptionFlag
    -> UserTypeCtxt
    -> TcType
    -> (TcType -> TcM HsWrapper)
    -> TcM (HsWrapper, HsWrapper)
    forall result.
    DeepSubsumptionFlag
    -> UserTypeCtxt
    -> TcType
    -> (TcType -> TcM result)
    -> TcM (HsWrapper, result)
    tcSkolemise DeepSubsumptionFlag
    ds_flag UserTypeCtxt
    ctxt TcType
    ty_expected ((TcType -> TcM HsWrapper) -> TcM (HsWrapper, HsWrapper))
    -> (TcType -> TcM HsWrapper) -> TcM (HsWrapper, HsWrapper)
    forall a b. (a -> b) -> a -> b
    $ \TcType
    sk_rho ->
                   case DeepSubsumptionFlag
    ds_flag of
                     DeepSubsumptionFlag
    Deep    -> Position p
    -> (TcType -> TcType -> TcM Coercion)
    -> CtOrigin
    -> UserTypeCtxt
    -> TcType
    -> TcType
    -> TcM HsWrapper
    forall (p :: Polarity).
    HasDebugCallStack =>
    Position p
    -> (TcType -> TcType -> TcM Coercion)
    -> CtOrigin
    -> UserTypeCtxt
    -> TcType
    -> TcType
    -> TcM HsWrapper
    tc_sub_type_deep Position p
    pos TcType -> TcType -> TcM Coercion
    unify CtOrigin
    inst_orig UserTypeCtxt
    ctxt TcType
    ty_actual TcType
    sk_rho
                     DeepSubsumptionFlag
    Shallow -> (TcType -> TcType -> TcM Coercion)
    -> CtOrigin -> TcType -> TcType -> TcM HsWrapper
    tc_sub_type_shallow TcType -> TcType -> TcM Coercion
    unify CtOrigin
    inst_orig TcType
    ty_actual TcType
    sk_rho

           ; return (sk_wrap <.> inner_wrap) }

    ----------------------
    tc_sub_type_shallow :: (TcType -> TcType -> TcM TcCoercionN)
                        -> CtOrigin
                        -> TcSigmaType
                        -> TcRhoType   -- Skolemised (shallow-ly)
                        -> TcM HsWrapper
    tc_sub_type_shallow :: (TcType -> TcType -> TcM Coercion)
    -> CtOrigin -> TcType -> TcType -> TcM HsWrapper
    tc_sub_type_shallow TcType -> TcType -> TcM Coercion
    unify CtOrigin
    inst_orig TcType
    ty_actual TcType
    sk_rho
      = do { (wrap, rho_a) <- CtOrigin -> TcType -> TcM (HsWrapper, TcType)
    topInstantiate CtOrigin
    inst_orig TcType
    ty_actual
           ; cow           <- unify rho_a sk_rho
           ; return (mkWpCastN cow <.> wrap) }

    ----------------------
    definitely_poly :: TcType -> Bool
    -- A very conservative test:
    -- see Note [Don't skolemise unnecessarily]
    definitely_poly :: TcType -> Bool
    definitely_poly TcType
    ty
      | ([TcTyVar]
    tvs, [TcType]
    theta, TcType
    tau) <- TcType -> ([TcTyVar], [TcType], TcType)
    tcSplitSigmaTy TcType
    ty
      , (TcTyVar
    tv:[TcTyVar]
    _) <- [TcTyVar]
    tvs   -- At least one tyvar
      , [TcType] -> Bool
    forall a. [a] -> Bool
    forall (t :: * -> *) a. Foldable t => t a -> Bool
    null [TcType]
    theta      -- No constraints; see (DP1)
      , TcTyVar
    tv TcTyVar -> TcType -> Bool
    `isInjectiveInType` TcType
    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 [Coercion errors in tcSubMult]
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    At the moment, we insist that all sub-multiplicity tests turn out
    (once the typechecker has finished its work) to be equalities,
    i.e. implementable by ReflCo.  Why?  Because our type system has
    no way to express non-Refl sub-multiplicities.

    How can we check that every call to `tcSubMult` returns `Refl`?
    It might not be `Refl` *yet*.

    [TODO: add counterexample #25130]

    So we take the following approach

    * In `tcEqMult`:
      - Emit a perfectly ordinary Wanted equality constraint for the equality,
        returning a coercion.

      - Wrap that coercion with `DE_Multiplicity` to make a `DelayedError`, and put
        that delayed error into `wc_errors` of the current WantedConstraints.  This
        is done by `ensureReflMultiplicityCo`.

    * When solving constraints, discard any `DE_Multiplicity` errors that wrap a
      reflective coercion, of kind `ty ~ ty`.  This is done in
      `GHC.Tc.Solver.simplifyDelayedErrors`

    * After constraint solving is complete report an error if there are any
      remaining `DE_Multiplicity` errors.  See
      `GHC.Tc.Errors.reportMultiplicityCoercionErrs`

    Wrinkles

    (DME1) If the multiplicity constraint is /solved/, but with a non-reflective
       coercion, we'll have just a `DE_Multiplicity` error left over.

       But if the multiplicity constraint is /unsolved/ (e.g. ManyTy ~ OneTy), we
       will have /both/ an unsolved Wanted in `wc_simple`, /and/ a `DE_Multiplicity`
       in `wc_errors`.  We don't want to report both.  Solution: suppress all
       `DE_Multiplicity` constraints if there are any unsolved wanted.

       This way, the delayed error is indeed only reported when the constraint is
       solved with a non-reflexivity coercion.

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

    tcEqMult :: CtOrigin -> Mult -> Mult -> TcM ()
    tcEqMult :: CtOrigin -> TcType -> TcType -> TcM ()
    tcEqMult CtOrigin
    origin TcType
    w_actual TcType
    w_expected = do
      {
      -- Note that here we do not call to `submult`, so we check
      -- for strict equality.
      ; coercion <- TypeOrKind -> CtOrigin -> TcType -> TcType -> TcM Coercion
    unifyTypeAndEmit TypeOrKind
    TypeLevel CtOrigin
    origin TcType
    w_actual TcType
    w_expected
      -- See Note [Coercion errors in tcSubMult].
      ; ensureReflMultiplicityCo coercion origin }

    {- *********************************************************************
    *                                                                      *
                        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 tcSkolemise Deep in tc_sub_type_deep

    2. In tcPolyExpr we must do deep skolemisation:
       see the call to tcSkolemise 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, tcSubTypeMono 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].

    Wrinkles:

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

    (DS2) When doing deep subsumption, we must be careful not to needlessly
          drop down to unification, e.g. in cases such as:
            (Bool -> ∀ d. d->d)   <=   alpha beta gamma
          See Note [FunTy vs non-FunTy case in tc_sub_type_deep].

    (DS3) The interaction between deep subsumption and required foralls
          (forall a -> ty) is a bit subtle.  See #24696 and
          Note [Deep subsumption and required foralls]

    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 [FunTy vs FunTy case in tc_sub_type_deep]
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    The goal of tc_sub_type_deep is to produce an HsWrapper that "proves" that the
    actual type is a subtype of the expected type. The most important case is how
    we deal with function arrows. Suppose we have:

      ty_actual   = act_arg -> act_res
      ty_expected = exp_arg -> exp_res

    To produce fun_wrap :: (act_arg -> act_res) ~> (exp_arg -> exp_res), we use
    the fact that the function arrow is contravariant in its argument type and
    covariant in its result type. Thus we recursively perform subtype checks
    on the argument types (with actual/expected switched) and the result types,
    to get:

      arg_wrap :: exp_arg ~> act_arg   -- NB: expected/actual have switched sides
      res_wrap :: act_res ~> exp_res

    Then fun_wrap = mkWpFun arg_wrap res_wrap.

    Wrinkle [Representation-polymorphism checking during subtyping]

      Inserting a WpFun HsWrapper amounts to impedance matching in deep subsumption
      via eta-expansion:

        f  ==>  \ (x :: exp_arg) -> res_wrap [ f (arg_wrap [x]) ]

      As we produce a lambda, we must enforce the representation polymorphism
      invariants described in Note [Representation polymorphism invariants] in GHC.Core.
      That is, we must ensure that both x (the lambda binder) and (arg_wrap [x]) (the function argument)
      have a fixed runtime representation.

      Note however that desugaring mkWpFun does not always introduce a lambda: if
      both the argument and result HsWrappers are casts, then a FunCo cast suffices,
      in which case we should not perform representation-polymorphism checking.

      This means that, in the FunTy/FunTy case of tc_sub_type_deep, we can skip
      the representation-polymorphism checks if the produced argument and result
      wrappers are identities or casts.
      It is important to do so, otherwise we reject valid programs.

        Here's a contrived example (there are undoubtedly more natural examples)
        (see testsuite/tests/rep-poly/NoEtaRequired):

          type Id :: k -> k
          type family Id a where

          type T :: TYPE r -> TYPE (Id r)
          type family T a where

          test :: forall r (a :: TYPE r). a :~~: T a -> ()
          test HRefl =
            let
              f :: (a -> a) -> ()
              f _ = ()
              g :: T a -> T a
              g = undefined
            in f g

        We don't need to eta-expand `g` to make `f g` typecheck; a cast suffices.
        Hence we should not perform representation-polymorphism checks; they would
        fail here.

    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 unify the multiplicities in tc_sub_type_deep,
    insisting on equality. This is only in the DeepSubsumption code anyway.

    Note [FunTy vs non-FunTy case in tc_sub_type_deep]
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Consider this, without Quick Look, but with Deep Subsumption:
       f :: ∀a b c. a b c -> Int
       g :: Bool -> ∀d. d -> d
    To typecheck the application (f g), we need to do the subsumption test

      (Bool -> ∀ d. d->d)   <=   alpha beta gamma

    where alpha, beta, gamma are the unification variables that instantiate a,b,c
    (respectively). We must not drop down to unification, or we will reject the call.
    Instead, we should only unify alpha := (->), in which case we end up with the
    usual FunTy vs FunTy case of Note [FunTy vs FunTy case in tc_sub_type_deep]:

      (Bool -> ∀ d. d->d)   <=   beta -> gamma

    which is straightforwardly solved by beta := Bool, using covariance in the return
    type of the function arrow, and instantiating the forall before unifying with gamma.

    The conclusion is this: when doing a deep subtype check (in tc_sub_type_deep),
    if the LHS is a FunTy and the RHS is a rho-type which is not a FunTy,
    then unify the RHS with a FunTy and continue by performing a sub-type check on
    the LHS vs the new RHS. And vice-versa (if it's the RHS that is a FunTy).

    See T11305 and T26225 for examples of when this is important.

    Note [Deep subsumption and required foralls]
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    A required forall, (forall a -> ty) behaves like a "rho-type", one with no
    top-level quantification.  In particular, it is neither implicitly instantiated nor
    skolemised.  So

      rid1 :: forall a -> a -> a
      rid1 = id

      rid2 :: forall a -> a -> a
      rid2 a = id

    Here `rid2` wll typecheck, but `rid1` will not, because we don't implicitly skolemise
    the  type.

    This "no implicit subsumption nor skolemisation" applies during subsumption.
    For example
       (forall a. a->a)  <=  (forall a -> a -> a)  -- NOT!
    does /not/ hold, because that would require implicitly skoleming the (forall a->).

    Note also that, in Core, `eqType` distinguishes between
       (forall a. blah) and forall a -> blah)
    See discussion on #22762 and these Notes in GHC.Core.TyCo.Compare
      * Note [ForAllTy and type equality]
      * Note [Comparing visibility]

    So during deep subsumption we simply stop (and drop down to equality) when we encounter
    a (forall a->).  This is a little odd:
    * Deep subsumption looks inside invisible foralls (forall a. ty)
    * Deep subsumption looks inside arrows (t1 -> t2)
    * But it does not look inside required foralls (forall a -> ty)

    There is discussion on #24696.  How is this implemented?

    * In `tc_sub_type_deep`, the calls to `topInstantiate` and `deeplyInstantiate`
      instantiate only /invisible/ binders.
    * In `tc_sub_type_ds`, the call to `tcSkolemise` skolemises only /invisible/
      binders.

    Here is a slightly more powerful alternative
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     In the story above, if we have
        (forall a -> Eq a => a -> a)  <=  (forall a -> Ord a => a -> a)
    we'll reject it, because both are rho-types but they aren't equal.  But in the
    "drop to equality" stage we could instead see if both rho-types are headed with
    (forall a ->) and if so strip that off and go back into deep subsumption.

    This is a bit more powerful, but also a bit more complicated, so GHC
    doesn't do it yet, awaiting credible user demand.  See #24696.
    -}

    data DeepSubsumptionFlag = Deep | Shallow

    instance Outputable DeepSubsumptionFlag where
        ppr :: DeepSubsumptionFlag -> SDoc
    ppr DeepSubsumptionFlag
    Deep    = String -> SDoc
    forall doc. IsLine doc => String -> doc
    text String
    "Deep"
        ppr DeepSubsumptionFlag
    Shallow = String -> SDoc
    forall doc. IsLine doc => String -> doc
    text String
    "Shallow"

    getDeepSubsumptionFlag :: TcM DeepSubsumptionFlag
    getDeepSubsumptionFlag :: TcM DeepSubsumptionFlag
    getDeepSubsumptionFlag = do { ds <- Extension -> TcM Bool
    forall gbl lcl. Extension -> TcRnIf gbl lcl Bool
    xoptM Extension
    LangExt.DeepSubsumption
                                ; if ds then return Deep else return Shallow }

    -- | 'tc_sub_type_deep' is where the actual work happens for deep subsumption.
    --
    -- Given @ty_actual@ (a sigma-type) and @ty_expected@ (deeply skolemised, i.e.
    -- a deep rho type), it returns an 'HsWrapper' @wrap :: ty_actual ~> ty_expected@.
    tc_sub_type_deep :: HasDebugCallStack
                     => Position p     -- ^ Position in the type (for error messages only)
                     -> (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_deep t1 t2
    --    => wrap :: t1 ~> t2
    -- Here is where the work actually happens!
    -- Precondition: ty_expected is deeply skolemised

    tc_sub_type_deep :: forall (p :: Polarity).
    HasDebugCallStack =>
    Position p
    -> (TcType -> TcType -> TcM Coercion)
    -> CtOrigin
    -> UserTypeCtxt
    -> TcType
    -> TcType
    -> TcM HsWrapper
    tc_sub_type_deep Position p
    pos TcType -> TcType -> TcM Coercion
    unify CtOrigin
    inst_orig UserTypeCtxt
    ctxt TcType
    ty_actual TcType
    ty_expected
      = Bool -> SDoc -> TcM HsWrapper -> TcM HsWrapper
    forall a. HasCallStack => Bool -> SDoc -> a -> a
    assertPpr (TcType -> Bool
    isDeepRhoTy TcType
    ty_expected) (TcType -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr TcType
    ty_expected) (TcM HsWrapper -> TcM HsWrapper) -> TcM HsWrapper -> TcM HsWrapper
    forall a b. (a -> b) -> a -> b
    $
        do { String -> SDoc -> TcM ()
    traceTc String
    "tc_sub_type_deep" (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
    <+> TcType -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr TcType
    ty_actual
                  , String -> SDoc
    forall doc. IsLine doc => String -> doc
    text String
    "ty_expected =" SDoc -> SDoc -> SDoc
    forall doc. IsLine doc => doc -> doc -> doc
    <+> TcType -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr TcType
    ty_expected ]
           ; TcType -> TcType -> TcM HsWrapper
    go TcType
    ty_actual TcType
    ty_expected }
      where

        -- 'unwrap' removes top-level type synonyms & looks through filled meta-tyvars
        unwrap :: TcType -> TcM TcType
        unwrap :: TcType -> TcM TcType
    unwrap TcType
    ty
          | Just TcType
    ty' <- TcType -> Maybe TcType
    coreView TcType
    ty
          = TcType -> TcM TcType
    unwrap TcType
    ty'
        unwrap ty :: TcType
    ty@(TyVarTy TcTyVar
    tv)
          = do { lookup_res <- TcTyVar -> IOEnv (Env TcGblEnv TcLclEnv) (Maybe TcType)
    isFilledMetaTyVar_maybe TcTyVar
    tv
               ; case lookup_res of
                     Just TcType
    ty' -> TcType -> TcM TcType
    unwrap TcType
    ty'
                     Maybe TcType
    Nothing  -> TcType -> TcM TcType
    forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
    forall (m :: * -> *) a. Monad m => a -> m a
    return TcType
    ty }
        unwrap TcType
    ty = TcType -> TcM TcType
    forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
    forall (m :: * -> *) a. Monad m => a -> m a
    return TcType
    ty

        go, go1 :: TcType -> TcType -> TcM HsWrapper
        go :: TcType -> TcType -> TcM HsWrapper
    go TcType
    ty_a TcType
    ty_e =
          do { ty_a' <- TcType -> TcM TcType
    unwrap TcType
    ty_a
             ; ty_e' <- unwrap ty_e
             ; go1 ty_a' ty_e' }

        -- If ty_actual is not a rho-type, instantiate it first; otherwise
        -- unification has no chance of succeeding.
        go1 :: TcType -> TcType -> TcM HsWrapper
    go1 TcType
    ty_a TcType
    ty_e
          | let ([TcTyVar]
    tvs, [TcType]
    theta, TcType
    _) = TcType -> ([TcTyVar], [TcType], TcType)
    tcSplitSigmaTy TcType
    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
    && [TcType] -> Bool
    forall a. [a] -> Bool
    forall (t :: * -> *) a. Foldable t => t a -> Bool
    null [TcType]
    theta)
          = do { (in_wrap, in_rho) <- CtOrigin -> TcType -> TcM (HsWrapper, TcType)
    topInstantiate CtOrigin
    inst_orig TcType
    ty_a
               ; body_wrap <- go in_rho ty_e
               ; return (body_wrap <.> in_wrap) }

        -- Main case: FunTy vs FunTy. go_fun does the work.
        go1 (FunTy { ft_af :: TcType -> FunTyFlag
    ft_af = FunTyFlag
    af1, ft_mult :: TcType -> TcType
    ft_mult = TcType
    act_mult, ft_arg :: TcType -> TcType
    ft_arg = TcType
    act_arg, ft_res :: TcType -> TcType
    ft_res = TcType
    act_res })
            (FunTy { ft_af :: TcType -> FunTyFlag
    ft_af = FunTyFlag
    af2, ft_mult :: TcType -> TcType
    ft_mult = TcType
    exp_mult, ft_arg :: TcType -> TcType
    ft_arg = TcType
    exp_arg, ft_res :: TcType -> TcType
    ft_res = TcType
    exp_res })
          | FunTyFlag -> Bool
    isVisibleFunArg FunTyFlag
    af1
          , FunTyFlag -> Bool
    isVisibleFunArg FunTyFlag
    af2
          = FunTyFlag
    -> TcType
    -> TcType
    -> TcType
    -> FunTyFlag
    -> TcType
    -> TcType
    -> TcType
    -> TcM HsWrapper
    go_fun FunTyFlag
    af1 TcType
    act_mult TcType
    act_arg TcType
    act_res
                   FunTyFlag
    af2 TcType
    exp_mult TcType
    exp_arg TcType
    exp_res

        -- See Note [FunTy vs non-FunTy case in tc_sub_type_deep]
        go1 (FunTy { ft_af :: TcType -> FunTyFlag
    ft_af = FunTyFlag
    af1, ft_mult :: TcType -> TcType
    ft_mult = TcType
    act_mult, ft_arg :: TcType -> TcType
    ft_arg = TcType
    act_arg, ft_res :: TcType -> TcType
    ft_res = TcType
    act_res }) TcType
    ty_e
          | FunTyFlag -> Bool
    isVisibleFunArg FunTyFlag
    af1
          = do { exp_mult <- TcM TcType
    newMultiplicityVar
               ; exp_arg  <- newOpenFlexiTyVarTy -- NB: no FRR check needed; we might not need to eta-expand
               ; exp_res  <- newOpenFlexiTyVarTy
               ; let exp_funTy = FunTy { ft_af :: FunTyFlag
    ft_af = FunTyFlag
    af1, ft_mult :: TcType
    ft_mult = TcType
    exp_mult, ft_arg :: TcType
    ft_arg = TcType
    exp_arg, ft_res :: TcType
    ft_res = TcType
    exp_res }
               ; unify_wrap <- just_unify exp_funTy ty_e
               ; fun_wrap <- go_fun af1 act_mult act_arg act_res af1 exp_mult exp_arg exp_res
               ; return $ unify_wrap <.> fun_wrap
                 -- unify_wrap :: exp_funTy ~> ty_e
                 -- fun_wrap :: ty_a ~> exp_funTy
               }
        go1 TcType
    ty_a (FunTy { ft_af :: TcType -> FunTyFlag
    ft_af = FunTyFlag
    af2, ft_mult :: TcType -> TcType
    ft_mult = TcType
    exp_mult, ft_arg :: TcType -> TcType
    ft_arg = TcType
    exp_arg, ft_res :: TcType -> TcType
    ft_res = TcType
    exp_res })
          | FunTyFlag -> Bool
    isVisibleFunArg FunTyFlag
    af2
          = do { act_mult <- TcM TcType
    newMultiplicityVar
               ; act_arg  <- newOpenFlexiTyVarTy -- NB: no FRR check needed; we might not need to eta-expand
               ; act_res  <- newOpenFlexiTyVarTy
               ; let act_funTy = FunTy { ft_af :: FunTyFlag
    ft_af = FunTyFlag
    af2, ft_mult :: TcType
    ft_mult = TcType
    act_mult, ft_arg :: TcType
    ft_arg = TcType
    act_arg, ft_res :: TcType
    ft_res = TcType
    act_res }

               ; unify_wrap <- just_unify ty_a act_funTy
               ; fun_wrap <- go_fun af2 act_mult act_arg act_res af2 exp_mult exp_arg exp_res
               ; return $ fun_wrap <.> unify_wrap
                 -- unify_wrap :: ty_a ~> act_funTy
                 -- fun_wrap :: act_funTy ~> ty_e
               }

        -- Otherwise, revert to unification.
        go1 TcType
    ty_a TcType
    ty_e = TcType -> TcType -> TcM HsWrapper
    just_unify TcType
    ty_a TcType
    ty_e

        just_unify :: TcType -> TcType -> TcM HsWrapper
    just_unify TcType
    ty_a TcType
    ty_e = do { cow <- TcType -> TcType -> TcM Coercion
    unify TcType
    ty_a TcType
    ty_e
                                  ; return (mkWpCastN cow) }

        -- FunTy/FunTy case: this is where we insert any necessary eta-expansions.
        go_fun :: FunTyFlag -> Mult -> TcType -> TcType -- actual FunTy
               -> FunTyFlag -> Mult -> TcType -> TcType -- expected FunTy
               -> TcM HsWrapper
        go_fun :: FunTyFlag
    -> TcType
    -> TcType
    -> TcType
    -> FunTyFlag
    -> TcType
    -> TcType
    -> TcType
    -> TcM HsWrapper
    go_fun FunTyFlag
    act_af TcType
    act_mult TcType
    act_arg TcType
    act_res FunTyFlag
    exp_af TcType
    exp_mult TcType
    exp_arg TcType
    exp_res
          -- See Note [FunTy vs FunTy case in tc_sub_type_deep]
          = do { arg_wrap  <- Position (FlipPolarity p)
    -> DeepSubsumptionFlag
    -> (TcType -> TcType -> TcM Coercion)
    -> CtOrigin
    -> UserTypeCtxt
    -> TcType
    -> TcType
    -> TcM HsWrapper
    forall (p :: Polarity).
    Position p
    -> DeepSubsumptionFlag
    -> (TcType -> TcType -> TcM Coercion)
    -> CtOrigin
    -> UserTypeCtxt
    -> TcType
    -> TcType
    -> TcM HsWrapper
    tc_sub_type_ds (Position p -> Position (FlipPolarity p)
    forall (p1 :: Polarity). Position p1 -> Position (FlipPolarity p1)
    Argument Position p
    pos) DeepSubsumptionFlag
    Deep TcType -> TcType -> TcM Coercion
    unify CtOrigin
    given_orig UserTypeCtxt
    GenSigCtxt TcType
    exp_arg TcType
    act_arg
                              -- GenSigCtxt: See Note [Setting the argument context]
               ; res_wrap  <- tc_sub_type_deep (Result pos) unify inst_orig ctxt act_res exp_res

               ; mkWpFun_FRR unify pos
                   act_af act_mult act_arg act_res
                   exp_af exp_mult exp_arg exp_res
                   arg_wrap res_wrap
               }
          where
            given_orig :: CtOrigin
    given_orig = SkolemInfoAnon -> CtOrigin
    GivenOrigin (UserTypeCtxt -> TcType -> [(Name, TcTyVar)] -> SkolemInfoAnon
    SigSkol UserTypeCtxt
    GenSigCtxt TcType
    exp_arg [])

    -- | Like 'mkWpFun', except that it performs the necessary
    -- representation-polymorphism checks on the argument type in the case that
    -- we introduce a lambda abstraction.
    mkWpFun_FRR
      :: (TcType -> TcType -> TcM TcCoercionN) -- ^ how to unify
      -> Position p
      -> FunTyFlag -> Type -> TcType -> Type --   actual FunTy
      -> FunTyFlag -> Type -> TcType -> Type -- expected FunTy
      -> HsWrapper -- ^ exp_arg ~> act_arg
      -> HsWrapper -- ^ act_res ~> exp_res
      -> TcM HsWrapper -- ^ act_funTy ~> exp_funTy
    mkWpFun_FRR :: forall (p :: Polarity).
    (TcType -> TcType -> TcM Coercion)
    -> Position p
    -> FunTyFlag
    -> TcType
    -> TcType
    -> TcType
    -> FunTyFlag
    -> TcType
    -> TcType
    -> TcType
    -> HsWrapper
    -> HsWrapper
    -> TcM HsWrapper
    mkWpFun_FRR TcType -> TcType -> TcM Coercion
    unify Position p
    pos FunTyFlag
    act_af TcType
    act_mult TcType
    act_arg TcType
    act_res FunTyFlag
    exp_af TcType
    exp_mult TcType
    exp_arg TcType
    exp_res HsWrapper
    arg_wrap HsWrapper
    res_wrap
      = do { ((exp_arg_co, exp_arg_frr), (act_arg_co, _act_arg_frr)) <-
                if Bool
    needs_frr_checks
                  -- See Wrinkle [Representation-polymorphism checking during subtyping]
                then do { exp_frr_wrap <- HasDebugCallStack =>
    FixedRuntimeRepContext -> TcType -> TcM (Coercion, TcType)
    FixedRuntimeRepContext -> TcType -> TcM (Coercion, TcType)
    hasFixedRuntimeRep (Bool -> FixedRuntimeRepContext
    frr_ctxt Bool
    True ) TcType
    exp_arg
                        ; act_frr_wrap <- hasFixedRuntimeRep (frr_ctxt False) act_arg
                        ; return (exp_frr_wrap, act_frr_wrap) }
                else ((Coercion, TcType), (Coercion, TcType))
    -> IOEnv
         (Env TcGblEnv TcLclEnv) ((Coercion, TcType), (Coercion, TcType))
    forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
    forall (m :: * -> *) a. Monad m => a -> m a
    return ((TcType -> Coercion
    mkNomReflCo TcType
    exp_arg, TcType
    exp_arg), (TcType -> Coercion
    mkNomReflCo TcType
    act_arg, TcType
    act_arg))

             -- Enforce equality of multiplicities (not the more natural sub-multiplicity).
             -- See Note [Multiplicity in deep subsumption]
           ; act_arg_mult_co <- unify act_mult exp_mult
               -- NB: don't use tcEqMult: that would require the evidence for
               -- equality to be Refl, but it might well not be (#26332).

           ; let
                exp_arg_fun_co =
                  Role -> FunTyFlag -> Coercion -> Coercion -> Coercion -> Coercion
    mkFunCo Role
    Nominal FunTyFlag
    exp_af
                     (Role -> TcType -> Coercion
    mkReflCo Role
    Nominal TcType
    exp_mult)
                     (Coercion -> Coercion
    mkSymCo Coercion
    exp_arg_co)
                     (Role -> TcType -> Coercion
    mkReflCo Role
    Nominal TcType
    exp_res)
                act_arg_fun_co =
                  Role -> FunTyFlag -> Coercion -> Coercion -> Coercion -> Coercion
    mkFunCo Role
    Nominal FunTyFlag
    act_af
                     Coercion
    act_arg_mult_co
                     Coercion
    act_arg_co
                     (Role -> TcType -> Coercion
    mkReflCo Role
    Nominal TcType
    act_res)
                arg_wrap_frr =
                  Coercion -> HsWrapper
    mkWpCastN (Coercion -> Coercion
    mkSymCo Coercion
    exp_arg_co) HsWrapper -> HsWrapper -> HsWrapper
    <.> HsWrapper
    arg_wrap HsWrapper -> HsWrapper -> HsWrapper
    <.> Coercion -> HsWrapper
    mkWpCastN Coercion
    act_arg_co
                   --  exp_arg_co :: exp_arg ~> exp_arg_frr
                   --  act_arg_co :: act_arg ~> act_arg_frr
                   --  arg_wrap :: exp_arg ~> act_arg
                   --  arg_wrap_frr :: exp_arg_frr ~> act_arg_frr

           ; return $
                mkWpCastN exp_arg_fun_co
                  <.>
                mkWpFun arg_wrap_frr res_wrap (Scaled exp_mult exp_arg_frr) exp_res
                  <.>
                mkWpCastN act_arg_fun_co
           }
      where
        needs_frr_checks :: Bool
        needs_frr_checks :: Bool
    needs_frr_checks =
          Bool -> Bool
    not (HsWrapper -> Bool
    hole_or_cast HsWrapper
    arg_wrap)
            Bool -> Bool -> Bool
    ||
          Bool -> Bool
    not (HsWrapper -> Bool
    hole_or_cast HsWrapper
    res_wrap)
        hole_or_cast :: HsWrapper -> Bool
        hole_or_cast :: HsWrapper -> Bool
    hole_or_cast HsWrapper
    WpHole = Bool
    True
        hole_or_cast (WpCast {}) = Bool
    True
        hole_or_cast HsWrapper
    _ = Bool
    False
        frr_ctxt :: Bool -> FixedRuntimeRepContext
        frr_ctxt :: Bool -> FixedRuntimeRepContext
    frr_ctxt Bool
    is_exp_ty =
          FRRDeepSubsumption
            { frrDSExpected :: Bool
    frrDSExpected = Bool
    is_exp_ty
            , frrDSPosition :: Position p
    frrDSPosition = Position p
    pos
            }

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

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

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

    dsInstantiate :: CtOrigin -> TcType -> TcM (HsWrapper, Type)
    -- Do topInstantiate or deeplyInstantiate, depending on -XDeepSubsumption
    dsInstantiate :: CtOrigin -> TcType -> TcM (HsWrapper, TcType)
    dsInstantiate CtOrigin
    orig TcType
    ty
      = do { ds_flag <- TcM DeepSubsumptionFlag
    getDeepSubsumptionFlag
           ; case ds_flag of
               DeepSubsumptionFlag
    Shallow -> CtOrigin -> TcType -> TcM (HsWrapper, TcType)
    topInstantiate    CtOrigin
    orig TcType
    ty
               DeepSubsumptionFlag
    Deep    -> CtOrigin -> TcType -> TcM (HsWrapper, TcType)
    deeplyInstantiate CtOrigin
    orig TcType
    ty }

    deeplyInstantiate :: CtOrigin -> TcType -> TcM (HsWrapper, Type)
    -- Instantiate invisible foralls, even ones nested
    -- (to the right) under arrows
    deeplyInstantiate :: CtOrigin -> TcType -> TcM (HsWrapper, TcType)
    deeplyInstantiate CtOrigin
    orig TcType
    ty
      = Subst -> TcType -> TcM (HsWrapper, TcType)
    go Subst
    init_subst TcType
    ty
      where
        init_subst :: Subst
    init_subst = InScopeSet -> Subst
    mkEmptySubst (VarSet -> InScopeSet
    mkInScopeSet (TcType -> VarSet
    tyCoVarsOfType TcType
    ty))

        go :: Subst -> TcType -> TcM (HsWrapper, TcType)
    go Subst
    subst TcType
    ty
          | Just ([Scaled TcType]
    arg_tys, [TcInvisTVBinder]
    bndrs, [TcType]
    theta, TcType
    rho) <- TcType
    -> Maybe ([Scaled TcType], [TcInvisTVBinder], [TcType], TcType)
    tcDeepSplitSigmaTy_maybe TcType
    ty
          = do { let tvs :: [TcTyVar]
    tvs = [TcInvisTVBinder] -> [TcTyVar]
    forall tv argf. [VarBndr tv argf] -> [tv]
    binderVars [TcInvisTVBinder]
    bndrs
               ; (subst', tvs') <- Subst -> [TcTyVar] -> TcM (Subst, [TcTyVar])
    newMetaTyVarsX Subst
    subst [TcTyVar]
    tvs
               ; let arg_tys' = HasDebugCallStack => Subst -> [Scaled TcType] -> [Scaled TcType]
    Subst -> [Scaled TcType] -> [Scaled TcType]
    substScaledTys   Subst
    subst' [Scaled TcType]
    arg_tys
                     theta'   = HasDebugCallStack => Subst -> [TcType] -> [TcType]
    Subst -> [TcType] -> [TcType]
    substTheta Subst
    subst' [TcType]
    theta
               ; ids1  <- newSysLocalIds (fsLit "di") arg_tys'
               ; wrap1 <- instCall orig (mkTyVarTys tvs') theta'
               ; (wrap2, rho2) <- go subst' rho
               ; return (mkWpEta ids1 (wrap2 <.> wrap1),
                         mkScaledFunTys arg_tys' rho2) }

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

    tcDeepSplitSigmaTy_maybe
      :: TcSigmaType -> Maybe ([Scaled TcType], [TcInvisTVBinder], 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 :: TcType
    -> Maybe ([Scaled TcType], [TcInvisTVBinder], [TcType], TcType)
    tcDeepSplitSigmaTy_maybe TcType
    ty
      = TcType
    -> Maybe ([Scaled TcType], [TcInvisTVBinder], [TcType], TcType)
    go TcType
    ty
      where
      go :: TcType
    -> Maybe ([Scaled TcType], [TcInvisTVBinder], [TcType], TcType)
    go TcType
    ty | Just (Scaled TcType
    arg_ty, TcType
    res_ty)           <- TcType -> Maybe (Scaled TcType, TcType)
    tcSplitFunTy_maybe TcType
    ty
            , Just ([Scaled TcType]
    arg_tys, [TcInvisTVBinder]
    tvs, [TcType]
    theta, TcType
    rho) <- TcType
    -> Maybe ([Scaled TcType], [TcInvisTVBinder], [TcType], TcType)
    go TcType
    res_ty
            = ([Scaled TcType], [TcInvisTVBinder], [TcType], TcType)
    -> Maybe ([Scaled TcType], [TcInvisTVBinder], [TcType], TcType)
    forall a. a -> Maybe a
    Just (Scaled TcType
    arg_tyScaled TcType -> [Scaled TcType] -> [Scaled TcType]
    forall a. a -> [a] -> [a]
    :[Scaled TcType]
    arg_tys, [TcInvisTVBinder]
    tvs, [TcType]
    theta, TcType
    rho)

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

            | Bool
    otherwise = Maybe ([Scaled TcType], [TcInvisTVBinder], [TcType], TcType)
    forall a. Maybe a
    Nothing

    isDeepRhoTy :: TcType -> Bool
    -- True if there are no foralls or (=>) at the top, or nested under
    -- arrows to the right.  e.g
    --    forall a. a                  False
    --    Int -> forall a. a           False
    --    (forall a. a) -> Int         True
    -- Returns True iff tcDeepSplitSigmaTy_maybe returns Nothing
    isDeepRhoTy :: TcType -> Bool
    isDeepRhoTy TcType
    ty
      | Bool -> Bool
    not (TcType -> Bool
    isRhoTy TcType
    ty)                       = Bool
    False  -- Foralls or (=>) at top
      | Just (Scaled TcType
    _, TcType
    res) <- TcType -> Maybe (Scaled TcType, TcType)
    tcSplitFunTy_maybe TcType
    ty = TcType -> Bool
    isDeepRhoTy TcType
    res
      | Bool
    otherwise                              = Bool
    True   -- No forall, (=>), or (->) at top

    isRhoTyDS :: DeepSubsumptionFlag -> TcType -> Bool
    isRhoTyDS :: DeepSubsumptionFlag -> TcType -> Bool
    isRhoTyDS DeepSubsumptionFlag
    ds_flag TcType
    ty
      = case DeepSubsumptionFlag
    ds_flag of
          DeepSubsumptionFlag
    Shallow -> TcType -> Bool
    isRhoTy TcType
    ty      -- isRhoTy: no top level forall or (=>)
          DeepSubsumptionFlag
    Deep    -> TcType -> Bool
    isDeepRhoTy TcType
    ty  -- "deep" version: no nested forall or (=>)

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

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

    unifyExprType :: HsExpr GhcRn -> TcType -> TcType -> TcM TcCoercionN
    unifyExprType :: HsExpr GhcRn -> TcType -> TcType -> TcM Coercion
    unifyExprType HsExpr GhcRn
    rn_expr TcType
    ty1 TcType
    ty2
      = Maybe TypedThing -> TcType -> TcType -> TcM Coercion
    unifyType (TypedThing -> Maybe TypedThing
    forall a. a -> Maybe a
    Just (HsExpr GhcRn -> TypedThing
    HsExprRnThing HsExpr GhcRn
    rn_expr)) TcType
    ty1 TcType
    ty2

    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 -> TcType -> TcType -> TcM Coercion
    unifyType Maybe TypedThing
    thing TcType
    ty1 TcType
    ty2
      = TypeOrKind -> CtOrigin -> TcType -> TcType -> TcM Coercion
    unifyTypeAndEmit TypeOrKind
    TypeLevel CtOrigin
    origin TcType
    ty1 TcType
    ty2
      where
        origin :: CtOrigin
    origin = TypeEqOrigin { uo_actual :: TcType
    uo_actual   = TcType
    ty1
                              , uo_expected :: TcType
    uo_expected = TcType
    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 :: TcType -> TcType -> TcM Coercion
    unifyInvisibleType TcType
    ty1 TcType
    ty2
      = TypeOrKind -> CtOrigin -> TcType -> TcType -> TcM Coercion
    unifyTypeAndEmit TypeOrKind
    TypeLevel CtOrigin
    origin TcType
    ty1 TcType
    ty2
      where
        origin :: CtOrigin
    origin = TypeEqOrigin { uo_actual :: TcType
    uo_actual   = TcType
    ty1
                              , uo_expected :: TcType
    uo_expected = TcType
    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 :: TcType -> TcType -> TcM Coercion
    unifyTypeET TcType
    ty1 TcType
    ty2
      = TypeOrKind -> CtOrigin -> TcType -> TcType -> TcM Coercion
    unifyTypeAndEmit TypeOrKind
    TypeLevel CtOrigin
    origin TcType
    ty1 TcType
    ty2
      where
        origin :: CtOrigin
    origin = TypeEqOrigin { uo_actual :: TcType
    uo_actual   = TcType
    ty2   -- NB swapped
                              , uo_expected :: TcType
    uo_expected = TcType
    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 -> TcType -> TcType -> TcM Coercion
    unifyKind Maybe TypedThing
    mb_thing TcType
    ty1 TcType
    ty2
      = TypeOrKind -> CtOrigin -> TcType -> TcType -> TcM Coercion
    unifyTypeAndEmit TypeOrKind
    KindLevel CtOrigin
    origin TcType
    ty1 TcType
    ty2
      where
        origin :: CtOrigin
    origin = TypeEqOrigin { uo_actual :: TcType
    uo_actual   = TcType
    ty1
                              , uo_expected :: TcType
    uo_expected = TcType
    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 -> TcType -> TcType -> TcM Coercion
    unifyTypeAndEmit TypeOrKind
    t_or_k CtOrigin
    orig TcType
    ty1 TcType
    ty2
      = do { 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
           ; loc <- getCtLocM orig (Just t_or_k)
           ; let 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
           ; co <- uType env ty1 ty2

           ; cts <- readTcRef ref
           ; unless (null cts) (emitSimples cts)
           ; return 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 -> TcType -> TcType -> UnifyEnv
    mkKindEnv env :: UnifyEnv
    env@(UE { u_loc :: UnifyEnv -> CtLoc
    u_loc = CtLoc
    ctloc }) TcType
    ty1 TcType
    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 -> TcType -> TcType -> 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 })
                TcType
    ty1 TcType
    ty2  -- ty1 is "actual", ty2 is "expected"
      = do { let pred_ty :: TcType
    pred_ty = Role -> TcType -> TcType -> TcType
    mkEqPredRole Role
    role TcType
    ty1 TcType
    ty2
           ; hole <- TcType -> TcM CoercionHole
    newCoercionHole TcType
    pred_ty
           ; let ct = CtEvidence -> Ct
    mkNonCanonical (CtEvidence -> Ct) -> CtEvidence -> Ct
    forall a b. (a -> b) -> a -> b
    $ WantedCtEvidence -> CtEvidence
    CtWanted (WantedCtEvidence -> CtEvidence) -> WantedCtEvidence -> CtEvidence
    forall a b. (a -> b) -> a -> b
    $
                        WantedCt { ctev_pred :: TcType
    ctev_pred      = TcType
    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 = CoercionHole -> Coercion
    HoleCo CoercionHole
    hole
           ; updTcRef ref (`snocBag` ct)
             -- snocBag: see Note [Work-list ordering] in GHC.Tc.Solver.Equality

           -- Error trace only
           -- NB. do *not* call mkErrCtxt unless tracing is on,
           --     because it is hugely expensive (#5631)
           ; whenDOptM Opt_D_dump_tc_trace $
             do { ctxt     <- getErrCtxt
                ; err_ctxt <- mkErrCtxt emptyTidyEnv ctxt
                ; traceTc "utype_defer" $
                    vcat ( ppr role
                         : debugPprType ty1
                         : debugPprType ty2
                         : map pprErrCtxtMsg err_ctxt )
                ; traceTc "utype_defer2" (ppr co) }

           ; return co }

    --------------
    uType :: UnifyEnv -> TcType -> TcType -> TcM Coercion
    uType env :: UnifyEnv
    env@(UE { u_role :: UnifyEnv -> Role
    u_role = Role
    role }) TcType
    orig_ty1 TcType
    orig_ty2
      | Role
    Phantom <- Role
    role
      = do { kind_co <- UnifyEnv -> TcType -> TcType -> TcM Coercion
    uType (UnifyEnv -> TcType -> TcType -> UnifyEnv
    mkKindEnv UnifyEnv
    env TcType
    orig_ty1 TcType
    orig_ty2)
                              (HasDebugCallStack => TcType -> TcType
    TcType -> TcType
    typeKind TcType
    orig_ty1) (HasDebugCallStack => TcType -> TcType
    TcType -> TcType
    typeKind TcType
    orig_ty2)
           ; return (mkPhantomCo kind_co orig_ty1 orig_ty2) }

      | Bool
    otherwise
      = do { tclvl <- TcM TcLevel
    getTcLevel
           ; traceTc "u_tys" $ vcat
                  [ text "tclvl" <+> ppr tclvl
                  , sep [ ppr orig_ty1, text "~" <> ppr role, ppr orig_ty2] ]
           ; co <- go orig_ty1 orig_ty2
           ; if isReflCo co
                then traceTc "u_tys yields no coercion" Outputable.empty
                else traceTc "u_tys yields coercion:" (ppr co)
           ; return co }
      where
        go :: TcType -> TcType -> TcM CoercionN
            -- The arguments to 'go' are always semantically identical
            -- to orig_ty{1,2} except for looking through type synonyms

         -- Unwrap casts before looking for variables. This way, we can easily
         -- recognize (t |> co) ~ (t |> co), which is nice. Previously, we
         -- didn't do it this way, and then the unification above was deferred.
        go :: TcType -> TcType -> TcM Coercion
    go (CastTy TcType
    t1 Coercion
    co1) TcType
    t2
          = do { co_tys <- UnifyEnv -> TcType -> TcType -> TcM Coercion
    uType UnifyEnv
    env TcType
    t1 TcType
    t2
               ; return (mkCoherenceLeftCo role t1 co1 co_tys) }

        go TcType
    t1 (CastTy TcType
    t2 Coercion
    co2)
          = do { co_tys <- UnifyEnv -> TcType -> TcType -> TcM Coercion
    uType UnifyEnv
    env TcType
    t1 TcType
    t2
               ; return (mkCoherenceRightCo role t2 co2 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) TcType
    ty2
          = do { lookup_res <- TcTyVar -> IOEnv (Env TcGblEnv TcLclEnv) (Maybe TcType)
    isFilledMetaTyVar_maybe TcTyVar
    tv1
               ; case lookup_res of
                   Just TcType
    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
    <+> TcType -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr TcType
    ty1)
                                  ; UnifyEnv -> TcType -> TcType -> TcM Coercion
    uType UnifyEnv
    env TcType
    ty1 TcType
    orig_ty2 }
                   Maybe TcType
    Nothing -> UnifyEnv -> SwapFlag -> TcTyVar -> TcType -> TcM Coercion
    uUnfilledVar UnifyEnv
    env SwapFlag
    NotSwapped TcTyVar
    tv1 TcType
    ty2 }

        go TcType
    ty1 (TyVarTy TcTyVar
    tv2)
          = do { lookup_res <- TcTyVar -> IOEnv (Env TcGblEnv TcLclEnv) (Maybe TcType)
    isFilledMetaTyVar_maybe TcTyVar
    tv2
               ; case lookup_res of
                   Just TcType
    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
    <+> TcType -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr TcType
    ty2)
                                  ; UnifyEnv -> TcType -> TcType -> TcM Coercion
    uType UnifyEnv
    env TcType
    orig_ty1 TcType
    ty2 }
                   Maybe TcType
    Nothing -> UnifyEnv -> SwapFlag -> TcTyVar -> TcType -> TcM Coercion
    uUnfilledVar UnifyEnv
    env SwapFlag
    IsSwapped TcTyVar
    tv2 TcType
    ty1 }

          -- See Note [Unifying type synonyms] in GHC.Core.Unify
        go ty1 :: TcType
    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 -> TcType -> Coercion
    mkReflCo Role
    role TcType
    ty1

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

        -- Functions (t1 -> t2) just check the two parts
        go (FunTy { ft_af :: TcType -> FunTyFlag
    ft_af = FunTyFlag
    af1, ft_mult :: TcType -> TcType
    ft_mult = TcType
    w1, ft_arg :: TcType -> TcType
    ft_arg = TcType
    arg1, ft_res :: TcType -> TcType
    ft_res = TcType
    res1 })
           (FunTy { ft_af :: TcType -> FunTyFlag
    ft_af = FunTyFlag
    af2, ft_mult :: TcType -> TcType
    ft_mult = TcType
    w2, ft_arg :: TcType -> TcType
    ft_arg = TcType
    arg2, ft_res :: TcType -> TcType
    ft_res = TcType
    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 { co_w <- UnifyEnv -> TcType -> TcType -> TcM Coercion
    uType (UnifyEnv
    env { u_role = funRole role SelMult }) TcType
    w1   TcType
    w2
               ; co_l <- uType (env { u_role = funRole role SelArg })  arg1 arg2
               ; co_r <- uType (env { u_role = funRole role SelRes })  res1 res2
               ; return $ mkNakedFunCo role af1 co_w co_l co_r }

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

        go (TyConApp TyCon
    tc1 [TcType]
    tys1) (TyConApp TyCon
    tc2 [TcType]
    tys2)
          -- See Note [Mismatched type lists and application decomposition]
          | TyCon
    tc1 TyCon -> TyCon -> Bool
    forall a. Eq a => a -> a -> Bool
    == TyCon
    tc2, [TcType] -> [TcType] -> Bool
    forall a b. [a] -> [b] -> Bool
    equalLength [TcType]
    tys1 [TcType]
    tys2
          , 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
    $$ [TcType] -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr [TcType]
    tys1 SDoc -> SDoc -> SDoc
    forall doc. IsDoc doc => doc -> doc -> doc
    $$ [TcType] -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr [TcType]
    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)))
               ; cos <- (Bool -> Role -> TcType -> TcType -> TcM Coercion)
    -> [Bool]
    -> [Role]
    -> [TcType]
    -> [TcType]
    -> 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 -> TcType -> TcType -> TcM Coercion
    u_tc_arg (TyCon -> [Bool]
    tyConVisibilities TyCon
    tc1)   -- Infinite
                                           (Role -> TyCon -> [Role]
    tyConRoleListX Role
    role TyCon
    tc1) -- Infinite
                                           [TcType]
    tys1 [TcType]
    tys2
               ; return $ mkTyConAppCo role tc1 cos }

        go (LitTy TyLit
    m) ty :: TcType
    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 -> TcType -> Coercion
    mkReflCo Role
    role TcType
    ty

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

        go ty1 :: TcType
    ty1@(AppTy TcType
    s1 TcType
    t1) ty2 :: TcType
    ty2@(TyConApp TyCon
    tc2 [TcType]
    ts2)
          | Just ([TcType]
    ts2', TcType
    t2') <- [TcType] -> Maybe ([TcType], TcType)
    forall a. [a] -> Maybe ([a], a)
    snocView [TcType]
    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
    -> TcType
    -> TcType
    -> TcType
    -> TcType
    -> TcType
    -> TcType
    -> TcM Coercion
    go_app (TyCon -> [TcType] -> Bool
    isNextTyConArgVisible TyCon
    tc2 [TcType]
    ts2')
                   TcType
    ty1 TcType
    s1 TcType
    t1 TcType
    ty2 (TyCon -> [TcType] -> TcType
    TyConApp TyCon
    tc2 [TcType]
    ts2') TcType
    t2'

        go ty1 :: TcType
    ty1@(TyConApp TyCon
    tc1 [TcType]
    ts1) ty2 :: TcType
    ty2@(AppTy TcType
    s2 TcType
    t2)
          | Just ([TcType]
    ts1', TcType
    t1') <- [TcType] -> Maybe ([TcType], TcType)
    forall a. [a] -> Maybe ([a], a)
    snocView [TcType]
    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
    -> TcType
    -> TcType
    -> TcType
    -> TcType
    -> TcType
    -> TcType
    -> TcM Coercion
    go_app (TyCon -> [TcType] -> Bool
    isNextTyConArgVisible TyCon
    tc1 [TcType]
    ts1')
                   TcType
    ty1 (TyCon -> [TcType] -> TcType
    TyConApp TyCon
    tc1 [TcType]
    ts1') TcType
    t1' TcType
    ty2 TcType
    s2 TcType
    t2

        go ty1 :: TcType
    ty1@(CoercionTy Coercion
    co1) ty2 :: TcType
    ty2@(CoercionTy Coercion
    co2)
          = do { kco <- UnifyEnv -> TcType -> TcType -> TcM Coercion
    uType (UnifyEnv -> TcType -> TcType -> UnifyEnv
    mkKindEnv UnifyEnv
    env TcType
    ty1 TcType
    ty2)
                              (Coercion -> TcType
    coercionType Coercion
    co1) (Coercion -> TcType
    coercionType Coercion
    co2)
               ; return $ mkProofIrrelCo role kco co1 co2 }

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

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

        ------------------
        u_tc_arg :: Bool -> Role -> TcType -> TcType -> TcM Coercion
    u_tc_arg Bool
    is_vis Role
    role TcType
    ty1 TcType
    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
    $$ TcType -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr TcType
    ty1 SDoc -> SDoc -> SDoc
    forall doc. IsDoc doc => doc -> doc -> doc
    $$ TcType -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr TcType
    ty2)
               ; UnifyEnv -> TcType -> TcType -> TcM Coercion
    uType UnifyEnv
    env_arg TcType
    ty1 TcType
    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
    -> TcType
    -> TcType
    -> TcType
    -> TcType
    -> TcType
    -> TcType
    -> TcM Coercion
    go_app Bool
    vis TcType
    ty1 TcType
    s1 TcType
    t1 TcType
    ty2 TcType
    s2 TcType
    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) }
               ; co_t <- UnifyEnv -> TcType -> TcType -> TcM Coercion
    uType UnifyEnv
    env_arg TcType
    t1 TcType
    t2
               ; co_s <- uType env s1 s2
               ; return $ mkAppCo co_s co_t }
          | Bool
    otherwise
          = TcType -> TcType -> TcM Coercion
    defer TcType
    ty1 TcType
    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.  See Note [Unifying type synonyms] in GHC.Core.Unify.

    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 -> TcType -> TcM Coercion
    uUnfilledVar UnifyEnv
    env SwapFlag
    swapped TcTyVar
    tv1 TcType
    ty2
      | Role
    Nominal <- UnifyEnv -> Role
    u_role UnifyEnv
    env
      = do { ty2 <- ZonkM TcType -> TcM TcType
    forall a. ZonkM a -> TcM a
    liftZonkM (ZonkM TcType -> TcM TcType) -> ZonkM TcType -> TcM TcType
    forall a b. (a -> b) -> a -> b
    $ TcType -> ZonkM TcType
    zonkTcType TcType
    ty2
                      -- Zonk to expose things to the occurs check, and so
                      -- that if ty2 looks like a type variable then it
                      -- /is/ a type variable
           ; uUnfilledVar1 env swapped tv1 ty2 }

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

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

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

      where
        -- 'go' handles the case where both are
        -- tyvars so we might want to swap
        -- E.g. maybe tv2 is a meta-tyvar and tv1 is not
        go :: 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 (TcType -> Coercion
    mkNomReflCo (TcTyVar -> TcType
    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 { 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
                    ; uUnfilledVar2 env (flipSwap swapped) tv2 (mkTyVarTy tv1) }

               | Bool
    otherwise
               = UnifyEnv -> SwapFlag -> TcTyVar -> TcType -> TcM Coercion
    uUnfilledVar2 UnifyEnv
    env SwapFlag
    swapped TcTyVar
    tv1 TcType
    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 -> TcType -> 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 TcType
    ty2
      = do { cur_lvl <- TcM TcLevel
    getTcLevel
               -- See Note [Unification preconditions], (UNTOUCHABLE) wrinkles
               -- Here we don't know about given equalities; so we treat
               -- /any/ level outside this one as untouchable.  Hence cur_lvl.
           ; if simpleUnifyCheck UC_OnTheFly cur_lvl tv1 ty2 /= SUC_CanUnify
             then not_ok_so_defer cur_lvl
             else
        do { def_eqs <- readTcRef def_eq_ref  -- Capture current state of def_eqs

           -- Attempt to unify kinds
           -- When doing so, be careful to preserve orientation;
           --    see Note [Kind Equality Orientation] in GHC.Tc.Solver.Equality
           --    and wrinkle (W2) in Note [Fundeps with instances, and equality orientation]
           --        in GHC.Tc.Solver.Dict
           -- Failing to preserve orientation led to #25597.
           ; let kind_env = SwapFlag
    -> (TcType -> TcType -> UnifyEnv) -> TcType -> TcType -> UnifyEnv
    forall a b. SwapFlag -> (a -> a -> b) -> a -> a -> b
    unSwap SwapFlag
    swapped (UnifyEnv -> TcType -> TcType -> UnifyEnv
    mkKindEnv UnifyEnv
    env) TcType
    ty1 TcType
    ty2
           ; co_k <- unSwap swapped (uType kind_env) (tyVarKind tv1) (typeKind ty2)

           ; traceTc "uUnfilledVar2 ok" $
             vcat [ ppr tv1 <+> dcolon <+> ppr (tyVarKind tv1)
                  , ppr ty2 <+> dcolon <+> ppr (typeKind  ty2)
                  , ppr (isReflCo co_k), ppr co_k ]

           ; if isReflCo 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 { liftZonkM $ writeMetaTyVar tv1 ty2
                     ; case u_unified 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]
    :)
                     ; return (mkNomReflCo ty2) }  -- Unification is always Nominal

             else -- The kinds don't match yet, so defer instead.
                  do { writeTcRef def_eq_ref 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.
                     ; defer }
             }}
      where
        ty1 :: TcType
    ty1 = TcTyVar -> TcType
    mkTyVarTy TcTyVar
    tv1
        defer :: TcM Coercion
    defer = SwapFlag
    -> (TcType -> TcType -> TcM Coercion)
    -> TcType
    -> TcType
    -> TcM Coercion
    forall a b. SwapFlag -> (a -> a -> b) -> a -> a -> b
    unSwap SwapFlag
    swapped (UnifyEnv -> TcType -> TcType -> TcM Coercion
    uType_defer UnifyEnv
    env) TcType
    ty1 TcType
    ty2

        not_ok_so_defer :: TcLevel -> TcM Coercion
    not_ok_so_defer TcLevel
    cur_lvl =
          do { String -> SDoc -> TcM ()
    traceTc String
    "uUnfilledVar2 not ok" (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
    "tv1:" SDoc -> SDoc -> SDoc
    forall doc. IsLine doc => doc -> doc -> doc
    <+> TcTyVar -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr TcTyVar
    tv1
                      , String -> SDoc
    forall doc. IsLine doc => String -> doc
    text String
    "ty2:" SDoc -> SDoc -> SDoc
    forall doc. IsLine doc => doc -> doc -> doc
    <+> TcType -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr TcType
    ty2
                      , String -> SDoc
    forall doc. IsLine doc => String -> doc
    text String
    "simple-unify-chk:" SDoc -> SDoc -> SDoc
    forall doc. IsLine doc => doc -> doc -> doc
    <+> SimpleUnifyResult -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr (UnifyCheckCaller
    -> TcLevel -> TcTyVar -> TcType -> SimpleUnifyResult
    simpleUnifyCheck UnifyCheckCaller
    UC_OnTheFly TcLevel
    cur_lvl TcTyVar
    tv1 TcType
    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
    -- Only used when the levels are identical
    -- 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, mtv_tclvl :: TcTyVarDetails -> TcLevel
    mtv_tclvl = TcLevel
    lvl }
            | TcLevel
    QLInstVar <- TcLevel
    lvl
            -> Int
    5  -- Eliminate instantiation variables first
            | Bool
    otherwise
            -> 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 applies 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. (REWRITERS) the equality does not have any unsolved equalities in its rewriter
       set. If those other equalities have not been solved, unifying this equality
       will propagate strange-looking errors elswhere.  That is the whole point of
       rewriter sets.  Suppose our equality is
         [W] co1 {rew = {cok}}   (alpha :: k) ~ (Int |> {cok})
       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 `cok` in its rewriter set.  See
       Note [Unify only if the rewriter set is empty] 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.touchabilityTest. 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 -> TcType -> TcM Coercion
    matchExpectedFunKind TypedThing
    hs_ty Int
    n TcType
    k = Int -> TcType -> TcM Coercion
    go Int
    n TcType
    k
      where
        go :: Int -> TcType -> TcM Coercion
    go Int
    0 TcType
    k = Coercion -> TcM Coercion
    forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
    forall (m :: * -> *) a. Monad m => a -> m a
    return (TcType -> Coercion
    mkNomReflCo TcType
    k)

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

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

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

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

        defer :: Int -> TcType -> TcM Coercion
    defer Int
    n TcType
    k
          = do { arg_kinds <- Int -> TcM [TcType]
    newMetaKindVars Int
    n
               ; res_kind  <- newMetaKindVar
               ; let new_fun = [TcType] -> TcType -> TcType
    mkVisFunTysMany [TcType]
    arg_kinds TcType
    res_kind
                     origin  = TypeEqOrigin { uo_actual :: TcType
    uo_actual   = TcType
    k
                                            , uo_expected :: TcType
    uo_expected = TcType
    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
                                            }
               ; unifyTypeAndEmit KindLevel origin k new_fun }

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

    data UnifyCheckCaller
      = UC_OnTheFly   -- Called from the on-the-fly unifier
      | UC_QuickLook  -- Called from Quick Look
      | UC_Solver     -- Called from constraint solver

    -- | The result type of 'simpleUnifyCheck'.
    data SimpleUnifyResult
      -- | Definitely cannot unify (untouchable variable or incompatible top-shape)
      = SUC_CannotUnify
      -- | The variable is touchable and the top-shape test passed, but
      -- it may or may not be OK to unify
      | SUC_NotSure
      -- | Definitely OK to unify
      | SUC_CanUnify
      deriving stock (SimpleUnifyResult -> SimpleUnifyResult -> Bool
    (SimpleUnifyResult -> SimpleUnifyResult -> Bool)
    -> (SimpleUnifyResult -> SimpleUnifyResult -> Bool)
    -> Eq SimpleUnifyResult
    forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
    $c== :: SimpleUnifyResult -> SimpleUnifyResult -> Bool
    == :: SimpleUnifyResult -> SimpleUnifyResult -> Bool
    $c/= :: SimpleUnifyResult -> SimpleUnifyResult -> Bool
    /= :: SimpleUnifyResult -> SimpleUnifyResult -> Bool
    Eq, Eq SimpleUnifyResult
    Eq SimpleUnifyResult =>
    (SimpleUnifyResult -> SimpleUnifyResult -> Ordering)
    -> (SimpleUnifyResult -> SimpleUnifyResult -> Bool)
    -> (SimpleUnifyResult -> SimpleUnifyResult -> Bool)
    -> (SimpleUnifyResult -> SimpleUnifyResult -> Bool)
    -> (SimpleUnifyResult -> SimpleUnifyResult -> Bool)
    -> (SimpleUnifyResult -> SimpleUnifyResult -> SimpleUnifyResult)
    -> (SimpleUnifyResult -> SimpleUnifyResult -> SimpleUnifyResult)
    -> Ord SimpleUnifyResult
    SimpleUnifyResult -> SimpleUnifyResult -> Bool
    SimpleUnifyResult -> SimpleUnifyResult -> Ordering
    SimpleUnifyResult -> SimpleUnifyResult -> SimpleUnifyResult
    forall a.
    Eq a =>
    (a -> a -> Ordering)
    -> (a -> a -> Bool)
    -> (a -> a -> Bool)
    -> (a -> a -> Bool)
    -> (a -> a -> Bool)
    -> (a -> a -> a)
    -> (a -> a -> a)
    -> Ord a
    $ccompare :: SimpleUnifyResult -> SimpleUnifyResult -> Ordering
    compare :: SimpleUnifyResult -> SimpleUnifyResult -> Ordering
    $c< :: SimpleUnifyResult -> SimpleUnifyResult -> Bool
    < :: SimpleUnifyResult -> SimpleUnifyResult -> Bool
    $c<= :: SimpleUnifyResult -> SimpleUnifyResult -> Bool
    <= :: SimpleUnifyResult -> SimpleUnifyResult -> Bool
    $c> :: SimpleUnifyResult -> SimpleUnifyResult -> Bool
    > :: SimpleUnifyResult -> SimpleUnifyResult -> Bool
    $c>= :: SimpleUnifyResult -> SimpleUnifyResult -> Bool
    >= :: SimpleUnifyResult -> SimpleUnifyResult -> Bool
    $cmax :: SimpleUnifyResult -> SimpleUnifyResult -> SimpleUnifyResult
    max :: SimpleUnifyResult -> SimpleUnifyResult -> SimpleUnifyResult
    $cmin :: SimpleUnifyResult -> SimpleUnifyResult -> SimpleUnifyResult
    min :: SimpleUnifyResult -> SimpleUnifyResult -> SimpleUnifyResult
    Ord, Int -> SimpleUnifyResult -> ShowS
    [SimpleUnifyResult] -> ShowS
    SimpleUnifyResult -> String
    (Int -> SimpleUnifyResult -> ShowS)
    -> (SimpleUnifyResult -> String)
    -> ([SimpleUnifyResult] -> ShowS)
    -> Show SimpleUnifyResult
    forall a.
    (Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
    $cshowsPrec :: Int -> SimpleUnifyResult -> ShowS
    showsPrec :: Int -> SimpleUnifyResult -> ShowS
    $cshow :: SimpleUnifyResult -> String
    show :: SimpleUnifyResult -> String
    $cshowList :: [SimpleUnifyResult] -> ShowS
    showList :: [SimpleUnifyResult] -> ShowS
    Show)
    instance Semigroup SimpleUnifyResult where
      no :: SimpleUnifyResult
    no@SimpleUnifyResult
    SUC_CannotUnify <> :: SimpleUnifyResult -> SimpleUnifyResult -> SimpleUnifyResult
    <> SimpleUnifyResult
    _ = SimpleUnifyResult
    no
      SimpleUnifyResult
    SUC_CanUnify <> SimpleUnifyResult
    r = SimpleUnifyResult
    r
      SimpleUnifyResult
    _ <> no :: SimpleUnifyResult
    no@SimpleUnifyResult
    SUC_CannotUnify = SimpleUnifyResult
    no
      SimpleUnifyResult
    r <> SimpleUnifyResult
    SUC_CanUnify = SimpleUnifyResult
    r
      ns :: SimpleUnifyResult
    ns@SimpleUnifyResult
    SUC_NotSure <> SimpleUnifyResult
    SUC_NotSure = SimpleUnifyResult
    ns

    instance Outputable SimpleUnifyResult where
      ppr :: SimpleUnifyResult -> SDoc
    ppr = \case
        SimpleUnifyResult
    SUC_CannotUnify -> String -> SDoc
    forall doc. IsLine doc => String -> doc
    text String
    "SUC_CannotUnify"
        SimpleUnifyResult
    SUC_NotSure     -> String -> SDoc
    forall doc. IsLine doc => String -> doc
    text String
    "SUC_NotSure"
        SimpleUnifyResult
    SUC_CanUnify    -> String -> SDoc
    forall doc. IsLine doc => String -> doc
    text String
    "SUC_CanUnify"

    simpleUnifyCheck :: UnifyCheckCaller -> TcLevel -> TcTyVar -> TcType -> SimpleUnifyResult
    -- ^ A fast check for unification. May return "not sure", in which case
    -- unification might still be OK, but it'll take more work to do
    -- (use the full 'checkTypeEq').
    --
    -- * Rejects if lhs_tv occurs in rhs_ty (occurs check)
    -- * Rejects foralls unless
    --      lhs_tv is RuntimeUnk (used by GHCi debugger)
    --          or is a QL instantiation variable
    -- * Rejects a non-concrete type if lhs_tv is concrete
    -- * Rejects type families unless fam_ok=True
    -- * Does a level-check for type variables, to avoid skolem escape
    --
    -- This function is pretty heavily used, so it's optimised not to allocate
    simpleUnifyCheck :: UnifyCheckCaller
    -> TcLevel -> TcTyVar -> TcType -> SimpleUnifyResult
    simpleUnifyCheck UnifyCheckCaller
    caller TcLevel
    given_eq_lvl TcTyVar
    lhs_tv TcType
    rhs
      | Bool -> Bool
    not (Bool -> Bool) -> Bool -> Bool
    forall a b. (a -> b) -> a -> b
    $ TcLevel -> TcTyVar -> Bool
    touchabilityTest TcLevel
    given_eq_lvl TcTyVar
    lhs_tv
      = SimpleUnifyResult
    SUC_CannotUnify
      | Bool -> Bool
    not (Bool -> Bool) -> Bool -> Bool
    forall a b. (a -> b) -> a -> b
    $ MetaInfo -> TcType -> Bool
    checkTopShape MetaInfo
    lhs_info TcType
    rhs
      = SimpleUnifyResult
    SUC_CannotUnify
      | TcType -> Bool
    rhs_is_ok TcType
    rhs
      = SimpleUnifyResult
    SUC_CanUnify
      | Bool
    otherwise
      = SimpleUnifyResult
    SUC_NotSure
      where
        lhs_info :: MetaInfo
    lhs_info = TcTyVar -> MetaInfo
    metaTyVarInfo TcTyVar
    lhs_tv

        !(TcType -> Bool
    occ_in_ty, Coercion -> Bool
    occ_in_co) = Name -> (TcType -> Bool, Coercion -> Bool)
    mkOccFolders (TcTyVar -> Name
    tyVarName 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 UnifyCheckCaller
    caller of
                       UnifyCheckCaller
    UC_QuickLook -> TcTyVar -> Bool
    isQLInstTyVar TcTyVar
    lhs_tv
                       UnifyCheckCaller
    _            -> TcTyVar -> Bool
    isRuntimeUnkTyVar TcTyVar
    lhs_tv

        -- This fam_ok thing relates to a very specific perf problem
        -- See Note [Prevent unification with type families]
        -- A couple of QuickLook regression tests rely on unifying with type
        --   families, so we let it through there (not very principled, but let's
        --   see if it bites us)
        fam_ok :: Bool
    fam_ok = case UnifyCheckCaller
    caller of
                   UnifyCheckCaller
    UC_Solver     -> Bool
    True
                   UnifyCheckCaller
    UC_QuickLook  -> Bool
    True
                   UnifyCheckCaller
    UC_OnTheFly   -> Bool
    False

        rhs_is_ok :: TcType -> Bool
    rhs_is_ok (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
    `strictlyDeeperThan` TcLevel
    lhs_tv_lvl = Bool
    False
          | Bool
    lhs_tv_is_concrete, Bool -> Bool
    not (TcTyVar -> Bool
    isConcreteTyVar TcTyVar
    tv)    = Bool
    False
          | TcType -> Bool
    occ_in_ty (TcType -> Bool) -> TcType -> Bool
    forall a b. (a -> b) -> a -> b
    $! (TcTyVar -> TcType
    tyVarKind TcTyVar
    tv)                     = Bool
    False
          | Bool
    otherwise                                       = Bool
    True

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

        rhs_is_ok (TyConApp TyCon
    tc [TcType]
    tys)
          | Bool
    lhs_tv_is_concrete, Bool -> Bool
    not (TyCon -> Bool
    isConcreteTyCon TyCon
    tc) = Bool
    False
          | Bool -> Bool
    not Bool
    forall_ok, 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                                    = (TcType -> Bool) -> [TcType] -> Bool
    forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
    all TcType -> Bool
    rhs_is_ok [TcType]
    tys

        rhs_is_ok (ForAllTy (Bndr TcTyVar
    tv ForAllTyFlag
    _) TcType
    ty)
          | Bool
    forall_ok = TcType -> Bool
    rhs_is_ok (TcTyVar -> TcType
    tyVarKind TcTyVar
    tv) Bool -> Bool -> Bool
    && (TcTyVar
    tv TcTyVar -> TcTyVar -> Bool
    forall a. Eq a => a -> a -> Bool
    == TcTyVar
    lhs_tv Bool -> Bool -> Bool
    || TcType -> Bool
    rhs_is_ok TcType
    ty)
          | Bool
    otherwise = Bool
    False

        rhs_is_ok (AppTy TcType
    t1 TcType
    t2)    = TcType -> Bool
    rhs_is_ok TcType
    t1 Bool -> Bool -> Bool
    && TcType -> Bool
    rhs_is_ok TcType
    t2
        rhs_is_ok (CastTy TcType
    ty Coercion
    co)   = Bool -> Bool
    not (Coercion -> Bool
    occ_in_co Coercion
    co) Bool -> Bool -> Bool
    && TcType -> Bool
    rhs_is_ok TcType
    ty
        rhs_is_ok (CoercionTy Coercion
    co)  = Bool -> Bool
    not (Coercion -> Bool
    occ_in_co Coercion
    co)
        rhs_is_ok (LitTy {})       = Bool
    True

    mkOccFolders :: Name -> (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 :: Name -> (TcType -> Bool, Coercion -> Bool)
    mkOccFolders Name
    lhs_tv = (Any -> Bool
    getAny (Any -> Bool) -> (TcType -> Any) -> TcType -> Bool
    forall b c a. (b -> c) -> (a -> b) -> a -> c
    . TcType -> 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
        !(TcType -> Any
    check_ty, [TcType] -> Any
    _, Coercion -> Any
    check_co, [Coercion] -> Any
    _) = TyCoFolder VarSet Any
    -> VarSet
    -> (TcType -> Any, [TcType] -> Any, Coercion -> Any,
        [Coercion] -> Any)
    forall a env.
    Monoid a =>
    TyCoFolder env a
    -> env
    -> (TcType -> a, [TcType] -> a, Coercion -> a, [Coercion] -> a)
    foldTyCo TyCoFolder VarSet Any
    occ_folder VarSet
    emptyVarSet
        occ_folder :: TyCoFolder VarSet Any
    occ_folder = TyCoFolder { tcf_view :: TcType -> Maybe TcType
    tcf_view  = TcType -> Maybe TcType
    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 -> Name
    tyVarName TcTyVar
    v Name -> Name -> Bool
    forall a. Eq a => a -> a -> Bool
    == Name
    lhs_tv)
                      Any -> Any -> Any
    forall a. Monoid a => a -> a -> a
    `mappend` TcType -> Any
    check_ty (TcTyVar -> TcType
    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
      -- | Pure unifier failure.
      --
      -- Invariant: the CheckTyEqResult is not 'cteOK'; that it, it specifies a problem.
      = PuFail CheckTyEqResult
      -- | Pure unifier success.
      | PuOK (Bag a) b
      deriving stock ((forall a b. (a -> b) -> PuResult a a -> PuResult a b)
    -> (forall a b. a -> PuResult a b -> PuResult a a)
    -> Functor (PuResult a)
    forall a b. a -> PuResult a b -> PuResult a a
    forall a b. (a -> b) -> PuResult a a -> PuResult a b
    forall a a b. a -> PuResult a b -> PuResult a a
    forall a a b. (a -> b) -> PuResult a a -> PuResult a b
    forall (f :: * -> *).
    (forall a b. (a -> b) -> f a -> f b)
    -> (forall a b. a -> f b -> f a) -> Functor f
    $cfmap :: forall a a b. (a -> b) -> PuResult a a -> PuResult a b
    fmap :: forall a b. (a -> b) -> PuResult a a -> PuResult a b
    $c<$ :: forall a a b. a -> PuResult a b -> PuResult a a
    <$ :: forall a b. a -> PuResult a b -> PuResult a a
    Functor, (forall m. Monoid m => PuResult a m -> m)
    -> (forall m a. Monoid m => (a -> m) -> PuResult a a -> m)
    -> (forall m a. Monoid m => (a -> m) -> PuResult a a -> m)
    -> (forall a b. (a -> b -> b) -> b -> PuResult a a -> b)
    -> (forall a b. (a -> b -> b) -> b -> PuResult a a -> b)
    -> (forall b a. (b -> a -> b) -> b -> PuResult a a -> b)
    -> (forall b a. (b -> a -> b) -> b -> PuResult a a -> b)
    -> (forall a. (a -> a -> a) -> PuResult a a -> a)
    -> (forall a. (a -> a -> a) -> PuResult a a -> a)
    -> (forall a. PuResult a a -> [a])
    -> (forall a. PuResult a a -> Bool)
    -> (forall a. PuResult a a -> Int)
    -> (forall a. Eq a => a -> PuResult a a -> Bool)
    -> (forall a. Ord a => PuResult a a -> a)
    -> (forall a. Ord a => PuResult a a -> a)
    -> (forall a. Num a => PuResult a a -> a)
    -> (forall a. Num a => PuResult a a -> a)
    -> Foldable (PuResult a)
    forall a. Eq a => a -> PuResult a a -> Bool
    forall a. Num a => PuResult a a -> a
    forall a. Ord a => PuResult a a -> a
    forall m. Monoid m => PuResult a m -> m
    forall a. PuResult a a -> Bool
    forall a. PuResult a a -> Int
    forall a. PuResult a a -> [a]
    forall a. (a -> a -> a) -> PuResult a a -> a
    forall a a. Eq a => a -> PuResult a a -> Bool
    forall a a. Num a => PuResult a a -> a
    forall a a. Ord a => PuResult a a -> a
    forall a m. Monoid m => PuResult a m -> m
    forall m a. Monoid m => (a -> m) -> PuResult a a -> m
    forall a a. PuResult a a -> Bool
    forall a a. PuResult a a -> Int
    forall a a. PuResult a a -> [a]
    forall b a. (b -> a -> b) -> b -> PuResult a a -> b
    forall a b. (a -> b -> b) -> b -> PuResult a a -> b
    forall a a. (a -> a -> a) -> PuResult a a -> a
    forall a m a. Monoid m => (a -> m) -> PuResult a a -> m
    forall a b a. (b -> a -> b) -> b -> PuResult a a -> b
    forall a a b. (a -> b -> b) -> b -> PuResult a a -> b
    forall (t :: * -> *).
    (forall m. Monoid m => t m -> m)
    -> (forall m a. Monoid m => (a -> m) -> t a -> m)
    -> (forall m a. Monoid m => (a -> m) -> t a -> m)
    -> (forall a b. (a -> b -> b) -> b -> t a -> b)
    -> (forall a b. (a -> b -> b) -> b -> t a -> b)
    -> (forall b a. (b -> a -> b) -> b -> t a -> b)
    -> (forall b a. (b -> a -> b) -> b -> t a -> b)
    -> (forall a. (a -> a -> a) -> t a -> a)
    -> (forall a. (a -> a -> a) -> t a -> a)
    -> (forall a. t a -> [a])
    -> (forall a. t a -> Bool)
    -> (forall a. t a -> Int)
    -> (forall a. Eq a => a -> t a -> Bool)
    -> (forall a. Ord a => t a -> a)
    -> (forall a. Ord a => t a -> a)
    -> (forall a. Num a => t a -> a)
    -> (forall a. Num a => t a -> a)
    -> Foldable t
    $cfold :: forall a m. Monoid m => PuResult a m -> m
    fold :: forall m. Monoid m => PuResult a m -> m
    $cfoldMap :: forall a m a. Monoid m => (a -> m) -> PuResult a a -> m
    foldMap :: forall m a. Monoid m => (a -> m) -> PuResult a a -> m
    $cfoldMap' :: forall a m a. Monoid m => (a -> m) -> PuResult a a -> m
    foldMap' :: forall m a. Monoid m => (a -> m) -> PuResult a a -> m
    $cfoldr :: forall a a b. (a -> b -> b) -> b -> PuResult a a -> b
    foldr :: forall a b. (a -> b -> b) -> b -> PuResult a a -> b
    $cfoldr' :: forall a a b. (a -> b -> b) -> b -> PuResult a a -> b
    foldr' :: forall a b. (a -> b -> b) -> b -> PuResult a a -> b
    $cfoldl :: forall a b a. (b -> a -> b) -> b -> PuResult a a -> b
    foldl :: forall b a. (b -> a -> b) -> b -> PuResult a a -> b
    $cfoldl' :: forall a b a. (b -> a -> b) -> b -> PuResult a a -> b
    foldl' :: forall b a. (b -> a -> b) -> b -> PuResult a a -> b
    $cfoldr1 :: forall a a. (a -> a -> a) -> PuResult a a -> a
    foldr1 :: forall a. (a -> a -> a) -> PuResult a a -> a
    $cfoldl1 :: forall a a. (a -> a -> a) -> PuResult a a -> a
    foldl1 :: forall a. (a -> a -> a) -> PuResult a a -> a
    $ctoList :: forall a a. PuResult a a -> [a]
    toList :: forall a. PuResult a a -> [a]
    $cnull :: forall a a. PuResult a a -> Bool
    null :: forall a. PuResult a a -> Bool
    $clength :: forall a a. PuResult a a -> Int
    length :: forall a. PuResult a a -> Int
    $celem :: forall a a. Eq a => a -> PuResult a a -> Bool
    elem :: forall a. Eq a => a -> PuResult a a -> Bool
    $cmaximum :: forall a a. Ord a => PuResult a a -> a
    maximum :: forall a. Ord a => PuResult a a -> a
    $cminimum :: forall a a. Ord a => PuResult a a -> a
    minimum :: forall a. Ord a => PuResult a a -> a
    $csum :: forall a a. Num a => PuResult a a -> a
    sum :: forall a. Num a => PuResult a a -> a
    $cproduct :: forall a a. Num a => PuResult a a -> a
    product :: forall a. Num a => PuResult a a -> a
    Foldable, Functor (PuResult a)
    Foldable (PuResult a)
    (Functor (PuResult a), Foldable (PuResult a)) =>
    (forall (f :: * -> *) a b.
     Applicative f =>
     (a -> f b) -> PuResult a a -> f (PuResult a b))
    -> (forall (f :: * -> *) a.
        Applicative f =>
        PuResult a (f a) -> f (PuResult a a))
    -> (forall (m :: * -> *) a b.
        Monad m =>
        (a -> m b) -> PuResult a a -> m (PuResult a b))
    -> (forall (m :: * -> *) a.
        Monad m =>
        PuResult a (m a) -> m (PuResult a a))
    -> Traversable (PuResult a)
    forall a. Functor (PuResult a)
    forall a. Foldable (PuResult a)
    forall a (m :: * -> *) a.
    Monad m =>
    PuResult a (m a) -> m (PuResult a a)
    forall a (f :: * -> *) a.
    Applicative f =>
    PuResult a (f a) -> f (PuResult a a)
    forall a (m :: * -> *) a b.
    Monad m =>
    (a -> m b) -> PuResult a a -> m (PuResult a b)
    forall a (f :: * -> *) a b.
    Applicative f =>
    (a -> f b) -> PuResult a a -> f (PuResult a b)
    forall (t :: * -> *).
    (Functor t, Foldable t) =>
    (forall (f :: * -> *) a b.
     Applicative f =>
     (a -> f b) -> t a -> f (t b))
    -> (forall (f :: * -> *) a. Applicative f => t (f a) -> f (t a))
    -> (forall (m :: * -> *) a b.
        Monad m =>
        (a -> m b) -> t a -> m (t b))
    -> (forall (m :: * -> *) a. Monad m => t (m a) -> m (t a))
    -> Traversable t
    forall (m :: * -> *) a.
    Monad m =>
    PuResult a (m a) -> m (PuResult a a)
    forall (f :: * -> *) a.
    Applicative f =>
    PuResult a (f a) -> f (PuResult a a)
    forall (m :: * -> *) a b.
    Monad m =>
    (a -> m b) -> PuResult a a -> m (PuResult a b)
    forall (f :: * -> *) a b.
    Applicative f =>
    (a -> f b) -> PuResult a a -> f (PuResult a b)
    $ctraverse :: forall a (f :: * -> *) a b.
    Applicative f =>
    (a -> f b) -> PuResult a a -> f (PuResult a b)
    traverse :: forall (f :: * -> *) a b.
    Applicative f =>
    (a -> f b) -> PuResult a a -> f (PuResult a b)
    $csequenceA :: forall a (f :: * -> *) a.
    Applicative f =>
    PuResult a (f a) -> f (PuResult a a)
    sequenceA :: forall (f :: * -> *) a.
    Applicative f =>
    PuResult a (f a) -> f (PuResult a a)
    $cmapM :: forall a (m :: * -> *) a b.
    Monad m =>
    (a -> m b) -> PuResult a a -> m (PuResult a b)
    mapM :: forall (m :: * -> *) a b.
    Monad m =>
    (a -> m b) -> PuResult a a -> m (PuResult a b)
    $csequence :: forall a (m :: * -> *) a.
    Monad m =>
    PuResult a (m a) -> m (PuResult a a)
    sequence :: forall (m :: * -> *) a.
    Monad m =>
    PuResult a (m a) -> m (PuResult a a)
    Traversable)

    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 ])

    okCheckRefl :: TcType -> PuResult a Reduction
    okCheckRefl :: forall a. TcType -> PuResult a Reduction
    okCheckRefl TcType
    ty = Bag a -> Reduction -> PuResult a Reduction
    forall a b. Bag a -> b -> PuResult a b
    PuOK Bag a
    forall a. Bag a
    emptyBag (Role -> TcType -> Reduction
    mkReflRedn Role
    Nominal TcType
    ty)

    mapCheck :: Monad m
             => (x -> m (PuResult a Reduction))
             -> [x]
             -> m (PuResult a Reductions)
    mapCheck :: forall (m :: * -> *) x a.
    Monad m =>
    (x -> m (PuResult a Reduction)) -> [x] -> m (PuResult a Reductions)
    mapCheck x -> m (PuResult a Reduction)
    f [x]
    xs
      = do { (ress :: [PuResult a Reduction]) <- (x -> m (PuResult a Reduction)) -> [x] -> m [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 -> m (PuResult a Reduction)
    f [x]
    xs
           ; return (unzipRedns <$> sequenceA ress) }
             -- sequenceA :: [PuResult a Reduction] -> PuResult a [Reduction]
             -- unzipRedns :: [Reduction] -> Reductions
    {-# INLINEABLE mapCheck #-}

    -----------------------------
    -- | Options describing how to deal with a type equality
    -- in the eager unifier. See 'checkTyEqRhs'
    data TyEqFlags m a
      = -- | TFTyFam: LHS is a type family application
        -- Invariant: we are not unifying; see `notUnifying_TEFTask`
        TEFTyFam
        { forall (m :: * -> *) a. TyEqFlags m a -> CheckTyEqProblem
    tefTyFam_occursCheck :: CheckTyEqProblem
           -- ^ The 'CheckTyEqProblem' to report for occurs-check failures
           -- (soluble or insoluble)
        , forall (m :: * -> *) a. TyEqFlags m a -> TyCon
    tefTyFam_tyCon :: TyCon
        , forall (m :: * -> *) a. TyEqFlags m a -> [TcType]
    tefTyFam_args  :: [Type]
        , forall (m :: * -> *) a. TyEqFlags m a -> TyEqFamApp m a
    tef_fam_app :: TyEqFamApp m a
            -- ^ How to deal with type family applications
        }

      -- | TEFTyVar: LHS is a 'TyVar'.
      | TEFTyVar
        -- NB: this constructor does not actually store a 'TyVar', in order to
        -- support being called from 'makeTypeConcrete' (which works as if we
        -- created a fresh 'ConcreteTv' metavariable; see (3) in Note [TyEqFlags])
        { forall (m :: * -> *) a. TyEqFlags m a -> OccursCheck
    tefTyVar_occursCheck    :: OccursCheck
            -- ^ Occurs check
        , forall (m :: * -> *) a. TyEqFlags m a -> LevelCheck m
    tefTyVar_levelCheck     :: LevelCheck m
            -- ^ Level check
        , forall (m :: * -> *) a. TyEqFlags m a -> ConcreteCheck m
    tefTyVar_concreteCheck  :: ConcreteCheck m
            -- ^ Concreteness check
        , tef_fam_app :: TyEqFamApp m a
            -- ^ How to deal with type family applications
        }

    -- | 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 m a where
      -- | Just recurse
      TEFA_Recurse     :: TyEqFamApp m a
      -- | Recurse, but replace with cycle breaker if that fails,
      -- using the specified 'FamAppBreaker'
      TEFA_Break       :: FamAppBreaker a -> TyEqFamApp TcM a

    -- | A defunctionalisation of family application breaker functions.
    --     Interpreter: `famAppBreaker`
    data FamAppBreaker a where
      BreakGiven  :: FamAppBreaker (TcTyVar, TcType)
      BreakWanted :: CtEvidence -> TcTyVar -> FamAppBreaker Ct

    data OccursCheck where
      -- | No occurs check.
      OC_None :: OccursCheck
      -- | Do an occurs check between the LHS tyvar and the RHS.
      OC_Check ::
        { OccursCheck -> Name
    occurs_tv_name :: Name
          -- ^ The 'Name' to perform an occurs-check on
        , OccursCheck -> CheckTyEqProblem
    occurs_problem :: CheckTyEqProblem
          -- ^ Which 'CheckTyEqProblem' to report for occurs-check failures
          -- (soluble or insoluble)
        } -> OccursCheck

    -- | What level check to perform, in a call to the pure unifier?
    -- A defunctionalisation of the possible level-check functions
    --   Interpreter: `tyVarLevelCheck`
    data LevelCheck m where
      -- | No level check.
      LC_None :: LevelCheck m
      -- | Do a level check between the LHS tyvar and the occurrence tyvar.
      --
      -- Fail if the level check fails.
      --
      -- True <=> lenient check, e.g. the levels have a chance of working out
      -- after promotion.
      LC_Check ::
        { forall (m :: * -> *). LevelCheck m -> TcLevel
    lc_lvlc    :: TcLevel
        , forall (m :: * -> *). LevelCheck m -> Bool
    lc_lenient :: Bool
        } -> LevelCheck m

      -- | 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.
      --
      --   - False <=> don't promote under type families (the common case)
      --   -  True <=> promote even under type families
      --             (see Note [Defaulting equalities] in GHC.Tc.Solver)
      LC_Promote
        :: { LevelCheck (IOEnv (Env TcGblEnv TcLclEnv)) -> TcLevel
    lc_lvlp :: TcLevel
           , LevelCheck (IOEnv (Env TcGblEnv TcLclEnv)) -> Bool
    lc_deep :: Bool
           } -> LevelCheck TcM

    data ConcreteCheck m where
      -- | No concreteness check.
      CC_None :: ConcreteCheck m
      -- | Simple check for concreteness, leniently returning 'OK'
      -- if concreteness could be achieved after promotion.
      CC_Check :: ConcreteCheck m
      -- | Proper concreteness check: promote non-concrete metavariables,
      -- failing if there are any problems.
      CC_Promote :: ConcreteTvOrigin -> ConcreteCheck TcM

    {- Note [TyEqFlags]
    ~~~~~~~~~~~~~~~~~~~
    When we call the eager unifier, e.g. through 'checkTyEqRhs', we specify what
    kind of checks the unifier performs via the 'TyEqFlags' argument. In particular,
    when the LHS type in a unification is a type variable, we might want to perform
    different checks; this is achieved using the 'TEFTyVar' constructor to 'TyEqFlags':

      1. `notUnifying_TEFTask`
         LHS is a skolem tyvar, or an untouchable meta-tyvar.
         We are not unifying; we only want to perform occurs-checks.

          TEFTyVar
            { tefTyVar_occursCheck   = OC_Check ...
            , tefTyVar_levelCheck    = LC_None
            , tefTyVar_concreteCheck = CC_None
            , tef_fam_app            = TEFA_Recurse
            }

      2a. `unifyingLHSMetaTyVar_TEFTask`
         We are unifying; we want to perform an occurs check, a level check,
         and a concreteness check (when the meta-tyvar is a ConcreteTv).

          TEFTyVar
            { tefTyVar_occursCheck   = OC_Check ...
            , tefTyVar_levelCheck    = LC_Promote ...
            , tefTyVar_concreteCheck = CC_Promote or CC_None
                -- depending on whether or not the lhs tv is concrete
            , tef_fam_app            = TEFA_Recurse
            }

      2b. `defaulting_TEFTask`
         We are in the top-level defaulting code, considering unifying a
         touchable meta-tyvar with a type.

          TEFTyVar
            { tefTyVar_occursCheck   = OC_None
            , tefTyVar_levelCheck    = LC_None
            , tefTyVar_concreteCheck = CC_Promote or CC_None
                -- depending on whether or not the lhs tv is concrete
            , tef_fam_app            = TEFA_Recurse
            }

      3. `makeTypeConcrete`
         LHS is a fresh ConcreteTv meta-tyvar (see call to 'checkTyEqRhs' in
         `makeTypeConcrete`). We are unifying; we only want to perform
         a concreteness check.

          TEFTyVar
            { tefTyVar_occursCheck   = OC_None
            , tefTyVar_levelCheck    = LC_None
            , tefTyVar_concreteCheck = CC_Promote conc_orig
            , tef_fam_app            = TEFA_Recurse
            }

      4. `pureTyEqFlags_LHSMetaTyVar`
         We want to perform a non-monadic check, i.e. we want to know whether we are able
         to unify 'lhs_tv' with 'rhs_ty', but don't want to actually perform
         a side-effecting unification. This is used in 'mightEqualLater'.

          TEFTyVar
            { tefTyVar_occursCheck   = OC_Check ...
            , tefTyVar_levelCheck    = LC_Check ...
            , tefTyVar_concreteCheck = CC_Check or CC_None
                -- depending on whether or not the lhs tv is concrete
            , tef_fam_app            = TEFA_Recurse
            }

         Here 'LC_Check True' and 'ConcreteSimpleCheck' make 'checkTyEqRhs' perform
         conservative pure checks, without actually carrying out any promotion.
    -}

    -- | Create a "not unifying" 'TyEqFlags' from a 'CanEqLHS'.
    --
    -- See use-case (1) in Note [TyEqFlags].
    notUnifying_TEFTask :: CheckTyEqProblem -> CanEqLHS -> TyEqFlags m a
    notUnifying_TEFTask :: forall (m :: * -> *) a.
    CheckTyEqProblem -> CanEqLHS -> TyEqFlags m a
    notUnifying_TEFTask CheckTyEqProblem
    occ_prob = \case
      TyFamLHS TyCon
    tc [TcType]
    tys ->
        TEFTyFam
          { tefTyFam_tyCon :: TyCon
    tefTyFam_tyCon = TyCon
    tc
          , tefTyFam_args :: [TcType]
    tefTyFam_args  = [TcType]
    tys
          , tefTyFam_occursCheck :: CheckTyEqProblem
    tefTyFam_occursCheck = CheckTyEqProblem
    occ_prob
          , tef_fam_app :: TyEqFamApp m a
    tef_fam_app = TyEqFamApp m a
    forall (m :: * -> *) a. TyEqFamApp m a
    TEFA_Recurse
          }
      TyVarLHS TcTyVar
    tv ->
        TEFTyVar
          { tefTyVar_occursCheck :: OccursCheck
    tefTyVar_occursCheck   = Name -> CheckTyEqProblem -> OccursCheck
    OC_Check (TcTyVar -> Name
    tyVarName TcTyVar
    tv) CheckTyEqProblem
    occ_prob
          , tefTyVar_levelCheck :: LevelCheck m
    tefTyVar_levelCheck    = LevelCheck m
    forall (m :: * -> *). LevelCheck m
    LC_None
          , tefTyVar_concreteCheck :: ConcreteCheck m
    tefTyVar_concreteCheck = ConcreteCheck m
    forall (m :: * -> *). ConcreteCheck m
    CC_None
          , tef_fam_app :: TyEqFamApp m a
    tef_fam_app            = TyEqFamApp m a
    forall (m :: * -> *) a. TyEqFamApp m a
    TEFA_Recurse
         }
        -- We need an occurs-check here, but no level check.
        -- See Note [Promotion and level-checking] wrinkle (W1)
        -- TEFA_Recurse: see Note [Don't cycle-break Wanteds when not unifying]

    -- | Create "unifying" 'TyEqFlags' from a 'TyVarLHS'.
    --
    -- Invariant: the argument 'TcTyVar' is a 'MetaTv'.
    unifyingLHSMetaTyVar_TEFTask :: CtEvidence -> TcTyVar -> TyEqFlags TcM Ct
    unifyingLHSMetaTyVar_TEFTask :: CtEvidence
    -> TcTyVar -> TyEqFlags (IOEnv (Env TcGblEnv TcLclEnv)) Ct
    unifyingLHSMetaTyVar_TEFTask CtEvidence
    ev TcTyVar
    lhs_tv =
      TEFTyVar
        { tefTyVar_occursCheck :: OccursCheck
    tefTyVar_occursCheck   = Name -> CheckTyEqProblem -> OccursCheck
    OC_Check (TcTyVar -> Name
    tyVarName TcTyVar
    lhs_tv) CheckTyEqProblem
    cteInsolubleOccurs
        , tefTyVar_levelCheck :: LevelCheck (IOEnv (Env TcGblEnv TcLclEnv))
    tefTyVar_levelCheck    = LC_Promote { lc_lvlp :: TcLevel
    lc_lvlp = TcTyVar -> TcLevel
    tcTyVarLevel TcTyVar
    lhs_tv
                                              , lc_deep :: Bool
    lc_deep = Bool
    False }
        , tefTyVar_concreteCheck :: ConcreteCheck (IOEnv (Env TcGblEnv TcLclEnv))
    tefTyVar_concreteCheck = TcTyVar -> ConcreteCheck (IOEnv (Env TcGblEnv TcLclEnv))
    mkConcreteCheck TcTyVar
    lhs_tv
        , tef_fam_app :: TyEqFamApp (IOEnv (Env TcGblEnv TcLclEnv)) Ct
    tef_fam_app            = CtEvidence
    -> EqRel
    -> FamAppBreaker Ct
    -> TyEqFamApp (IOEnv (Env TcGblEnv TcLclEnv)) Ct
    forall a.
    CtEvidence
    -> EqRel
    -> FamAppBreaker a
    -> TyEqFamApp (IOEnv (Env TcGblEnv TcLclEnv)) a
    mkTEFA_Break CtEvidence
    ev EqRel
    NomEq (CtEvidence -> TcTyVar -> FamAppBreaker Ct
    BreakWanted CtEvidence
    ev TcTyVar
    lhs_tv)
        }

    defaulting_TEFTask :: TcTyVar -> TyEqFlags TcM a
    -- Used during top-level defauting in GHC.Tc.Solver.Default.defaultEquality
    -- Invariant: the argument 'TcTyVar' is a 'MetaTv'.
    defaulting_TEFTask :: forall a. TcTyVar -> TyEqFlags (IOEnv (Env TcGblEnv TcLclEnv)) a
    defaulting_TEFTask TcTyVar
    lhs_tv =
      TEFTyVar
        { tefTyVar_occursCheck :: OccursCheck
    tefTyVar_occursCheck   = Name -> CheckTyEqProblem -> OccursCheck
    OC_Check (TcTyVar -> Name
    tyVarName TcTyVar
    lhs_tv) CheckTyEqProblem
    cteInsolubleOccurs
        , tefTyVar_levelCheck :: LevelCheck (IOEnv (Env TcGblEnv TcLclEnv))
    tefTyVar_levelCheck    = LC_Promote { lc_lvlp :: TcLevel
    lc_lvlp = TcTyVar -> TcLevel
    tcTyVarLevel TcTyVar
    lhs_tv
                                              , lc_deep :: Bool
    lc_deep = Bool
    True }
                  -- LC_Promote: promote deeper unification variables (DE4)
                  -- lc_deep =  True: ...including under type families (DE5)
        , tefTyVar_concreteCheck :: ConcreteCheck (IOEnv (Env TcGblEnv TcLclEnv))
    tefTyVar_concreteCheck = TcTyVar -> ConcreteCheck (IOEnv (Env TcGblEnv TcLclEnv))
    mkConcreteCheck TcTyVar
    lhs_tv
        , tef_fam_app :: TyEqFamApp (IOEnv (Env TcGblEnv TcLclEnv)) a
    tef_fam_app = TyEqFamApp (IOEnv (Env TcGblEnv TcLclEnv)) a
    forall (m :: * -> *) a. TyEqFamApp m a
    TEFA_Recurse
        }

    mkConcreteCheck :: TcTyVar -> ConcreteCheck TcM
    mkConcreteCheck :: TcTyVar -> ConcreteCheck (IOEnv (Env TcGblEnv TcLclEnv))
    mkConcreteCheck TcTyVar
    lhs_tv = case TcTyVar -> Maybe ConcreteTvOrigin
    isConcreteTyVar_maybe TcTyVar
    lhs_tv of
                               Maybe ConcreteTvOrigin
    Nothing        -> ConcreteCheck (IOEnv (Env TcGblEnv TcLclEnv))
    forall (m :: * -> *). ConcreteCheck m
    CC_None
                               Just ConcreteTvOrigin
    conc_orig -> ConcreteTvOrigin -> ConcreteCheck (IOEnv (Env TcGblEnv TcLclEnv))
    CC_Promote ConcreteTvOrigin
    conc_orig

    -- | 'TyEqFlags' for a pure call of 'checkTyEqRhs'.
    --
    -- A call to 'checkTyEqRhs' with these 'TyEqFlags' will perform an optimistic
    -- check: it will return 'PuFail' if there is definitely a problem, but it
    -- might return 'PuOK' if it isn't entirely sure.
    pureTyEqFlags_LHSMetaTyVar :: TyVar -> TyEqFlags Identity ()
    pureTyEqFlags_LHSMetaTyVar :: TcTyVar -> TyEqFlags Identity ()
    pureTyEqFlags_LHSMetaTyVar TcTyVar
    lhs_tv =
      TEFTyVar
        { tefTyVar_occursCheck :: OccursCheck
    tefTyVar_occursCheck   = Name -> CheckTyEqProblem -> OccursCheck
    OC_Check (TcTyVar -> Name
    tyVarName TcTyVar
    lhs_tv) CheckTyEqProblem
    cteInsolubleOccurs
        , tefTyVar_levelCheck :: LevelCheck Identity
    tefTyVar_levelCheck    = LC_Check { lc_lvlc :: TcLevel
    lc_lvlc = TcTyVar -> TcLevel
    tcTyVarLevel TcTyVar
    lhs_tv
                                            , lc_lenient :: Bool
    lc_lenient = Bool
    True }
        , tefTyVar_concreteCheck :: ConcreteCheck Identity
    tefTyVar_concreteCheck = case TcTyVar -> Maybe ConcreteTvOrigin
    isConcreteTyVar_maybe TcTyVar
    lhs_tv of
                                      Maybe ConcreteTvOrigin
    Nothing -> ConcreteCheck Identity
    forall (m :: * -> *). ConcreteCheck m
    CC_None
                                      Just {} -> ConcreteCheck Identity
    forall (m :: * -> *). ConcreteCheck m
    CC_Check   -- No promotion
        , tef_fam_app :: TyEqFamApp Identity ()
    tef_fam_app = TyEqFamApp Identity ()
    forall (m :: * -> *) a. TyEqFamApp m a
    TEFA_Recurse }

    mkTEFA_Break :: CtEvidence -> EqRel -> FamAppBreaker a -> TyEqFamApp TcM a
    mkTEFA_Break :: forall a.
    CtEvidence
    -> EqRel
    -> FamAppBreaker a
    -> TyEqFamApp (IOEnv (Env TcGblEnv TcLclEnv)) a
    mkTEFA_Break CtEvidence
    ev EqRel
    eq_rel FamAppBreaker a
    breaker
      | EqRel
    NomEq <- EqRel
    eq_rel
      , Bool -> Bool
    not Bool
    cycle_breaker_origin
      = FamAppBreaker a -> TyEqFamApp (IOEnv (Env TcGblEnv TcLclEnv)) a
    forall a.
    FamAppBreaker a -> TyEqFamApp (IOEnv (Env TcGblEnv TcLclEnv)) a
    TEFA_Break FamAppBreaker a
    breaker
      | Bool
    otherwise
      = TyEqFamApp (IOEnv (Env TcGblEnv TcLclEnv)) a
    forall (m :: * -> *) a. TyEqFamApp m a
    TEFA_Recurse
      where
        -- cycle_breaker_origin: see Detail (7) of Note [Type equality cycles]
        -- in GHC.Tc.Solver.Equality
        cycle_breaker_origin :: Bool
    cycle_breaker_origin = case CtLoc -> CtOrigin
    ctLocOrigin (CtEvidence -> CtLoc
    ctEvLoc CtEvidence
    ev) of
                                  CycleBreakerOrigin {} -> Bool
    True
                                  CtOrigin
    _                     -> Bool
    False

    -- | Do we want to perform a concreteness check in 'checkTyEqRhs'?
    tefConcrete :: TyEqFlags m a -> Bool
    tefConcrete :: forall (m :: * -> *) a. TyEqFlags m a -> Bool
    tefConcrete (TEFTyFam {}) = Bool
    False
    tefConcrete (TEFTyVar { tefTyVar_concreteCheck :: forall (m :: * -> *) a. TyEqFlags m a -> ConcreteCheck m
    tefTyVar_concreteCheck = ConcreteCheck m
    conc }) =
      ConcreteCheck m -> Bool
    forall (m :: * -> *). ConcreteCheck m -> Bool
    wantConcreteCheck ConcreteCheck m
    conc

    wantConcreteCheck :: ConcreteCheck m -> Bool
    wantConcreteCheck :: forall (m :: * -> *). ConcreteCheck m -> Bool
    wantConcreteCheck = \case
        ConcreteCheck m
    CC_None -> Bool
    False
        ConcreteCheck m
    CC_Check -> Bool
    True
        CC_Promote {} -> Bool
    True

    -- | Given a family-application @ty@, return a @'Reduction' :: ty ~ cbv@
    -- where @cbv@ is a fresh loop-breaker tyvar (for Given), or
    -- just a fresh 'TauTv' (for Wanted)
    famAppBreaker :: FamAppBreaker a -> TcType -> TcM (PuResult a Reduction)
    famAppBreaker :: forall a. FamAppBreaker a -> TcType -> TcM (PuResult a Reduction)
    famAppBreaker FamAppBreaker a
    BreakGiven TcType
    fam_app
       = do { new_tv <- TcType -> TcM TcTyVar
    TcM.newCycleBreakerTyVar (HasDebugCallStack => TcType -> TcType
    TcType -> TcType
    typeKind TcType
    fam_app)
            ; return (PuOK (unitBag (new_tv, fam_app))
                           (mkReflRedn Nominal (mkTyVarTy new_tv))) }
                     -- Why reflexive? See Detail (4) of Note [Type equality cycles]
                     -- in GHC.Tc.Solver.Equality
    famAppBreaker (BreakWanted CtEvidence
    ev TcTyVar
    lhs_tv) TcType
    fam_app
      -- Occurs check or skolem escape; so flatten
      = do { reason <- CheckTyEqProblem
    -> Name -> TcLevel -> VarSet -> TcM CheckTyEqResult
    checkPromoteFreeVars CheckTyEqProblem
    cteInsolubleOccurs
                         (TcTyVar -> Name
    tyVarName TcTyVar
    lhs_tv) TcLevel
    lhs_tv_lvl
                         (TcType -> VarSet
    tyCoVarsOfType TcType
    fam_app_kind)
           ; if not (cterHasNoProblem reason)  -- Failed to promote free vars
             then return $ PuFail reason
             else
        do { new_tv_ty <-
              case lhs_tv_info of
                ConcreteTv ConcreteTvOrigin
    conc_info ->
                  -- Make a concrete tyvar if lhs_tv is concrete
                  -- e.g.  alpha[2,conc] ~ Maybe (F beta[4])
                  --       We want to flatten to
                  --       alpha[2,conc] ~ Maybe gamma[2,conc]
                  --       gamma[2,conc] ~ F beta[4]
                  ConcreteTvOrigin -> TcLevel -> TcType -> TcM TcType
    TcM.newConcreteTyVarTyAtLevel ConcreteTvOrigin
    conc_info TcLevel
    lhs_tv_lvl TcType
    fam_app_kind
                MetaInfo
    _ -> TcLevel -> TcType -> TcM TcType
    TcM.newMetaTyVarTyAtLevel TcLevel
    lhs_tv_lvl TcType
    fam_app_kind

           ; let pty = TcType -> TcType -> TcType
    mkNomEqPred TcType
    fam_app TcType
    new_tv_ty
           ; hole <- TcM.newCoercionHole pty
           ; let new_ev = WantedCt { ctev_pred :: TcType
    ctev_pred      = TcType
    pty
                                   , ctev_dest :: TcEvDest
    ctev_dest      = CoercionHole -> TcEvDest
    HoleDest CoercionHole
    hole
                                   , ctev_loc :: CtLoc
    ctev_loc       = CtLoc
    cb_loc
                                   , ctev_rewriters :: RewriterSet
    ctev_rewriters = CtEvidence -> RewriterSet
    ctEvRewriters CtEvidence
    ev }
           ; return (PuOK (singleCt (mkNonCanonical $ CtWanted new_ev))
                          (mkReduction (HoleCo hole) new_tv_ty)) } }
      where
        fam_app_kind :: TcType
    fam_app_kind = HasDebugCallStack => TcType -> TcType
    TcType -> TcType
    typeKind TcType
    fam_app
        (MetaInfo
    lhs_tv_info, TcLevel
    lhs_tv_lvl) =
          case TcTyVar -> TcTyVarDetails
    tcTyVarDetails TcTyVar
    lhs_tv of
             MetaTv { mtv_info :: TcTyVarDetails -> MetaInfo
    mtv_info = MetaInfo
    info, mtv_tclvl :: TcTyVarDetails -> TcLevel
    mtv_tclvl = TcLevel
    lvl } -> (MetaInfo
    info,TcLevel
    lvl)
             -- lhs_tv should be a meta-tyvar
             TcTyVarDetails
    _ -> String -> SDoc -> (MetaInfo, TcLevel)
    forall a. HasCallStack => String -> SDoc -> a
    pprPanic String
    "famAppBreaker BreakWanted: lhs_tv is not a meta-tyvar"
                    (TcTyVar -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr TcTyVar
    lhs_tv)
        cb_loc :: CtLoc
    cb_loc = CtLoc -> (CtOrigin -> CtOrigin) -> CtLoc
    updateCtLocOrigin (CtEvidence -> CtLoc
    ctEvLoc CtEvidence
    ev) CtOrigin -> CtOrigin
    CycleBreakerOrigin
          -- CycleBreakerOrigin: see Detail (7) of Note [Type equality cycles]

    instance Outputable (TyEqFlags m a) where
      ppr :: TyEqFlags m a -> SDoc
    ppr = \case
        TEFTyFam CheckTyEqProblem
    occ TyCon
    tc [TcType]
    tys TyEqFamApp m a
    fam_app ->
          String -> SDoc
    forall doc. IsLine doc => String -> doc
    text String
    "TEFTyFam" SDoc -> SDoc -> SDoc
    forall doc. IsLine doc => doc -> doc -> doc
    <> SDoc -> SDoc
    forall doc. IsLine doc => doc -> doc
    braces (
            [SDoc] -> SDoc
    forall doc. IsLine doc => [doc] -> doc
    hcat [ CheckTyEqProblem -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr CheckTyEqProblem
    occ
                 , TcType -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr (TyCon -> [TcType] -> TcType
    mkTyConApp TyCon
    tc [TcType]
    tys)
                 , TyEqFamApp m a -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr TyEqFamApp m a
    fam_app ] )
        TEFTyVar OccursCheck
    occ LevelCheck m
    lc ConcreteCheck m
    conc TyEqFamApp m a
    fam_app ->
          String -> SDoc
    forall doc. IsLine doc => String -> doc
    text String
    "TEFTyVar" SDoc -> SDoc -> SDoc
    forall doc. IsLine doc => doc -> doc -> doc
    <> SDoc -> SDoc
    forall doc. IsLine doc => doc -> doc
    braces ([SDoc] -> SDoc
    forall doc. IsLine doc => [doc] -> doc
    hcat (SDoc -> [SDoc] -> [SDoc]
    forall doc. IsLine doc => doc -> [doc] -> [doc]
    punctuate SDoc
    forall doc. IsLine doc => doc
    comma [SDoc]
    fields))
          where
            fields :: [SDoc]
    fields = [ String -> SDoc
    forall doc. IsLine doc => String -> doc
    text String
    "OccursCheck:" SDoc -> SDoc -> SDoc
    forall doc. IsLine doc => doc -> doc -> doc
    <+> OccursCheck -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr OccursCheck
    occ ]
                       [SDoc] -> [SDoc] -> [SDoc]
    forall a. [a] -> [a] -> [a]
    ++
                     [ String -> SDoc
    forall doc. IsLine doc => String -> doc
    text String
    "LevelCheck:" SDoc -> SDoc -> SDoc
    forall doc. IsLine doc => doc -> doc -> doc
    <+> LevelCheck m -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr LevelCheck m
    lc ]
                       [SDoc] -> [SDoc] -> [SDoc]
    forall a. [a] -> [a] -> [a]
    ++
                     [ String -> SDoc
    forall doc. IsLine doc => String -> doc
    text String
    "ConcreteCheck:" SDoc -> SDoc -> SDoc
    forall doc. IsLine doc => doc -> doc -> doc
    <+> ConcreteCheck m -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr ConcreteCheck m
    conc ]
                       [SDoc] -> [SDoc] -> [SDoc]
    forall a. [a] -> [a] -> [a]
    ++
                     [ String -> SDoc
    forall doc. IsLine doc => String -> doc
    text String
    "FamApp:" SDoc -> SDoc -> SDoc
    forall doc. IsLine doc => doc -> doc -> doc
    <+> TyEqFamApp m a -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr TyEqFamApp m a
    fam_app ]

    instance Outputable (TyEqFamApp m a) where
      ppr :: TyEqFamApp m a -> SDoc
    ppr TyEqFamApp m a
    TEFA_Recurse         = String -> SDoc
    forall doc. IsLine doc => String -> doc
    text String
    "TEFA_Recurse"
      ppr (TEFA_Break FamAppBreaker a
    breaker) = String -> SDoc
    forall doc. IsLine doc => String -> doc
    text String
    "TEFA_BreakGiven" SDoc -> SDoc -> SDoc
    forall doc. IsLine doc => doc -> doc -> doc
    <+> FamAppBreaker a -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr FamAppBreaker a
    breaker

    instance Outputable (FamAppBreaker a) where
      ppr :: FamAppBreaker a -> SDoc
    ppr FamAppBreaker a
    BreakGiven          = String -> SDoc
    forall doc. IsLine doc => String -> doc
    text String
    "BreakGiven"
      ppr (BreakWanted CtEvidence
    ev TcTyVar
    tv) = SDoc -> SDoc
    forall doc. IsLine doc => doc -> doc
    parens (SDoc -> SDoc) -> SDoc -> SDoc
    forall a b. (a -> b) -> a -> b
    $ String -> SDoc
    forall doc. IsLine doc => String -> doc
    text String
    "BreakWanted" SDoc -> SDoc -> SDoc
    forall doc. IsLine doc => doc -> doc -> doc
    <+> CtEvidence -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr CtEvidence
    ev SDoc -> SDoc -> SDoc
    forall doc. IsLine doc => doc -> doc -> doc
    <+> TcTyVar -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr TcTyVar
    tv

    instance Outputable OccursCheck where
      ppr :: OccursCheck -> SDoc
    ppr OccursCheck
    OC_None = String -> SDoc
    forall doc. IsLine doc => String -> doc
    text String
    "OC_None"
      ppr (OC_Check { occurs_tv_name :: OccursCheck -> Name
    occurs_tv_name = Name
    nm }) = String -> SDoc
    forall doc. IsLine doc => String -> doc
    text String
    "OC_Check" SDoc -> SDoc -> SDoc
    forall doc. IsLine doc => doc -> doc -> doc
    <+> Name -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr Name
    nm
    instance Outputable (ConcreteCheck m) where
      ppr :: ConcreteCheck m -> SDoc
    ppr ConcreteCheck m
    CC_None = String -> SDoc
    forall doc. IsLine doc => String -> doc
    text String
    "CC_None"
      ppr ConcreteCheck m
    CC_Check = String -> SDoc
    forall doc. IsLine doc => String -> doc
    text String
    "CC_Check"
      ppr (CC_Promote {}) = String -> SDoc
    forall doc. IsLine doc => String -> doc
    text String
    "CC_Promote"
    instance Outputable (LevelCheck m) where
      ppr :: LevelCheck m -> SDoc
    ppr (LevelCheck m
    LC_None) = String -> SDoc
    forall doc. IsLine doc => String -> doc
    text String
    "LC_None"
      ppr (LC_Check TcLevel
    lvl Bool
    lenient) = String -> SDoc
    forall doc. IsLine doc => String -> doc
    text String
    "LC_Check" 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
    <+> Bool -> SDoc -> SDoc
    forall doc. IsOutput doc => Bool -> doc -> doc
    ppWhen Bool
    lenient (String -> SDoc
    forall doc. IsLine doc => String -> doc
    text String
    "(lenient)")
      ppr (LC_Promote TcLevel
    lvl Bool
    deep)  = String -> SDoc
    forall doc. IsLine doc => String -> doc
    text String
    "LC_Promote" 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
    <+> Bool -> SDoc -> SDoc
    forall doc. IsOutput doc => Bool -> doc -> doc
    ppWhen Bool
    deep (String -> SDoc
    forall doc. IsLine doc => String -> doc
    text String
    "(deep)")

    -- | Adjust the 'TyEqFlags' when going under a type family:
    --
    --  1. Only the outer family application gets the loop-breaker treatment
    --  2. Weaken level checks for tyvar promotion. For example, in @[W] alpha[2] ~ Maybe (F beta[3])@,
    --     do not promote @beta[3]@, instead promote @(F beta[3])@.
    --  3. Occurs checks become potentially soluble (after additional type family
    --     reductions).
    famAppArgFlags :: TyEqFlags m a -> TyEqFlags m a
    famAppArgFlags :: forall (m :: * -> *) a. TyEqFlags m a -> TyEqFlags m a
    famAppArgFlags TyEqFlags m a
    flags = case TyEqFlags m a
    flags of
      TEFTyFam {} ->
        TyEqFlags m a
    flags
          { tef_fam_app = TEFA_Recurse -- (1)
          , tefTyFam_occursCheck = cteSolubleOccurs -- (3)
          }
      TEFTyVar { tefTyVar_occursCheck :: forall (m :: * -> *) a. TyEqFlags m a -> OccursCheck
    tefTyVar_occursCheck = OccursCheck
    occ, tefTyVar_levelCheck :: forall (m :: * -> *) a. TyEqFlags m a -> LevelCheck m
    tefTyVar_levelCheck = LevelCheck m
    mb_lc } ->
        TyEqFlags m a
    flags
          { tef_fam_app = TEFA_Recurse -- (1)
          , tefTyVar_levelCheck = zap_lc mb_lc -- (2)
          , tefTyVar_occursCheck = soluble_occ occ -- (3)
          }
      where
        soluble_occ :: OccursCheck -> OccursCheck
    soluble_occ = \case
          OC_Check Name
    tv CheckTyEqProblem
    _ -> Name -> CheckTyEqProblem -> OccursCheck
    OC_Check Name
    tv CheckTyEqProblem
    cteSolubleOccurs
          OccursCheck
    OC_None -> OccursCheck
    OC_None
        zap_lc :: LevelCheck m -> LevelCheck m
    zap_lc = \case
          LC_Promote { lc_lvlp :: LevelCheck (IOEnv (Env TcGblEnv TcLclEnv)) -> TcLevel
    lc_lvlp = TcLevel
    lvl, lc_deep :: LevelCheck (IOEnv (Env TcGblEnv TcLclEnv)) -> Bool
    lc_deep = Bool
    deeply }
            | Bool -> Bool
    not Bool
    deeply
            -> LC_Check { lc_lvlc :: TcLevel
    lc_lvlc = TcLevel
    lvl, lc_lenient :: Bool
    lc_lenient = Bool
    False }
          LevelCheck m
    lc -> LevelCheck m
    lc

    {- Note [checkTyEqRhs]
    ~~~~~~~~~~~~~~~~~~~~~~
    The key function `checkTyEqRhs ty_eq_flags rhs` is called on the
    RHS of a type equality
           lhs ~ rhs
    and checks to see if `rhs` satisfies, or can be made to satisfy,
    invariants described by `ty_eq_flags`.  It can succeded or fail; in
    the latter case it returns a `CheckTyEqResult` that describes why it
    failed.

    When `lhs` is a touchable type variable, so unification might happen, then
    `checkTyEqRhs` enforces the unification preconditions of Note [Unification preconditions].

    Notably, it can check for things like:
      * Insoluble occurs check
          e.g.  alpha[tau] ~ [alpha]
           or   F Int      ~ [F Int]
      * Potentially-soluble occurs check
          e.g.  alpha[tau] ~ [F alpha beta]
      * Impredicativity error:
          e.g.  alpha[tau] ~ (forall a. a->a)
      * Skolem escape
          e.g  alpha[1] ~ (b[sk:2], Int)
      * Concreteness error
          e.g. alpha[conc] ~ r[sk]

    Its specific behaviour is governed by the `TyEqFlags` that are passed
    to it; see Note [TyEqFlags].

    Note, however, that `checkTyEqRhs` specifically does /not/ check for:
      * Touchability of the LHS (in the case of a unification variable)
      * Shape of the LHS (e.g. we can't unify Int with a TyVarTv)
    These things are checked by `simpleUnifyCheck`.
    -}

    -- | Perform the checks specified by the 'TyEqFlags' on the RHS, in order to
    -- enforce the unification preconditions of Note [Unification preconditions].
    --
    -- See Note [checkTyEqRhs].
    checkTyEqRhs :: forall m a
                 .  Monad m
                 => TyEqFlags m a
                 -> TcType           -- Already zonked
                 -> m (PuResult a Reduction)
    checkTyEqRhs :: forall (m :: * -> *) a.
    Monad m =>
    TyEqFlags m a -> TcType -> m (PuResult a Reduction)
    checkTyEqRhs TyEqFlags m a
    flags TcType
    rhs
      -- Crucial special case for a top-level equality of the form 'alpha ~ F tys'.
      -- We don't want to flatten that (F tys), as this gets us right back to where
      -- we started!
      --
      -- See also Note [Special case for top-level of Given equality]
      | Just (TyFamLHS TyCon
    tc [TcType]
    tys) <- TcType -> Maybe CanEqLHS
    canTyFamEqLHS_maybe TcType
    rhs
      , Bool -> Bool
    not (Bool -> Bool) -> Bool -> Bool
    forall a b. (a -> b) -> a -> b
    $ TyEqFlags m a -> Bool
    forall (m :: * -> *) a. TyEqFlags m a -> Bool
    tefConcrete TyEqFlags m a
    flags
      = TyEqFlags m a -> TyCon -> [TcType] -> m (PuResult a Reduction)
    forall (m :: * -> *) a.
    Monad m =>
    TyEqFlags m a -> TyCon -> [TcType] -> m (PuResult a Reduction)
    recurseIntoFamTyConApp TyEqFlags m a
    flags TyCon
    tc [TcType]
    tys
      | Bool
    otherwise
      = TyEqFlags m a -> TcType -> m (PuResult a Reduction)
    forall (m :: * -> *) a.
    Monad m =>
    TyEqFlags m a -> TcType -> m (PuResult a Reduction)
    check_ty_eq_rhs TyEqFlags m a
    flags TcType
    rhs

    {- Note [Special case for top-level of Given equality]
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    We take care when examining
        [G] F ty ~ G (...(F ty)...)
    where both sides are TyFamLHSs.  We don't want to flatten that RHS to
        [G] F ty ~ cbv
        [G] G (...(F ty)...) ~ cbv
    Instead we'd like to say "occurs-check" and swap LHS and RHS, which yields a
    canonical constraint
        [G] G (...(F ty)...) ~ F ty
    That tends to rewrite a big type to smaller one. This happens in T15703,
    where we had:
        [G] Pure g ~ From1 (To1 (Pure g))
    Making a loop breaker and rewriting left to right just makes much bigger
    types than swapping it over.

    (We might hope to have swapped it over before getting to checkTypeEq,
    but better safe than sorry.)

    NB: We never see a TyVarLHS here, such as
        [G] a ~ F tys here
    because we'd have swapped it to
       [G] F tys ~ a
    in canEqCanLHS2, before getting to checkTypeEq.
    -}

    check_ty_eq_rhs :: forall m a
                    .  Monad m
                    => TyEqFlags m a
                    -> TcType           -- Already zonked
                    -> m (PuResult a Reduction)
    check_ty_eq_rhs :: forall (m :: * -> *) a.
    Monad m =>
    TyEqFlags m a -> TcType -> m (PuResult a Reduction)
    check_ty_eq_rhs TyEqFlags m a
    flags TcType
    ty
      = case TcType
    ty of
          LitTy {}        -> PuResult a Reduction -> m (PuResult a Reduction)
    forall a. a -> m a
    forall (m :: * -> *) a. Monad m => a -> m a
    return (PuResult a Reduction -> m (PuResult a Reduction))
    -> PuResult a Reduction -> m (PuResult a Reduction)
    forall a b. (a -> b) -> a -> b
    $ TcType -> PuResult a Reduction
    forall a. TcType -> PuResult a Reduction
    okCheckRefl TcType
    ty
          TyConApp TyCon
    tc [TcType]
    tys -> TyEqFlags m a
    -> TcType -> TyCon -> [TcType] -> m (PuResult a Reduction)
    forall (m :: * -> *) a.
    Monad m =>
    TyEqFlags m a
    -> TcType -> TyCon -> [TcType] -> m (PuResult a Reduction)
    checkTyConApp TyEqFlags m a
    flags TcType
    ty TyCon
    tc [TcType]
    tys
          TyVarTy TcTyVar
    tv      -> TyEqFlags m a -> TcTyVar -> m (PuResult a Reduction)
    forall (m :: * -> *) a.
    Monad m =>
    TyEqFlags m a -> TcTyVar -> m (PuResult a Reduction)
    checkTyVar TyEqFlags m 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 :: TcType -> FunTyFlag
    ft_af = FunTyFlag
    af, ft_mult :: TcType -> TcType
    ft_mult = TcType
    w, ft_arg :: TcType -> TcType
    ft_arg = TcType
    a, ft_res :: TcType -> TcType
    ft_res = TcType
    r}
           | FunTyFlag -> Bool
    isInvisibleFunArg FunTyFlag
    af  -- e.g.  Num a => blah
           -> PuResult a Reduction -> m (PuResult a Reduction)
    forall a. a -> m a
    forall (m :: * -> *) a. Monad m => a -> m a
    return (PuResult a Reduction -> m (PuResult a Reduction))
    -> PuResult a Reduction -> m (PuResult a Reduction)
    forall a b. (a -> b) -> a -> b
    $ CheckTyEqResult -> PuResult a Reduction
    forall a b. CheckTyEqResult -> PuResult a b
    PuFail CheckTyEqResult
    impredicativeProblem -- Not allowed (TyEq:F)
           | Bool
    otherwise
           -> do { w_res <- TyEqFlags m a -> TcType -> m (PuResult a Reduction)
    forall (m :: * -> *) a.
    Monad m =>
    TyEqFlags m a -> TcType -> m (PuResult a Reduction)
    check_ty_eq_rhs TyEqFlags m a
    flags TcType
    w
                 ; a_res <- check_ty_eq_rhs flags a
                 ; r_res <- check_ty_eq_rhs flags r
                 ; return (mkFunRedn Nominal af <$> w_res <*> a_res <*> r_res) }

          AppTy TcType
    fun TcType
    arg -> do { fun_res <- TyEqFlags m a -> TcType -> m (PuResult a Reduction)
    forall (m :: * -> *) a.
    Monad m =>
    TyEqFlags m a -> TcType -> m (PuResult a Reduction)
    check_ty_eq_rhs TyEqFlags m a
    flags TcType
    fun
                              ; arg_res <- check_ty_eq_rhs flags arg
                              ; return (mkAppRedn <$> fun_res <*> arg_res) }

          CastTy TcType
    ty Coercion
    co  -> do { ty_res <- TyEqFlags m a -> TcType -> m (PuResult a Reduction)
    forall (m :: * -> *) a.
    Monad m =>
    TyEqFlags m a -> TcType -> m (PuResult a Reduction)
    check_ty_eq_rhs TyEqFlags m a
    flags TcType
    ty
                              ; co_res <- checkCo flags co
                              ; return (mkCastRedn1 Nominal ty <$> co_res <*> ty_res) }

          CoercionTy Coercion
    co -> do { co_res <- TyEqFlags m a -> Coercion -> m (PuResult a Coercion)
    forall (m :: * -> *) a.
    Monad m =>
    TyEqFlags m a -> Coercion -> m (PuResult a Coercion)
    checkCo TyEqFlags m a
    flags Coercion
    co
                              ; return (mkReflCoRedn Nominal <$> co_res) }

          ForAllTy {}   -> PuResult a Reduction -> m (PuResult a Reduction)
    forall a. a -> m a
    forall (m :: * -> *) a. Monad m => a -> m a
    return (PuResult a Reduction -> m (PuResult a Reduction))
    -> PuResult a Reduction -> m (PuResult a Reduction)
    forall a b. (a -> b) -> a -> b
    $ CheckTyEqResult -> PuResult a Reduction
    forall a b. CheckTyEqResult -> PuResult a b
    PuFail CheckTyEqResult
    impredicativeProblem -- Not allowed (TyEq:F)
    {-# INLINEABLE check_ty_eq_rhs #-}

    -------------------
    checkCo :: Monad m => TyEqFlags m a -> Coercion -> m (PuResult a Coercion)
    -- See Note [checkCo]
    checkCo :: forall (m :: * -> *) a.
    Monad m =>
    TyEqFlags m a -> Coercion -> m (PuResult a Coercion)
    checkCo TyEqFlags m a
    flags Coercion
    co =
      case TyEqFlags m a
    flags of
        TEFTyFam {} ->
          -- NB: 'TEFTyFam' case means we are not unifying.
          PuResult a Coercion -> m (PuResult a Coercion)
    forall a. a -> m 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)
        TEFTyVar
          { tefTyVar_concreteCheck :: forall (m :: * -> *) a. TyEqFlags m a -> ConcreteCheck m
    tefTyVar_concreteCheck = ConcreteCheck m
    conc
          , tefTyVar_levelCheck :: forall (m :: * -> *) a. TyEqFlags m a -> LevelCheck m
    tefTyVar_levelCheck    = LevelCheck m
    lc
          , tefTyVar_occursCheck :: forall (m :: * -> *) a. TyEqFlags m a -> OccursCheck
    tefTyVar_occursCheck   = OccursCheck
    occ
          }
            -- Coercions cannot appear in concrete types.
            --
            -- See Note [Concrete types] in GHC.Tc.Utils.Concrete.
            | case ConcreteCheck m
    conc of { ConcreteCheck m
    CC_None -> Bool
    False; ConcreteCheck m
    _ -> Bool
    True }
            -> PuResult a Coercion -> m (PuResult a Coercion)
    forall a. a -> m a
    forall (m :: * -> *) a. Monad m => a -> m a
    return (PuResult a Coercion -> m (PuResult a Coercion))
    -> PuResult a Coercion -> m (PuResult a Coercion)
    forall a b. (a -> b) -> a -> b
    $ CheckTyEqResult -> PuResult a Coercion
    forall a b. CheckTyEqResult -> PuResult a b
    PuFail (CheckTyEqProblem -> CheckTyEqResult
    cteProblem CheckTyEqProblem
    cteConcrete)

            -- Occurs check (can promote)
            | OC_Check Name
    lhs_tv CheckTyEqProblem
    occ_prob <- OccursCheck
    occ
            , LC_Promote { lc_lvlp :: LevelCheck (IOEnv (Env TcGblEnv TcLclEnv)) -> TcLevel
    lc_lvlp = TcLevel
    lhs_tv_lvl } <- LevelCheck m
    lc
            -> do { reason <- CheckTyEqProblem
    -> Name -> TcLevel -> VarSet -> TcM CheckTyEqResult
    checkPromoteFreeVars CheckTyEqProblem
    occ_prob Name
    lhs_tv TcLevel
    lhs_tv_lvl (Coercion -> VarSet
    tyCoVarsOfCo Coercion
    co)
                  ; return $
                    if cterHasNoProblem reason
                    then pure co
                    else PuFail reason }

            -- Occurs check (no promotion)
            | OC_Check Name
    lhs_tv CheckTyEqProblem
    occ_prob <- OccursCheck
    occ
            , Name -> Unique
    nameUnique Name
    lhs_tv Unique -> VarSet -> Bool
    `elemVarSetByKey` Coercion -> VarSet
    tyCoVarsOfCo Coercion
    co
            -> PuResult a Coercion -> m (PuResult a Coercion)
    forall a. a -> m a
    forall (m :: * -> *) a. Monad m => a -> m a
    return (PuResult a Coercion -> m (PuResult a Coercion))
    -> PuResult a Coercion -> m (PuResult a Coercion)
    forall a b. (a -> b) -> a -> b
    $ CheckTyEqResult -> PuResult a Coercion
    forall a b. CheckTyEqResult -> PuResult a b
    PuFail (CheckTyEqProblem -> CheckTyEqResult
    cteProblem CheckTyEqProblem
    occ_prob)

            | Bool
    otherwise
            -> PuResult a Coercion -> m (PuResult a Coercion)
    forall a. a -> m 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.

    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.
    This is dealt with by `checkFamApp`.

    (CFA1) 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)))

    (CFA2) 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.

    (CFA3) 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.

    Once these three cases are dealt with, the `tef_fam_app` field of `TypeEqFlags`
    says what to do:

    (CFA4) `TEFA_Recurse` is straightforward: just recurse into the arguments,
      BUT use `recurseIntoFamTyConApp` to record that we are now "under" a
      type-family application; see `famAppArgFlags`.

    (CFA5) `TEFA_Break` is the clever one. It does a two-step process:

      (1) Recurse into the arguments with `recurseIntoFamTyConApp`.

      (2) If any of the arguments fail (level-check error, occurs check,
          concreteness failure), use the `FamAppBreaker` to create a cycle breaker.

      Remarks:

      * It would be possible to use Step (2) above always, skipping Step (1).
        But this would create many unnecessary cycle-breaker variables.
        This was the cause of #25933.

      * 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))`
        - In Step (1), `recurseIntoFamTyConApp` sets `tef_fam_app := TEFA_Recurse`,
          before looking at the argument `(G alpha)`.  So we will not cycle-break
          the latter
        - The occurs check will fire when we hit `alpha`
        - `checkFamApp` on `(F (G alpha))` will see the failure and invoke
           the `FamAppBreaker`.

      * Step (1) may fail because of a level-check problem, which activates step (2).
        This is what implements (CFA2).
    -}

    -------------------
    checkTyConApp :: Monad m
                  => TyEqFlags m a
                  -> TcType -> TyCon -> [TcType]
                  -> m (PuResult a Reduction)
    checkTyConApp :: forall (m :: * -> *) a.
    Monad m =>
    TyEqFlags m a
    -> TcType -> TyCon -> [TcType] -> m (PuResult a Reduction)
    checkTyConApp TyEqFlags m a
    flags TcType
    tc_app TyCon
    tc [TcType]
    tys
      | TyCon -> Bool
    isTypeFamilyTyCon TyCon
    tc
      , let arity :: Int
    arity = TyCon -> Int
    tyConArity TyCon
    tc
      = if [TcType]
    tys [TcType] -> Int -> Bool
    forall a. [a] -> Int -> Bool
    `lengthIs` Int
    arity
        then TyEqFlags m a
    -> TcType -> TyCon -> [TcType] -> m (PuResult a Reduction)
    forall (m :: * -> *) a.
    Monad m =>
    TyEqFlags m a
    -> TcType -> TyCon -> [TcType] -> m (PuResult a Reduction)
    checkFamApp TyEqFlags m a
    flags TcType
    tc_app TyCon
    tc [TcType]
    tys  -- Common case
        else do { let ([TcType]
    fun_args, [TcType]
    extra_args) = Int -> [TcType] -> ([TcType], [TcType])
    forall a. Int -> [a] -> ([a], [a])
    splitAt (TyCon -> Int
    tyConArity TyCon
    tc) [TcType]
    tys
                      fun_app :: TcType
    fun_app                = TyCon -> [TcType] -> TcType
    mkTyConApp TyCon
    tc [TcType]
    fun_args
                ; fun_res   <- TyEqFlags m a
    -> TcType -> TyCon -> [TcType] -> m (PuResult a Reduction)
    forall (m :: * -> *) a.
    Monad m =>
    TyEqFlags m a
    -> TcType -> TyCon -> [TcType] -> m (PuResult a Reduction)
    checkFamApp TyEqFlags m a
    flags TcType
    fun_app TyCon
    tc [TcType]
    fun_args
                ; extra_res <- mapCheck (check_ty_eq_rhs flags) extra_args
                ; return (mkAppRedns <$> fun_res <*> extra_res) }

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

      | Bool -> Bool
    not (TyCon -> Bool
    isTauTyCon TyCon
    tc)
      = PuResult a Reduction -> m (PuResult a Reduction)
    forall a. a -> m a
    forall (m :: * -> *) a. Monad m => a -> m a
    return (PuResult a Reduction -> m (PuResult a Reduction))
    -> PuResult a Reduction -> m (PuResult a Reduction)
    forall a b. (a -> b) -> a -> b
    $ CheckTyEqResult -> PuResult a Reduction
    forall a b. CheckTyEqResult -> PuResult a b
    PuFail CheckTyEqResult
    impredicativeProblem

      | TyEqFlags m a -> Bool
    forall (m :: * -> *) a. TyEqFlags m a -> Bool
    tefConcrete TyEqFlags m a
    flags
      , Bool -> Bool
    not (TyCon -> Bool
    isConcreteTyCon TyCon
    tc)
      = PuResult a Reduction -> m (PuResult a Reduction)
    forall a. a -> m a
    forall (m :: * -> *) a. Monad m => a -> m a
    return (PuResult a Reduction -> m (PuResult a Reduction))
    -> PuResult a Reduction -> m (PuResult a Reduction)
    forall a b. (a -> b) -> a -> b
    $ CheckTyEqResult -> PuResult a Reduction
    forall a b. CheckTyEqResult -> PuResult a b
    PuFail (CheckTyEqProblem -> CheckTyEqResult
    cteProblem CheckTyEqProblem
    cteConcrete)

      | Bool
    otherwise  -- Recurse on arguments
      = TyEqFlags m a -> TyCon -> [TcType] -> m (PuResult a Reduction)
    forall (m :: * -> *) a.
    Monad m =>
    TyEqFlags m a -> TyCon -> [TcType] -> m (PuResult a Reduction)
    recurseIntoTyConApp TyEqFlags m a
    flags TyCon
    tc [TcType]
    tys

    -------------------
    recurseIntoTyConApp :: Monad m
                        => TyEqFlags m a
                        -> TyCon -> [TcType]
                        -> m (PuResult a Reduction)
    recurseIntoTyConApp :: forall (m :: * -> *) a.
    Monad m =>
    TyEqFlags m a -> TyCon -> [TcType] -> m (PuResult a Reduction)
    recurseIntoTyConApp TyEqFlags m a
    flags TyCon
    tc [TcType]
    tys
      = do { tys_res <- (TcType -> m (PuResult a Reduction))
    -> [TcType] -> m (PuResult a Reductions)
    forall (m :: * -> *) x a.
    Monad m =>
    (x -> m (PuResult a Reduction)) -> [x] -> m (PuResult a Reductions)
    mapCheck (TyEqFlags m a -> TcType -> m (PuResult a Reduction)
    forall (m :: * -> *) a.
    Monad m =>
    TyEqFlags m a -> TcType -> m (PuResult a Reduction)
    check_ty_eq_rhs TyEqFlags m a
    flags) [TcType]
    tys
           ; return (mkTyConAppRedn Nominal tc <$> tys_res) }

    recurseIntoFamTyConApp :: Monad m
                           => TyEqFlags m a
                           -> TyCon -> [TcType]
                           -> m (PuResult a Reduction)
    recurseIntoFamTyConApp :: forall (m :: * -> *) a.
    Monad m =>
    TyEqFlags m a -> TyCon -> [TcType] -> m (PuResult a Reduction)
    recurseIntoFamTyConApp TyEqFlags m a
    flags TyCon
    tc [TcType]
    tys
      = TyEqFlags m a -> TyCon -> [TcType] -> m (PuResult a Reduction)
    forall (m :: * -> *) a.
    Monad m =>
    TyEqFlags m a -> TyCon -> [TcType] -> m (PuResult a Reduction)
    recurseIntoTyConApp (TyEqFlags m a -> TyEqFlags m a
    forall (m :: * -> *) a. TyEqFlags m a -> TyEqFlags m a
    famAppArgFlags TyEqFlags m a
    flags) TyCon
    tc [TcType]
    tys
        -- famAppArgFlags: adjust flags when going under fam app

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

    -- | See Note [Family applications in canonical constraints]
    checkFamApp :: forall m a.
                   Monad m
                => TyEqFlags m a
                -> TcType -> TyCon -> [TcType]  -- Saturated family application
                -> m (PuResult a Reduction)
    checkFamApp :: forall (m :: * -> *) a.
    Monad m =>
    TyEqFlags m a
    -> TcType -> TyCon -> [TcType] -> m (PuResult a Reduction)
    checkFamApp TyEqFlags m a
    flags TcType
    fam_app TyCon
    tc [TcType]
    tys =
      case TyEqFlags m a
    flags of
        TEFTyFam { tefTyFam_tyCon :: forall (m :: * -> *) a. TyEqFlags m a -> TyCon
    tefTyFam_tyCon = TyCon
    lhs_tc, tefTyFam_args :: forall (m :: * -> *) a. TyEqFlags m a -> [TcType]
    tefTyFam_args = [TcType]
    lhs_tys
                 , tefTyFam_occursCheck :: forall (m :: * -> *) a. TyEqFlags m a -> CheckTyEqProblem
    tefTyFam_occursCheck = CheckTyEqProblem
    occ_prob }
          | TyCon -> [TcType] -> TyCon -> [TcType] -> Bool
    tcEqTyConApps TyCon
    lhs_tc [TcType]
    lhs_tys TyCon
    tc [TcType]
    tys
          -- There is an occurs check F ty ~ ...(F ty)...
          -- Do not recurse; see (CFA1) in Note [Family applications in canonical constraints]
          -> CheckTyEqProblem -> m (PuResult a Reduction)
    do_not_recurse CheckTyEqProblem
    occ_prob
        TEFTyVar { tefTyVar_concreteCheck :: forall (m :: * -> *) a. TyEqFlags m a -> ConcreteCheck m
    tefTyVar_concreteCheck = ConcreteCheck m
    conc }
          | ConcreteCheck m -> Bool
    forall (m :: * -> *). ConcreteCheck m -> Bool
    wantConcreteCheck ConcreteCheck m
    conc
          -- We are checking for concreteness, e.g. kappa[conc] ~ ...(F ty)...
          -- Do not recurse: type family applications are not concrete.
          -- See (CFA3) in Note [Family applications in canonical constraints]
          -> CheckTyEqProblem -> m (PuResult a Reduction)
    do_not_recurse CheckTyEqProblem
    cteConcrete
        TyEqFlags m a
    _ ->
            -- We can recurse into the arguments of the type family application.
            case TyEqFamApp m a
    fam_flags of
              TyEqFamApp m a
    TEFA_Recurse   ->
                -- Simply recurse into the arguments.
                -- See (CFA4) in Note [Family applications in canonical constraints]
                TyEqFlags m a -> TyCon -> [TcType] -> m (PuResult a Reduction)
    forall (m :: * -> *) a.
    Monad m =>
    TyEqFlags m a -> TyCon -> [TcType] -> m (PuResult a Reduction)
    recurseIntoFamTyConApp TyEqFlags m a
    flags TyCon
    tc [TcType]
    tys
              TEFA_Break FamAppBreaker a
    brk ->
                -- Recurse into the arguments, and cycle-break if that fails
                --
                -- e.g.  alpha[2] ~ Maybe (F beta[2])    No problem: just unify
                --       alpha[2] ~ Maybe (F beta[4])    Level-check problem: break
                --
                -- NB: in the latter case, don't promote beta[4]; use 'recurseIntoFamTyConApp'
                -- which modifies the flags with 'famAppArgFlags'.
                do { rec_res <- TyEqFlags m a -> TyCon -> [TcType] -> m (PuResult a Reduction)
    forall (m :: * -> *) a.
    Monad m =>
    TyEqFlags m a -> TyCon -> [TcType] -> m (PuResult a Reduction)
    recurseIntoFamTyConApp TyEqFlags m a
    flags TyCon
    tc [TcType]
    tys
                   ; case rec_res of
                       PuOK {}   -> PuResult a Reduction -> m (PuResult a Reduction)
    forall a. a -> m a
    forall (m :: * -> *) a. Monad m => a -> m a
    return PuResult a Reduction
    rec_res
                       PuFail {} -> FamAppBreaker a -> TcType -> TcM (PuResult a Reduction)
    forall a. FamAppBreaker a -> TcType -> TcM (PuResult a Reduction)
    famAppBreaker FamAppBreaker a
    brk TcType
    fam_app
                   }
      where
        fam_flags :: TyEqFamApp m a
    fam_flags = TyEqFlags m a -> TyEqFamApp m a
    forall (m :: * -> *) a. TyEqFlags m a -> TyEqFamApp m a
    tef_fam_app TyEqFlags m a
    flags
        do_not_recurse :: CheckTyEqProblem -> m (PuResult a Reduction)
    do_not_recurse CheckTyEqProblem
    prob =
          case TyEqFamApp m a
    fam_flags of
            TyEqFamApp m a
    TEFA_Recurse   -> PuResult a Reduction -> m (PuResult a Reduction)
    forall a. a -> m a
    forall (m :: * -> *) a. Monad m => a -> m a
    return (PuResult a Reduction -> m (PuResult a Reduction))
    -> PuResult a Reduction -> m (PuResult a Reduction)
    forall a b. (a -> b) -> a -> b
    $ CheckTyEqResult -> PuResult a Reduction
    forall a b. CheckTyEqResult -> PuResult a b
    PuFail (CheckTyEqProblem -> CheckTyEqResult
    cteProblem CheckTyEqProblem
    prob)
            TEFA_Break FamAppBreaker a
    brk -> FamAppBreaker a -> TcType -> TcM (PuResult a Reduction)
    forall a. FamAppBreaker a -> TcType -> TcM (PuResult a Reduction)
    famAppBreaker FamAppBreaker a
    brk TcType
    fam_app

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

    -- | The result of a single check in 'checkTyVar', such as a concreteness check
    -- or a level check.
    data TyVarCheckResult m where
      -- | Check succeded; nothing else to do.
      TyVarCheck_Success :: TyVarCheckResult m
      -- | Check succeeded, but requires an additional promotion.
      --
      -- Invariant: at least one of the fields is not 'Nothing'.
      TyVarCheck_Promote
        :: Maybe TcLevel
             -- ^ @Just lvl@ <=> 'TyVar' needs to be promoted to @lvl@
        -> Maybe ConcreteTvOrigin
             -- ^ @Just conc_orig@ <=> 'TyVar' needs to be make concrete
        -> TyVarCheckResult TcM

      -- | Check failed with some 'CheckTyEqProblem's.
      --
      -- Invariant: the 'CheckTyEqResult' is not 'cteOK'.
      TyVarCheck_Error
        :: CheckTyEqResult -> TyVarCheckResult m

    instance Semigroup (TyVarCheckResult m) where
      TyVarCheckResult m
    TyVarCheck_Success <> :: TyVarCheckResult m -> TyVarCheckResult m -> TyVarCheckResult m
    <> TyVarCheckResult m
    r = TyVarCheckResult m
    r
      TyVarCheckResult m
    r <> TyVarCheckResult m
    TyVarCheck_Success = TyVarCheckResult m
    r
      TyVarCheck_Error CheckTyEqResult
    e1 <> TyVarCheck_Error CheckTyEqResult
    e2 =
        CheckTyEqResult -> TyVarCheckResult m
    forall (m :: * -> *). CheckTyEqResult -> TyVarCheckResult m
    TyVarCheck_Error (CheckTyEqResult
    e1 CheckTyEqResult -> CheckTyEqResult -> CheckTyEqResult
    forall a. Semigroup a => a -> a -> a
    S.<> CheckTyEqResult
    e2)
      e :: TyVarCheckResult m
    e@(TyVarCheck_Error {}) <> TyVarCheckResult m
    _ = TyVarCheckResult m
    e
      TyVarCheckResult m
    _ <> e :: TyVarCheckResult m
    e@(TyVarCheck_Error {}) = TyVarCheckResult m
    e
      TyVarCheck_Promote Maybe TcLevel
    l1 Maybe ConcreteTvOrigin
    c1 <> TyVarCheck_Promote Maybe TcLevel
    l2 Maybe ConcreteTvOrigin
    c2 =
        Maybe TcLevel
    -> Maybe ConcreteTvOrigin
    -> TyVarCheckResult (IOEnv (Env TcGblEnv TcLclEnv))
    TyVarCheck_Promote
          ((TcLevel -> TcLevel -> TcLevel)
    -> Maybe TcLevel -> Maybe TcLevel -> Maybe TcLevel
    forall a. (a -> a -> a) -> Maybe a -> Maybe a -> Maybe a
    combineMaybe TcLevel -> TcLevel -> TcLevel
    minTcLevel Maybe TcLevel
    l1 Maybe TcLevel
    l2)
          ((ConcreteTvOrigin -> ConcreteTvOrigin -> ConcreteTvOrigin)
    -> Maybe ConcreteTvOrigin
    -> Maybe ConcreteTvOrigin
    -> Maybe ConcreteTvOrigin
    forall a. (a -> a -> a) -> Maybe a -> Maybe a -> Maybe a
    combineMaybe ConcreteTvOrigin -> ConcreteTvOrigin -> ConcreteTvOrigin
    forall a b. a -> b -> a
    const Maybe ConcreteTvOrigin
    c1 Maybe ConcreteTvOrigin
    c2) -- pick one 'ConcreteTvOrigin' arbitrarily

    combineMaybe :: (a -> a -> a) -> Maybe a -> Maybe a -> Maybe a
    combineMaybe :: forall a. (a -> a -> a) -> Maybe a -> Maybe a -> Maybe a
    combineMaybe a -> a -> a
    _ Maybe a
    Nothing Maybe a
    r = Maybe a
    r
    combineMaybe a -> a -> a
    _ Maybe a
    r Maybe a
    Nothing = Maybe a
    r
    combineMaybe a -> a -> a
    f (Just a
    a) (Just a
    b) = a -> Maybe a
    forall a. a -> Maybe a
    Just (a -> a -> a
    f a
    a a
    b)
    instance Monoid (TyVarCheckResult m) where
      mempty :: TyVarCheckResult m
    mempty = TyVarCheckResult m
    forall (m :: * -> *). TyVarCheckResult m
    TyVarCheck_Success

    checkTyVar :: forall m a. Monad m => TyEqFlags m a -> TcTyVar -> m (PuResult a Reduction)
    checkTyVar :: forall (m :: * -> *) a.
    Monad m =>
    TyEqFlags m a -> TcTyVar -> m (PuResult a Reduction)
    checkTyVar TyEqFlags m a
    flags TcTyVar
    occ_tv
      = case TyEqFlags m a
    flags of
          TEFTyFam {}
            -> m (PuResult a Reduction)
    success   -- Nothing to do if the LHS is a type-family
          TEFTyVar { tefTyVar_occursCheck :: forall (m :: * -> *) a. TyEqFlags m a -> OccursCheck
    tefTyVar_occursCheck = OccursCheck
    occ, tefTyVar_levelCheck :: forall (m :: * -> *) a. TyEqFlags m a -> LevelCheck m
    tefTyVar_levelCheck = LevelCheck m
    lc
                   , tefTyVar_concreteCheck :: forall (m :: * -> *) a. TyEqFlags m a -> ConcreteCheck m
    tefTyVar_concreteCheck = ConcreteCheck m
    conc }
            -> do { already_promoted <- TcTyVar -> LevelCheck m -> ConcreteCheck m -> m Bool
    forall (m :: * -> *).
    Monad m =>
    TcTyVar -> LevelCheck m -> ConcreteCheck m -> m Bool
    promotionDone TcTyVar
    occ_tv LevelCheck m
    lc ConcreteCheck m
    conc

                  ; if already_promoted
                    then 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
                      -- so the only reason for a filled meta-tyvar is promotion

                    else do_rhs_checks
                         [ simpleOccursCheck      occ  occ_tv
                         , tyVarLevelCheck        lc   occ_tv
                         , tyVarConcretenessCheck conc occ_tv ]
                  }
      where
        success :: m (PuResult a Reduction)
    success = PuResult a Reduction -> m (PuResult a Reduction)
    forall a. a -> m a
    forall (m :: * -> *) a. Monad m => a -> m a
    return (PuResult a Reduction -> m (PuResult a Reduction))
    -> PuResult a Reduction -> m (PuResult a Reduction)
    forall a b. (a -> b) -> a -> b
    $ TcType -> PuResult a Reduction
    forall a. TcType -> PuResult a Reduction
    okCheckRefl (TcTyVar -> TcType
    mkTyVarTy TcTyVar
    occ_tv)

        -- Combine the results of individual checks. See 'TyVarCheckResult'.
        do_rhs_checks :: [TyVarCheckResult m] -> m (PuResult a Reduction)
        do_rhs_checks :: [TyVarCheckResult m] -> m (PuResult a Reduction)
    do_rhs_checks [TyVarCheckResult m]
    checks =
          case [TyVarCheckResult m] -> TyVarCheckResult m
    forall a. Monoid a => [a] -> a
    mconcat [TyVarCheckResult m]
    checks of
            TyVarCheckResult m
    TyVarCheck_Success                -> m (PuResult a Reduction)
    success
            TyVarCheck_Promote Maybe TcLevel
    mb_lvl Maybe ConcreteTvOrigin
    mb_conc -> TyEqFlags (IOEnv (Env TcGblEnv TcLclEnv)) a
    -> Maybe TcLevel
    -> Maybe ConcreteTvOrigin
    -> TcM (PuResult a Reduction)
    promote TyEqFlags m a
    TyEqFlags (IOEnv (Env TcGblEnv TcLclEnv)) a
    flags Maybe TcLevel
    mb_lvl Maybe ConcreteTvOrigin
    mb_conc
            TyVarCheck_Error CheckTyEqResult
    cte_prob         -> PuResult a Reduction -> m (PuResult a Reduction)
    forall a. a -> m a
    forall (m :: * -> *) a. Monad m => a -> m a
    return (PuResult a Reduction -> m (PuResult a Reduction))
    -> PuResult a Reduction -> m (PuResult a Reduction)
    forall a b. (a -> b) -> a -> b
    $ CheckTyEqResult -> PuResult a Reduction
    forall a b. CheckTyEqResult -> PuResult a b
    PuFail CheckTyEqResult
    cte_prob

        ---------------------
        -- occ_tv is definitely a MetaTyVar; we need to promote it/make it concrete
        promote :: TyEqFlags TcM a -> Maybe TcLevel -> Maybe ConcreteTvOrigin
                -> TcM (PuResult a Reduction)
        promote :: TyEqFlags (IOEnv (Env TcGblEnv TcLclEnv)) a
    -> Maybe TcLevel
    -> Maybe ConcreteTvOrigin
    -> TcM (PuResult a Reduction)
    promote TyEqFlags (IOEnv (Env TcGblEnv TcLclEnv)) a
    flags Maybe TcLevel
    mb_lhs_tv_lvl Maybe ConcreteTvOrigin
    mb_conc
          | 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 | Just ConcreteTvOrigin
    conc <- Maybe ConcreteTvOrigin
    mb_conc = ConcreteTvOrigin -> MetaInfo
    ConcreteTv ConcreteTvOrigin
    conc
                              | Bool
    otherwise            = MetaInfo
    info_occ
                     new_lvl :: TcLevel
    new_lvl =
                        case Maybe TcLevel
    mb_lhs_tv_lvl of
                          Maybe TcLevel
    Nothing         -> TcLevel
    lvl_occ
                          Just TcLevel
    lhs_tv_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
               --
               -- This is important for several reasons:
               --
               --  1. To ensure there is no occurs check or skolem-escape
               --     in the kind of occ_tv.
               --  2. If the LHS is a concrete type variable and the RHS is an
               --     unfilled meta-tyvar, we need to ensure that the kind of
               --     'occ_tv' is concrete.   Test cases: T23051, T23176.
               ; let occ_kind :: TcType
    occ_kind = TcTyVar -> TcType
    tyVarKind TcTyVar
    occ_tv
               ; kind_result <- TyEqFlags (IOEnv (Env TcGblEnv TcLclEnv)) a
    -> TcType -> TcM (PuResult a Reduction)
    forall (m :: * -> *) a.
    Monad m =>
    TyEqFlags m a -> TcType -> m (PuResult a Reduction)
    check_ty_eq_rhs TyEqFlags (IOEnv (Env TcGblEnv TcLclEnv)) a
    flags TcType
    occ_kind
               ; for kind_result $ \ Reduction
    kind_redn ->
            do { let kind_co :: Coercion
    kind_co  = Reduction -> Coercion
    reductionCoercion Reduction
    kind_redn
                     new_kind :: TcType
    new_kind = Reduction -> TcType
    reductionReducedType Reduction
    kind_redn
                     occ_tv' :: TcTyVar
    occ_tv'  = TcTyVar -> TcType -> TcTyVar
    setTyVarKind TcTyVar
    occ_tv TcType
    new_kind
               ; new_tv_ty <- MetaInfo -> TcLevel -> TcTyVar -> TcM TcType
    promote_meta_tyvar MetaInfo
    new_info TcLevel
    new_lvl TcTyVar
    occ_tv'
               ; return $ mkGReflLeftRedn Nominal new_tv_ty (mkSymCo kind_co)
               } }

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

    ---------------------
    promotionDone :: Monad m => TcTyVar -> LevelCheck m -> ConcreteCheck m -> m Bool
    promotionDone :: forall (m :: * -> *).
    Monad m =>
    TcTyVar -> LevelCheck m -> ConcreteCheck m -> m Bool
    promotionDone TcTyVar
    occ_tv (LC_Promote {}) ConcreteCheck m
    _ = TcTyVar -> TcM Bool
    isFilledMetaTyVar TcTyVar
    occ_tv
    promotionDone TcTyVar
    occ_tv LevelCheck m
    _ (CC_Promote {}) = TcTyVar -> TcM Bool
    isFilledMetaTyVar TcTyVar
    occ_tv
    promotionDone TcTyVar
    _      LevelCheck m
    _               ConcreteCheck m
    _ = Bool -> m Bool
    forall a. a -> m a
    forall (m :: * -> *) a. Monad m => a -> m a
    return Bool
    False

    ---------------------
    simpleOccursCheck :: OccursCheck -> TcTyVar -> TyVarCheckResult m
    -- ^ The "interpreter" for 'OccursCheck'
    simpleOccursCheck :: forall (m :: * -> *). OccursCheck -> TcTyVar -> TyVarCheckResult m
    simpleOccursCheck OccursCheck
    OC_None TcTyVar
    _
      = TyVarCheckResult m
    forall (m :: * -> *). TyVarCheckResult m
    TyVarCheck_Success
    simpleOccursCheck (OC_Check Name
    lhs_tv CheckTyEqProblem
    occ_prob) TcTyVar
    occ_tv
      | Name
    lhs_tv Name -> Name -> Bool
    forall a. Eq a => a -> a -> Bool
    == TcTyVar -> Name
    tyVarName TcTyVar
    occ_tv Bool -> Bool -> Bool
    || TcType -> Bool
    check_kind (TcTyVar -> TcType
    tyVarKind TcTyVar
    occ_tv)
      = CheckTyEqResult -> TyVarCheckResult m
    forall (m :: * -> *). CheckTyEqResult -> TyVarCheckResult m
    TyVarCheck_Error (CheckTyEqProblem -> CheckTyEqResult
    cteProblem CheckTyEqProblem
    occ_prob)
      | Bool
    otherwise
      = TyVarCheckResult m
    forall (m :: * -> *). TyVarCheckResult m
    TyVarCheck_Success
      where
        (TcType -> Bool
    check_kind, Coercion -> Bool
    _) = Name -> (TcType -> Bool, Coercion -> Bool)
    mkOccFolders Name
    lhs_tv

    -------------------------
    tyVarLevelCheck :: LevelCheck m -> TcTyVar -> TyVarCheckResult m
    -- ^ The "interpreter" for 'LevelCheck'
    tyVarLevelCheck :: forall (m :: * -> *). LevelCheck m -> TcTyVar -> TyVarCheckResult m
    tyVarLevelCheck LevelCheck m
    LC_None TcTyVar
    _ = TyVarCheckResult m
    forall (m :: * -> *). TyVarCheckResult m
    TyVarCheck_Success
    tyVarLevelCheck LevelCheck m
    lc TcTyVar
    occ_tv
      | Bool -> Bool
    not Bool
    occ_is_deeper
      = TyVarCheckResult m
    forall (m :: * -> *). TyVarCheckResult m
    TyVarCheck_Success
      | TcTyVar -> Bool
    isSkolemTyVar TcTyVar
    occ_tv
      = CheckTyEqResult -> TyVarCheckResult m
    forall (m :: * -> *). CheckTyEqResult -> TyVarCheckResult m
    TyVarCheck_Error (CheckTyEqProblem -> CheckTyEqResult
    cteProblem CheckTyEqProblem
    cteSkolemEscape)
      | Bool
    otherwise
      = case LevelCheck m
    lc of
          LC_Check { lc_lenient :: forall (m :: * -> *). LevelCheck m -> Bool
    lc_lenient = Bool
    lenient } ->
            if Bool
    lenient
            then TyVarCheckResult m
    forall (m :: * -> *). TyVarCheckResult m
    TyVarCheck_Success
            else CheckTyEqResult -> TyVarCheckResult m
    forall (m :: * -> *). CheckTyEqResult -> TyVarCheckResult m
    TyVarCheck_Error (CheckTyEqProblem -> CheckTyEqResult
    cteProblem CheckTyEqProblem
    cteSkolemEscape)
          LC_Promote { lc_lvlp :: LevelCheck (IOEnv (Env TcGblEnv TcLclEnv)) -> TcLevel
    lc_lvlp = TcLevel
    lhs_tv_lvl } ->
            Maybe TcLevel
    -> Maybe ConcreteTvOrigin
    -> TyVarCheckResult (IOEnv (Env TcGblEnv TcLclEnv))
    TyVarCheck_Promote (TcLevel -> Maybe TcLevel
    forall a. a -> Maybe a
    Just TcLevel
    lhs_tv_lvl) Maybe ConcreteTvOrigin
    forall a. Maybe a
    Nothing
      where
        occ_is_deeper :: Bool
    occ_is_deeper =
          case LevelCheck m
    lc of
            LC_Check { lc_lvlc :: forall (m :: * -> *). LevelCheck m -> TcLevel
    lc_lvlc = TcLevel
    lhs_tv_lvl } ->
              TcTyVar -> TcLevel
    tcTyVarLevel TcTyVar
    occ_tv TcLevel -> TcLevel -> Bool
    `strictlyDeeperThan` TcLevel
    lhs_tv_lvl
            LC_Promote { lc_lvlp :: LevelCheck (IOEnv (Env TcGblEnv TcLclEnv)) -> TcLevel
    lc_lvlp = TcLevel
    lhs_tv_lvl } ->
              TcTyVar -> TcLevel
    tcTyVarLevel TcTyVar
    occ_tv TcLevel -> TcLevel -> Bool
    `strictlyDeeperThan` TcLevel
    lhs_tv_lvl

    -------------------------
    tyVarConcretenessCheck :: ConcreteCheck m -> TcTyVar -> TyVarCheckResult m
    -- ^ The "interpreter" for 'ConcreteCheck'
    tyVarConcretenessCheck :: forall (m :: * -> *).
    ConcreteCheck m -> TcTyVar -> TyVarCheckResult m
    tyVarConcretenessCheck ConcreteCheck m
    cc TcTyVar
    occ_tv
      | ConcreteCheck m
    CC_None <- ConcreteCheck m
    cc             -- No concreteness checks => ok
      = TyVarCheckResult m
    forall (m :: * -> *). TyVarCheckResult m
    TyVarCheck_Success
      | TcTyVar -> Bool
    isConcreteTyVar TcTyVar
    occ_tv    -- It's concrete already  => ok
      = TyVarCheckResult m
    forall (m :: * -> *). TyVarCheckResult m
    TyVarCheck_Success
      | Bool -> Bool
    not (TcTyVar -> Bool
    isMetaTyVar TcTyVar
    occ_tv)  -- Not a meta-tyvar => error
      = CheckTyEqResult -> TyVarCheckResult m
    forall (m :: * -> *). CheckTyEqResult -> TyVarCheckResult m
    TyVarCheck_Error (CheckTyEqProblem -> CheckTyEqResult
    cteProblem CheckTyEqProblem
    cteConcrete)

      | Bool
    otherwise  -- It's a non-concrete meta-tyvar
      = case ConcreteCheck m
    cc of
           ConcreteCheck m
    CC_Check -> TyVarCheckResult m
    forall (m :: * -> *). TyVarCheckResult m
    TyVarCheck_Success
           CC_Promote ConcreteTvOrigin
    conc_orig -> Maybe TcLevel
    -> Maybe ConcreteTvOrigin
    -> TyVarCheckResult (IOEnv (Env TcGblEnv TcLclEnv))
    TyVarCheck_Promote Maybe TcLevel
    forall a. Maybe a
    Nothing (ConcreteTvOrigin -> Maybe ConcreteTvOrigin
    forall a. a -> Maybe a
    Just ConcreteTvOrigin
    conc_orig)
           -- CC_None is dealt with at the top

    -------------------------
    checkPromoteFreeVars :: CheckTyEqProblem    -- What occurs check problem to report
                         -> Name -> TcLevel
                         -> TyCoVarSet -> TcM CheckTyEqResult
    -- Check this set of TyCoVars for
    --   (a) occurs check
    --   (b) promote if necessary, or report skolem escape
    checkPromoteFreeVars :: CheckTyEqProblem
    -> Name -> TcLevel -> VarSet -> TcM CheckTyEqResult
    checkPromoteFreeVars CheckTyEqProblem
    occ_prob Name
    lhs_tv TcLevel
    lhs_tv_lvl VarSet
    vs
      = do { 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)
           ; return (mconcat 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 -> Name
    tyVarName TcTyVar
    v Name -> Name -> Bool
    forall a. Eq a => a -> a -> Bool
    == Name
    lhs_tv = 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 :: TyVar -> TcM CheckTyEqResult
        promote_one :: TcTyVar -> TcM CheckTyEqResult
    promote_one TcTyVar
    tv =
          do { _ <- MetaInfo -> TcLevel -> TcTyVar -> TcM TcType
    promote_meta_tyvar MetaInfo
    TauTv TcLevel
    lhs_tv_lvl TcTyVar
    tv
             ; return cteOK }

    promote_meta_tyvar :: MetaInfo -> TcLevel -> TcTyVar -> TcM TcType
    promote_meta_tyvar :: MetaInfo -> TcLevel -> TcTyVar -> TcM TcType
    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
             mb_filled <- TcTyVar -> IOEnv (Env TcGblEnv TcLclEnv) (Maybe TcType)
    isFilledMetaTyVar_maybe TcTyVar
    occ_tv
           ; case mb_filled of {
               Just TcType
    ty -> TcType -> TcM TcType
    forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
    forall (m :: * -> *) a. Monad m => a -> m a
    return TcType
    ty ;
               Maybe TcType
    Nothing ->

        -- OK, not done already, so clone/promote it
        do { new_tv <- MetaInfo -> TcLevel -> TcTyVar -> TcM TcTyVar
    cloneMetaTyVarWithInfo MetaInfo
    info TcLevel
    dest_lvl TcTyVar
    occ_tv
           ; liftZonkM $ writeMetaTyVar occ_tv (mkTyVarTy new_tv)
           ; traceTc "promoteTyVar" (ppr occ_tv <+> text "-->" <+> ppr new_tv)
           ; return (mkTyVarTy new_tv) } } }

    -------------------------
    touchabilityTest :: TcLevel -> TcTyVar -> 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@ <=> the variable is touchable
    touchabilityTest :: TcLevel -> TcTyVar -> Bool
    touchabilityTest TcLevel
    given_eq_lvl TcTyVar
    tv
      | MetaTv { mtv_tclvl :: TcTyVarDetails -> TcLevel
    mtv_tclvl = TcLevel
    tv_lvl } <- TcTyVar -> TcTyVarDetails
    tcTyVarDetails TcTyVar
    tv
      = 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 -> TcType -> Bool
    checkTopShape MetaInfo
    info TcType
    xi
      = case MetaInfo
    info of
          MetaInfo
    TyVarTv ->
            case TcType -> Maybe TcTyVar
    getTyVar_maybe TcType
    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

    --------------------------------------------------------------------------------
    -- Making a type concrete.

    -- | Try to turn the provided type into a concrete type, by ensuring
    -- unfilled metavariables are appropriately marked as concrete.
    --
    -- Returns a coercion whose RHS is a zonked type which is "as concrete as possible",
    -- and a collection of Wanted equality constraints that are necessary to make
    -- the type concrete.
    --
    -- For example, for an input @TYPE a[sk]@ we will return a coercion with RHS
    -- @TYPE gamma[conc]@ together with the Wanted equality constraint @a ~# gamma@.
    --
    -- INVARIANT: the RHS type of the returned coercion is equal to the input type,
    -- up to zonking and the returned Wanted equality constraints.
    --
    -- INVARIANT: if this function returns an empty list of constraints
    -- then the RHS type of the returned coercion is concrete,
    -- in the sense of Note [Concrete types].
    makeTypeConcrete :: FastString -> ConcreteTvOrigin
                     -> TcType -> TcM (TcCoercion, Cts)
    makeTypeConcrete :: FastString -> ConcreteTvOrigin -> TcType -> TcM (Coercion, Bag Ct)
    makeTypeConcrete FastString
    occ_fs ConcreteTvOrigin
    conc_orig TcType
    ty =
      do { String -> SDoc -> TcM ()
    traceTc String
    "makeTypeConcrete {" (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:" SDoc -> SDoc -> SDoc
    forall doc. IsLine doc => doc -> doc -> doc
    <+> TcType -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr TcType
    ty ]

         -- To make a type 'ty' concrete, we query what would happen were we
         -- to try unifying
         --
         --   alpha[conc] ~# ty
         --
         -- for a fresh concrete metavariable 'alpha'.
         --
         -- We do this by calling 'checkTyEqRhs' with suitable 'TyEqFlags'.
         -- NB: we don't actually need to create a fresh concrete metavariable
         -- in order to call 'checkTyEqRhs'.
         ; let ty_eq_flags :: TyEqFlags (IOEnv (Env TcGblEnv TcLclEnv)) ()
    ty_eq_flags =
                TEFTyVar
                  { tefTyVar_occursCheck :: OccursCheck
    tefTyVar_occursCheck   = OccursCheck
    OC_None
                      -- LHS is a fresh meta-tyvar: no occurs check needed
                  , tefTyVar_levelCheck :: LevelCheck (IOEnv (Env TcGblEnv TcLclEnv))
    tefTyVar_levelCheck    = LevelCheck (IOEnv (Env TcGblEnv TcLclEnv))
    forall (m :: * -> *). LevelCheck m
    LC_None
                  , tefTyVar_concreteCheck :: ConcreteCheck (IOEnv (Env TcGblEnv TcLclEnv))
    tefTyVar_concreteCheck = ConcreteTvOrigin -> ConcreteCheck (IOEnv (Env TcGblEnv TcLclEnv))
    CC_Promote ConcreteTvOrigin
    conc_orig
                  , tef_fam_app :: TyEqFamApp (IOEnv (Env TcGblEnv TcLclEnv)) ()
    tef_fam_app            = TyEqFamApp (IOEnv (Env TcGblEnv TcLclEnv)) ()
    forall (m :: * -> *) a. TyEqFamApp m a
    TEFA_Recurse
                  }

         -- NB: 'checkTyEqRhs' expects a fully zonked type as input.
         ; ty' <- ZonkM TcType -> TcM TcType
    forall a. ZonkM a -> TcM a
    liftZonkM (ZonkM TcType -> TcM TcType) -> ZonkM TcType -> TcM TcType
    forall a b. (a -> b) -> a -> b
    $ TcType -> ZonkM TcType
    zonkTcType TcType
    ty
         ; pu_res <- checkTyEqRhs @TcM @() ty_eq_flags ty'
         -- NB: 'checkTyEqRhs' will also check the kind, thus upholding the
         -- invariant that the kind of a concrete type must also be a concrete type.

         ; (cts, final_co) <-
             case pu_res of
               PuOK Bag ()
    _ Reduction
    redn ->
                do { String -> SDoc -> TcM ()
    traceTc String
    "makeTypeConcrete: unifier success" (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:" SDoc -> SDoc -> SDoc
    forall doc. IsLine doc => doc -> doc -> doc
    <+> TcType -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr TcType
    ty SDoc -> SDoc -> SDoc
    forall doc. IsLine doc => doc -> doc -> doc
    <+> SDoc
    dcolon SDoc -> SDoc -> SDoc
    forall doc. IsLine doc => doc -> doc -> doc
    <+> TcType -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr (HasDebugCallStack => TcType -> TcType
    TcType -> TcType
    typeKind TcType
    ty)
                            , String -> SDoc
    forall doc. IsLine doc => String -> doc
    text String
    "redn:" SDoc -> SDoc -> SDoc
    forall doc. IsLine doc => doc -> doc -> doc
    <+> Reduction -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr Reduction
    redn
                            ]
                   ; (Bag Ct, Coercion)
    -> IOEnv (Env TcGblEnv TcLclEnv) (Bag Ct, Coercion)
    forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
    forall (m :: * -> *) a. Monad m => a -> m a
    return (Bag Ct
    forall a. Bag a
    emptyBag, Coercion -> Coercion
    mkSymCo (Coercion -> Coercion) -> Coercion -> Coercion
    forall a b. (a -> b) -> a -> b
    $ Reduction -> Coercion
    reductionCoercion Reduction
    redn)
                      -- NB: the unifier returns a 'Reduction' with the concrete
                      -- type on the left, but we want a coercion with it on the
                      -- right; so we use 'mkSymCo'.
                   }
               PuFail CheckTyEqResult
    _prob ->
                 do { String -> SDoc -> TcM ()
    traceTc String
    "makeTypeConcrete: unifier failure" (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:" SDoc -> SDoc -> SDoc
    forall doc. IsLine doc => doc -> doc -> doc
    <+> TcType -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr TcType
    ty SDoc -> SDoc -> SDoc
    forall doc. IsLine doc => doc -> doc -> doc
    <+> SDoc
    dcolon SDoc -> SDoc -> SDoc
    forall doc. IsLine doc => doc -> doc -> doc
    <+> TcType -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr (HasDebugCallStack => TcType -> TcType
    TcType -> TcType
    typeKind TcType
    ty)
                            , String -> SDoc
    forall doc. IsLine doc => String -> doc
    text String
    "problem:" SDoc -> SDoc -> SDoc
    forall doc. IsLine doc => doc -> doc -> doc
    <+> CheckTyEqResult -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr CheckTyEqResult
    _prob
                            ]
                      -- We failed to make 'ty' concrete. In order to continue
                      -- typechecking, we proceed as follows:
                      --
                      --   - create a new concrete metavariable alpha[conc]
                      --   - emit the equality @ty ~# alpha[conc]@.
                      --
                      -- This equality will eventually get reported as insoluble
                      -- to the user.

                    -- The kind of a concrete metavariable must itself be concrete,
                    -- so we need to do a concreteness check on the kind first.
                    ; let ki :: TcType
    ki = HasDebugCallStack => TcType -> TcType
    TcType -> TcType
    typeKind TcType
    ty
                    ; (kind_co, kind_cts) <-
                        if TcType -> Bool
    isConcreteType TcType
    ki
                        then (Coercion, Bag Ct) -> TcM (Coercion, Bag Ct)
    forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
    forall (m :: * -> *) a. Monad m => a -> m a
    return (TcType -> Coercion
    mkNomReflCo TcType
    ki, Bag Ct
    forall a. Bag a
    emptyBag)
                        else FastString -> ConcreteTvOrigin -> TcType -> TcM (Coercion, Bag Ct)
    makeTypeConcrete FastString
    occ_fs ConcreteTvOrigin
    conc_orig TcType
    ki

                    -- Now create the new concrete metavariable.
                    ; conc_tv <- newConcreteTyVar conc_orig occ_fs (coercionRKind kind_co)
                    ; let conc_ty = TcTyVar -> TcType
    mkTyVarTy TcTyVar
    conc_tv
                          pty = Role -> TcType -> TcType -> TcType
    mkEqPredRole Role
    Nominal TcType
    ty' TcType
    conc_ty
                    ; hole <- newCoercionHole pty
                    ; loc <- getCtLocM orig (Just KindLevel)
                    ; let ct = CtEvidence -> Ct
    mkNonCanonical (CtEvidence -> Ct) -> CtEvidence -> Ct
    forall a b. (a -> b) -> a -> b
    $ WantedCtEvidence -> CtEvidence
    CtWanted
                             (WantedCtEvidence -> CtEvidence) -> WantedCtEvidence -> CtEvidence
    forall a b. (a -> b) -> a -> b
    $ WantedCt { ctev_pred :: TcType
    ctev_pred      = TcType
    pty
                                        , ctev_dest :: TcEvDest
    ctev_dest      = CoercionHole -> TcEvDest
    HoleDest CoercionHole
    hole
                                        , ctev_loc :: CtLoc
    ctev_loc       = CtLoc
    loc
                                        , ctev_rewriters :: RewriterSet
    ctev_rewriters = RewriterSet
    emptyRewriterSet }
                    ; return (kind_cts S.<> unitBag ct, HoleCo hole)
                    }

         ; traceTc "makeTypeConcrete }" $
            vcat [ text "ty :" <+> _ppr_ty ty
                 , text "ty':" <+> _ppr_ty ty'
                 , text "final_co:" <+> _ppr_co final_co ]

         ; return (final_co, cts)
         }
      where

        _ppr_ty :: TcType -> SDoc
    _ppr_ty TcType
    ty = TcType -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr TcType
    ty SDoc -> SDoc -> SDoc
    forall doc. IsLine doc => doc -> doc -> doc
    <+> SDoc
    dcolon SDoc -> SDoc -> SDoc
    forall doc. IsLine doc => doc -> doc -> doc
    <+> TcType -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr (HasDebugCallStack => TcType -> TcType
    TcType -> TcType
    typeKind TcType
    ty)
        _ppr_co :: Coercion -> SDoc
    _ppr_co Coercion
    co = Coercion -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr Coercion
    co SDoc -> SDoc -> SDoc
    forall doc. IsLine doc => doc -> doc -> doc
    <+> SDoc
    dcolon SDoc -> SDoc -> SDoc
    forall doc. IsLine doc => doc -> doc -> doc
    <+> SDoc -> SDoc
    forall doc. IsLine doc => doc -> doc
    parens (TcType -> SDoc
    _ppr_ty (HasDebugCallStack => Coercion -> TcType
    Coercion -> TcType
    coercionLKind Coercion
    co)) 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
    <+> SDoc -> SDoc
    forall doc. IsLine doc => doc -> doc
    parens (TcType -> SDoc
    _ppr_ty (HasDebugCallStack => Coercion -> TcType
    Coercion -> TcType
    coercionRKind Coercion
    co))

        orig :: CtOrigin
        orig :: CtOrigin
    orig = case ConcreteTvOrigin
    conc_orig of
          ConcreteFRR FixedRuntimeRepOrigin
    frr_orig -> FixedRuntimeRepOrigin -> CtOrigin
    FRROrigin FixedRuntimeRepOrigin
    frr_orig

    {- *********************************************************************
    *                                                                      *
                     mightEqualLater
    *                                                                      *
    ********************************************************************* -}

    {- Note [What might equal later?]
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    We must determine whether a Given might later equal a Wanted:
      see Note [Instance and Given overlap] in GHC.Tc.Solver.Dict

    We definitely need to account for the possibility that any metavariable might be
    arbitrarily instantiated. Yet we do *not* want to allow skolems to be
    instantiated, as we've already rewritten with respect to any Givens. (We're
    solving a Wanted here, and so all Givens have already been processed.)

    This is best understood by example.

    1. C alpha[tau]  ~?  C Int

       That Given certainly might match later.

    2. C a[sk]  ~?  C Int

       No. No new givens are going to arise that will get the `a` to rewrite
       to Int.  Example:
          f :: forall a. C a => blah
          f = rhs  -- Gives rise to [W] C Int
       It would be silly to fail to solve ([W] C Int), just because we have
       ([G] C a) in the Givens!

    3. C alpha[tv]   ~?  C Int

       In this variant of (1) that alpha[tv] is a TyVarTv, unifiable only with
       other type /variables/.  It cannot equal Int later.

    4. C (F alpha[tau])   ~?   C Int

       Sure -- that can equal later, if we learn something useful about alpha.

    5. C (F alpha[tv])  ~?  C Int

       This, too, might equal later. Perhaps we have [G] F b ~ Int elsewhere.
       Or maybe we have C (F alpha[tv] beta[tv]), these unify with each other,
       and F x x = Int. Remember: returning True doesn't commit ourselves to
       anything.

    6. C (F a[sk])  ~?  C Int.  For example
          f :: forall a. C (F a) => blah
          f = rhs  -- Gives rise to [W] C Int

       No, this won't match later. If we could rewrite (F a), we would
       have by now. But see also Red Herring below.

       This arises in instance decls too.  For example in GHC.Core.Ppr we see
         instance Outputable (XTickishId pass)
               => Outputable (GenTickish pass) where
       If we have [W] Outputable Int in the body, we don't want to fail to solve
       it because (XTickishId pass) might simplify to Int.

    7. C (Maybe alpha[tau])  ~?  C alpha[tau]

       We say this cannot equal later, because it would require
       alpha := Maybe (Maybe (Maybe ...)). While such a type can be contrived,
       we choose not to worry about it. See Note [Infinitary substitution in lookup]
       in GHC.Core.InstEnv. Getting this wrong led to #19107, tested in
       typecheck/should_compile/T19107.

    8. C alpha[cbv]   ~?  C Int
       where alpha[cbv] = F a

       The alpha[cbv] is a cycle-breaker var which stands for F a. See
       Note [Type equality cycles] in GHC.Tc.Solver.Equality
       This is just like case 6, and we say "no". Saying "no" here is
       essential in getting the parser to type-check, with its use of DisambECP.

    9. C alpha[cbv]   ~?   C Int
       where alpha[cbv] = F beta[tau]

       Here, we might indeed equal later. Distinguishing between
       this case and Example 8 is why we need the InertSet in mightEqualLater.

    10. C (F alpha[tau], Int)  ~?  C (Bool, F alpha[tau])

       This cannot equal later, because F alpha would have to equal both Bool and
       Int.

    To deal with type family applications, we use the "fine-grained" Core unifier.
    See Note [Apartness and type families] in GHC.Core.Unify, controlled
    by the `bind_fam :: BindFamFun` function defined in `mightEqualLater`.

    One tricky point: a type family application that mentions only skolems (example
    6) is settled: any skolems would have been rewritten w.r.t. Givens by now. These
    type family applications match only themselves. However: a type family
    application that mentions metavariables, on the other hand, can match
    anything. So, if the original type family application contains a metavariable,
    we use BindMe to tell the unifier to allow it in the substitution. On the other
    hand, a type family application with only skolems is considered rigid. See the
    use of `mentions_meta_ty_var` in `mightEqualLater`.

    This treatment fixes #18910 and is tested in
    typecheck/should_compile/InstanceGivenOverlap{,2}

    Red Herring
    ~~~~~~~~~~~
    In #21208, we have this scenario:

      instance forall b. C b
      [G] C a[sk]
      [W] C (F a[sk])

    What should we do with that wanted? According to the logic above, the Given
    cannot match later (this is example 6), and so we use the global instance.
    But wait, you say: What if we learn later (say by a future type instance F a = a)
    that F a unifies with a? That looks like the Given might really match later!

    This mechanism described in this Note is *not* about this kind of situation, however.
    It is all asking whether a Given might match the Wanted *in this run of the solver*.
    It is *not* about whether a variable might be instantiated so that the Given matches,
    or whether a type instance introduced in a downstream module might make the Given match.
    The reason we care about what might match later is only about avoiding order-dependence.
    That is, we don't want to commit to a course of action that depends on seeing constraints
    in a certain order. But an instantiation of a variable and a later type instance
    don't introduce order dependency in this way, and so mightMatchLater is right to ignore
    these possibilities.

    Here is an example, with no type families, that is perhaps clearer:

      instance forall b. C (Maybe b)
      [G] C (Maybe Int)
      [W] C (Maybe a)

    What to do? We *might* say that the Given could match later and should thus block
    us from using the global instance. But we don't do this. Instead, we rely on class
    coherence to say that choosing the global instance is just fine, even if later we
    call a function with (a := Int). After all, in this run of the solver, [G] C (Maybe Int)
    will definitely never match [W] C (Maybe a). (Recall that we process Givens before
    Wanteds, so there is no [G] a ~ Int hanging about unseen.)

    Interestingly, in the first case (from #21208), the behavior changed between
    GHC 8.10.7 and GHC 9.2, with the latter behaving correctly and the former
    reporting overlapping instances.

    Test case: typecheck/should_compile/T21208.

    -}

    --------------------------------------------------------------------------------
    -- mightEqualLater

    mightEqualLater :: InertSet -> TcPredType -> CtLoc -> TcPredType -> CtLoc -> Maybe Subst
    -- See Note [What might equal later?]
    -- Used to implement logic in Note [Instance and Given overlap] in GHC.Tc.Solver.Dict
    mightEqualLater :: InertSet -> TcType -> CtLoc -> TcType -> CtLoc -> Maybe Subst
    mightEqualLater InertSet
    inert_set TcType
    given_pred CtLoc
    given_loc TcType
    wanted_pred CtLoc
    wanted_loc
      | CtLoc -> CtLoc -> Bool
    prohibitedSuperClassSolve CtLoc
    given_loc CtLoc
    wanted_loc
      = Maybe Subst
    forall a. Maybe a
    Nothing

      | Bool
    otherwise
      = case BindFamFun -> BindTvFun -> [TcType] -> [TcType] -> UnifyResult
    tcUnifyTysFG BindFamFun
    bind_fam BindTvFun
    bind_tv [TcType
    given_pred] [TcType
    wanted_pred] of
          Unifiable Subst
    subst
            -> Subst -> Maybe Subst
    forall a. a -> Maybe a
    Just Subst
    subst
          MaybeApart MaybeApartReason
    reason Subst
    subst
            | MaybeApartReason
    MARInfinite <- MaybeApartReason
    reason -- see Example 7 in the Note.
            -> Maybe Subst
    forall a. Maybe a
    Nothing
            | Bool
    otherwise
            -> Subst -> Maybe Subst
    forall a. a -> Maybe a
    Just Subst
    subst
          UnifyResult
    SurelyApart -> Maybe Subst
    forall a. Maybe a
    Nothing

      where
        bind_tv :: BindTvFun
        bind_tv :: BindTvFun
    bind_tv TcTyVar
    tv TcType
    rhs_ty
          | MetaTv { mtv_info :: TcTyVarDetails -> MetaInfo
    mtv_info = MetaInfo
    info } <- TcTyVar -> TcTyVarDetails
    tcTyVarDetails TcTyVar
    tv
          , TcTyVar -> MetaInfo -> TcType -> Bool
    ok_shape TcTyVar
    tv MetaInfo
    info TcType
    rhs_ty
          , TcTyVar -> TcType -> Bool
    can_unify TcTyVar
    tv TcType
    rhs_ty
          = BindFlag
    BindMe

          | Bool
    otherwise
          = BindFlag
    DontBindMe

        bind_fam :: BindFamFun
        -- See Examples (4), (5), and (6) from the Note, especially (6)
        bind_fam :: BindFamFun
    bind_fam TyCon
    _fam_tc [TcType]
    fam_args TcType
    _rhs
          | (TcTyVar -> Bool) -> [TcType] -> Bool
    anyFreeVarsOfTypes TcTyVar -> Bool
    mentions_meta_ty_var [TcType]
    fam_args = BindFlag
    BindMe
          | Bool
    otherwise                                        = BindFlag
    DontBindMe

        can_unify :: TcTyVar -> TcType -> Bool
        can_unify :: TcTyVar -> TcType -> Bool
    can_unify TcTyVar
    tv TcType
    rhs_ty
          -- See Note [Use checkTyEqRhs in mightEqualLater]
          | PuOK {} <- Identity (PuResult () Reduction) -> PuResult () Reduction
    forall a. Identity a -> a
    runIdentity (Identity (PuResult () Reduction) -> PuResult () Reduction)
    -> Identity (PuResult () Reduction) -> PuResult () Reduction
    forall a b. (a -> b) -> a -> b
    $ TyEqFlags Identity () -> TcType -> Identity (PuResult () Reduction)
    forall (m :: * -> *) a.
    Monad m =>
    TyEqFlags m a -> TcType -> m (PuResult a Reduction)
    checkTyEqRhs (TcTyVar -> TyEqFlags Identity ()
    pureTyEqFlags_LHSMetaTyVar TcTyVar
    tv) TcType
    rhs_ty
          = Bool
    True
          | Bool
    otherwise
          = Bool
    False

        -- True for TauTv and TyVarTv (and RuntimeUnkTv) meta-tyvars
        -- (as they can be unified)
        -- and also for CycleBreakerTvs that mentions meta-tyvars
        mentions_meta_ty_var :: TyVar -> Bool
        mentions_meta_ty_var :: TcTyVar -> Bool
    mentions_meta_ty_var TcTyVar
    tv
          | TcTyVar -> Bool
    isMetaTyVar TcTyVar
    tv
          = case TcTyVar -> MetaInfo
    metaTyVarInfo TcTyVar
    tv of
              -- See Examples 8 and 9 in the Note
              MetaInfo
    CycleBreakerTv -> (TcTyVar -> Bool) -> TcType -> Bool
    anyFreeVarsOfType TcTyVar -> Bool
    mentions_meta_ty_var
                                  (TcTyVar -> InertSet -> TcType
    lookupCycleBreakerVar TcTyVar
    tv InertSet
    inert_set)
              MetaInfo
    _ -> Bool
    True
          | Bool
    otherwise
          = Bool
    False

        -- Like checkTopShape, but allows cbv variables to unify
        ok_shape :: TcTyVar -> MetaInfo -> Type -> Bool
        ok_shape :: TcTyVar -> MetaInfo -> TcType -> Bool
    ok_shape TcTyVar
    _lhs_tv MetaInfo
    TyVarTv TcType
    rhs_ty  -- see Example 3 from the Note
          | Just TcTyVar
    rhs_tv <- TcType -> Maybe TcTyVar
    getTyVar_maybe TcType
    rhs_ty
          = case TcTyVar -> TcTyVarDetails
    tcTyVarDetails TcTyVar
    rhs_tv of
              MetaTv { mtv_info :: TcTyVarDetails -> MetaInfo
    mtv_info = MetaInfo
    TyVarTv } -> Bool
    True
              MetaTv {}                     -> Bool
    False  -- Could unify with anything
              SkolemTv {}                   -> Bool
    True
              TcTyVarDetails
    RuntimeUnk                    -> Bool
    True
          | Bool
    otherwise  -- not a var on the RHS
          = Bool
    False
        ok_shape TcTyVar
    lhs_tv MetaInfo
    _other TcType
    _rhs_ty = TcTyVar -> Bool
    mentions_meta_ty_var TcTyVar
    lhs_tv

    {- Note [Use checkTyEqRhs in mightEqualLater]
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    In 'mightEqualLater', we are checking whether two types ty1 and ty2 might become
    equal after further unifications. To do this, we call the pure unifier, via
    the function 'tcUnifyTysFG'. However, it is important that we don't return
    false positives:

      1. Level check:  ty1 = alpha[tau:1] /~ ty2 = k[sk:3]
      2. Occurs check: ty1 = beta[tau]    /~ ty2 = Maybe beta[tau]
      3. Concreteness: ty1 = kappa[conc]  /~ ty2 = k[sk].

    In these examples, ty1 and ty2 cannot unify; to inform the pure unifier of this
    fact, we use 'checkTyEqRhs' to provide the 'BindTvFun'.

    Failing to account for this caused #25744:

      work item = [W] w1: Eq (g[sk:1] x[sk:3])
      inerts = { [G] g1: Eq x[sk:3]
               , [G] g2: forall y. Eq y => Eq (g[sk:1] y)
               , [G] g3: Eq (f[tau:1] v[tau:1]) }

    We want to solve w1 using g1 and g2. The presence of g3 is irrelevant, because
    we cannot unify 'f[tau:1] v[tau:1]' and 'g[sk:1] x[sk:3]' due to skolem escape.
    -}

    -- | Return the type family application a CycleBreakerTv maps to.
    lookupCycleBreakerVar :: TcTyVar    -- ^ cbv, must be a CycleBreakerTv
                          -> InertSet
                          -> TcType     -- ^ type family application the cbv maps to
    lookupCycleBreakerVar :: TcTyVar -> InertSet -> TcType
    lookupCycleBreakerVar TcTyVar
    cbv (IS { inert_cycle_breakers :: InertSet -> CycleBreakerVarStack
    inert_cycle_breakers = CycleBreakerVarStack
    cbvs_stack })
    -- This function looks at every environment in the stack. This is necessary
    -- to avoid #20231. This function (and its one usage site) is the only reason
    -- that we store a stack instead of just the top environment.
      | Just TcType
    tyfam_app <- Bool -> Maybe TcType -> Maybe TcType
    forall a. HasCallStack => Bool -> a -> a
    assert (TcTyVar -> Bool
    isCycleBreakerTyVar TcTyVar
    cbv) (Maybe TcType -> Maybe TcType) -> Maybe TcType -> Maybe TcType
    forall a b. (a -> b) -> a -> b
    $
                          NonEmpty (Maybe TcType) -> Maybe TcType
    forall (f :: * -> *) a. Foldable f => f (Maybe a) -> Maybe a
    firstJusts ((Bag (TcTyVar, TcType) -> Maybe TcType)
    -> CycleBreakerVarStack -> NonEmpty (Maybe TcType)
    forall a b. (a -> b) -> NonEmpty a -> NonEmpty b
    NE.map (TcTyVar -> Bag (TcTyVar, TcType) -> Maybe TcType
    forall a b. Eq a => a -> Bag (a, b) -> Maybe b
    lookupBag TcTyVar
    cbv) CycleBreakerVarStack
    cbvs_stack)
      = TcType
    tyfam_app
      | Bool
    otherwise
      = String -> SDoc -> TcType
    forall a. HasCallStack => String -> SDoc -> a
    pprPanic String
    "lookupCycleBreakerVar found an unbound cycle breaker" (TcTyVar -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr TcTyVar
    cbv SDoc -> SDoc -> SDoc
    forall doc. IsDoc doc => doc -> doc -> doc
    $$ CycleBreakerVarStack -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr CycleBreakerVarStack
    cbvs_stack)

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