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

    -}

    {-# LANGUAGE CPP #-}
    {-# LANGUAGE MultiWayIf #-}

    -- | Functions for inferring (and simplifying) the context for derived instances.
    module GHC.Tc.Deriv.Infer
       ( inferConstraints
       , simplifyInstanceContexts
       )
    where

    #include "HsVersions.h"

    import GHC.Prelude

    import GHC.Data.Bag
    import GHC.Types.Basic
    import GHC.Core.Class
    import GHC.Core.DataCon
    import GHC.Utils.Error
    import GHC.Tc.Utils.Instantiate
    import GHC.Utils.Outputable
    import GHC.Utils.Panic
    import GHC.Data.Pair
    import GHC.Builtin.Names
    import GHC.Tc.Deriv.Utils
    import GHC.Tc.Utils.Env
    import GHC.Tc.Deriv.Generate
    import GHC.Tc.Deriv.Functor
    import GHC.Tc.Deriv.Generics
    import GHC.Tc.Utils.TcMType
    import GHC.Tc.Utils.Monad
    import GHC.Tc.Types.Origin
    import GHC.Tc.Types.Constraint
    import GHC.Core.Predicate
    import GHC.Tc.Utils.TcType
    import GHC.Core.TyCon
    import GHC.Core.TyCo.Ppr (pprTyVars)
    import GHC.Core.Type
    import GHC.Tc.Solver
    import GHC.Tc.Validity (validDerivPred)
    import GHC.Tc.Utils.Unify (buildImplicationFor, checkConstraints)
    import GHC.Builtin.Types (typeToTypeKind)
    import GHC.Core.Unify (tcUnifyTy)
    import GHC.Utils.Misc
    import GHC.Types.Var
    import GHC.Types.Var.Set

    import Control.Monad
    import Control.Monad.Trans.Class  (lift)
    import Control.Monad.Trans.Reader (ask)
    import Data.List                  (sortBy)
    import Data.Maybe

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

    inferConstraints :: DerivSpecMechanism
                     -> DerivM ([ThetaOrigin], [TyVar], [TcType])
    -- inferConstraints figures out the constraints needed for the
    -- instance declaration generated by a 'deriving' clause on a
    -- data type declaration. It also returns the new in-scope type
    -- variables and instance types, in case they were changed due to
    -- the presence of functor-like constraints.
    -- See Note [Inferring the instance context]

    -- e.g. inferConstraints
    --        C Int (T [a])    -- Class and inst_tys
    --        :RTList a        -- Rep tycon and its arg tys
    -- where T [a] ~R :RTList a
    --
    -- Generate a sufficiently large set of constraints that typechecking the
    -- generated method definitions should succeed.   This set will be simplified
    -- before being used in the instance declaration
    inferConstraints :: DerivSpecMechanism -> DerivM ([ThetaOrigin], [TcTyVar], ThetaType)
    inferConstraints DerivSpecMechanism
    mechanism
      = do { DerivEnv { denv_tvs :: DerivEnv -> [TcTyVar]
    denv_tvs      = [TcTyVar]
    tvs
                      , denv_cls :: DerivEnv -> Class
    denv_cls      = Class
    main_cls
                      , denv_inst_tys :: DerivEnv -> ThetaType
    denv_inst_tys = ThetaType
    inst_tys } <- ReaderT DerivEnv (IOEnv (Env TcGblEnv TcLclEnv)) DerivEnv
    forall (m :: * -> *) r. Monad m => ReaderT r m r
    ask
           ; Bool
    wildcard <- DerivM Bool
    isStandaloneWildcardDeriv
           ; let infer_constraints :: DerivM ([ThetaOrigin], [TyVar], [TcType])
                 infer_constraints :: DerivM ([ThetaOrigin], [TcTyVar], ThetaType)
    infer_constraints =
                   case DerivSpecMechanism
    mechanism of
                     DerivSpecStock{dsm_stock_dit :: DerivSpecMechanism -> DerivInstTys
    dsm_stock_dit = DerivInstTys
    dit}
                       -> DerivInstTys -> DerivM ([ThetaOrigin], [TcTyVar], ThetaType)
    inferConstraintsStock DerivInstTys
    dit
                     DerivSpecMechanism
    DerivSpecAnyClass
                       -> DerivM [ThetaOrigin]
    -> DerivM ([ThetaOrigin], [TcTyVar], ThetaType)
    infer_constraints_simple DerivM [ThetaOrigin]
    inferConstraintsAnyclass
                     DerivSpecNewtype { dsm_newtype_dit :: DerivSpecMechanism -> DerivInstTys
    dsm_newtype_dit =
                                          DerivInstTys{dit_cls_tys :: DerivInstTys -> ThetaType
    dit_cls_tys = ThetaType
    cls_tys}
                                      , dsm_newtype_rep_ty :: DerivSpecMechanism -> PredType
    dsm_newtype_rep_ty = PredType
    rep_ty }
                       -> DerivM [ThetaOrigin]
    -> DerivM ([ThetaOrigin], [TcTyVar], ThetaType)
    infer_constraints_simple (DerivM [ThetaOrigin]
     -> DerivM ([ThetaOrigin], [TcTyVar], ThetaType))
    -> DerivM [ThetaOrigin]
    -> DerivM ([ThetaOrigin], [TcTyVar], ThetaType)
    forall a b. (a -> b) -> a -> b
    $
                          ThetaType -> PredType -> DerivM [ThetaOrigin]
    inferConstraintsCoerceBased ThetaType
    cls_tys PredType
    rep_ty
                     DerivSpecVia { dsm_via_cls_tys :: DerivSpecMechanism -> ThetaType
    dsm_via_cls_tys = ThetaType
    cls_tys
                                  , dsm_via_ty :: DerivSpecMechanism -> PredType
    dsm_via_ty = PredType
    via_ty }
                       -> DerivM [ThetaOrigin]
    -> DerivM ([ThetaOrigin], [TcTyVar], ThetaType)
    infer_constraints_simple (DerivM [ThetaOrigin]
     -> DerivM ([ThetaOrigin], [TcTyVar], ThetaType))
    -> DerivM [ThetaOrigin]
    -> DerivM ([ThetaOrigin], [TcTyVar], ThetaType)
    forall a b. (a -> b) -> a -> b
    $
                          ThetaType -> PredType -> DerivM [ThetaOrigin]
    inferConstraintsCoerceBased ThetaType
    cls_tys PredType
    via_ty

                 -- Most deriving strategies do not need to do anything special to
                 -- the type variables and arguments to the class in the derived
                 -- instance, so they can pass through unchanged. The exception to
                 -- this rule is stock deriving. See
                 -- Note [Inferring the instance context].
                 infer_constraints_simple
                   :: DerivM [ThetaOrigin]
                   -> DerivM ([ThetaOrigin], [TyVar], [TcType])
                 infer_constraints_simple :: DerivM [ThetaOrigin]
    -> DerivM ([ThetaOrigin], [TcTyVar], ThetaType)
    infer_constraints_simple DerivM [ThetaOrigin]
    infer_thetas = do
                   [ThetaOrigin]
    thetas <- DerivM [ThetaOrigin]
    infer_thetas
                   ([ThetaOrigin], [TcTyVar], ThetaType)
    -> DerivM ([ThetaOrigin], [TcTyVar], ThetaType)
    forall (f :: * -> *) a. Applicative f => a -> f a
    pure ([ThetaOrigin]
    thetas, [TcTyVar]
    tvs, ThetaType
    inst_tys)

                 -- Constraints arising from superclasses
                 -- See Note [Superclasses of derived instance]
                 cls_tvs :: [TcTyVar]
    cls_tvs  = Class -> [TcTyVar]
    classTyVars Class
    main_cls
                 sc_constraints :: [ThetaOrigin]
    sc_constraints = ASSERT2( equalLength cls_tvs inst_tys
                                         , ppr main_cls <+> ppr inst_tys )
                                  [ CtOrigin
    -> TypeOrKind
    -> [TcTyVar]
    -> [TcTyVar]
    -> ThetaType
    -> ThetaType
    -> ThetaOrigin
    mkThetaOrigin (Bool -> CtOrigin
    mkDerivOrigin Bool
    wildcard)
                                                  TypeOrKind
    TypeLevel [] [] [] (ThetaType -> ThetaOrigin) -> ThetaType -> ThetaOrigin
    forall a b. (a -> b) -> a -> b
    $
                                    HasCallStack => TCvSubst -> ThetaType -> ThetaType
    TCvSubst -> ThetaType -> ThetaType
    substTheta TCvSubst
    cls_subst (Class -> ThetaType
    classSCTheta Class
    main_cls) ]
                 cls_subst :: TCvSubst
    cls_subst = ASSERT( equalLength cls_tvs inst_tys )
                             [TcTyVar] -> ThetaType -> TCvSubst
    HasDebugCallStack => [TcTyVar] -> ThetaType -> TCvSubst
    zipTvSubst [TcTyVar]
    cls_tvs ThetaType
    inst_tys

           ; ([ThetaOrigin]
    inferred_constraints, [TcTyVar]
    tvs', ThetaType
    inst_tys') <- DerivM ([ThetaOrigin], [TcTyVar], ThetaType)
    infer_constraints
           ; TcRn () -> ReaderT DerivEnv (IOEnv (Env TcGblEnv TcLclEnv)) ()
    forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
    (MonadTrans t, Monad m) =>
    m a -> t m a
    lift (TcRn () -> ReaderT DerivEnv (IOEnv (Env TcGblEnv TcLclEnv)) ())
    -> TcRn () -> ReaderT DerivEnv (IOEnv (Env TcGblEnv TcLclEnv)) ()
    forall a b. (a -> b) -> a -> b
    $ String -> SDoc -> TcRn ()
    traceTc String
    "inferConstraints" (SDoc -> TcRn ()) -> SDoc -> TcRn ()
    forall a b. (a -> b) -> a -> b
    $ [SDoc] -> SDoc
    vcat
                  [ Class -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr Class
    main_cls SDoc -> SDoc -> SDoc
    <+> ThetaType -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr ThetaType
    inst_tys'
                  , [ThetaOrigin] -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr [ThetaOrigin]
    inferred_constraints
                  ]
           ; ([ThetaOrigin], [TcTyVar], ThetaType)
    -> DerivM ([ThetaOrigin], [TcTyVar], ThetaType)
    forall (m :: * -> *) a. Monad m => a -> m a
    return ( [ThetaOrigin]
    sc_constraints [ThetaOrigin] -> [ThetaOrigin] -> [ThetaOrigin]
    forall a. [a] -> [a] -> [a]
    ++ [ThetaOrigin]
    inferred_constraints
                    , [TcTyVar]
    tvs', ThetaType
    inst_tys' ) }

    -- | Like 'inferConstraints', but used only in the case of the @stock@ deriving
    -- strategy. The constraints are inferred by inspecting the fields of each data
    -- constructor. In this example:
    --
    -- > data Foo = MkFoo Int Char deriving Show
    --
    -- We would infer the following constraints ('ThetaOrigin's):
    --
    -- > (Show Int, Show Char)
    --
    -- Note that this function also returns the type variables ('TyVar's) and
    -- class arguments ('TcType's) for the resulting instance. This is because
    -- when deriving 'Functor'-like classes, we must sometimes perform kind
    -- substitutions to ensure the resulting instance is well kinded, which may
    -- affect the type variables and class arguments. In this example:
    --
    -- > newtype Compose (f :: k -> Type) (g :: Type -> k) (a :: Type) =
    -- >   Compose (f (g a)) deriving stock Functor
    --
    -- We must unify @k@ with @Type@ in order for the resulting 'Functor' instance
    -- to be well kinded, so we return @[]@/@[Type, f, g]@ for the
    -- 'TyVar's/'TcType's, /not/ @[k]@/@[k, f, g]@.
    -- See Note [Inferring the instance context].
    inferConstraintsStock :: DerivInstTys
                          -> DerivM ([ThetaOrigin], [TyVar], [TcType])
    inferConstraintsStock :: DerivInstTys -> DerivM ([ThetaOrigin], [TcTyVar], ThetaType)
    inferConstraintsStock (DerivInstTys { dit_cls_tys :: DerivInstTys -> ThetaType
    dit_cls_tys     = ThetaType
    cls_tys
                                        , dit_tc :: DerivInstTys -> TyCon
    dit_tc          = TyCon
    tc
                                        , dit_tc_args :: DerivInstTys -> ThetaType
    dit_tc_args     = ThetaType
    tc_args
                                        , dit_rep_tc :: DerivInstTys -> TyCon
    dit_rep_tc      = TyCon
    rep_tc
                                        , dit_rep_tc_args :: DerivInstTys -> ThetaType
    dit_rep_tc_args = ThetaType
    rep_tc_args })
      = do DerivEnv { denv_tvs :: DerivEnv -> [TcTyVar]
    denv_tvs      = [TcTyVar]
    tvs
                    , denv_cls :: DerivEnv -> Class
    denv_cls      = Class
    main_cls
                    , denv_inst_tys :: DerivEnv -> ThetaType
    denv_inst_tys = ThetaType
    inst_tys } <- ReaderT DerivEnv (IOEnv (Env TcGblEnv TcLclEnv)) DerivEnv
    forall (m :: * -> *) r. Monad m => ReaderT r m r
    ask
           Bool
    wildcard <- DerivM Bool
    isStandaloneWildcardDeriv

           let inst_ty :: PredType
    inst_ty    = TyCon -> ThetaType -> PredType
    mkTyConApp TyCon
    tc ThetaType
    tc_args
               tc_binders :: [TyConBinder]
    tc_binders = TyCon -> [TyConBinder]
    tyConBinders TyCon
    rep_tc
               choose_level :: TyConBinder -> TypeOrKind
    choose_level TyConBinder
    bndr
                 | TyConBinder -> Bool
    isNamedTyConBinder TyConBinder
    bndr = TypeOrKind
    KindLevel
                 | Bool
    otherwise               = TypeOrKind
    TypeLevel
               t_or_ks :: [TypeOrKind]
    t_or_ks = (TyConBinder -> TypeOrKind) -> [TyConBinder] -> [TypeOrKind]
    forall a b. (a -> b) -> [a] -> [b]
    map TyConBinder -> TypeOrKind
    choose_level [TyConBinder]
    tc_binders [TypeOrKind] -> [TypeOrKind] -> [TypeOrKind]
    forall a. [a] -> [a] -> [a]
    ++ TypeOrKind -> [TypeOrKind]
    forall a. a -> [a]
    repeat TypeOrKind
    TypeLevel
                  -- want to report *kind* errors when possible

                  -- Constraints arising from the arguments of each constructor
               con_arg_constraints
                 :: (CtOrigin -> TypeOrKind
                              -> Type
                              -> [([PredOrigin], Maybe TCvSubst)])
                 -> ([ThetaOrigin], [TyVar], [TcType])
               con_arg_constraints :: (CtOrigin
     -> TypeOrKind -> PredType -> [([PredOrigin], Maybe TCvSubst)])
    -> ([ThetaOrigin], [TcTyVar], ThetaType)
    con_arg_constraints CtOrigin
    -> TypeOrKind -> PredType -> [([PredOrigin], Maybe TCvSubst)]
    get_arg_constraints
                 = let ([[PredOrigin]]
    predss, [Maybe TCvSubst]
    mbSubsts) = [([PredOrigin], Maybe TCvSubst)]
    -> ([[PredOrigin]], [Maybe TCvSubst])
    forall a b. [(a, b)] -> ([a], [b])
    unzip
                         [ ([PredOrigin], Maybe TCvSubst)
    preds_and_mbSubst
                         | DataCon
    data_con <- TyCon -> [DataCon]
    tyConDataCons TyCon
    rep_tc
                         , (Int
    arg_n, TypeOrKind
    arg_t_or_k, Scaled PredType
    arg_ty)
                             <- [Int]
    -> [TypeOrKind]
    -> [Scaled PredType]
    -> [(Int, TypeOrKind, Scaled PredType)]
    forall a b c. [a] -> [b] -> [c] -> [(a, b, c)]
    zip3 [Int
    1..] [TypeOrKind]
    t_or_ks ([Scaled PredType] -> [(Int, TypeOrKind, Scaled PredType)])
    -> [Scaled PredType] -> [(Int, TypeOrKind, Scaled PredType)]
    forall a b. (a -> b) -> a -> b
    $
                                DataCon -> ThetaType -> [Scaled PredType]
    dataConInstOrigArgTys DataCon
    data_con ThetaType
    all_rep_tc_args
                           -- No constraints for unlifted types
                           -- See Note [Deriving and unboxed types]
                         , Bool -> Bool
    not (HasDebugCallStack => PredType -> Bool
    PredType -> Bool
    isUnliftedType (Scaled PredType -> PredType
    forall a. Scaled a -> a
    irrelevantMult Scaled PredType
    arg_ty))
                         , let orig :: CtOrigin
    orig = DataCon -> Int -> Bool -> CtOrigin
    DerivOriginDC DataCon
    data_con Int
    arg_n Bool
    wildcard
                         , ([PredOrigin], Maybe TCvSubst)
    preds_and_mbSubst
                             <- CtOrigin
    -> TypeOrKind -> PredType -> [([PredOrigin], Maybe TCvSubst)]
    get_arg_constraints CtOrigin
    orig TypeOrKind
    arg_t_or_k (Scaled PredType -> PredType
    forall a. Scaled a -> a
    irrelevantMult Scaled PredType
    arg_ty)
                         ]
                       preds :: [PredOrigin]
    preds = [[PredOrigin]] -> [PredOrigin]
    forall (t :: * -> *) a. Foldable t => t [a] -> [a]
    concat [[PredOrigin]]
    predss
                       -- If the constraints require a subtype to be of kind
                       -- (* -> *) (which is the case for functor-like
                       -- constraints), then we explicitly unify the subtype's
                       -- kinds with (* -> *).
                       -- See Note [Inferring the instance context]
                       subst :: TCvSubst
    subst        = (TCvSubst -> TCvSubst -> TCvSubst)
    -> TCvSubst -> [TCvSubst] -> TCvSubst
    forall (t :: * -> *) b a.
    Foldable t =>
    (b -> a -> b) -> b -> t a -> b
    foldl' TCvSubst -> TCvSubst -> TCvSubst
    composeTCvSubst
                                             TCvSubst
    emptyTCvSubst ([Maybe TCvSubst] -> [TCvSubst]
    forall a. [Maybe a] -> [a]
    catMaybes [Maybe TCvSubst]
    mbSubsts)
                       unmapped_tvs :: [TcTyVar]
    unmapped_tvs = (TcTyVar -> Bool) -> [TcTyVar] -> [TcTyVar]
    forall a. (a -> Bool) -> [a] -> [a]
    filter (\TcTyVar
    v -> TcTyVar
    v TcTyVar -> TCvSubst -> Bool
    `notElemTCvSubst` TCvSubst
    subst
                                                 Bool -> Bool -> Bool
    && Bool -> Bool
    not (TcTyVar
    v TcTyVar -> TCvSubst -> Bool
    `isInScope` TCvSubst
    subst)) [TcTyVar]
    tvs
                       (TCvSubst
    subst', [TcTyVar]
    _)  = HasCallStack => TCvSubst -> [TcTyVar] -> (TCvSubst, [TcTyVar])
    TCvSubst -> [TcTyVar] -> (TCvSubst, [TcTyVar])
    substTyVarBndrs TCvSubst
    subst [TcTyVar]
    unmapped_tvs
                       preds' :: [PredOrigin]
    preds'       = (PredOrigin -> PredOrigin) -> [PredOrigin] -> [PredOrigin]
    forall a b. (a -> b) -> [a] -> [b]
    map (HasCallStack => TCvSubst -> PredOrigin -> PredOrigin
    TCvSubst -> PredOrigin -> PredOrigin
    substPredOrigin TCvSubst
    subst') [PredOrigin]
    preds
                       inst_tys' :: ThetaType
    inst_tys'    = HasCallStack => TCvSubst -> ThetaType -> ThetaType
    TCvSubst -> ThetaType -> ThetaType
    substTys TCvSubst
    subst' ThetaType
    inst_tys
                       tvs' :: [TcTyVar]
    tvs'         = ThetaType -> [TcTyVar]
    tyCoVarsOfTypesWellScoped ThetaType
    inst_tys'
                   in ([[PredOrigin] -> ThetaOrigin
    mkThetaOriginFromPreds [PredOrigin]
    preds'], [TcTyVar]
    tvs', ThetaType
    inst_tys')

               is_generic :: Bool
    is_generic  = Class
    main_cls Class -> Unique -> Bool
    forall a. Uniquable a => a -> Unique -> Bool
    `hasKey` Unique
    genClassKey
               is_generic1 :: Bool
    is_generic1 = Class
    main_cls Class -> Unique -> Bool
    forall a. Uniquable a => a -> Unique -> Bool
    `hasKey` Unique
    gen1ClassKey
               -- is_functor_like: see Note [Inferring the instance context]
               is_functor_like :: Bool
    is_functor_like = HasDebugCallStack => PredType -> PredType
    PredType -> PredType
    tcTypeKind PredType
    inst_ty HasDebugCallStack => PredType -> PredType -> Bool
    PredType -> PredType -> Bool
    `tcEqKind` PredType
    typeToTypeKind
                              Bool -> Bool -> Bool
    || Bool
    is_generic1

               get_gen1_constraints :: Class -> CtOrigin -> TypeOrKind -> Type
                                    -> [([PredOrigin], Maybe TCvSubst)]
               get_gen1_constraints :: Class
    -> CtOrigin
    -> TypeOrKind
    -> PredType
    -> [([PredOrigin], Maybe TCvSubst)]
    get_gen1_constraints Class
    functor_cls CtOrigin
    orig TypeOrKind
    t_or_k PredType
    ty
                  = CtOrigin
    -> TypeOrKind
    -> Class
    -> ThetaType
    -> [([PredOrigin], Maybe TCvSubst)]
    mk_functor_like_constraints CtOrigin
    orig TypeOrKind
    t_or_k Class
    functor_cls (ThetaType -> [([PredOrigin], Maybe TCvSubst)])
    -> ThetaType -> [([PredOrigin], Maybe TCvSubst)]
    forall a b. (a -> b) -> a -> b
    $
                    TcTyVar -> PredType -> ThetaType
    get_gen1_constrained_tys TcTyVar
    last_tv PredType
    ty

               get_std_constrained_tys :: CtOrigin -> TypeOrKind -> Type
                                       -> [([PredOrigin], Maybe TCvSubst)]
               get_std_constrained_tys :: CtOrigin
    -> TypeOrKind -> PredType -> [([PredOrigin], Maybe TCvSubst)]
    get_std_constrained_tys CtOrigin
    orig TypeOrKind
    t_or_k PredType
    ty
                   | Bool
    is_functor_like
                   = CtOrigin
    -> TypeOrKind
    -> Class
    -> ThetaType
    -> [([PredOrigin], Maybe TCvSubst)]
    mk_functor_like_constraints CtOrigin
    orig TypeOrKind
    t_or_k Class
    main_cls (ThetaType -> [([PredOrigin], Maybe TCvSubst)])
    -> ThetaType -> [([PredOrigin], Maybe TCvSubst)]
    forall a b. (a -> b) -> a -> b
    $
                     TcTyVar -> PredType -> ThetaType
    deepSubtypesContaining TcTyVar
    last_tv PredType
    ty
                   | Bool
    otherwise
                   = [( [CtOrigin -> TypeOrKind -> Class -> PredType -> PredOrigin
    mk_cls_pred CtOrigin
    orig TypeOrKind
    t_or_k Class
    main_cls PredType
    ty]
                      , Maybe TCvSubst
    forall a. Maybe a
    Nothing )]

               mk_functor_like_constraints :: CtOrigin -> TypeOrKind
                                           -> Class -> [Type]
                                           -> [([PredOrigin], Maybe TCvSubst)]
               -- 'cls' is usually main_cls (Functor or Traversable etc), but if
               -- main_cls = Generic1, then 'cls' can be Functor; see
               -- get_gen1_constraints
               --
               -- For each type, generate two constraints,
               -- [cls ty, kind(ty) ~ (*->*)], and a kind substitution that results
               -- from unifying  kind(ty) with * -> *. If the unification is
               -- successful, it will ensure that the resulting instance is well
               -- kinded. If not, the second constraint will result in an error
               -- message which points out the kind mismatch.
               -- See Note [Inferring the instance context]
               mk_functor_like_constraints :: CtOrigin
    -> TypeOrKind
    -> Class
    -> ThetaType
    -> [([PredOrigin], Maybe TCvSubst)]
    mk_functor_like_constraints CtOrigin
    orig TypeOrKind
    t_or_k Class
    cls
                  = (PredType -> ([PredOrigin], Maybe TCvSubst))
    -> ThetaType -> [([PredOrigin], Maybe TCvSubst)]
    forall a b. (a -> b) -> [a] -> [b]
    map ((PredType -> ([PredOrigin], Maybe TCvSubst))
     -> ThetaType -> [([PredOrigin], Maybe TCvSubst)])
    -> (PredType -> ([PredOrigin], Maybe TCvSubst))
    -> ThetaType
    -> [([PredOrigin], Maybe TCvSubst)]
    forall a b. (a -> b) -> a -> b
    $ \PredType
    ty -> let ki :: PredType
    ki = HasDebugCallStack => PredType -> PredType
    PredType -> PredType
    tcTypeKind PredType
    ty in
                                 ( [ CtOrigin -> TypeOrKind -> Class -> PredType -> PredOrigin
    mk_cls_pred CtOrigin
    orig TypeOrKind
    t_or_k Class
    cls PredType
    ty
                                   , CtOrigin -> TypeOrKind -> PredType -> PredOrigin
    mkPredOrigin CtOrigin
    orig TypeOrKind
    KindLevel
                                       (PredType -> PredType -> PredType
    mkPrimEqPred PredType
    ki PredType
    typeToTypeKind) ]
                                 , PredType -> PredType -> Maybe TCvSubst
    tcUnifyTy PredType
    ki PredType
    typeToTypeKind
                                 )

               rep_tc_tvs :: [TcTyVar]
    rep_tc_tvs      = TyCon -> [TcTyVar]
    tyConTyVars TyCon
    rep_tc
               last_tv :: TcTyVar
    last_tv         = [TcTyVar] -> TcTyVar
    forall a. [a] -> a
    last [TcTyVar]
    rep_tc_tvs
               -- When we first gather up the constraints to solve, most of them
               -- contain rep_tc_tvs, i.e., the type variables from the derived
               -- datatype's type constructor. We don't want these type variables
               -- to appear in the final instance declaration, so we must
               -- substitute each type variable with its counterpart in the derived
               -- instance. rep_tc_args lists each of these counterpart types in
               -- the same order as the type variables.
               all_rep_tc_args :: ThetaType
    all_rep_tc_args = TyCon -> ThetaType -> ThetaType
    tyConInstArgTys TyCon
    rep_tc ThetaType
    rep_tc_args

                   -- Stupid constraints
               stupid_constraints :: [ThetaOrigin]
    stupid_constraints
                 = [ CtOrigin
    -> TypeOrKind
    -> [TcTyVar]
    -> [TcTyVar]
    -> ThetaType
    -> ThetaType
    -> ThetaOrigin
    mkThetaOrigin CtOrigin
    deriv_origin TypeOrKind
    TypeLevel [] [] [] (ThetaType -> ThetaOrigin) -> ThetaType -> ThetaOrigin
    forall a b. (a -> b) -> a -> b
    $
                     HasCallStack => TCvSubst -> ThetaType -> ThetaType
    TCvSubst -> ThetaType -> ThetaType
    substTheta TCvSubst
    tc_subst (TyCon -> ThetaType
    tyConStupidTheta TyCon
    rep_tc) ]
               tc_subst :: TCvSubst
    tc_subst = -- See the comment with all_rep_tc_args for an
                          -- explanation of this assertion
                          ASSERT( equalLength rep_tc_tvs all_rep_tc_args )
                          [TcTyVar] -> ThetaType -> TCvSubst
    HasDebugCallStack => [TcTyVar] -> ThetaType -> TCvSubst
    zipTvSubst [TcTyVar]
    rep_tc_tvs ThetaType
    all_rep_tc_args

               -- Extra Data constraints
               -- The Data class (only) requires that for
               --    instance (...) => Data (T t1 t2)
               -- IF   t1:*, t2:*
               -- THEN (Data t1, Data t2) are among the (...) constraints
               -- Reason: when the IF holds, we generate a method
               --             dataCast2 f = gcast2 f
               --         and we need the Data constraints to typecheck the method
               extra_constraints :: [ThetaOrigin]
    extra_constraints = [[PredOrigin] -> ThetaOrigin
    mkThetaOriginFromPreds [PredOrigin]
    constrs]
                 where
                   constrs :: [PredOrigin]
    constrs
                     | Class
    main_cls Class -> Unique -> Bool
    forall a. Uniquable a => a -> Unique -> Bool
    `hasKey` Unique
    dataClassKey
                     , (PredType -> Bool) -> ThetaType -> Bool
    forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
    all (PredType -> Bool
    isLiftedTypeKind (PredType -> Bool) -> (PredType -> PredType) -> PredType -> Bool
    forall b c a. (b -> c) -> (a -> b) -> a -> c
    . HasDebugCallStack => PredType -> PredType
    PredType -> PredType
    tcTypeKind) ThetaType
    rep_tc_args
                     = [ CtOrigin -> TypeOrKind -> Class -> PredType -> PredOrigin
    mk_cls_pred CtOrigin
    deriv_origin TypeOrKind
    t_or_k Class
    main_cls PredType
    ty
                       | (TypeOrKind
    t_or_k, PredType
    ty) <- [TypeOrKind] -> ThetaType -> [(TypeOrKind, PredType)]
    forall a b. [a] -> [b] -> [(a, b)]
    zip [TypeOrKind]
    t_or_ks ThetaType
    rep_tc_args]
                     | Bool
    otherwise
                     = []

               mk_cls_pred :: CtOrigin -> TypeOrKind -> Class -> PredType -> PredOrigin
    mk_cls_pred CtOrigin
    orig TypeOrKind
    t_or_k Class
    cls PredType
    ty
                    -- Don't forget to apply to cls_tys' too
                  = CtOrigin -> TypeOrKind -> PredType -> PredOrigin
    mkPredOrigin CtOrigin
    orig TypeOrKind
    t_or_k (Class -> ThetaType -> PredType
    mkClassPred Class
    cls (ThetaType
    cls_tys' ThetaType -> ThetaType -> ThetaType
    forall a. [a] -> [a] -> [a]
    ++ [PredType
    ty]))
               cls_tys' :: ThetaType
    cls_tys' | Bool
    is_generic1 = []
                          -- In the awkward Generic1 case, cls_tys' should be
                          -- empty, since we are applying the class Functor.

                        | Bool
    otherwise   = ThetaType
    cls_tys

               deriv_origin :: CtOrigin
    deriv_origin = Bool -> CtOrigin
    mkDerivOrigin Bool
    wildcard

           if    -- Generic constraints are easy
              |  Bool
    is_generic
               -> ([ThetaOrigin], [TcTyVar], ThetaType)
    -> DerivM ([ThetaOrigin], [TcTyVar], ThetaType)
    forall (m :: * -> *) a. Monad m => a -> m a
    return ([], [TcTyVar]
    tvs, ThetaType
    inst_tys)

                 -- Generic1 needs Functor
                 -- See Note [Getting base classes]
              |  Bool
    is_generic1
               -> ASSERT( rep_tc_tvs `lengthExceeds` 0 )
                  -- Generic1 has a single kind variable
                  ASSERT( cls_tys `lengthIs` 1 )
                  do { Class
    functorClass <- IOEnv (Env TcGblEnv TcLclEnv) Class
    -> ReaderT DerivEnv (IOEnv (Env TcGblEnv TcLclEnv)) Class
    forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
    (MonadTrans t, Monad m) =>
    m a -> t m a
    lift (IOEnv (Env TcGblEnv TcLclEnv) Class
     -> ReaderT DerivEnv (IOEnv (Env TcGblEnv TcLclEnv)) Class)
    -> IOEnv (Env TcGblEnv TcLclEnv) Class
    -> ReaderT DerivEnv (IOEnv (Env TcGblEnv TcLclEnv)) Class
    forall a b. (a -> b) -> a -> b
    $ Name -> IOEnv (Env TcGblEnv TcLclEnv) Class
    tcLookupClass Name
    functorClassName
                     ; ([ThetaOrigin], [TcTyVar], ThetaType)
    -> DerivM ([ThetaOrigin], [TcTyVar], ThetaType)
    forall (f :: * -> *) a. Applicative f => a -> f a
    pure (([ThetaOrigin], [TcTyVar], ThetaType)
     -> DerivM ([ThetaOrigin], [TcTyVar], ThetaType))
    -> ([ThetaOrigin], [TcTyVar], ThetaType)
    -> DerivM ([ThetaOrigin], [TcTyVar], ThetaType)
    forall a b. (a -> b) -> a -> b
    $ (CtOrigin
     -> TypeOrKind -> PredType -> [([PredOrigin], Maybe TCvSubst)])
    -> ([ThetaOrigin], [TcTyVar], ThetaType)
    con_arg_constraints
                            ((CtOrigin
      -> TypeOrKind -> PredType -> [([PredOrigin], Maybe TCvSubst)])
     -> ([ThetaOrigin], [TcTyVar], ThetaType))
    -> (CtOrigin
        -> TypeOrKind -> PredType -> [([PredOrigin], Maybe TCvSubst)])
    -> ([ThetaOrigin], [TcTyVar], ThetaType)
    forall a b. (a -> b) -> a -> b
    $ Class
    -> CtOrigin
    -> TypeOrKind
    -> PredType
    -> [([PredOrigin], Maybe TCvSubst)]
    get_gen1_constraints Class
    functorClass }

                 -- The others are a bit more complicated
              |  Bool
    otherwise
               -> -- See the comment with all_rep_tc_args for an explanation of
                  -- this assertion
                  ASSERT2( equalLength rep_tc_tvs all_rep_tc_args
                         , ppr main_cls <+> ppr rep_tc
                           $$ ppr rep_tc_tvs $$ ppr all_rep_tc_args )
                    do { let ([ThetaOrigin]
    arg_constraints, [TcTyVar]
    tvs', ThetaType
    inst_tys')
                               = (CtOrigin
     -> TypeOrKind -> PredType -> [([PredOrigin], Maybe TCvSubst)])
    -> ([ThetaOrigin], [TcTyVar], ThetaType)
    con_arg_constraints CtOrigin
    -> TypeOrKind -> PredType -> [([PredOrigin], Maybe TCvSubst)]
    get_std_constrained_tys
                       ; TcRn () -> ReaderT DerivEnv (IOEnv (Env TcGblEnv TcLclEnv)) ()
    forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
    (MonadTrans t, Monad m) =>
    m a -> t m a
    lift (TcRn () -> ReaderT DerivEnv (IOEnv (Env TcGblEnv TcLclEnv)) ())
    -> TcRn () -> ReaderT DerivEnv (IOEnv (Env TcGblEnv TcLclEnv)) ()
    forall a b. (a -> b) -> a -> b
    $ String -> SDoc -> TcRn ()
    traceTc String
    "inferConstraintsStock" (SDoc -> TcRn ()) -> SDoc -> TcRn ()
    forall a b. (a -> b) -> a -> b
    $ [SDoc] -> SDoc
    vcat
                              [ Class -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr Class
    main_cls SDoc -> SDoc -> SDoc
    <+> ThetaType -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr ThetaType
    inst_tys'
                              , [ThetaOrigin] -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr [ThetaOrigin]
    arg_constraints
                              ]
                       ; ([ThetaOrigin], [TcTyVar], ThetaType)
    -> DerivM ([ThetaOrigin], [TcTyVar], ThetaType)
    forall (m :: * -> *) a. Monad m => a -> m a
    return ( [ThetaOrigin]
    stupid_constraints [ThetaOrigin] -> [ThetaOrigin] -> [ThetaOrigin]
    forall a. [a] -> [a] -> [a]
    ++ [ThetaOrigin]
    extra_constraints
                                                     [ThetaOrigin] -> [ThetaOrigin] -> [ThetaOrigin]
    forall a. [a] -> [a] -> [a]
    ++ [ThetaOrigin]
    arg_constraints
                                , [TcTyVar]
    tvs', ThetaType
    inst_tys') }

    -- | Like 'inferConstraints', but used only in the case of @DeriveAnyClass@,
    -- which gathers its constraints based on the type signatures of the class's
    -- methods instead of the types of the data constructor's field.
    --
    -- See Note [Gathering and simplifying constraints for DeriveAnyClass]
    -- for an explanation of how these constraints are used to determine the
    -- derived instance context.
    inferConstraintsAnyclass :: DerivM [ThetaOrigin]
    inferConstraintsAnyclass :: DerivM [ThetaOrigin]
    inferConstraintsAnyclass
      = do { DerivEnv { denv_cls :: DerivEnv -> Class
    denv_cls      = Class
    cls
                      , denv_inst_tys :: DerivEnv -> ThetaType
    denv_inst_tys = ThetaType
    inst_tys } <- ReaderT DerivEnv (IOEnv (Env TcGblEnv TcLclEnv)) DerivEnv
    forall (m :: * -> *) r. Monad m => ReaderT r m r
    ask
           ; Bool
    wildcard <- DerivM Bool
    isStandaloneWildcardDeriv

           ; let gen_dms :: [(TcTyVar, PredType)]
    gen_dms = [ (TcTyVar
    sel_id, PredType
    dm_ty)
                           | (TcTyVar
    sel_id, Just (Name
    _, GenericDM PredType
    dm_ty)) <- Class -> [(TcTyVar, DefMethInfo)]
    classOpItems Class
    cls ]

                 cls_tvs :: [TcTyVar]
    cls_tvs = Class -> [TcTyVar]
    classTyVars Class
    cls

                 do_one_meth :: (Id, Type) -> TcM ThetaOrigin
                   -- (Id,Type) are the selector Id and the generic default method type
                   -- NB: the latter is /not/ quantified over the class variables
                   -- See Note [Gathering and simplifying constraints for DeriveAnyClass]
                 do_one_meth :: (TcTyVar, PredType) -> TcM ThetaOrigin
    do_one_meth (TcTyVar
    sel_id, PredType
    gen_dm_ty)
                   = do { let ([TcTyVar]
    sel_tvs, PredType
    _cls_pred, PredType
    meth_ty)
                                       = PredType -> ([TcTyVar], PredType, PredType)
    tcSplitMethodTy (TcTyVar -> PredType
    varType TcTyVar
    sel_id)
                              meth_ty' :: PredType
    meth_ty' = HasCallStack => [TcTyVar] -> ThetaType -> PredType -> PredType
    [TcTyVar] -> ThetaType -> PredType -> PredType
    substTyWith [TcTyVar]
    sel_tvs ThetaType
    inst_tys PredType
    meth_ty
                              ([TcTyVar]
    meth_tvs, ThetaType
    meth_theta, PredType
    meth_tau)
                                       = PredType -> ([TcTyVar], ThetaType, PredType)
    tcSplitNestedSigmaTys PredType
    meth_ty'

                              gen_dm_ty' :: PredType
    gen_dm_ty' = HasCallStack => [TcTyVar] -> ThetaType -> PredType -> PredType
    [TcTyVar] -> ThetaType -> PredType -> PredType
    substTyWith [TcTyVar]
    cls_tvs ThetaType
    inst_tys PredType
    gen_dm_ty
                              ([TcTyVar]
    dm_tvs, ThetaType
    dm_theta, PredType
    dm_tau)
                                         = PredType -> ([TcTyVar], ThetaType, PredType)
    tcSplitNestedSigmaTys PredType
    gen_dm_ty'
                              tau_eq :: PredType
    tau_eq     = PredType -> PredType -> PredType
    mkPrimEqPred PredType
    meth_tau PredType
    dm_tau
                        ; ThetaOrigin -> TcM ThetaOrigin
    forall (m :: * -> *) a. Monad m => a -> m a
    return (CtOrigin
    -> TypeOrKind
    -> [TcTyVar]
    -> [TcTyVar]
    -> ThetaType
    -> ThetaType
    -> ThetaOrigin
    mkThetaOrigin (Bool -> CtOrigin
    mkDerivOrigin Bool
    wildcard) TypeOrKind
    TypeLevel
                                    [TcTyVar]
    meth_tvs [TcTyVar]
    dm_tvs ThetaType
    meth_theta (PredType
    tau_eqPredType -> ThetaType -> ThetaType
    forall a. a -> [a] -> [a]
    :ThetaType
    dm_theta)) }

           ; TcRn [ThetaOrigin] -> DerivM [ThetaOrigin]
    forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
    (MonadTrans t, Monad m) =>
    m a -> t m a
    lift (TcRn [ThetaOrigin] -> DerivM [ThetaOrigin])
    -> TcRn [ThetaOrigin] -> DerivM [ThetaOrigin]
    forall a b. (a -> b) -> a -> b
    $ ((TcTyVar, PredType) -> TcM ThetaOrigin)
    -> [(TcTyVar, PredType)] -> TcRn [ThetaOrigin]
    forall (t :: * -> *) (m :: * -> *) a b.
    (Traversable t, Monad m) =>
    (a -> m b) -> t a -> m (t b)
    mapM (TcTyVar, PredType) -> TcM ThetaOrigin
    do_one_meth [(TcTyVar, PredType)]
    gen_dms }

    -- Like 'inferConstraints', but used only for @GeneralizedNewtypeDeriving@ and
    -- @DerivingVia@. Since both strategies generate code involving 'coerce', the
    -- inferred constraints set up the scaffolding needed to typecheck those uses
    -- of 'coerce'. In this example:
    --
    -- > newtype Age = MkAge Int deriving newtype Num
    --
    -- We would infer the following constraints ('ThetaOrigin's):
    --
    -- > (Num Int, Coercible Age Int)
    inferConstraintsCoerceBased :: [Type] -> Type
                                -> DerivM [ThetaOrigin]
    inferConstraintsCoerceBased :: ThetaType -> PredType -> DerivM [ThetaOrigin]
    inferConstraintsCoerceBased ThetaType
    cls_tys PredType
    rep_ty = do
      DerivEnv { denv_tvs :: DerivEnv -> [TcTyVar]
    denv_tvs      = [TcTyVar]
    tvs
               , denv_cls :: DerivEnv -> Class
    denv_cls      = Class
    cls
               , denv_inst_tys :: DerivEnv -> ThetaType
    denv_inst_tys = ThetaType
    inst_tys } <- ReaderT DerivEnv (IOEnv (Env TcGblEnv TcLclEnv)) DerivEnv
    forall (m :: * -> *) r. Monad m => ReaderT r m r
    ask
      Bool
    sa_wildcard <- DerivM Bool
    isStandaloneWildcardDeriv
      let -- The following functions are polymorphic over the representation
          -- type, since we might either give it the underlying type of a
          -- newtype (for GeneralizedNewtypeDeriving) or a @via@ type
          -- (for DerivingVia).
          rep_tys :: PredType -> ThetaType
    rep_tys PredType
    ty  = ThetaType
    cls_tys ThetaType -> ThetaType -> ThetaType
    forall a. [a] -> [a] -> [a]
    ++ [PredType
    ty]
          rep_pred :: PredType -> PredType
    rep_pred PredType
    ty = Class -> ThetaType -> PredType
    mkClassPred Class
    cls (PredType -> ThetaType
    rep_tys PredType
    ty)
          rep_pred_o :: PredType -> PredOrigin
    rep_pred_o PredType
    ty = CtOrigin -> TypeOrKind -> PredType -> PredOrigin
    mkPredOrigin CtOrigin
    deriv_origin TypeOrKind
    TypeLevel (PredType -> PredType
    rep_pred PredType
    ty)
                  -- rep_pred is the representation dictionary, from where
                  -- we are going to get all the methods for the final
                  -- dictionary
          deriv_origin :: CtOrigin
    deriv_origin = Bool -> CtOrigin
    mkDerivOrigin Bool
    sa_wildcard

          -- Next we collect constraints for the class methods
          -- If there are no methods, we don't need any constraints
          -- Otherwise we need (C rep_ty), for the representation methods,
          -- and constraints to coerce each individual method
          meth_preds :: Type -> [PredOrigin]
          meth_preds :: PredType -> [PredOrigin]
    meth_preds PredType
    ty
            | [TcTyVar] -> Bool
    forall (t :: * -> *) a. Foldable t => t a -> Bool
    null [TcTyVar]
    meths = [] -- No methods => no constraints
                              -- (#12814)
            | Bool
    otherwise = PredType -> PredOrigin
    rep_pred_o PredType
    ty PredOrigin -> [PredOrigin] -> [PredOrigin]
    forall a. a -> [a] -> [a]
    : PredType -> [PredOrigin]
    coercible_constraints PredType
    ty
          meths :: [TcTyVar]
    meths = Class -> [TcTyVar]
    classMethods Class
    cls
          coercible_constraints :: PredType -> [PredOrigin]
    coercible_constraints PredType
    ty
            = [ CtOrigin -> TypeOrKind -> PredType -> PredOrigin
    mkPredOrigin (TcTyVar -> PredType -> PredType -> Bool -> CtOrigin
    DerivOriginCoerce TcTyVar
    meth PredType
    t1 PredType
    t2 Bool
    sa_wildcard)
                             TypeOrKind
    TypeLevel (PredType -> PredType -> PredType
    mkReprPrimEqPred PredType
    t1 PredType
    t2)
              | TcTyVar
    meth <- [TcTyVar]
    meths
              , let (Pair PredType
    t1 PredType
    t2) = Class
    -> [TcTyVar] -> ThetaType -> PredType -> TcTyVar -> Pair PredType
    mkCoerceClassMethEqn Class
    cls [TcTyVar]
    tvs
                                           ThetaType
    inst_tys PredType
    ty TcTyVar
    meth ]

          all_thetas :: Type -> [ThetaOrigin]
          all_thetas :: PredType -> [ThetaOrigin]
    all_thetas PredType
    ty = [[PredOrigin] -> ThetaOrigin
    mkThetaOriginFromPreds ([PredOrigin] -> ThetaOrigin) -> [PredOrigin] -> ThetaOrigin
    forall a b. (a -> b) -> a -> b
    $ PredType -> [PredOrigin]
    meth_preds PredType
    ty]

      [ThetaOrigin] -> DerivM [ThetaOrigin]
    forall (f :: * -> *) a. Applicative f => a -> f a
    pure (PredType -> [ThetaOrigin]
    all_thetas PredType
    rep_ty)

    {- Note [Inferring the instance context]
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    There are two sorts of 'deriving', as represented by the two constructors
    for DerivContext:

      * InferContext mb_wildcard: This can either be:
        - The deriving clause for a data type.
            (e.g, data T a = T1 a deriving( Eq ))
          In this case, mb_wildcard = Nothing.
        - A standalone declaration with an extra-constraints wildcard
            (e.g., deriving instance _ => Eq (Foo a))
          In this case, mb_wildcard = Just loc, where loc is the location
          of the extra-constraints wildcard.

        Here we must infer an instance context,
        and generate instance declaration
          instance Eq a => Eq (T a) where ...

      * SupplyContext theta: standalone deriving
          deriving instance Eq a => Eq (T a)
        Here we only need to fill in the bindings;
        the instance context (theta) is user-supplied

    For the InferContext case, we must figure out the
    instance context (inferConstraintsStock). Suppose we are inferring
    the instance context for
        C t1 .. tn (T s1 .. sm)
    There are two cases

      * (T s1 .. sm) :: *         (the normal case)
        Then we behave like Eq and guess (C t1 .. tn t)
        for each data constructor arg of type t.  More
        details below.

      * (T s1 .. sm) :: * -> *    (the functor-like case)
        Then we behave like Functor.

    In both cases we produce a bunch of un-simplified constraints
    and them simplify them in simplifyInstanceContexts; see
    Note [Simplifying the instance context].

    In the functor-like case, we may need to unify some kind variables with * in
    order for the generated instance to be well-kinded. An example from #10524:

      newtype Compose (f :: k2 -> *) (g :: k1 -> k2) (a :: k1)
        = Compose (f (g a)) deriving Functor

    Earlier in the deriving pipeline, GHC unifies the kind of Compose f g
    (k1 -> *) with the kind of Functor's argument (* -> *), so k1 := *. But this
    alone isn't enough, since k2 wasn't unified with *:

      instance (Functor (f :: k2 -> *), Functor (g :: * -> k2)) =>
        Functor (Compose f g) where ...

    The two Functor constraints are ill-kinded. To ensure this doesn't happen, we:

      1. Collect all of a datatype's subtypes which require functor-like
         constraints.
      2. For each subtype, create a substitution by unifying the subtype's kind
         with (* -> *).
      3. Compose all the substitutions into one, then apply that substitution to
         all of the in-scope type variables and the instance types.

    Note [Getting base classes]
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Functor and Typeable are defined in package 'base', and that is not available
    when compiling 'ghc-prim'.  So we must be careful that 'deriving' for stuff in
    ghc-prim does not use Functor or Typeable implicitly via these lookups.

    Note [Deriving and unboxed types]
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    We have some special hacks to support things like
       data T = MkT Int# deriving ( Show )

    Specifically, we use GHC.Tc.Deriv.Generate.box to box the Int# into an Int
    (which we know how to show), and append a '#'. Parentheses are not required
    for unboxed values (`MkT -3#` is a valid expression).

    Note [Superclasses of derived instance]
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    In general, a derived instance decl needs the superclasses of the derived
    class too.  So if we have
            data T a = ...deriving( Ord )
    then the initial context for Ord (T a) should include Eq (T a).  Often this is
    redundant; we'll also generate an Ord constraint for each constructor argument,
    and that will probably generate enough constraints to make the Eq (T a) constraint
    be satisfied too.  But not always; consider:

     data S a = S
     instance Eq (S a)
     instance Ord (S a)

     data T a = MkT (S a) deriving( Ord )
     instance Num a => Eq (T a)

    The derived instance for (Ord (T a)) must have a (Num a) constraint!
    Similarly consider:
            data T a = MkT deriving( Data )
    Here there *is* no argument field, but we must nevertheless generate
    a context for the Data instances:
            instance Typeable a => Data (T a) where ...

    ************************************************************************
    *                                                                      *
             Finding the fixed point of deriving equations
    *                                                                      *
    ************************************************************************

    Note [Simplifying the instance context]
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Consider

            data T a b = C1 (Foo a) (Bar b)
                       | C2 Int (T b a)
                       | C3 (T a a)
                       deriving (Eq)

    We want to come up with an instance declaration of the form

            instance (Ping a, Pong b, ...) => Eq (T a b) where
                    x == y = ...

    It is pretty easy, albeit tedious, to fill in the code "...".  The
    trick is to figure out what the context for the instance decl is,
    namely Ping, Pong and friends.

    Let's call the context reqd for the T instance of class C at types
    (a,b, ...)  C (T a b).  Thus:

            Eq (T a b) = (Ping a, Pong b, ...)

    Now we can get a (recursive) equation from the data decl.  This part
    is done by inferConstraintsStock.

            Eq (T a b) = Eq (Foo a) u Eq (Bar b)    -- From C1
                       u Eq (T b a) u Eq Int        -- From C2
                       u Eq (T a a)                 -- From C3

    Foo and Bar may have explicit instances for Eq, in which case we can
    just substitute for them.  Alternatively, either or both may have
    their Eq instances given by deriving clauses, in which case they
    form part of the system of equations.

    Now all we need do is simplify and solve the equations, iterating to
    find the least fixpoint.  This is done by simplifyInstanceConstraints.
    Notice that the order of the arguments can
    switch around, as here in the recursive calls to T.

    Let's suppose Eq (Foo a) = Eq a, and Eq (Bar b) = Ping b.

    We start with:

            Eq (T a b) = {}         -- The empty set

    Next iteration:
            Eq (T a b) = Eq (Foo a) u Eq (Bar b)    -- From C1
                       u Eq (T b a) u Eq Int        -- From C2
                       u Eq (T a a)                 -- From C3

            After simplification:
                       = Eq a u Ping b u {} u {} u {}
                       = Eq a u Ping b

    Next iteration:

            Eq (T a b) = Eq (Foo a) u Eq (Bar b)    -- From C1
                       u Eq (T b a) u Eq Int        -- From C2
                       u Eq (T a a)                 -- From C3

            After simplification:
                       = Eq a u Ping b
                       u (Eq b u Ping a)
                       u (Eq a u Ping a)

                       = Eq a u Ping b u Eq b u Ping a

    The next iteration gives the same result, so this is the fixpoint.  We
    need to make a canonical form of the RHS to ensure convergence.  We do
    this by simplifying the RHS to a form in which

            - the classes constrain only tyvars
            - the list is sorted by tyvar (major key) and then class (minor key)
            - no duplicates, of course

    Note [Deterministic simplifyInstanceContexts]
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Canonicalisation uses nonDetCmpType which is nondeterministic. Sorting
    with nonDetCmpType puts the returned lists in a nondeterministic order.
    If we were to return them, we'd get class constraints in
    nondeterministic order.

    Consider:

      data ADT a b = Z a b deriving Eq

    The generated code could be either:

      instance (Eq a, Eq b) => Eq (Z a b) where

    Or:

      instance (Eq b, Eq a) => Eq (Z a b) where

    To prevent the order from being nondeterministic we only
    canonicalize when comparing and return them in the same order as
    simplifyDeriv returned them.
    See also Note [nonDetCmpType nondeterminism]
    -}

    simplifyInstanceContexts :: [DerivSpec [ThetaOrigin]]
                             -> TcM [DerivSpec ThetaType]
    -- Used only for deriving clauses or standalone deriving with an
    -- extra-constraints wildcard (InferContext)
    -- See Note [Simplifying the instance context]

    simplifyInstanceContexts :: [DerivSpec [ThetaOrigin]] -> TcM [DerivSpec ThetaType]
    simplifyInstanceContexts [] = [DerivSpec ThetaType] -> TcM [DerivSpec ThetaType]
    forall (m :: * -> *) a. Monad m => a -> m a
    return []

    simplifyInstanceContexts [DerivSpec [ThetaOrigin]]
    infer_specs
      = do  { String -> SDoc -> TcRn ()
    traceTc String
    "simplifyInstanceContexts" (SDoc -> TcRn ()) -> SDoc -> TcRn ()
    forall a b. (a -> b) -> a -> b
    $ [SDoc] -> SDoc
    vcat ((DerivSpec [ThetaOrigin] -> SDoc)
    -> [DerivSpec [ThetaOrigin]] -> [SDoc]
    forall a b. (a -> b) -> [a] -> [b]
    map DerivSpec [ThetaOrigin] -> SDoc
    forall theta. Outputable theta => DerivSpec theta -> SDoc
    pprDerivSpec [DerivSpec [ThetaOrigin]]
    infer_specs)
            ; Int -> [ThetaType] -> TcM [DerivSpec ThetaType]
    iterate_deriv Int
    1 [ThetaType]
    initial_solutions }
      where
        ------------------------------------------------------------------
            -- The initial solutions for the equations claim that each
            -- instance has an empty context; this solution is certainly
            -- in canonical form.
        initial_solutions :: [ThetaType]
        initial_solutions :: [ThetaType]
    initial_solutions = [ [] | DerivSpec [ThetaOrigin]
    _ <- [DerivSpec [ThetaOrigin]]
    infer_specs ]

        ------------------------------------------------------------------
            -- iterate_deriv calculates the next batch of solutions,
            -- compares it with the current one; finishes if they are the
            -- same, otherwise recurses with the new solutions.
            -- It fails if any iteration fails
        iterate_deriv :: Int -> [ThetaType] -> TcM [DerivSpec ThetaType]
        iterate_deriv :: Int -> [ThetaType] -> TcM [DerivSpec ThetaType]
    iterate_deriv Int
    n [ThetaType]
    current_solns
          | Int
    n Int -> Int -> Bool
    forall a. Ord a => a -> a -> Bool
    > Int
    20  -- Looks as if we are in an infinite loop
                    -- This can happen if we have -XUndecidableInstances
                    -- (See GHC.Tc.Solver.tcSimplifyDeriv.)
          = String -> SDoc -> TcM [DerivSpec ThetaType]
    forall a. HasCallStack => String -> SDoc -> a
    pprPanic String
    "solveDerivEqns: probable loop"
                     ([SDoc] -> SDoc
    vcat ((DerivSpec [ThetaOrigin] -> SDoc)
    -> [DerivSpec [ThetaOrigin]] -> [SDoc]
    forall a b. (a -> b) -> [a] -> [b]
    map DerivSpec [ThetaOrigin] -> SDoc
    forall theta. Outputable theta => DerivSpec theta -> SDoc
    pprDerivSpec [DerivSpec [ThetaOrigin]]
    infer_specs) SDoc -> SDoc -> SDoc
    $$ [ThetaType] -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr [ThetaType]
    current_solns)
          | Bool
    otherwise
          = do {      -- Extend the inst info from the explicit instance decls
                      -- with the current set of solutions, and simplify each RHS
                 [ClsInst]
    inst_specs <- (ThetaType
     -> DerivSpec [ThetaOrigin]
     -> IOEnv (Env TcGblEnv TcLclEnv) ClsInst)
    -> [ThetaType]
    -> [DerivSpec [ThetaOrigin]]
    -> IOEnv (Env TcGblEnv TcLclEnv) [ClsInst]
    forall (m :: * -> *) a b c.
    Applicative m =>
    (a -> b -> m c) -> [a] -> [b] -> m [c]
    zipWithM ThetaType
    -> DerivSpec [ThetaOrigin] -> IOEnv (Env TcGblEnv TcLclEnv) ClsInst
    forall theta.
    ThetaType
    -> DerivSpec theta -> IOEnv (Env TcGblEnv TcLclEnv) ClsInst
    newDerivClsInst [ThetaType]
    current_solns [DerivSpec [ThetaOrigin]]
    infer_specs
               ; [ThetaType]
    new_solns <- TcM [ThetaType] -> TcM [ThetaType]
    forall r. TcM r -> TcM r
    checkNoErrs (TcM [ThetaType] -> TcM [ThetaType])
    -> TcM [ThetaType] -> TcM [ThetaType]
    forall a b. (a -> b) -> a -> b
    $
                              [ClsInst] -> TcM [ThetaType] -> TcM [ThetaType]
    forall a. [ClsInst] -> TcM a -> TcM a
    extendLocalInstEnv [ClsInst]
    inst_specs (TcM [ThetaType] -> TcM [ThetaType])
    -> TcM [ThetaType] -> TcM [ThetaType]
    forall a b. (a -> b) -> a -> b
    $
                              (DerivSpec [ThetaOrigin]
     -> IOEnv (Env TcGblEnv TcLclEnv) ThetaType)
    -> [DerivSpec [ThetaOrigin]] -> TcM [ThetaType]
    forall (t :: * -> *) (m :: * -> *) a b.
    (Traversable t, Monad m) =>
    (a -> m b) -> t a -> m (t b)
    mapM DerivSpec [ThetaOrigin] -> IOEnv (Env TcGblEnv TcLclEnv) ThetaType
    gen_soln [DerivSpec [ThetaOrigin]]
    infer_specs

               ; if ([ThetaType]
    current_solns [ThetaType] -> [ThetaType] -> Bool
    `eqSolution` [ThetaType]
    new_solns) then
                    [DerivSpec ThetaType] -> TcM [DerivSpec ThetaType]
    forall (m :: * -> *) a. Monad m => a -> m a
    return [ DerivSpec [ThetaOrigin]
    spec { ds_theta :: ThetaType
    ds_theta = ThetaType
    soln }
                           | (DerivSpec [ThetaOrigin]
    spec, ThetaType
    soln) <- [DerivSpec [ThetaOrigin]]
    -> [ThetaType] -> [(DerivSpec [ThetaOrigin], ThetaType)]
    forall a b. [a] -> [b] -> [(a, b)]
    zip [DerivSpec [ThetaOrigin]]
    infer_specs [ThetaType]
    current_solns ]
                 else
                    Int -> [ThetaType] -> TcM [DerivSpec ThetaType]
    iterate_deriv (Int
    nInt -> Int -> Int
    forall a. Num a => a -> a -> a
    +Int
    1) [ThetaType]
    new_solns }

        eqSolution :: [ThetaType] -> [ThetaType] -> Bool
    eqSolution [ThetaType]
    a [ThetaType]
    b = (ThetaType -> ThetaType -> Bool)
    -> [ThetaType] -> [ThetaType] -> Bool
    forall a. (a -> a -> Bool) -> [a] -> [a] -> Bool
    eqListBy ((PredType -> PredType -> Bool) -> ThetaType -> ThetaType -> Bool
    forall a. (a -> a -> Bool) -> [a] -> [a] -> Bool
    eqListBy PredType -> PredType -> Bool
    eqType) ([ThetaType] -> [ThetaType]
    canSolution [ThetaType]
    a) ([ThetaType] -> [ThetaType]
    canSolution [ThetaType]
    b)
           -- Canonicalise for comparison
           -- See Note [Deterministic simplifyInstanceContexts]
        canSolution :: [ThetaType] -> [ThetaType]
    canSolution = (ThetaType -> ThetaType) -> [ThetaType] -> [ThetaType]
    forall a b. (a -> b) -> [a] -> [b]
    map ((PredType -> PredType -> Ordering) -> ThetaType -> ThetaType
    forall a. (a -> a -> Ordering) -> [a] -> [a]
    sortBy PredType -> PredType -> Ordering
    nonDetCmpType)
        ------------------------------------------------------------------
        gen_soln :: DerivSpec [ThetaOrigin] -> TcM ThetaType
        gen_soln :: DerivSpec [ThetaOrigin] -> IOEnv (Env TcGblEnv TcLclEnv) ThetaType
    gen_soln (DS { ds_loc :: forall theta. DerivSpec theta -> SrcSpan
    ds_loc = SrcSpan
    loc, ds_tvs :: forall theta. DerivSpec theta -> [TcTyVar]
    ds_tvs = [TcTyVar]
    tyvars
                     , ds_cls :: forall theta. DerivSpec theta -> Class
    ds_cls = Class
    clas, ds_tys :: forall theta. DerivSpec theta -> ThetaType
    ds_tys = ThetaType
    inst_tys, ds_theta :: forall theta. DerivSpec theta -> theta
    ds_theta = [ThetaOrigin]
    deriv_rhs })
          = SrcSpan
    -> IOEnv (Env TcGblEnv TcLclEnv) ThetaType
    -> IOEnv (Env TcGblEnv TcLclEnv) ThetaType
    forall a. SrcSpan -> TcRn a -> TcRn a
    setSrcSpan SrcSpan
    loc  (IOEnv (Env TcGblEnv TcLclEnv) ThetaType
     -> IOEnv (Env TcGblEnv TcLclEnv) ThetaType)
    -> IOEnv (Env TcGblEnv TcLclEnv) ThetaType
    -> IOEnv (Env TcGblEnv TcLclEnv) ThetaType
    forall a b. (a -> b) -> a -> b
    $
            SDoc
    -> IOEnv (Env TcGblEnv TcLclEnv) ThetaType
    -> IOEnv (Env TcGblEnv TcLclEnv) ThetaType
    forall a. SDoc -> TcM a -> TcM a
    addErrCtxt (PredType -> SDoc
    derivInstCtxt PredType
    the_pred) (IOEnv (Env TcGblEnv TcLclEnv) ThetaType
     -> IOEnv (Env TcGblEnv TcLclEnv) ThetaType)
    -> IOEnv (Env TcGblEnv TcLclEnv) ThetaType
    -> IOEnv (Env TcGblEnv TcLclEnv) ThetaType
    forall a b. (a -> b) -> a -> b
    $
            do { ThetaType
    theta <- PredType
    -> [TcTyVar]
    -> [ThetaOrigin]
    -> IOEnv (Env TcGblEnv TcLclEnv) ThetaType
    simplifyDeriv PredType
    the_pred [TcTyVar]
    tyvars [ThetaOrigin]
    deriv_rhs
                    -- checkValidInstance tyvars theta clas inst_tys
                    -- Not necessary; see Note [Exotic derived instance contexts]

               ; String -> SDoc -> TcRn ()
    traceTc String
    "GHC.Tc.Deriv" ([ThetaOrigin] -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr [ThetaOrigin]
    deriv_rhs SDoc -> SDoc -> SDoc
    $$ ThetaType -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr ThetaType
    theta)
                    -- Claim: the result instance declaration is guaranteed valid
                    -- Hence no need to call:
                    --   checkValidInstance tyvars theta clas inst_tys
               ; ThetaType -> IOEnv (Env TcGblEnv TcLclEnv) ThetaType
    forall (m :: * -> *) a. Monad m => a -> m a
    return ThetaType
    theta }
          where
            the_pred :: PredType
    the_pred = Class -> ThetaType -> PredType
    mkClassPred Class
    clas ThetaType
    inst_tys

    derivInstCtxt :: PredType -> SDoc
    derivInstCtxt :: PredType -> SDoc
    derivInstCtxt PredType
    pred
      = String -> SDoc
    text String
    "When deriving the instance for" SDoc -> SDoc -> SDoc
    <+> SDoc -> SDoc
    parens (PredType -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr PredType
    pred)

    {-
    ***********************************************************************************
    *                                                                                 *
    *            Simplify derived constraints
    *                                                                                 *
    ***********************************************************************************
    -}

    -- | Given @instance (wanted) => C inst_ty@, simplify 'wanted' as much
    -- as possible. Fail if not possible.
    simplifyDeriv :: PredType -- ^ @C inst_ty@, head of the instance we are
                              -- deriving.  Only used for SkolemInfo.
                  -> [TyVar]  -- ^ The tyvars bound by @inst_ty@.
                  -> [ThetaOrigin] -- ^ Given and wanted constraints
                  -> TcM ThetaType -- ^ Needed constraints (after simplification),
                                   -- i.e. @['PredType']@.
    simplifyDeriv :: PredType
    -> [TcTyVar]
    -> [ThetaOrigin]
    -> IOEnv (Env TcGblEnv TcLclEnv) ThetaType
    simplifyDeriv PredType
    pred [TcTyVar]
    tvs [ThetaOrigin]
    thetas
      = do { (TCvSubst
    skol_subst, [TcTyVar]
    tvs_skols) <- [TcTyVar] -> TcM (TCvSubst, [TcTyVar])
    tcInstSkolTyVars [TcTyVar]
    tvs -- Skolemize
                    -- The constraint solving machinery
                    -- expects *TcTyVars* not TyVars.
                    -- We use *non-overlappable* (vanilla) skolems
                    -- See Note [Overlap and deriving]

           ; let skol_set :: VarSet
    skol_set  = [TcTyVar] -> VarSet
    mkVarSet [TcTyVar]
    tvs_skols
                 skol_info :: SkolemInfo
    skol_info = PredType -> SkolemInfo
    DerivSkol PredType
    pred
                 doc :: SDoc
    doc = String -> SDoc
    text String
    "deriving" SDoc -> SDoc -> SDoc
    <+> SDoc -> SDoc
    parens (PredType -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr PredType
    pred)

                 mk_given_ev :: PredType -> TcM EvVar
                 mk_given_ev :: PredType -> TcM TcTyVar
    mk_given_ev PredType
    given =
                   let given_pred :: PredType
    given_pred = HasCallStack => TCvSubst -> PredType -> PredType
    TCvSubst -> PredType -> PredType
    substTy TCvSubst
    skol_subst PredType
    given
                   in PredType -> TcM TcTyVar
    forall gbl lcl. PredType -> TcRnIf gbl lcl TcTyVar
    newEvVar PredType
    given_pred

                 emit_wanted_constraints :: [TyVar] -> [PredOrigin] -> TcM ()
                 emit_wanted_constraints :: [TcTyVar] -> [PredOrigin] -> TcRn ()
    emit_wanted_constraints [TcTyVar]
    metas_to_be [PredOrigin]
    preds
                   = do { -- We instantiate metas_to_be with fresh meta type
                          -- variables. Currently, these can only be type variables
                          -- quantified in generic default type signatures.
                          -- See Note [Gathering and simplifying constraints for
                          -- DeriveAnyClass]
                          (TCvSubst
    meta_subst, [TcTyVar]
    _meta_tvs) <- [TcTyVar] -> TcM (TCvSubst, [TcTyVar])
    newMetaTyVars [TcTyVar]
    metas_to_be

                        -- Now make a constraint for each of the instantiated predicates
                        ; let wanted_subst :: TCvSubst
    wanted_subst = TCvSubst
    skol_subst TCvSubst -> TCvSubst -> TCvSubst
    `unionTCvSubst` TCvSubst
    meta_subst
                              mk_wanted_ct :: PredOrigin -> IOEnv (Env TcGblEnv TcLclEnv) Ct
    mk_wanted_ct (PredOrigin PredType
    wanted CtOrigin
    orig TypeOrKind
    t_or_k)
                                = do { CtEvidence
    ev <- CtOrigin -> Maybe TypeOrKind -> PredType -> TcM CtEvidence
    newWanted CtOrigin
    orig (TypeOrKind -> Maybe TypeOrKind
    forall a. a -> Maybe a
    Just TypeOrKind
    t_or_k) (PredType -> TcM CtEvidence) -> PredType -> TcM CtEvidence
    forall a b. (a -> b) -> a -> b
    $
                                             TCvSubst -> PredType -> PredType
    substTyUnchecked TCvSubst
    wanted_subst PredType
    wanted
                                     ; Ct -> IOEnv (Env TcGblEnv TcLclEnv) Ct
    forall (m :: * -> *) a. Monad m => a -> m a
    return (CtEvidence -> Ct
    mkNonCanonical CtEvidence
    ev) }
                        ; [Ct]
    cts <- (PredOrigin -> IOEnv (Env TcGblEnv TcLclEnv) Ct)
    -> [PredOrigin] -> IOEnv (Env TcGblEnv TcLclEnv) [Ct]
    forall (t :: * -> *) (m :: * -> *) a b.
    (Traversable t, Monad m) =>
    (a -> m b) -> t a -> m (t b)
    mapM PredOrigin -> IOEnv (Env TcGblEnv TcLclEnv) Ct
    mk_wanted_ct [PredOrigin]
    preds

                        -- And emit them into the monad
                        ; Cts -> TcRn ()
    emitSimples ([Ct] -> Cts
    listToCts [Ct]
    cts) }

                 -- Create the implications we need to solve. For stock and newtype
                 -- deriving, these implication constraints will be simple class
                 -- constraints like (C a, Ord b).
                 -- But with DeriveAnyClass, we make an implication constraint.
                 -- See Note [Gathering and simplifying constraints for DeriveAnyClass]
                 mk_wanteds :: ThetaOrigin -> TcM WantedConstraints
                 mk_wanteds :: ThetaOrigin -> TcM WantedConstraints
    mk_wanteds (ThetaOrigin { to_anyclass_skols :: ThetaOrigin -> [TcTyVar]
    to_anyclass_skols  = [TcTyVar]
    ac_skols
                                         , to_anyclass_metas :: ThetaOrigin -> [TcTyVar]
    to_anyclass_metas  = [TcTyVar]
    ac_metas
                                         , to_anyclass_givens :: ThetaOrigin -> ThetaType
    to_anyclass_givens = ThetaType
    ac_givens
                                         , to_wanted_origins :: ThetaOrigin -> [PredOrigin]
    to_wanted_origins  = [PredOrigin]
    preds })
                   = do { [TcTyVar]
    ac_given_evs <- (PredType -> TcM TcTyVar)
    -> ThetaType -> IOEnv (Env TcGblEnv TcLclEnv) [TcTyVar]
    forall (t :: * -> *) (m :: * -> *) a b.
    (Traversable t, Monad m) =>
    (a -> m b) -> t a -> m (t b)
    mapM PredType -> TcM TcTyVar
    mk_given_ev ThetaType
    ac_givens
                        ; ((TcEvBinds, ())
    _, WantedConstraints
    wanteds)
                            <- TcM (TcEvBinds, ()) -> TcM ((TcEvBinds, ()), WantedConstraints)
    forall a. TcM a -> TcM (a, WantedConstraints)
    captureConstraints (TcM (TcEvBinds, ()) -> TcM ((TcEvBinds, ()), WantedConstraints))
    -> TcM (TcEvBinds, ()) -> TcM ((TcEvBinds, ()), WantedConstraints)
    forall a b. (a -> b) -> a -> b
    $
                               SkolemInfo
    -> [TcTyVar] -> [TcTyVar] -> TcRn () -> TcM (TcEvBinds, ())
    forall result.
    SkolemInfo
    -> [TcTyVar] -> [TcTyVar] -> TcM result -> TcM (TcEvBinds, result)
    checkConstraints SkolemInfo
    skol_info [TcTyVar]
    ac_skols [TcTyVar]
    ac_given_evs (TcRn () -> TcM (TcEvBinds, ())) -> TcRn () -> TcM (TcEvBinds, ())
    forall a b. (a -> b) -> a -> b
    $
                                  -- The checkConstraints bumps the TcLevel, and
                                  -- wraps the wanted constraints in an implication,
                                  -- when (but only when) necessary
                               [TcTyVar] -> [PredOrigin] -> TcRn ()
    emit_wanted_constraints [TcTyVar]
    ac_metas [PredOrigin]
    preds
                        ; WantedConstraints -> TcM WantedConstraints
    forall (f :: * -> *) a. Applicative f => a -> f a
    pure WantedConstraints
    wanteds }

           -- See [STEP DAC BUILD]
           -- Generate the implication constraints, one for each method, to solve
           -- with the skolemized variables.  Start "one level down" because
           -- we are going to wrap the result in an implication with tvs_skols,
           -- in step [DAC RESIDUAL]
           ; (TcLevel
    tc_lvl, [WantedConstraints]
    wanteds) <- TcM [WantedConstraints] -> TcM (TcLevel, [WantedConstraints])
    forall a. TcM a -> TcM (TcLevel, a)
    pushTcLevelM (TcM [WantedConstraints] -> TcM (TcLevel, [WantedConstraints]))
    -> TcM [WantedConstraints] -> TcM (TcLevel, [WantedConstraints])
    forall a b. (a -> b) -> a -> b
    $
                                  (ThetaOrigin -> TcM WantedConstraints)
    -> [ThetaOrigin] -> TcM [WantedConstraints]
    forall (t :: * -> *) (m :: * -> *) a b.
    (Traversable t, Monad m) =>
    (a -> m b) -> t a -> m (t b)
    mapM ThetaOrigin -> TcM WantedConstraints
    mk_wanteds [ThetaOrigin]
    thetas

           ; String -> SDoc -> TcRn ()
    traceTc String
    "simplifyDeriv inputs" (SDoc -> TcRn ()) -> SDoc -> TcRn ()
    forall a b. (a -> b) -> a -> b
    $
             [SDoc] -> SDoc
    vcat [ [TcTyVar] -> SDoc
    pprTyVars [TcTyVar]
    tvs SDoc -> SDoc -> SDoc
    $$ [ThetaOrigin] -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr [ThetaOrigin]
    thetas SDoc -> SDoc -> SDoc
    $$ [WantedConstraints] -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr [WantedConstraints]
    wanteds, SDoc
    doc ]

           -- See [STEP DAC SOLVE]
           -- Simplify the constraints, starting at the same level at which
           -- they are generated (c.f. the call to runTcSWithEvBinds in
           -- simplifyInfer)
           ; WantedConstraints
    solved_wanteds <- TcLevel -> TcM WantedConstraints -> TcM WantedConstraints
    forall a. TcLevel -> TcM a -> TcM a
    setTcLevel TcLevel
    tc_lvl   (TcM WantedConstraints -> TcM WantedConstraints)
    -> TcM WantedConstraints -> TcM WantedConstraints
    forall a b. (a -> b) -> a -> b
    $
                               TcS WantedConstraints -> TcM WantedConstraints
    forall a. TcS a -> TcM a
    runTcSDeriveds      (TcS WantedConstraints -> TcM WantedConstraints)
    -> TcS WantedConstraints -> TcM WantedConstraints
    forall a b. (a -> b) -> a -> b
    $
                               WantedConstraints -> TcS WantedConstraints
    solveWantedsAndDrop (WantedConstraints -> TcS WantedConstraints)
    -> WantedConstraints -> TcS WantedConstraints
    forall a b. (a -> b) -> a -> b
    $
                               [WantedConstraints] -> WantedConstraints
    unionsWC [WantedConstraints]
    wanteds

           -- It's not yet zonked!  Obviously zonk it before peering at it
           ; WantedConstraints
    solved_wanteds <- WantedConstraints -> TcM WantedConstraints
    zonkWC WantedConstraints
    solved_wanteds

           -- See [STEP DAC HOIST]
           -- From the simplified constraints extract a subset 'good' that will
           -- become the context 'min_theta' for the derived instance.
           ; let residual_simple :: Cts
    residual_simple = Bool -> WantedConstraints -> Cts
    approximateWC Bool
    True WantedConstraints
    solved_wanteds
                 good :: Bag PredType
    good = (Ct -> Maybe PredType) -> Cts -> Bag PredType
    forall a b. (a -> Maybe b) -> Bag a -> Bag b
    mapMaybeBag Ct -> Maybe PredType
    get_good Cts
    residual_simple

                 -- Returns @Just p@ (where @p@ is the type of the Ct) if a Ct is
                 -- suitable to be inferred in the context of a derived instance.
                 -- Returns @Nothing@ if the Ct is too exotic.
                 -- See Note [Exotic derived instance contexts] for what
                 -- constitutes an exotic constraint.
                 get_good :: Ct -> Maybe PredType
                 get_good :: Ct -> Maybe PredType
    get_good Ct
    ct | VarSet -> PredType -> Bool
    validDerivPred VarSet
    skol_set PredType
    p
                             , Ct -> Bool
    isWantedCt Ct
    ct
                             = PredType -> Maybe PredType
    forall a. a -> Maybe a
    Just PredType
    p
                              -- TODO: This is wrong
                              -- NB re 'isWantedCt': residual_wanted may contain
                              -- unsolved CtDerived and we stick them into the
                              -- bad set so that reportUnsolved may decide what
                              -- to do with them
                             | Bool
    otherwise
                             = Maybe PredType
    forall a. Maybe a
    Nothing
                               where p :: PredType
    p = Ct -> PredType
    ctPred Ct
    ct

           ; String -> SDoc -> TcRn ()
    traceTc String
    "simplifyDeriv outputs" (SDoc -> TcRn ()) -> SDoc -> TcRn ()
    forall a b. (a -> b) -> a -> b
    $
             [SDoc] -> SDoc
    vcat [ [TcTyVar] -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr [TcTyVar]
    tvs_skols, Cts -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr Cts
    residual_simple, Bag PredType -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr Bag PredType
    good ]

           -- Return the good unsolved constraints (unskolemizing on the way out.)
           ; let min_theta :: ThetaType
    min_theta = (PredType -> PredType) -> ThetaType -> ThetaType
    forall a. (a -> PredType) -> [a] -> [a]
    mkMinimalBySCs PredType -> PredType
    forall a. a -> a
    id (Bag PredType -> ThetaType
    forall a. Bag a -> [a]
    bagToList Bag PredType
    good)
                 -- An important property of mkMinimalBySCs (used above) is that in
                 -- addition to removing constraints that are made redundant by
                 -- superclass relationships, it also removes _duplicate_
                 -- constraints.
                 -- See Note [Gathering and simplifying constraints for
                 --           DeriveAnyClass]
                 subst_skol :: TCvSubst
    subst_skol = [TcTyVar] -> ThetaType -> TCvSubst
    HasDebugCallStack => [TcTyVar] -> ThetaType -> TCvSubst
    zipTvSubst [TcTyVar]
    tvs_skols (ThetaType -> TCvSubst) -> ThetaType -> TCvSubst
    forall a b. (a -> b) -> a -> b
    $ [TcTyVar] -> ThetaType
    mkTyVarTys [TcTyVar]
    tvs
                              -- The reverse substitution (sigh)

           -- See [STEP DAC RESIDUAL]
           -- Ensure that min_theta is enough to solve /all/ the constraints in
           -- solved_wanteds, by solving the implication constraint
           --
           --    forall tvs. min_theta => solved_wanteds
           ; [TcTyVar]
    min_theta_vars <- (PredType -> TcM TcTyVar)
    -> ThetaType -> IOEnv (Env TcGblEnv TcLclEnv) [TcTyVar]
    forall (t :: * -> *) (m :: * -> *) a b.
    (Traversable t, Monad m) =>
    (a -> m b) -> t a -> m (t b)
    mapM PredType -> TcM TcTyVar
    forall gbl lcl. PredType -> TcRnIf gbl lcl TcTyVar
    newEvVar ThetaType
    min_theta
           ; (Bag Implication
    leftover_implic, TcEvBinds
    _)
               <- TcLevel
    -> SkolemInfo
    -> [TcTyVar]
    -> [TcTyVar]
    -> WantedConstraints
    -> TcM (Bag Implication, TcEvBinds)
    buildImplicationFor TcLevel
    tc_lvl SkolemInfo
    skol_info [TcTyVar]
    tvs_skols
                                      [TcTyVar]
    min_theta_vars WantedConstraints
    solved_wanteds
           -- This call to simplifyTop is purely for error reporting
           -- See Note [Error reporting for deriving clauses]
           -- See also Note [Exotic derived instance contexts], which are caught
           -- in this line of code.
           ; Bag Implication -> TcRn ()
    simplifyTopImplic Bag Implication
    leftover_implic

           ; ThetaType -> IOEnv (Env TcGblEnv TcLclEnv) ThetaType
    forall (m :: * -> *) a. Monad m => a -> m a
    return (HasCallStack => TCvSubst -> ThetaType -> ThetaType
    TCvSubst -> ThetaType -> ThetaType
    substTheta TCvSubst
    subst_skol ThetaType
    min_theta) }

    {-
    Note [Overlap and deriving]
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Consider some overlapping instances:
      instance Show a => Show [a] where ..
      instance Show [Char] where ...

    Now a data type with deriving:
      data T a = MkT [a] deriving( Show )

    We want to get the derived instance
      instance Show [a] => Show (T a) where...
    and NOT
      instance Show a => Show (T a) where...
    so that the (Show (T Char)) instance does the Right Thing

    It's very like the situation when we're inferring the type
    of a function
       f x = show [x]
    and we want to infer
       f :: Show [a] => a -> String

    BOTTOM LINE: use vanilla, non-overlappable skolems when inferring
                 the context for the derived instance.
                 Hence tcInstSkolTyVars not tcInstSuperSkolTyVars

    Note [Gathering and simplifying constraints for DeriveAnyClass]
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    DeriveAnyClass works quite differently from stock and newtype deriving in
    the way it gathers and simplifies constraints to be used in a derived
    instance's context. Stock and newtype deriving gather constraints by looking
    at the data constructors of the data type for which we are deriving an
    instance. But DeriveAnyClass doesn't need to know about a data type's
    definition at all!

    To see why, consider this example of DeriveAnyClass:

      class Foo a where
        bar :: forall b. Ix b => a -> b -> String
        default bar :: (Show a, Ix c) => a -> c -> String
        bar x y = show x ++ show (range (y,y))

        baz :: Eq a => a -> a -> Bool
        default baz :: (Ord a, Show a) => a -> a -> Bool
        baz x y = compare x y == EQ

    Because 'bar' and 'baz' have default signatures, this generates a top-level
    definition for these generic default methods

      $gdm_bar :: forall a. Foo a
               => forall c. (Show a, Ix c)
               => a -> c -> String
      $gdm_bar x y = show x ++ show (range (y,y))

    (and similarly for baz).  Now consider a 'deriving' clause
      data Maybe s = ... deriving Foo

    This derives an instance of the form:
      instance (CX) => Foo (Maybe s) where
        bar = $gdm_bar
        baz = $gdm_baz

    Now it is GHC's job to fill in a suitable instance context (CX).  If
    GHC were typechecking the binding
       bar = $gdm bar
    it would
       * skolemise the expected type of bar
       * instantiate the type of $gdm_bar with meta-type variables
       * build an implication constraint

    [STEP DAC BUILD]
    So that's what we do.  We build the constraint (call it C1)

       forall[2] b. Ix b => (Show (Maybe s), Ix cc,
                            Maybe s -> b -> String
                                ~ Maybe s -> cc -> String)

    Here:
    * The level of this forall constraint is forall[2], because we are later
      going to wrap it in a forall[1] in [STEP DAC RESIDUAL]

    * The 'b' comes from the quantified type variable in the expected type
      of bar (i.e., 'to_anyclass_skols' in 'ThetaOrigin'). The 'cc' is a unification
      variable that comes from instantiating the quantified type variable 'c' in
      $gdm_bar's type (i.e., 'to_anyclass_metas' in 'ThetaOrigin).

    * The (Ix b) constraint comes from the context of bar's type
      (i.e., 'to_wanted_givens' in 'ThetaOrigin'). The (Show (Maybe s)) and (Ix cc)
      constraints come from the context of $gdm_bar's type
      (i.e., 'to_anyclass_givens' in 'ThetaOrigin').

    * The equality constraint (Maybe s -> b -> String) ~ (Maybe s -> cc -> String)
      comes from marrying up the instantiated type of $gdm_bar with the specified
      type of bar. Notice that the type variables from the instance, 's' in this
      case, are global to this constraint.

    Note that it is vital that we instantiate the `c` in $gdm_bar's type with a new
    unification variable for each iteration of simplifyDeriv. If we re-use the same
    unification variable across multiple iterations, then bad things can happen,
    such as #14933.

    Similarly for 'baz', giving the constraint C2

       forall[2]. Eq (Maybe s) => (Ord a, Show a,
                                  Maybe s -> Maybe s -> Bool
                                    ~ Maybe s -> Maybe s -> Bool)

    In this case baz has no local quantification, so the implication
    constraint has no local skolems and there are no unification
    variables.

    [STEP DAC SOLVE]
    We can combine these two implication constraints into a single
    constraint (C1, C2), and simplify, unifying cc:=b, to get:

       forall[2] b. Ix b => Show a
       /\
       forall[2]. Eq (Maybe s) => (Ord a, Show a)

    [STEP DAC HOIST]
    Let's call that (C1', C2').  Now we need to hoist the unsolved
    constraints out of the implications to become our candidate for
    (CX). That is done by approximateWC, which will return:

      (Show a, Ord a, Show a)

    Now we can use mkMinimalBySCs to remove superclasses and duplicates, giving

      (Show a, Ord a)

    And that's what GHC uses for CX.

    [STEP DAC RESIDUAL]
    In this case we have solved all the leftover constraints, but what if
    we don't?  Simple!  We just form the final residual constraint

       forall[1] s. CX => (C1',C2')

    and simplify that. In simple cases it'll succeed easily, because CX
    literally contains the constraints in C1', C2', but if there is anything
    more complicated it will be reported in a civilised way.

    Note [Error reporting for deriving clauses]
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    A surprisingly tricky aspect of deriving to get right is reporting sensible
    error messages. In particular, if simplifyDeriv reaches a constraint that it
    cannot solve, which might include:

    1. Insoluble constraints
    2. "Exotic" constraints (See Note [Exotic derived instance contexts])

    Then we report an error immediately in simplifyDeriv.

    Another possible choice is to punt and let another part of the typechecker
    (e.g., simplifyInstanceContexts) catch the errors. But this tends to lead
    to worse error messages, so we do it directly in simplifyDeriv.

    simplifyDeriv checks for errors in a clever way. If the deriving machinery
    infers the context (Foo a)--that is, if this instance is to be generated:

      instance Foo a => ...

    Then we form an implication of the form:

      forall a. Foo a => <residual_wanted_constraints>

    And pass it to the simplifier. If the context (Foo a) is enough to discharge
    all the constraints in <residual_wanted_constraints>, then everything is
    hunky-dory. But if <residual_wanted_constraints> contains, say, an insoluble
    constraint, then (Foo a) won't be able to solve it, causing GHC to error.

    Note [Exotic derived instance contexts]
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    In a 'derived' instance declaration, we *infer* the context.  It's a
    bit unclear what rules we should apply for this; the Haskell report is
    silent.  Obviously, constraints like (Eq a) are fine, but what about
            data T f a = MkT (f a) deriving( Eq )
    where we'd get an Eq (f a) constraint.  That's probably fine too.

    One could go further: consider
            data T a b c = MkT (Foo a b c) deriving( Eq )
            instance (C Int a, Eq b, Eq c) => Eq (Foo a b c)

    Notice that this instance (just) satisfies the Paterson termination
    conditions.  Then we *could* derive an instance decl like this:

            instance (C Int a, Eq b, Eq c) => Eq (T a b c)
    even though there is no instance for (C Int a), because there just
    *might* be an instance for, say, (C Int Bool) at a site where we
    need the equality instance for T's.

    However, this seems pretty exotic, and it's quite tricky to allow
    this, and yet give sensible error messages in the (much more common)
    case where we really want that instance decl for C.

    So for now we simply require that the derived instance context
    should have only type-variable constraints.

    Here is another example:
            data Fix f = In (f (Fix f)) deriving( Eq )
    Here, if we are prepared to allow -XUndecidableInstances we
    could derive the instance
            instance Eq (f (Fix f)) => Eq (Fix f)
    but this is so delicate that I don't think it should happen inside
    'deriving'. If you want this, write it yourself!

    NB: if you want to lift this condition, make sure you still meet the
    termination conditions!  If not, the deriving mechanism generates
    larger and larger constraints.  Example:
      data Succ a = S a
      data Seq a = Cons a (Seq (Succ a)) | Nil deriving Show

    Note the lack of a Show instance for Succ.  First we'll generate
      instance (Show (Succ a), Show a) => Show (Seq a)
    and then
      instance (Show (Succ (Succ a)), Show (Succ a), Show a) => Show (Seq a)
    and so on.  Instead we want to complain of no instance for (Show (Succ a)).

    The bottom line
    ~~~~~~~~~~~~~~~
    Allow constraints which consist only of type variables, with no repeats.
    -}