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

Functions for inferring (and simplifying) the context for derived instances.
-}

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

module TcDerivInfer (inferConstraints, simplifyInstanceContexts) where

#include "HsVersions.h"

import GhcPrelude

import Bag
import BasicTypes
import Class
import DataCon
import ErrUtils
import Inst
import Outputable
import PrelNames
import TcDerivUtils
import TcEnv
import TcGenFunctor
import TcGenGenerics
import TcMType
import TcRnMonad
import TcType
import TyCon
import Type
import TcSimplify
import TcValidity (validDerivPred)
import TcUnify (buildImplicationFor, checkConstraints)
import Unify (tcUnifyTy)
import Util
import Var
import VarSet

import Control.Monad
import Control.Monad.Trans.Class  (lift)
import Control.Monad.Trans.Reader (ask)
import Data.List
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 mechanism
  = do { DerivEnv { denv_tc          = tc
                  , denv_tc_args     = tc_args
                  , denv_cls         = main_cls
                  , denv_cls_tys     = cls_tys } <- ask
       ; wildcard <- isStandaloneWildcardDeriv
       ; let is_anyclass = isDerivSpecAnyClass mechanism
             infer_constraints
               | is_anyclass = inferConstraintsDAC inst_tys
               | otherwise   = inferConstraintsDataConArgs inst_ty inst_tys

             inst_ty  = mkTyConApp tc tc_args
             inst_tys = cls_tys ++ [inst_ty]

             -- Constraints arising from superclasses
             -- See Note [Superclasses of derived instance]
             cls_tvs  = classTyVars main_cls
             sc_constraints = ASSERT2( equalLength cls_tvs inst_tys
                                     , ppr main_cls <+> ppr inst_tys )
                              [ mkThetaOrigin (mkDerivOrigin wildcard)
                                              TypeLevel [] [] [] $
                                substTheta cls_subst (classSCTheta main_cls) ]
             cls_subst = ASSERT( equalLength cls_tvs inst_tys )
                         zipTvSubst cls_tvs inst_tys

       ; (inferred_constraints, tvs', inst_tys') <- infer_constraints
       ; lift $ traceTc "inferConstraints" $ vcat
              [ ppr main_cls <+> ppr inst_tys'
              , ppr inferred_constraints
              ]
       ; return ( sc_constraints ++ inferred_constraints
                , tvs', inst_tys' ) }

-- | Like 'inferConstraints', but used only in the case of deriving strategies
-- where the constraints are inferred by inspecting the fields of each data
-- constructor (i.e., stock- and newtype-deriving).
inferConstraintsDataConArgs :: TcType -> [TcType]
                            -> DerivM ([ThetaOrigin], [TyVar], [TcType])
inferConstraintsDataConArgs inst_ty inst_tys
  = do DerivEnv { denv_tvs         = tvs
                , denv_rep_tc      = rep_tc
                , denv_rep_tc_args = rep_tc_args
                , denv_cls         = main_cls
                , denv_cls_tys     = cls_tys } <- ask
       wildcard <- isStandaloneWildcardDeriv

       let tc_binders = tyConBinders rep_tc
           choose_level bndr
             | isNamedTyConBinder bndr = KindLevel
             | otherwise               = TypeLevel
           t_or_ks = map choose_level tc_binders ++ repeat 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 get_arg_constraints
             = let (predss, mbSubsts) = unzip
                     [ preds_and_mbSubst
                     | data_con <- tyConDataCons rep_tc
                     , (arg_n, arg_t_or_k, arg_ty)
                         <- zip3 [1..] t_or_ks $
                            dataConInstOrigArgTys data_con all_rep_tc_args
                       -- No constraints for unlifted types
                       -- See Note [Deriving and unboxed types]
                     , not (isUnliftedType arg_ty)
                     , let orig = DerivOriginDC data_con arg_n wildcard
                     , preds_and_mbSubst
                         <- get_arg_constraints orig arg_t_or_k arg_ty
                     ]
                   preds = concat 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        = foldl' composeTCvSubst
                                         emptyTCvSubst (catMaybes mbSubsts)
                   unmapped_tvs = filter (\v -> v `notElemTCvSubst` subst
                                             && not (v `isInScope` subst)) tvs
                   (subst', _)  = substTyVarBndrs subst unmapped_tvs
                   preds'       = map (substPredOrigin subst') preds
                   inst_tys'    = substTys subst' inst_tys
                   tvs'         = tyCoVarsOfTypesWellScoped inst_tys'
               in ([mkThetaOriginFromPreds preds'], tvs', inst_tys')

           is_generic  = main_cls `hasKey` genClassKey
           is_generic1 = main_cls `hasKey` gen1ClassKey
           -- is_functor_like: see Note [Inferring the instance context]
           is_functor_like = tcTypeKind inst_ty `tcEqKind` typeToTypeKind
                          || is_generic1

           get_gen1_constraints :: Class -> CtOrigin -> TypeOrKind -> Type
                                -> [([PredOrigin], Maybe TCvSubst)]
           get_gen1_constraints functor_cls orig t_or_k ty
              = mk_functor_like_constraints orig t_or_k functor_cls $
                get_gen1_constrained_tys last_tv ty

           get_std_constrained_tys :: CtOrigin -> TypeOrKind -> Type
                                   -> [([PredOrigin], Maybe TCvSubst)]
           get_std_constrained_tys orig t_or_k ty
               | is_functor_like
               = mk_functor_like_constraints orig t_or_k main_cls $
                 deepSubtypesContaining last_tv ty
               | otherwise
               = [( [mk_cls_pred orig t_or_k main_cls ty]
                  , 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 orig t_or_k cls
              = map $ \ty -> let ki = tcTypeKind ty in
                             ( [ mk_cls_pred orig t_or_k cls ty
                               , mkPredOrigin orig KindLevel
                                   (mkPrimEqPred ki typeToTypeKind) ]
                             , tcUnifyTy ki typeToTypeKind
                             )

           rep_tc_tvs      = tyConTyVars rep_tc
           last_tv         = last 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
             = rep_tc_args ++ map mkTyVarTy
                                  (drop (length rep_tc_args) rep_tc_tvs)

               -- Stupid constraints
           stupid_constraints
             = [ mkThetaOrigin deriv_origin TypeLevel [] [] [] $
                 substTheta tc_subst (tyConStupidTheta rep_tc) ]
           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 )
                      zipTvSubst rep_tc_tvs 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 = [mkThetaOriginFromPreds constrs]
             where
               constrs
                 | main_cls `hasKey` dataClassKey
                 , all (isLiftedTypeKind . tcTypeKind) rep_tc_args
                 = [ mk_cls_pred deriv_origin t_or_k main_cls ty
                   | (t_or_k, ty) <- zip t_or_ks rep_tc_args]
                 | otherwise
                 = []

           mk_cls_pred orig t_or_k cls ty
                -- Don't forget to apply to cls_tys' too
              = mkPredOrigin orig t_or_k (mkClassPred cls (cls_tys' ++ [ty]))
           cls_tys' | is_generic1 = []
                      -- In the awkward Generic1 case, cls_tys' should be
                      -- empty, since we are applying the class Functor.

                    | otherwise   = cls_tys

           deriv_origin = mkDerivOrigin wildcard

       if    -- Generic constraints are easy
          |  is_generic
           -> return ([], tvs, inst_tys)

             -- Generic1 needs Functor
             -- See Note [Getting base classes]
          |  is_generic1
           -> ASSERT( rep_tc_tvs `lengthExceeds` 0 )
              -- Generic1 has a single kind variable
              ASSERT( cls_tys `lengthIs` 1 )
              do { functorClass <- lift $ tcLookupClass functorClassName
                 ; pure $ con_arg_constraints
                        $ get_gen1_constraints functorClass }

             -- The others are a bit more complicated
          |  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 (arg_constraints, tvs', inst_tys')
                           = con_arg_constraints get_std_constrained_tys
                   ; lift $ traceTc "inferConstraintsDataConArgs" $ vcat
                          [ ppr main_cls <+> ppr inst_tys'
                          , ppr arg_constraints
                          ]
                   ; return ( stupid_constraints ++ extra_constraints
                                                 ++ arg_constraints
                            , tvs', inst_tys') }

typeToTypeKind :: Kind
typeToTypeKind = liftedTypeKind `mkVisFunTy` liftedTypeKind

-- | 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.
inferConstraintsDAC :: [TcType] -> DerivM ([ThetaOrigin], [TyVar], [TcType])
inferConstraintsDAC inst_tys
  = do { DerivEnv { denv_tvs = tvs
                  , denv_cls = cls } <- ask
       ; wildcard <- isStandaloneWildcardDeriv

       ; let gen_dms = [ (sel_id, dm_ty)
                       | (sel_id, Just (_, GenericDM dm_ty)) <- classOpItems cls ]

             cls_tvs = classTyVars 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 (sel_id, gen_dm_ty)
               = do { let (sel_tvs, _cls_pred, meth_ty)
                                   = tcSplitMethodTy (varType sel_id)
                          meth_ty' = substTyWith sel_tvs inst_tys meth_ty
                          (meth_tvs, meth_theta, meth_tau)
                                   = tcSplitNestedSigmaTys meth_ty'

                          gen_dm_ty' = substTyWith cls_tvs inst_tys gen_dm_ty
                          (dm_tvs, dm_theta, dm_tau)
                                     = tcSplitNestedSigmaTys gen_dm_ty'
                          tau_eq     = mkPrimEqPred meth_tau dm_tau
                    ; return (mkThetaOrigin (mkDerivOrigin wildcard) TypeLevel
                                meth_tvs dm_tvs meth_theta (tau_eq:dm_theta)) }

       ; theta_origins <- lift $ mapM do_one_meth gen_dms
       ; return (theta_origins, tvs, inst_tys) }

{- 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 (inferConstraintsDataConArgs). 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
Trac #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 TcGenDeriv.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 inferConstraintsDataConArgs.

        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 [] = return []

simplifyInstanceContexts infer_specs
  = do  { traceTc "simplifyInstanceContexts" $ vcat (map pprDerivSpec infer_specs)
        ; iterate_deriv 1 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 = [ [] | _ <- 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 n current_solns
      | n > 20  -- Looks as if we are in an infinite loop
                -- This can happen if we have -XUndecidableInstances
                -- (See TcSimplify.tcSimplifyDeriv.)
      = pprPanic "solveDerivEqns: probable loop"
                 (vcat (map pprDerivSpec infer_specs) $$ ppr current_solns)
      | otherwise
      = do {      -- Extend the inst info from the explicit instance decls
                  -- with the current set of solutions, and simplify each RHS
             inst_specs <- zipWithM newDerivClsInst current_solns infer_specs
           ; new_solns <- checkNoErrs $
                          extendLocalInstEnv inst_specs $
                          mapM gen_soln infer_specs

           ; if (current_solns `eqSolution` new_solns) then
                return [ spec { ds_theta = soln }
                       | (spec, soln) <- zip infer_specs current_solns ]
             else
                iterate_deriv (n+1) new_solns }

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

           ; traceTc "TcDeriv" (ppr deriv_rhs $$ ppr theta)
                -- Claim: the result instance declaration is guaranteed valid
                -- Hence no need to call:
                --   checkValidInstance tyvars theta clas inst_tys
           ; return theta }
      where
        the_pred = mkClassPred clas inst_tys

derivInstCtxt :: PredType -> MsgDoc
derivInstCtxt pred
  = text "When deriving the instance for" <+> parens (ppr 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 pred tvs thetas
  = do { (skol_subst, tvs_skols) <- tcInstSkolTyVars tvs -- Skolemize
                -- The constraint solving machinery
                -- expects *TcTyVars* not TyVars.
                -- We use *non-overlappable* (vanilla) skolems
                -- See Note [Overlap and deriving]

       ; let skol_set  = mkVarSet tvs_skols
             skol_info = DerivSkol pred
             doc = text "deriving" <+> parens (ppr pred)

             mk_given_ev :: PredType -> TcM EvVar
             mk_given_ev given =
               let given_pred = substTy skol_subst given
               in newEvVar given_pred

             emit_wanted_constraints :: [TyVar] -> [PredOrigin] -> TcM ()
             emit_wanted_constraints metas_to_be 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]
                      (meta_subst, _meta_tvs) <- newMetaTyVars metas_to_be

                    -- Now make a constraint for each of the instantiated predicates
                    ; let wanted_subst = skol_subst `unionTCvSubst` meta_subst
                          mk_wanted_ct (PredOrigin wanted orig t_or_k)
                            = do { ev <- newWanted orig (Just t_or_k) $
                                         substTyUnchecked wanted_subst wanted
                                 ; return (mkNonCanonical ev) }
                    ; cts <- mapM mk_wanted_ct preds

                    -- And emit them into the monad
                    ; emitSimples (listToCts 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 { to_anyclass_skols  = ac_skols
                                     , to_anyclass_metas  = ac_metas
                                     , to_anyclass_givens = ac_givens
                                     , to_wanted_origins  = preds })
               = do { ac_given_evs <- mapM mk_given_ev ac_givens
                    ; (_, wanteds)
                        <- captureConstraints $
                           checkConstraints skol_info ac_skols ac_given_evs $
                              -- The checkConstraints bumps the TcLevel, and
                              -- wraps the wanted constraints in an implication,
                              -- when (but only when) necessary
                           emit_wanted_constraints ac_metas preds
                    ; pure 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]
       ; (tc_lvl, wanteds) <- pushTcLevelM $
                              mapM mk_wanteds thetas

       ; traceTc "simplifyDeriv inputs" $
         vcat [ pprTyVars tvs $$ ppr thetas $$ ppr wanteds, 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)
       ; solved_wanteds <- setTcLevel tc_lvl   $
                           runTcSDeriveds      $
                           solveWantedsAndDrop $
                           unionsWC wanteds

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

       -- See [STEP DAC HOIST]
       -- Split the resulting constraints into bad and good constraints,
       -- building an @unsolved :: WantedConstraints@ representing all
       -- the constraints we can't just shunt to the predicates.
       -- See Note [Exotic derived instance contexts]
       ; let residual_simple = approximateWC True solved_wanteds
             (bad, good) = partitionBagWith get_good residual_simple

             get_good :: Ct -> Either Ct PredType
             get_good ct | validDerivPred skol_set p
                         , isWantedCt ct
                         = Right 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
                         | otherwise
                         = Left ct
                           where p = ctPred ct

       ; traceTc "simplifyDeriv outputs" $
         vcat [ ppr tvs_skols, ppr residual_simple, ppr good, ppr bad ]

       -- Return the good unsolved constraints (unskolemizing on the way out.)
       ; let min_theta = mkMinimalBySCs id (bagToList 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 = zipTvSubst tvs_skols $ mkTyVarTys tvs
                          -- The reverse substitution (sigh)

       -- See [STEP DAC RESIDUAL]
       ; min_theta_vars <- mapM newEvVar min_theta
       ; (leftover_implic, _)
           <- buildImplicationFor tc_lvl skol_info tvs_skols
                                  min_theta_vars 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.
       ; simplifyTopImplic leftover_implic

       ; return (substTheta subst_skol 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 Trac #14933.

Similarly for 'baz', givng 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 suprisingly 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.
-}


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

Error-checking and other utilities for @deriving@ clauses or declarations.
-}

{-# LANGUAGE TypeFamilies #-}

module TcDerivUtils (
        DerivM, DerivEnv(..),
        DerivSpec(..), pprDerivSpec,
        DerivSpecMechanism(..), derivSpecMechanismToStrategy, isDerivSpecStock,
        isDerivSpecNewtype, isDerivSpecAnyClass, isDerivSpecVia,
        DerivContext(..), OriginativeDerivStatus(..),
        isStandaloneDeriv, isStandaloneWildcardDeriv, mkDerivOrigin,
        PredOrigin(..), ThetaOrigin(..), mkPredOrigin,
        mkThetaOrigin, mkThetaOriginFromPreds, substPredOrigin,
        checkOriginativeSideConditions, hasStockDeriving,
        canDeriveAnyClass,
        std_class_via_coercible, non_coercible_class,
        newDerivClsInst, extendLocalInstEnv
    ) where

import GhcPrelude

import Bag
import BasicTypes
import Class
import DataCon
import DynFlags
import ErrUtils
import HscTypes (lookupFixity, mi_fix)
import HsSyn
import Inst
import InstEnv
import LoadIface (loadInterfaceForName)
import Module (getModule)
import Name
import Outputable
import PrelNames
import SrcLoc
import TcGenDeriv
import TcGenFunctor
import TcGenGenerics
import TcRnMonad
import TcType
import THNames (liftClassKey)
import TyCon
import Type
import Util
import VarSet

import Control.Monad.Trans.Reader
import Data.Maybe
import qualified GHC.LanguageExtensions as LangExt
import ListSetOps (assocMaybe)

-- | To avoid having to manually plumb everything in 'DerivEnv' throughout
-- various functions in @TcDeriv@ and @TcDerivInfer@, we use 'DerivM', which
-- is a simple reader around 'TcRn'.
type DerivM = ReaderT DerivEnv TcRn

-- | Is GHC processing a standalone deriving declaration?
isStandaloneDeriv :: DerivM Bool
isStandaloneDeriv = asks (go . denv_ctxt)
  where
    go :: DerivContext -> Bool
    go (InferContext wildcard) = isJust wildcard
    go (SupplyContext {})      = True

-- | Is GHC processing a standalone deriving declaration with an
-- extra-constraints wildcard as the context?
-- (e.g., @deriving instance _ => Eq (Foo a)@)
isStandaloneWildcardDeriv :: DerivM Bool
isStandaloneWildcardDeriv = asks (go . denv_ctxt)
  where
    go :: DerivContext -> Bool
    go (InferContext wildcard) = isJust wildcard
    go (SupplyContext {})      = False

-- | @'mkDerivOrigin' wc@ returns 'StandAloneDerivOrigin' if @wc@ is 'True',
-- and 'DerivClauseOrigin' if @wc@ is 'False'. Useful for error-reporting.
mkDerivOrigin :: Bool -> CtOrigin
mkDerivOrigin standalone_wildcard
  | standalone_wildcard = StandAloneDerivOrigin
  | otherwise           = DerivClauseOrigin

-- | Contains all of the information known about a derived instance when
-- determining what its @EarlyDerivSpec@ should be.
data DerivEnv = DerivEnv
  { denv_overlap_mode :: Maybe OverlapMode
    -- ^ Is this an overlapping instance?
  , denv_tvs          :: [TyVar]
    -- ^ Universally quantified type variables in the instance
  , denv_cls          :: Class
    -- ^ Class for which we need to derive an instance
  , denv_cls_tys      :: [Type]
    -- ^ Other arguments to the class except the last
  , denv_tc           :: TyCon
    -- ^ Type constructor for which the instance is requested
    --   (last arguments to the type class)
  , denv_tc_args      :: [Type]
    -- ^ Arguments to the type constructor
  , denv_rep_tc       :: TyCon
    -- ^ The representation tycon for 'denv_tc'
    --   (for data family instances)
  , denv_rep_tc_args  :: [Type]
    -- ^ The representation types for 'denv_tc_args'
    --   (for data family instances)
  , denv_ctxt         :: DerivContext
    -- ^ @'SupplyContext' theta@ for standalone deriving (where @theta@ is the
    --   context of the instance).
    --   'InferContext' for @deriving@ clauses, or for standalone deriving that
    --   uses a wildcard constraint.
    --   See @Note [Inferring the instance context]@.
  , denv_strat        :: Maybe (DerivStrategy GhcTc)
    -- ^ 'Just' if user requests a particular deriving strategy.
    --   Otherwise, 'Nothing'.
  }

instance Outputable DerivEnv where
  ppr (DerivEnv { denv_overlap_mode = overlap_mode
                , denv_tvs          = tvs
                , denv_cls          = cls
                , denv_cls_tys      = cls_tys
                , denv_tc           = tc
                , denv_tc_args      = tc_args
                , denv_rep_tc       = rep_tc
                , denv_rep_tc_args  = rep_tc_args
                , denv_ctxt         = ctxt
                , denv_strat        = mb_strat })
    = hang (text "DerivEnv")
         2 (vcat [ text "denv_overlap_mode" <+> ppr overlap_mode
                 , text "denv_tvs"          <+> ppr tvs
                 , text "denv_cls"          <+> ppr cls
                 , text "denv_cls_tys"      <+> ppr cls_tys
                 , text "denv_tc"           <+> ppr tc
                 , text "denv_tc_args"      <+> ppr tc_args
                 , text "denv_rep_tc"       <+> ppr rep_tc
                 , text "denv_rep_tc_args"  <+> ppr rep_tc_args
                 , text "denv_ctxt"         <+> ppr ctxt
                 , text "denv_strat"        <+> ppr mb_strat ])

data DerivSpec theta = DS { ds_loc                 :: SrcSpan
                          , ds_name                :: Name         -- DFun name
                          , ds_tvs                 :: [TyVar]
                          , ds_theta               :: theta
                          , ds_cls                 :: Class
                          , ds_tys                 :: [Type]
                          , ds_tc                  :: TyCon
                          , ds_overlap             :: Maybe OverlapMode
                          , ds_standalone_wildcard :: Maybe SrcSpan
                              -- See Note [Inferring the instance context]
                              -- in TcDerivInfer
                          , ds_mechanism           :: DerivSpecMechanism }
        -- This spec implies a dfun declaration of the form
        --       df :: forall tvs. theta => C tys
        -- The Name is the name for the DFun we'll build
        -- The tyvars bind all the variables in the theta
        -- For type families, the tycon in
        --       in ds_tys is the *family* tycon
        --       in ds_tc is the *representation* type
        -- For non-family tycons, both are the same

        -- the theta is either the given and final theta, in standalone deriving,
        -- or the not-yet-simplified list of constraints together with their origin

        -- ds_mechanism specifies the means by which GHC derives the instance.
        -- See Note [Deriving strategies] in TcDeriv

{-
Example:

     newtype instance T [a] = MkT (Tree a) deriving( C s )
==>
     axiom T [a] = :RTList a
     axiom :RTList a = Tree a

     DS { ds_tvs = [a,s], ds_cls = C, ds_tys = [s, T [a]]
        , ds_tc = :RTList, ds_mechanism = DerivSpecNewtype (Tree a) }
-}

pprDerivSpec :: Outputable theta => DerivSpec theta -> SDoc
pprDerivSpec (DS { ds_loc = l, ds_name = n, ds_tvs = tvs, ds_cls = c,
                   ds_tys = tys, ds_theta = rhs,
                   ds_standalone_wildcard = wildcard, ds_mechanism = mech })
  = hang (text "DerivSpec")
       2 (vcat [ text "ds_loc                  =" <+> ppr l
               , text "ds_name                 =" <+> ppr n
               , text "ds_tvs                  =" <+> ppr tvs
               , text "ds_cls                  =" <+> ppr c
               , text "ds_tys                  =" <+> ppr tys
               , text "ds_theta                =" <+> ppr rhs
               , text "ds_standalone_wildcard  =" <+> ppr wildcard
               , text "ds_mechanism            =" <+> ppr mech ])

instance Outputable theta => Outputable (DerivSpec theta) where
  ppr = pprDerivSpec

-- What action to take in order to derive a class instance.
-- See Note [Deriving strategies] in TcDeriv
data DerivSpecMechanism
  = DerivSpecStock   -- "Standard" classes
      (SrcSpan -> TyCon
               -> [Type]
               -> TcM (LHsBinds GhcPs, BagDerivStuff, [Name]))
      -- This function returns three things:
      --
      -- 1. @LHsBinds GhcPs@: The derived instance's function bindings
      --    (e.g., @compare (T x) (T y) = compare x y@)
      -- 2. @BagDerivStuff@: Auxiliary bindings needed to support the derived
      --    instance. As examples, derived 'Generic' instances require
      --    associated type family instances, and derived 'Eq' and 'Ord'
      --    instances require top-level @con2tag@ functions.
      --    See Note [Auxiliary binders] in TcGenDeriv.
      -- 3. @[Name]@: A list of Names for which @-Wunused-binds@ should be
      --    suppressed. This is used to suppress unused warnings for record
      --    selectors when deriving 'Read', 'Show', or 'Generic'.
      --    See Note [Deriving and unused record selectors].

  | DerivSpecNewtype -- -XGeneralizedNewtypeDeriving
      Type -- The newtype rep type

  | DerivSpecAnyClass -- -XDeriveAnyClass

  | DerivSpecVia -- -XDerivingVia
      Type -- The @via@ type

-- | Convert a 'DerivSpecMechanism' to its corresponding 'DerivStrategy'.
derivSpecMechanismToStrategy :: DerivSpecMechanism -> DerivStrategy GhcTc
derivSpecMechanismToStrategy DerivSpecStock{}   = StockStrategy
derivSpecMechanismToStrategy DerivSpecNewtype{} = NewtypeStrategy
derivSpecMechanismToStrategy DerivSpecAnyClass  = AnyclassStrategy
derivSpecMechanismToStrategy (DerivSpecVia t)   = ViaStrategy t

isDerivSpecStock, isDerivSpecNewtype, isDerivSpecAnyClass, isDerivSpecVia
  :: DerivSpecMechanism -> Bool
isDerivSpecStock (DerivSpecStock{}) = True
isDerivSpecStock _                  = False

isDerivSpecNewtype (DerivSpecNewtype{}) = True
isDerivSpecNewtype _                    = False

isDerivSpecAnyClass DerivSpecAnyClass = True
isDerivSpecAnyClass _                 = False

isDerivSpecVia (DerivSpecVia{}) = True
isDerivSpecVia _                = False

instance Outputable DerivSpecMechanism where
  ppr (DerivSpecStock{})   = text "DerivSpecStock"
  ppr (DerivSpecNewtype t) = text "DerivSpecNewtype" <> colon <+> ppr t
  ppr DerivSpecAnyClass    = text "DerivSpecAnyClass"
  ppr (DerivSpecVia t)     = text "DerivSpecVia" <> colon <+> ppr t

-- | Whether GHC is processing a @deriving@ clause or a standalone deriving
-- declaration.
data DerivContext
  = InferContext (Maybe SrcSpan) -- ^ @'InferContext mb_wildcard@ is either:
                                 --
                                 -- * A @deriving@ clause (in which case
                                 --   @mb_wildcard@ is 'Nothing').
                                 --
                                 -- * A standalone deriving declaration with
                                 --   an extra-constraints wildcard as the
                                 --   context (in which case @mb_wildcard@ is
                                 --   @'Just' loc@, where @loc@ is the location
                                 --   of the wildcard.
                                 --
                                 -- GHC should infer the context.

  | SupplyContext ThetaType      -- ^ @'SupplyContext' theta@ is a standalone
                                 -- deriving declaration, where @theta@ is the
                                 -- context supplied by the user.

instance Outputable DerivContext where
  ppr (InferContext standalone) = text "InferContext"  <+> ppr standalone
  ppr (SupplyContext theta)     = text "SupplyContext" <+> ppr theta

-- | Records whether a particular class can be derived by way of an
-- /originative/ deriving strategy (i.e., @stock@ or @anyclass@).
--
-- See @Note [Deriving strategies]@ in "TcDeriv".
data OriginativeDerivStatus
  = CanDeriveStock            -- Stock class, can derive
      (SrcSpan -> TyCon -> [Type]
               -> TcM (LHsBinds GhcPs, BagDerivStuff, [Name]))
  | StockClassError SDoc      -- Stock class, but can't do it
  | CanDeriveAnyClass         -- See Note [Deriving any class]
  | NonDerivableClass SDoc    -- Cannot derive with either stock or anyclass

-- A stock class is one either defined in the Haskell report or for which GHC
-- otherwise knows how to generate code for (possibly requiring the use of a
-- language extension), such as Eq, Ord, Ix, Data, Generic, etc.)

-- | A 'PredType' annotated with the origin of the constraint 'CtOrigin',
-- and whether or the constraint deals in types or kinds.
data PredOrigin = PredOrigin PredType CtOrigin TypeOrKind

-- | A list of wanted 'PredOrigin' constraints ('to_wanted_origins') to
-- simplify when inferring a derived instance's context. These are used in all
-- deriving strategies, but in the particular case of @DeriveAnyClass@, we
-- need extra information. In particular, we need:
--
-- * 'to_anyclass_skols', the list of type variables bound by a class method's
--   regular type signature, which should be rigid.
--
-- * 'to_anyclass_metas', the list of type variables bound by a class method's
--   default type signature. These can be unified as necessary.
--
-- * 'to_anyclass_givens', the list of constraints from a class method's
--   regular type signature, which can be used to help solve constraints
--   in the 'to_wanted_origins'.
--
-- (Note that 'to_wanted_origins' will likely contain type variables from the
-- derived type class or data type, neither of which will appear in
-- 'to_anyclass_skols' or 'to_anyclass_metas'.)
--
-- For all other deriving strategies, it is always the case that
-- 'to_anyclass_skols', 'to_anyclass_metas', and 'to_anyclass_givens' are
-- empty.
--
-- Here is an example to illustrate this:
--
-- @
-- class Foo a where
--   bar :: forall b. Ix b => a -> b -> String
--   default bar :: forall y. (Show a, Ix y) => a -> y -> String
--   bar x y = show x ++ show (range (y, y))
--
--   baz :: Eq a => a -> a -> Bool
--   default baz :: Ord a => a -> a -> Bool
--   baz x y = compare x y == EQ
--
-- data Quux q = Quux deriving anyclass Foo
-- @
--
-- Then it would generate two 'ThetaOrigin's, one for each method:
--
-- @
-- [ ThetaOrigin { to_anyclass_skols  = [b]
--               , to_anyclass_metas  = [y]
--               , to_anyclass_givens = [Ix b]
--               , to_wanted_origins  = [ Show (Quux q), Ix y
--                                      , (Quux q -> b -> String) ~
--                                        (Quux q -> y -> String)
--                                      ] }
-- , ThetaOrigin { to_anyclass_skols  = []
--               , to_anyclass_metas  = []
--               , to_anyclass_givens = [Eq (Quux q)]
--               , to_wanted_origins  = [ Ord (Quux q)
--                                      , (Quux q -> Quux q -> Bool) ~
--                                        (Quux q -> Quux q -> Bool)
--                                      ] }
-- ]
-- @
--
-- (Note that the type variable @q@ is bound by the data type @Quux@, and thus
-- it appears in neither 'to_anyclass_skols' nor 'to_anyclass_metas'.)
--
-- See @Note [Gathering and simplifying constraints for DeriveAnyClass]@
-- in "TcDerivInfer" for an explanation of how 'to_wanted_origins' are
-- determined in @DeriveAnyClass@, as well as how 'to_anyclass_skols',
-- 'to_anyclass_metas', and 'to_anyclass_givens' are used.
data ThetaOrigin
  = ThetaOrigin { to_anyclass_skols  :: [TyVar]
                , to_anyclass_metas  :: [TyVar]
                , to_anyclass_givens :: ThetaType
                , to_wanted_origins  :: [PredOrigin] }

instance Outputable PredOrigin where
  ppr (PredOrigin ty _ _) = ppr ty -- The origin is not so interesting when debugging

instance Outputable ThetaOrigin where
  ppr (ThetaOrigin { to_anyclass_skols  = ac_skols
                   , to_anyclass_metas  = ac_metas
                   , to_anyclass_givens = ac_givens
                   , to_wanted_origins  = wanted_origins })
    = hang (text "ThetaOrigin")
         2 (vcat [ text "to_anyclass_skols  =" <+> ppr ac_skols
                 , text "to_anyclass_metas  =" <+> ppr ac_metas
                 , text "to_anyclass_givens =" <+> ppr ac_givens
                 , text "to_wanted_origins  =" <+> ppr wanted_origins ])

mkPredOrigin :: CtOrigin -> TypeOrKind -> PredType -> PredOrigin
mkPredOrigin origin t_or_k pred = PredOrigin pred origin t_or_k

mkThetaOrigin :: CtOrigin -> TypeOrKind
              -> [TyVar] -> [TyVar] -> ThetaType -> ThetaType
              -> ThetaOrigin
mkThetaOrigin origin t_or_k skols metas givens
  = ThetaOrigin skols metas givens . map (mkPredOrigin origin t_or_k)

-- A common case where the ThetaOrigin only contains wanted constraints, with
-- no givens or locally scoped type variables.
mkThetaOriginFromPreds :: [PredOrigin] -> ThetaOrigin
mkThetaOriginFromPreds = ThetaOrigin [] [] []

substPredOrigin :: HasCallStack => TCvSubst -> PredOrigin -> PredOrigin
substPredOrigin subst (PredOrigin pred origin t_or_k)
  = PredOrigin (substTy subst pred) origin t_or_k

{-
************************************************************************
*                                                                      *
                Class deriving diagnostics
*                                                                      *
************************************************************************

Only certain blessed classes can be used in a deriving clause (without the
assistance of GeneralizedNewtypeDeriving or DeriveAnyClass). These classes
are listed below in the definition of hasStockDeriving. The stockSideConditions
function determines the criteria that needs to be met in order for a particular
stock class to be able to be derived successfully.

A class might be able to be used in a deriving clause if -XDeriveAnyClass
is willing to support it. The canDeriveAnyClass function checks if this is the
case.
-}

hasStockDeriving
  :: Class -> Maybe (SrcSpan
                     -> TyCon
                     -> [Type]
                     -> TcM (LHsBinds GhcPs, BagDerivStuff, [Name]))
hasStockDeriving clas
  = assocMaybe gen_list (getUnique clas)
  where
    gen_list
      :: [(Unique, SrcSpan
                   -> TyCon
                   -> [Type]
                   -> TcM (LHsBinds GhcPs, BagDerivStuff, [Name]))]
    gen_list = [ (eqClassKey,          simpleM gen_Eq_binds)
               , (ordClassKey,         simpleM gen_Ord_binds)
               , (enumClassKey,        simpleM gen_Enum_binds)
               , (boundedClassKey,     simple gen_Bounded_binds)
               , (ixClassKey,          simpleM gen_Ix_binds)
               , (showClassKey,        read_or_show gen_Show_binds)
               , (readClassKey,        read_or_show gen_Read_binds)
               , (dataClassKey,        simpleM gen_Data_binds)
               , (functorClassKey,     simple gen_Functor_binds)
               , (foldableClassKey,    simple gen_Foldable_binds)
               , (traversableClassKey, simple gen_Traversable_binds)
               , (liftClassKey,        simple gen_Lift_binds)
               , (genClassKey,         generic (gen_Generic_binds Gen0))
               , (gen1ClassKey,        generic (gen_Generic_binds Gen1)) ]

    simple gen_fn loc tc _
      = let (binds, deriv_stuff) = gen_fn loc tc
        in return (binds, deriv_stuff, [])

    simpleM gen_fn loc tc _
      = do { (binds, deriv_stuff) <- gen_fn loc tc
           ; return (binds, deriv_stuff, []) }

    read_or_show gen_fn loc tc _
      = do { fix_env <- getDataConFixityFun tc
           ; let (binds, deriv_stuff) = gen_fn fix_env loc tc
                 field_names          = all_field_names tc
           ; return (binds, deriv_stuff, field_names) }

    generic gen_fn _ tc inst_tys
      = do { (binds, faminst) <- gen_fn tc inst_tys
           ; let field_names = all_field_names tc
           ; return (binds, unitBag (DerivFamInst faminst), field_names) }

    -- See Note [Deriving and unused record selectors]
    all_field_names = map flSelector . concatMap dataConFieldLabels
                                     . tyConDataCons

{-
Note [Deriving and unused record selectors]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider this (see Trac #13919):

  module Main (main) where

  data Foo = MkFoo {bar :: String} deriving Show

  main :: IO ()
  main = print (Foo "hello")

Strictly speaking, the record selector `bar` is unused in this module, since
neither `main` nor the derived `Show` instance for `Foo` mention `bar`.
However, the behavior of `main` is affected by the presence of `bar`, since
it will print different output depending on whether `MkFoo` is defined using
record selectors or not. Therefore, we do not to issue a
"Defined but not used: â€˜barâ€™" warning for this module, since removing `bar`
changes the program's behavior. This is the reason behind the [Name] part of
the return type of `hasStockDeriving`â€”it tracks all of the record selector
`Name`s for which -Wunused-binds should be suppressed.

Currently, the only three stock derived classes that require this are Read,
Show, and Generic, as their derived code all depend on the record selectors
of the derived data type's constructors.

See also Note [Newtype deriving and unused constructors] in TcDeriv for
another example of a similar trick.
-}

getDataConFixityFun :: TyCon -> TcM (Name -> Fixity)
-- If the TyCon is locally defined, we want the local fixity env;
-- but if it is imported (which happens for standalone deriving)
-- we need to get the fixity env from the interface file
-- c.f. RnEnv.lookupFixity, and Trac #9830
getDataConFixityFun tc
  = do { this_mod <- getModule
       ; if nameIsLocalOrFrom this_mod name
         then do { fix_env <- getFixityEnv
                 ; return (lookupFixity fix_env) }
         else do { iface <- loadInterfaceForName doc name
                            -- Should already be loaded!
                 ; return (mi_fix iface . nameOccName) } }
  where
    name = tyConName tc
    doc = text "Data con fixities for" <+> ppr name

------------------------------------------------------------------
-- Check side conditions that dis-allow derivability for the originative
-- deriving strategies (stock and anyclass).
-- See Note [Deriving strategies] in TcDeriv for an explanation of what
-- "originative" means.
--
-- This is *apart* from the coerce-based strategies, newtype and via.
--
-- Here we get the representation tycon in case of family instances as it has
-- the data constructors - but we need to be careful to fall back to the
-- family tycon (with indexes) in error messages.

checkOriginativeSideConditions
  :: DynFlags -> DerivContext -> Class -> [TcType]
  -> TyCon -> TyCon
  -> OriginativeDerivStatus
checkOriginativeSideConditions dflags deriv_ctxt cls cls_tys tc rep_tc
    -- First, check if stock deriving is possible...
  | Just cond <- stockSideConditions deriv_ctxt cls
  = case (cond dflags tc rep_tc) of
        NotValid err -> StockClassError err  -- Class-specific error
        IsValid  | null (filterOutInvisibleTypes (classTyCon cls) cls_tys)
                   -- All stock derivable classes are unary in the sense that
                   -- there should be not types in cls_tys (i.e., no type args
                   -- other than last). Note that cls_types can contain
                   -- invisible types as well (e.g., for Generic1, which is
                   -- poly-kinded), so make sure those are not counted.
                 , Just gen_fn <- hasStockDeriving cls
                   -> CanDeriveStock gen_fn
                 | otherwise -> StockClassError (classArgsErr cls cls_tys)
                   -- e.g. deriving( Eq s )

    -- ...if not, try falling back on DeriveAnyClass.
  | NotValid err <- canDeriveAnyClass dflags
  = NonDerivableClass err  -- Neither anyclass nor stock work

  | otherwise
  = CanDeriveAnyClass   -- DeriveAnyClass should work

classArgsErr :: Class -> [Type] -> SDoc
classArgsErr cls cls_tys = quotes (ppr (mkClassPred cls cls_tys)) <+> text "is not a class"

-- Side conditions (whether the datatype must have at least one constructor,
-- required language extensions, etc.) for using GHC's stock deriving
-- mechanism on certain classes (as opposed to classes that require
-- GeneralizedNewtypeDeriving or DeriveAnyClass). Returns Nothing for a
-- class for which stock deriving isn't possible.
stockSideConditions :: DerivContext -> Class -> Maybe Condition
stockSideConditions deriv_ctxt cls
  | cls_key == eqClassKey          = Just (cond_std `andCond` cond_args cls)
  | cls_key == ordClassKey         = Just (cond_std `andCond` cond_args cls)
  | cls_key == showClassKey        = Just (cond_std `andCond` cond_args cls)
  | cls_key == readClassKey        = Just (cond_std `andCond` cond_args cls)
  | cls_key == enumClassKey        = Just (cond_std `andCond` cond_isEnumeration)
  | cls_key == ixClassKey          = Just (cond_std `andCond` cond_enumOrProduct cls)
  | cls_key == boundedClassKey     = Just (cond_std `andCond` cond_enumOrProduct cls)
  | cls_key == dataClassKey        = Just (checkFlag LangExt.DeriveDataTypeable `andCond`
                                           cond_vanilla `andCond`
                                           cond_args cls)
  | cls_key == functorClassKey     = Just (checkFlag LangExt.DeriveFunctor `andCond`
                                           cond_vanilla `andCond`
                                           cond_functorOK True False)
  | cls_key == foldableClassKey    = Just (checkFlag LangExt.DeriveFoldable `andCond`
                                           cond_vanilla `andCond`
                                           cond_functorOK False True)
                                           -- Functor/Fold/Trav works ok
                                           -- for rank-n types
  | cls_key == traversableClassKey = Just (checkFlag LangExt.DeriveTraversable `andCond`
                                           cond_vanilla `andCond`
                                           cond_functorOK False False)
  | cls_key == genClassKey         = Just (checkFlag LangExt.DeriveGeneric `andCond`
                                           cond_vanilla `andCond`
                                           cond_RepresentableOk)
  | cls_key == gen1ClassKey        = Just (checkFlag LangExt.DeriveGeneric `andCond`
                                           cond_vanilla `andCond`
                                           cond_Representable1Ok)
  | cls_key == liftClassKey        = Just (checkFlag LangExt.DeriveLift `andCond`
                                           cond_vanilla `andCond`
                                           cond_args cls)
  | otherwise                      = Nothing
  where
    cls_key = getUnique cls
    cond_std     = cond_stdOK deriv_ctxt False
      -- Vanilla data constructors, at least one, and monotype arguments
    cond_vanilla = cond_stdOK deriv_ctxt True
      -- Vanilla data constructors but allow no data cons or polytype arguments

canDeriveAnyClass :: DynFlags -> Validity
-- IsValid: we can (try to) derive it via an empty instance declaration
-- NotValid s:  we can't, reason s
canDeriveAnyClass dflags
  | not (xopt LangExt.DeriveAnyClass dflags)
  = NotValid (text "Try enabling DeriveAnyClass")
  | otherwise
  = IsValid   -- OK!

type Condition
   = DynFlags

  -> TyCon    -- ^ The data type's 'TyCon'. For data families, this is the
              -- family 'TyCon'.

  -> TyCon    -- ^ For data families, this is the representation 'TyCon'.
              -- Otherwise, this is the same as the other 'TyCon' argument.

  -> Validity -- ^ 'IsValid' if deriving an instance for this 'TyCon' is
              -- possible. Otherwise, it's @'NotValid' err@, where @err@
              -- explains what went wrong.

orCond :: Condition -> Condition -> Condition
orCond c1 c2 dflags tc rep_tc
  = case (c1 dflags tc rep_tc, c2 dflags tc rep_tc) of
     (IsValid,    _)          -> IsValid    -- c1 succeeds
     (_,          IsValid)    -> IsValid    -- c21 succeeds
     (NotValid x, NotValid y) -> NotValid (x $$ text "  or" $$ y)
                                            -- Both fail

andCond :: Condition -> Condition -> Condition
andCond c1 c2 dflags tc rep_tc
  = c1 dflags tc rep_tc `andValid` c2 dflags tc rep_tc

-- | Some common validity checks shared among stock derivable classes. One
-- check that absolutely must hold is that if an instance @C (T a)@ is being
-- derived, then @T@ must be a tycon for a data type or a newtype. The
-- remaining checks are only performed if using a @deriving@ clause (i.e.,
-- they're ignored if using @StandaloneDeriving@):
--
-- 1. The data type must have at least one constructor (this check is ignored
--    if using @EmptyDataDeriving@).
--
-- 2. The data type cannot have any GADT constructors.
--
-- 3. The data type cannot have any constructors with existentially quantified
--    type variables.
--
-- 4. The data type cannot have a context (e.g., @data Foo a = Eq a => MkFoo@).
--
-- 5. The data type cannot have fields with higher-rank types.
cond_stdOK
  :: DerivContext -- ^ 'SupplyContext' if this is standalone deriving with a
                  -- user-supplied context, 'InferContext' if not.
                  -- If it is the former, we relax some of the validity checks
                  -- we would otherwise perform (i.e., "just go for it").

  -> Bool         -- ^ 'True' <=> allow higher rank arguments and empty data
                  -- types (with no data constructors) even in the absence of
                  -- the -XEmptyDataDeriving extension.

  -> Condition
cond_stdOK deriv_ctxt permissive dflags tc rep_tc
  = valid_ADT `andValid` valid_misc
  where
    valid_ADT, valid_misc :: Validity
    valid_ADT
      | isAlgTyCon tc || isDataFamilyTyCon tc
      = IsValid
      | otherwise
        -- Complain about functions, primitive types, and other tycons that
        -- stock deriving can't handle.
      = NotValid $ text "The last argument of the instance must be a"
               <+> text "data or newtype application"

    valid_misc
      = case deriv_ctxt of
         SupplyContext _ -> IsValid
                -- Don't check these conservative conditions for
                -- standalone deriving; just generate the code
                -- and let the typechecker handle the result
         InferContext wildcard
           | null data_cons -- 1.
           , not permissive
           -> checkFlag LangExt.EmptyDataDeriving dflags tc rep_tc `orValid`
              NotValid (no_cons_why rep_tc $$ empty_data_suggestion)
           | not (null con_whys)
           -> NotValid (vcat con_whys $$ possible_fix_suggestion wildcard)
           | otherwise
           -> IsValid

    empty_data_suggestion =
      text "Use EmptyDataDeriving to enable deriving for empty data types"
    possible_fix_suggestion wildcard
      = case wildcard of
          Just _ ->
            text "Possible fix: fill in the wildcard constraint yourself"
          Nothing ->
            text "Possible fix: use a standalone deriving declaration instead"
    data_cons  = tyConDataCons rep_tc
    con_whys   = getInvalids (map check_con data_cons)

    check_con :: DataCon -> Validity
    check_con con
      | not (null eq_spec) -- 2.
      = bad "is a GADT"
      | not (null ex_tvs) -- 3.
      = bad "has existential type variables in its type"
      | not (null theta) -- 4.
      = bad "has constraints in its type"
      | not (permissive || all isTauTy (dataConOrigArgTys con)) -- 5.
      = bad "has a higher-rank type"
      | otherwise
      = IsValid
      where
        (_, ex_tvs, eq_spec, theta, _, _) = dataConFullSig con
        bad msg = NotValid (badCon con (text msg))

no_cons_why :: TyCon -> SDoc
no_cons_why rep_tc = quotes (pprSourceTyCon rep_tc) <+>
                     text "must have at least one data constructor"

cond_RepresentableOk :: Condition
cond_RepresentableOk _ _ rep_tc = canDoGenerics rep_tc

cond_Representable1Ok :: Condition
cond_Representable1Ok _ _ rep_tc = canDoGenerics1 rep_tc

cond_enumOrProduct :: Class -> Condition
cond_enumOrProduct cls = cond_isEnumeration `orCond`
                         (cond_isProduct `andCond` cond_args cls)

cond_args :: Class -> Condition
-- For some classes (eg Eq, Ord) we allow unlifted arg types
-- by generating specialised code.  For others (eg Data) we don't.
cond_args cls _ _ rep_tc
  = case bad_args of
      []     -> IsValid
      (ty:_) -> NotValid (hang (text "Don't know how to derive" <+> quotes (ppr cls))
                             2 (text "for type" <+> quotes (ppr ty)))
  where
    bad_args = [ arg_ty | con <- tyConDataCons rep_tc
                        , arg_ty <- dataConOrigArgTys con
                        , isUnliftedType arg_ty
                        , not (ok_ty arg_ty) ]

    cls_key = classKey cls
    ok_ty arg_ty
     | cls_key == eqClassKey   = check_in arg_ty ordOpTbl
     | cls_key == ordClassKey  = check_in arg_ty ordOpTbl
     | cls_key == showClassKey = check_in arg_ty boxConTbl
     | cls_key == liftClassKey = check_in arg_ty litConTbl
     | otherwise               = False    -- Read, Ix etc

    check_in :: Type -> [(Type,a)] -> Bool
    check_in arg_ty tbl = any (eqType arg_ty . fst) tbl

cond_isEnumeration :: Condition
cond_isEnumeration _ _ rep_tc
  | isEnumerationTyCon rep_tc = IsValid
  | otherwise                 = NotValid why
  where
    why = sep [ quotes (pprSourceTyCon rep_tc) <+>
                  text "must be an enumeration type"
              , text "(an enumeration consists of one or more nullary, non-GADT constructors)" ]
                  -- See Note [Enumeration types] in TyCon

cond_isProduct :: Condition
cond_isProduct _ _ rep_tc
  | isProductTyCon rep_tc = IsValid
  | otherwise             = NotValid why
  where
    why = quotes (pprSourceTyCon rep_tc) <+>
          text "must have precisely one constructor"

cond_functorOK :: Bool -> Bool -> Condition
-- OK for Functor/Foldable/Traversable class
-- Currently: (a) at least one argument
--            (b) don't use argument contravariantly
--            (c) don't use argument in the wrong place, e.g. data T a = T (X a a)
--            (d) optionally: don't use function types
--            (e) no "stupid context" on data type
cond_functorOK allowFunctions allowExQuantifiedLastTyVar _ _ rep_tc
  | null tc_tvs
  = NotValid (text "Data type" <+> quotes (ppr rep_tc)
              <+> text "must have some type parameters")

  | not (null bad_stupid_theta)
  = NotValid (text "Data type" <+> quotes (ppr rep_tc)
              <+> text "must not have a class context:" <+> pprTheta bad_stupid_theta)

  | otherwise
  = allValid (map check_con data_cons)
  where
    tc_tvs            = tyConTyVars rep_tc
    last_tv           = last tc_tvs
    bad_stupid_theta  = filter is_bad (tyConStupidTheta rep_tc)
    is_bad pred       = last_tv `elemVarSet` exactTyCoVarsOfType pred
      -- See Note [Check that the type variable is truly universal]

    data_cons = tyConDataCons rep_tc
    check_con con = allValid (check_universal con : foldDataConArgs (ft_check con) con)

    check_universal :: DataCon -> Validity
    check_universal con
      | allowExQuantifiedLastTyVar
      = IsValid -- See Note [DeriveFoldable with ExistentialQuantification]
                -- in TcGenFunctor
      | Just tv <- getTyVar_maybe (last (tyConAppArgs (dataConOrigResTy con)))
      , tv `elem` dataConUnivTyVars con
      , not (tv `elemVarSet` exactTyCoVarsOfTypes (dataConTheta con))
      = IsValid   -- See Note [Check that the type variable is truly universal]
      | otherwise
      = NotValid (badCon con existential)

    ft_check :: DataCon -> FFoldType Validity
    ft_check con = FT { ft_triv = IsValid, ft_var = IsValid
                      , ft_co_var = NotValid (badCon con covariant)
                      , ft_fun = \x y -> if allowFunctions then x `andValid` y
                                                           else NotValid (badCon con functions)
                      , ft_tup = \_ xs  -> allValid xs
                      , ft_ty_app = \_ x   -> x
                      , ft_bad_app = NotValid (badCon con wrong_arg)
                      , ft_forall = \_ x   -> x }

    existential = text "must be truly polymorphic in the last argument of the data type"
    covariant   = text "must not use the type variable in a function argument"
    functions   = text "must not contain function types"
    wrong_arg   = text "must use the type variable only as the last argument of a data type"

checkFlag :: LangExt.Extension -> Condition
checkFlag flag dflags _ _
  | xopt flag dflags = IsValid
  | otherwise        = NotValid why
  where
    why = text "You need " <> text flag_str
          <+> text "to derive an instance for this class"
    flag_str = case [ flagSpecName f | f <- xFlags , flagSpecFlag f == flag ] of
                 [s]   -> s
                 other -> pprPanic "checkFlag" (ppr other)

std_class_via_coercible :: Class -> Bool
-- These standard classes can be derived for a newtype
-- using the coercible trick *even if no -XGeneralizedNewtypeDeriving
-- because giving so gives the same results as generating the boilerplate
std_class_via_coercible clas
  = classKey clas `elem` [eqClassKey, ordClassKey, ixClassKey, boundedClassKey]
        -- Not Read/Show because they respect the type
        -- Not Enum, because newtypes are never in Enum

non_coercible_class :: Class -> Bool
-- *Never* derive Read, Show, Typeable, Data, Generic, Generic1, Lift
-- by Coercible, even with -XGeneralizedNewtypeDeriving
-- Also, avoid Traversable, as the Coercible-derived instance and the "normal"-derived
-- instance behave differently if there's a non-lawful Applicative out there.
-- Besides, with roles, Coercible-deriving Traversable is ill-roled.
non_coercible_class cls
  = classKey cls `elem` ([ readClassKey, showClassKey, dataClassKey
                         , genClassKey, gen1ClassKey, typeableClassKey
                         , traversableClassKey, liftClassKey ])

badCon :: DataCon -> SDoc -> SDoc
badCon con msg = text "Constructor" <+> quotes (ppr con) <+> msg

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

newDerivClsInst :: ThetaType -> DerivSpec theta -> TcM ClsInst
newDerivClsInst theta (DS { ds_name = dfun_name, ds_overlap = overlap_mode
                          , ds_tvs = tvs, ds_cls = clas, ds_tys = tys })
  = newClsInst overlap_mode dfun_name tvs theta clas tys

extendLocalInstEnv :: [ClsInst] -> TcM a -> TcM a
-- Add new locally-defined instances; don't bother to check
-- for functional dependency errors -- that'll happen in TcInstDcls
extendLocalInstEnv dfuns thing_inside
 = do { env <- getGblEnv
      ; let  inst_env' = extendInstEnvList (tcg_inst_env env) dfuns
             env'      = env { tcg_inst_env = inst_env' }
      ; setGblEnv env' thing_inside }

{-
Note [Deriving any class]
~~~~~~~~~~~~~~~~~~~~~~~~~
Classic uses of a deriving clause, or a standalone-deriving declaration, are
for:
  * a stock class like Eq or Show, for which GHC knows how to generate
    the instance code
  * a newtype, via the mechanism enabled by GeneralizedNewtypeDeriving

The DeriveAnyClass extension adds a third way to derive instances, based on
empty instance declarations.

The canonical use case is in combination with GHC.Generics and default method
signatures. These allow us to have instance declarations being empty, but still
useful, e.g.

  data T a = ...blah..blah... deriving( Generic )
  instance C a => C (T a)  -- No 'where' clause

where C is some "random" user-defined class.

This boilerplate code can be replaced by the more compact

  data T a = ...blah..blah... deriving( Generic, C )

if DeriveAnyClass is enabled.

This is not restricted to Generics; any class can be derived, simply giving
rise to an empty instance.

Unfortunately, it is not clear how to determine the context (when using a
deriving clause; in standalone deriving, the user provides the context).
GHC uses the same heuristic for figuring out the class context that it uses for
Eq in the case of *-kinded classes, and for Functor in the case of
* -> *-kinded classes. That may not be optimal or even wrong. But in such
cases, standalone deriving can still be used.

Note [Check that the type variable is truly universal]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For Functor and Traversable instances, we must check that the *last argument*
of the type constructor is used truly universally quantified.  Example

   data T a b where
     T1 :: a -> b -> T a b      -- Fine! Vanilla H-98
     T2 :: b -> c -> T a b      -- Fine! Existential c, but we can still map over 'b'
     T3 :: b -> T Int b         -- Fine! Constraint 'a', but 'b' is still polymorphic
     T4 :: Ord b => b -> T a b  -- No!  'b' is constrained
     T5 :: b -> T b b           -- No!  'b' is constrained
     T6 :: T a (b,b)            -- No!  'b' is constrained

Notice that only the first of these constructors is vanilla H-98. We only
need to take care about the last argument (b in this case).  See Trac #8678.
Eg. for T1-T3 we can write

     fmap f (T1 a b) = T1 a (f b)
     fmap f (T2 b c) = T2 (f b) c
     fmap f (T3 x)   = T3 (f x)

We need not perform these checks for Foldable instances, however, since
functions in Foldable can only consume existentially quantified type variables,
rather than produce them (as is the case in Functor and Traversable functions.)
As a result, T can have a derived Foldable instance:

    foldr f z (T1 a b) = f b z
    foldr f z (T2 b c) = f b z
    foldr f z (T3 x)   = f x z
    foldr f z (T4 x)   = f x z
    foldr f z (T5 x)   = f x z
    foldr _ z T6       = z

See Note [DeriveFoldable with ExistentialQuantification] in TcGenFunctor.

For Functor and Traversable, we must take care not to let type synonyms
unfairly reject a type for not being truly universally quantified. An
example of this is:

    type C (a :: Constraint) b = a
    data T a b = C (Show a) b => MkT b

Here, the existential context (C (Show a) b) does technically mention the last
type variable b. But this is OK, because expanding the type synonym C would
give us the context (Show a), which doesn't mention b. Therefore, we must make
sure to expand type synonyms before performing this check. Not doing so led to
Trac #13813.
-}