{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveFunctor #-}

module GHC.Tc.Solver.Canonical(
     canonicalize,
     unifyDerived,
     makeSuperClasses, maybeSym,
     StopOrContinue(..), stopWith, continueWith,
     solveCallStack    -- For GHC.Tc.Solver
  ) where

#include "HsVersions.h"

import GHC.Prelude

import GHC.Tc.Types.Constraint
import GHC.Core.Predicate
import GHC.Tc.Types.Origin
import GHC.Tc.Utils.Unify( swapOverTyVars, metaTyVarUpdateOK, MetaTyVarUpdateResult(..) )
import GHC.Tc.Utils.TcType
import GHC.Core.Type
import GHC.Tc.Solver.Flatten
import GHC.Tc.Solver.Monad
import GHC.Tc.Types.Evidence
import GHC.Tc.Types.EvTerm
import GHC.Core.Class
import GHC.Core.TyCon
import GHC.Core.Multiplicity
import GHC.Core.TyCo.Rep   -- cleverly decomposes types, good for completeness checking
import GHC.Core.Coercion
import GHC.Core
import GHC.Types.Id( mkTemplateLocals )
import GHC.Core.FamInstEnv ( FamInstEnvs )
import GHC.Tc.Instance.Family ( tcTopNormaliseNewTypeTF_maybe )
import GHC.Types.Var
import GHC.Types.Var.Env( mkInScopeSet )
import GHC.Types.Var.Set( delVarSetList )
import GHC.Utils.Outputable
import GHC.Driver.Session( DynFlags )
import GHC.Types.Name.Set
import GHC.Types.Name.Reader
import GHC.Hs.Type( HsIPName(..) )

import GHC.Data.Pair
import GHC.Utils.Misc
import GHC.Data.Bag
import GHC.Utils.Monad
import Control.Monad
import Data.Maybe ( isJust )
import Data.List  ( zip4 )
import GHC.Types.Basic

import Data.Bifunctor ( bimap )
import Data.Foldable ( traverse_ )

{-
************************************************************************
*                                                                      *
*                      The Canonicaliser                               *
*                                                                      *
************************************************************************

Note [Canonicalization]
~~~~~~~~~~~~~~~~~~~~~~~

Canonicalization converts a simple constraint to a canonical form. It is
unary (i.e. treats individual constraints one at a time).

Constraints originating from user-written code come into being as
CNonCanonicals. We know nothing about these constraints. So, first:

     Classify CNonCanoncal constraints, depending on whether they
     are equalities, class predicates, or other.

Then proceed depending on the shape of the constraint. Generally speaking,
each constraint gets flattened and then decomposed into one of several forms
(see type Ct in GHC.Tc.Types).

When an already-canonicalized constraint gets kicked out of the inert set,
it must be recanonicalized. But we know a bit about its shape from the
last time through, so we can skip the classification step.

-}

-- Top-level canonicalization
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

canonicalize :: Ct -> TcS (StopOrContinue Ct)
canonicalize :: Ct -> TcS (StopOrContinue Ct)
canonicalize (CNonCanonical { cc_ev :: Ct -> CtEvidence
cc_ev = CtEvidence
ev })
  = {-# SCC "canNC" #-}
    case TcType -> Pred
classifyPredType TcType
pred of
      ClassPred Class
cls [TcType]
tys     -> do String -> SDoc -> TcS ()
traceTcS String
"canEvNC:cls" (Class -> SDoc
forall a. Outputable a => a -> SDoc
ppr Class
cls SDoc -> SDoc -> SDoc
<+> [TcType] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [TcType]
tys)
                                  CtEvidence -> Class -> [TcType] -> TcS (StopOrContinue Ct)
canClassNC CtEvidence
ev Class
cls [TcType]
tys
      EqPred EqRel
eq_rel TcType
ty1 TcType
ty2 -> do String -> SDoc -> TcS ()
traceTcS String
"canEvNC:eq" (TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
ty1 SDoc -> SDoc -> SDoc
$$ TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
ty2)
                                  CtEvidence -> EqRel -> TcType -> TcType -> TcS (StopOrContinue Ct)
canEqNC    CtEvidence
ev EqRel
eq_rel TcType
ty1 TcType
ty2
      IrredPred {}          -> do String -> SDoc -> TcS ()
traceTcS String
"canEvNC:irred" (TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
pred)
                                  CtIrredStatus -> CtEvidence -> TcS (StopOrContinue Ct)
canIrred CtIrredStatus
OtherCIS CtEvidence
ev
      ForAllPred [TcTyVar]
tvs [TcType]
theta TcType
p -> do String -> SDoc -> TcS ()
traceTcS String
"canEvNC:forall" (TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
pred)
                                   CtEvidence
-> [TcTyVar] -> [TcType] -> TcType -> TcS (StopOrContinue Ct)
canForAllNC CtEvidence
ev [TcTyVar]
tvs [TcType]
theta TcType
p
  where
    pred :: TcType
pred = CtEvidence -> TcType
ctEvPred CtEvidence
ev

canonicalize (CQuantCan (QCI { qci_ev :: QCInst -> CtEvidence
qci_ev = CtEvidence
ev, qci_pend_sc :: QCInst -> Bool
qci_pend_sc = Bool
pend_sc }))
  = CtEvidence -> Bool -> TcS (StopOrContinue Ct)
canForAll CtEvidence
ev Bool
pend_sc

canonicalize (CIrredCan { cc_ev :: Ct -> CtEvidence
cc_ev = CtEvidence
ev, cc_status :: Ct -> CtIrredStatus
cc_status = CtIrredStatus
status })
  | EqPred EqRel
eq_rel TcType
ty1 TcType
ty2 <- TcType -> Pred
classifyPredType (CtEvidence -> TcType
ctEvPred CtEvidence
ev)
  = -- For insolubles (all of which are equalities, do /not/ flatten the arguments
    -- In #14350 doing so led entire-unnecessary and ridiculously large
    -- type function expansion.  Instead, canEqNC just applies
    -- the substitution to the predicate, and may do decomposition;
    --    e.g. a ~ [a], where [G] a ~ [Int], can decompose
    CtEvidence -> EqRel -> TcType -> TcType -> TcS (StopOrContinue Ct)
canEqNC CtEvidence
ev EqRel
eq_rel TcType
ty1 TcType
ty2

  | Bool
otherwise
  = CtIrredStatus -> CtEvidence -> TcS (StopOrContinue Ct)
canIrred CtIrredStatus
status CtEvidence
ev

canonicalize (CDictCan { cc_ev :: Ct -> CtEvidence
cc_ev = CtEvidence
ev, cc_class :: Ct -> Class
cc_class  = Class
cls
                       , cc_tyargs :: Ct -> [TcType]
cc_tyargs = [TcType]
xis, cc_pend_sc :: Ct -> Bool
cc_pend_sc = Bool
pend_sc })
  = {-# SCC "canClass" #-}
    CtEvidence -> Class -> [TcType] -> Bool -> TcS (StopOrContinue Ct)
canClass CtEvidence
ev Class
cls [TcType]
xis Bool
pend_sc

canonicalize (CTyEqCan { cc_ev :: Ct -> CtEvidence
cc_ev = CtEvidence
ev
                       , cc_tyvar :: Ct -> TcTyVar
cc_tyvar  = TcTyVar
tv
                       , cc_rhs :: Ct -> TcType
cc_rhs    = TcType
xi
                       , cc_eq_rel :: Ct -> EqRel
cc_eq_rel = EqRel
eq_rel })
  = {-# SCC "canEqLeafTyVarEq" #-}
    CtEvidence -> EqRel -> TcType -> TcType -> TcS (StopOrContinue Ct)
canEqNC CtEvidence
ev EqRel
eq_rel (TcTyVar -> TcType
mkTyVarTy TcTyVar
tv) TcType
xi
      -- NB: Don't use canEqTyVar because that expects flattened types,
      -- and tv and xi may not be flat w.r.t. an updated inert set

canonicalize (CFunEqCan { cc_ev :: Ct -> CtEvidence
cc_ev = CtEvidence
ev
                        , cc_fun :: Ct -> TyCon
cc_fun    = TyCon
fn
                        , cc_tyargs :: Ct -> [TcType]
cc_tyargs = [TcType]
xis1
                        , cc_fsk :: Ct -> TcTyVar
cc_fsk    = TcTyVar
fsk })
  = {-# SCC "canEqLeafFunEq" #-}
    CtEvidence
-> TyCon -> [TcType] -> TcTyVar -> TcS (StopOrContinue Ct)
canCFunEqCan CtEvidence
ev TyCon
fn [TcType]
xis1 TcTyVar
fsk

{-
************************************************************************
*                                                                      *
*                      Class Canonicalization
*                                                                      *
************************************************************************
-}

canClassNC :: CtEvidence -> Class -> [Type] -> TcS (StopOrContinue Ct)
-- "NC" means "non-canonical"; that is, we have got here
-- from a NonCanonical constraint, not from a CDictCan
-- Precondition: EvVar is class evidence
canClassNC :: CtEvidence -> Class -> [TcType] -> TcS (StopOrContinue Ct)
canClassNC CtEvidence
ev Class
cls [TcType]
tys
  | CtEvidence -> Bool
isGiven CtEvidence
ev  -- See Note [Eagerly expand given superclasses]
  = do { [Ct]
sc_cts <- CtEvidence
-> [TcTyVar] -> [TcType] -> Class -> [TcType] -> TcS [Ct]
mkStrictSuperClasses CtEvidence
ev [] [] Class
cls [TcType]
tys
       ; [Ct] -> TcS ()
emitWork [Ct]
sc_cts
       ; CtEvidence -> Class -> [TcType] -> Bool -> TcS (StopOrContinue Ct)
canClass CtEvidence
ev Class
cls [TcType]
tys Bool
False }

  | CtEvidence -> Bool
isWanted CtEvidence
ev
  , Just FastString
ip_name <- Class -> [TcType] -> Maybe FastString
isCallStackPred Class
cls [TcType]
tys
  , OccurrenceOf Name
func <- CtLoc -> CtOrigin
ctLocOrigin CtLoc
loc
  -- If we're given a CallStack constraint that arose from a function
  -- call, we need to push the current call-site onto the stack instead
  -- of solving it directly from a given.
  -- See Note [Overview of implicit CallStacks] in GHC.Tc.Types.Evidence
  -- and Note [Solving CallStack constraints] in GHC.Tc.Solver.Monad
  = do { -- First we emit a new constraint that will capture the
         -- given CallStack.
       ; let new_loc :: CtLoc
new_loc = CtLoc -> CtOrigin -> CtLoc
setCtLocOrigin CtLoc
loc (HsIPName -> CtOrigin
IPOccOrigin (FastString -> HsIPName
HsIPName FastString
ip_name))
                            -- We change the origin to IPOccOrigin so
                            -- this rule does not fire again.
                            -- See Note [Overview of implicit CallStacks]

       ; CtEvidence
new_ev <- CtLoc -> TcType -> TcS CtEvidence
newWantedEvVarNC CtLoc
new_loc TcType
pred

         -- Then we solve the wanted by pushing the call-site
         -- onto the newly emitted CallStack
       ; let ev_cs :: EvCallStack
ev_cs = Name -> RealSrcSpan -> EvExpr -> EvCallStack
EvCsPushCall Name
func (CtLoc -> RealSrcSpan
ctLocSpan CtLoc
loc) (CtEvidence -> EvExpr
ctEvExpr CtEvidence
new_ev)
       ; CtEvidence -> EvCallStack -> TcS ()
solveCallStack CtEvidence
ev EvCallStack
ev_cs

       ; CtEvidence -> Class -> [TcType] -> Bool -> TcS (StopOrContinue Ct)
canClass CtEvidence
new_ev Class
cls [TcType]
tys Bool
False }

  | Bool
otherwise
  = CtEvidence -> Class -> [TcType] -> Bool -> TcS (StopOrContinue Ct)
canClass CtEvidence
ev Class
cls [TcType]
tys (Class -> Bool
has_scs Class
cls)

  where
    has_scs :: Class -> Bool
has_scs Class
cls = Bool -> Bool
not ([TcType] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null (Class -> [TcType]
classSCTheta Class
cls))
    loc :: CtLoc
loc  = CtEvidence -> CtLoc
ctEvLoc CtEvidence
ev
    pred :: TcType
pred = CtEvidence -> TcType
ctEvPred CtEvidence
ev

solveCallStack :: CtEvidence -> EvCallStack -> TcS ()
-- Also called from GHC.Tc.Solver when defaulting call stacks
solveCallStack :: CtEvidence -> EvCallStack -> TcS ()
solveCallStack CtEvidence
ev EvCallStack
ev_cs = do
  -- We're given ev_cs :: CallStack, but the evidence term should be a
  -- dictionary, so we have to coerce ev_cs to a dictionary for
  -- `IP ip CallStack`. See Note [Overview of implicit CallStacks]
  EvExpr
cs_tm <- EvCallStack -> TcS EvExpr
forall (m :: * -> *).
(MonadThings m, HasModule m, HasDynFlags m) =>
EvCallStack -> m EvExpr
evCallStack EvCallStack
ev_cs
  let ev_tm :: EvTerm
ev_tm = EvExpr -> TcCoercion -> EvTerm
mkEvCast EvExpr
cs_tm (TcType -> TcCoercion
wrapIP (CtEvidence -> TcType
ctEvPred CtEvidence
ev))
  CtEvidence -> EvTerm -> TcS ()
setEvBindIfWanted CtEvidence
ev EvTerm
ev_tm

canClass :: CtEvidence
         -> Class -> [Type]
         -> Bool            -- True <=> un-explored superclasses
         -> TcS (StopOrContinue Ct)
-- Precondition: EvVar is class evidence

canClass :: CtEvidence -> Class -> [TcType] -> Bool -> TcS (StopOrContinue Ct)
canClass CtEvidence
ev Class
cls [TcType]
tys Bool
pend_sc
  =   -- all classes do *nominal* matching
    ASSERT2( ctEvRole ev == Nominal, ppr ev $$ ppr cls $$ ppr tys )
    do { ([TcType]
xis, [TcCoercion]
cos, TcCoercion
_kind_co) <- CtEvidence
-> TyCon -> [TcType] -> TcS ([TcType], [TcCoercion], TcCoercion)
flattenArgsNom CtEvidence
ev TyCon
cls_tc [TcType]
tys
       ; MASSERT( isTcReflCo _kind_co )
       ; let co :: TcCoercion
co = Role -> TyCon -> [TcCoercion] -> TcCoercion
mkTcTyConAppCo Role
Nominal TyCon
cls_tc [TcCoercion]
cos
             xi :: TcType
xi = Class -> [TcType] -> TcType
mkClassPred Class
cls [TcType]
xis
             mk_ct :: CtEvidence -> Ct
mk_ct CtEvidence
new_ev = CDictCan :: CtEvidence -> Class -> [TcType] -> Bool -> Ct
CDictCan { cc_ev :: CtEvidence
cc_ev = CtEvidence
new_ev
                                     , cc_tyargs :: [TcType]
cc_tyargs = [TcType]
xis
                                     , cc_class :: Class
cc_class = Class
cls
                                     , cc_pend_sc :: Bool
cc_pend_sc = Bool
pend_sc }
       ; StopOrContinue CtEvidence
mb <- CtEvidence
-> TcType -> TcCoercion -> TcS (StopOrContinue CtEvidence)
rewriteEvidence CtEvidence
ev TcType
xi TcCoercion
co
       ; String -> SDoc -> TcS ()
traceTcS String
"canClass" ([SDoc] -> SDoc
vcat [ CtEvidence -> SDoc
forall a. Outputable a => a -> SDoc
ppr CtEvidence
ev
                                   , TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
xi, StopOrContinue CtEvidence -> SDoc
forall a. Outputable a => a -> SDoc
ppr StopOrContinue CtEvidence
mb ])
       ; StopOrContinue Ct -> TcS (StopOrContinue Ct)
forall (m :: * -> *) a. Monad m => a -> m a
return ((CtEvidence -> Ct)
-> StopOrContinue CtEvidence -> StopOrContinue Ct
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap CtEvidence -> Ct
mk_ct StopOrContinue CtEvidence
mb) }
  where
    cls_tc :: TyCon
cls_tc = Class -> TyCon
classTyCon Class
cls

{- Note [The superclass story]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We need to add superclass constraints for two reasons:

* For givens [G], they give us a route to proof.  E.g.
    f :: Ord a => a -> Bool
    f x = x == x
  We get a Wanted (Eq a), which can only be solved from the superclass
  of the Given (Ord a).

* For wanteds [W], and deriveds [WD], [D], they may give useful
  functional dependencies.  E.g.
     class C a b | a -> b where ...
     class C a b => D a b where ...
  Now a [W] constraint (D Int beta) has (C Int beta) as a superclass
  and that might tell us about beta, via C's fundeps.  We can get this
  by generating a [D] (C Int beta) constraint.  It's derived because
  we don't actually have to cough up any evidence for it; it's only there
  to generate fundep equalities.

See Note [Why adding superclasses can help].

For these reasons we want to generate superclass constraints for both
Givens and Wanteds. But:

* (Minor) they are often not needed, so generating them aggressively
  is a waste of time.

* (Major) if we want recursive superclasses, there would be an infinite
  number of them.  Here is a real-life example (#10318);

     class (Frac (Frac a) ~ Frac a,
            Fractional (Frac a),
            IntegralDomain (Frac a))
         => IntegralDomain a where
      type Frac a :: *

  Notice that IntegralDomain has an associated type Frac, and one
  of IntegralDomain's superclasses is another IntegralDomain constraint.

So here's the plan:

1. Eagerly generate superclasses for given (but not wanted)
   constraints; see Note [Eagerly expand given superclasses].
   This is done using mkStrictSuperClasses in canClassNC, when
   we take a non-canonical Given constraint and cannonicalise it.

   However stop if you encounter the same class twice.  That is,
   mkStrictSuperClasses expands eagerly, but has a conservative
   termination condition: see Note [Expanding superclasses] in GHC.Tc.Utils.TcType.

2. Solve the wanteds as usual, but do no further expansion of
   superclasses for canonical CDictCans in solveSimpleGivens or
   solveSimpleWanteds; Note [Danger of adding superclasses during solving]

   However, /do/ continue to eagerly expand superclasses for new /given/
   /non-canonical/ constraints (canClassNC does this).  As #12175
   showed, a type-family application can expand to a class constraint,
   and we want to see its superclasses for just the same reason as
   Note [Eagerly expand given superclasses].

3. If we have any remaining unsolved wanteds
        (see Note [When superclasses help] in GHC.Tc.Types.Constraint)
   try harder: take both the Givens and Wanteds, and expand
   superclasses again.  See the calls to expandSuperClasses in
   GHC.Tc.Solver.simpl_loop and solveWanteds.

   This may succeed in generating (a finite number of) extra Givens,
   and extra Deriveds. Both may help the proof.

3a An important wrinkle: only expand Givens from the current level.
   Two reasons:
      - We only want to expand it once, and that is best done at
        the level it is bound, rather than repeatedly at the leaves
        of the implication tree
      - We may be inside a type where we can't create term-level
        evidence anyway, so we can't superclass-expand, say,
        (a ~ b) to get (a ~# b).  This happened in #15290.

4. Go round to (2) again.  This loop (2,3,4) is implemented
   in GHC.Tc.Solver.simpl_loop.

The cc_pend_sc flag in a CDictCan records whether the superclasses of
this constraint have been expanded.  Specifically, in Step 3 we only
expand superclasses for constraints with cc_pend_sc set to true (i.e.
isPendingScDict holds).

Why do we do this?  Two reasons:

* To avoid repeated work, by repeatedly expanding the superclasses of
  same constraint,

* To terminate the above loop, at least in the -XNoRecursiveSuperClasses
  case.  If there are recursive superclasses we could, in principle,
  expand forever, always encountering new constraints.

When we take a CNonCanonical or CIrredCan, but end up classifying it
as a CDictCan, we set the cc_pend_sc flag to False.

Note [Superclass loops]
~~~~~~~~~~~~~~~~~~~~~~~
Suppose we have
  class C a => D a
  class D a => C a

Then, when we expand superclasses, we'll get back to the self-same
predicate, so we have reached a fixpoint in expansion and there is no
point in fruitlessly expanding further.  This case just falls out from
our strategy.  Consider
  f :: C a => a -> Bool
  f x = x==x
Then canClassNC gets the [G] d1: C a constraint, and eager emits superclasses
G] d2: D a, [G] d3: C a (psc).  (The "psc" means it has its sc_pend flag set.)
When processing d3 we find a match with d1 in the inert set, and we always
keep the inert item (d1) if possible: see Note [Replacement vs keeping] in
GHC.Tc.Solver.Interact.  So d3 dies a quick, happy death.

Note [Eagerly expand given superclasses]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In step (1) of Note [The superclass story], why do we eagerly expand
Given superclasses by one layer?  (By "one layer" we mean expand transitively
until you meet the same class again -- the conservative criterion embodied
in expandSuperClasses.  So a "layer" might be a whole stack of superclasses.)
We do this eagerly for Givens mainly because of some very obscure
cases like this:

   instance Bad a => Eq (T a)

   f :: (Ord (T a)) => blah
   f x = ....needs Eq (T a), Ord (T a)....

Here if we can't satisfy (Eq (T a)) from the givens we'll use the
instance declaration; but then we are stuck with (Bad a).  Sigh.
This is really a case of non-confluent proofs, but to stop our users
complaining we expand one layer in advance.

Note [Instance and Given overlap] in GHC.Tc.Solver.Interact.

We also want to do this if we have

   f :: F (T a) => blah

where
   type instance F (T a) = Ord (T a)

So we may need to do a little work on the givens to expose the
class that has the superclasses.  That's why the superclass
expansion for Givens happens in canClassNC.

This same scenario happens with quantified constraints, whose superclasses
are also eagerly expanded. Test case: typecheck/should_compile/T16502b
These are handled in canForAllNC, analogously to canClassNC.

Note [Why adding superclasses can help]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Examples of how adding superclasses can help:

    --- Example 1
        class C a b | a -> b
    Suppose we want to solve
         [G] C a b
         [W] C a beta
    Then adding [D] beta~b will let us solve it.

    -- Example 2 (similar but using a type-equality superclass)
        class (F a ~ b) => C a b
    And try to sllve:
         [G] C a b
         [W] C a beta
    Follow the superclass rules to add
         [G] F a ~ b
         [D] F a ~ beta
    Now we get [D] beta ~ b, and can solve that.

    -- Example (tcfail138)
      class L a b | a -> b
      class (G a, L a b) => C a b

      instance C a b' => G (Maybe a)
      instance C a b  => C (Maybe a) a
      instance L (Maybe a) a

    When solving the superclasses of the (C (Maybe a) a) instance, we get
      [G] C a b, and hance by superclasses, [G] G a, [G] L a b
      [W] G (Maybe a)
    Use the instance decl to get
      [W] C a beta
    Generate its derived superclass
      [D] L a beta.  Now using fundeps, combine with [G] L a b to get
      [D] beta ~ b
    which is what we want.

Note [Danger of adding superclasses during solving]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Here's a serious, but now out-dated example, from #4497:

   class Num (RealOf t) => Normed t
   type family RealOf x

Assume the generated wanted constraint is:
   [W] RealOf e ~ e
   [W] Normed e

If we were to be adding the superclasses during simplification we'd get:
   [W] RealOf e ~ e
   [W] Normed e
   [D] RealOf e ~ fuv
   [D] Num fuv
==>
   e := fuv, Num fuv, Normed fuv, RealOf fuv ~ fuv

While looks exactly like our original constraint. If we add the
superclass of (Normed fuv) again we'd loop.  By adding superclasses
definitely only once, during canonicalisation, this situation can't
happen.

Mind you, now that Wanteds cannot rewrite Derived, I think this particular
situation can't happen.

Note [Nested quantified constraint superclasses]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider (typecheck/should_compile/T17202)

  class C1 a
  class (forall c. C1 c) => C2 a
  class (forall b. (b ~ F a) => C2 a) => C3 a

Elsewhere in the code, we get a [G] g1 :: C3 a. We expand its superclass
to get [G] g2 :: (forall b. (b ~ F a) => C2 a). This constraint has a
superclass, as well. But we now must be careful: we cannot just add
(forall c. C1 c) as a Given, because we need to remember g2's context.
That new constraint is Given only when forall b. (b ~ F a) is true.

It's tempting to make the new Given be (forall b. (b ~ F a) => forall c. C1 c),
but that's problematic, because it's nested, and ForAllPred is not capable
of representing a nested quantified constraint. (We could change ForAllPred
to allow this, but the solution in this Note is much more local and simpler.)

So, we swizzle it around to get (forall b c. (b ~ F a) => C1 c).

More generally, if we are expanding the superclasses of
  g0 :: forall tvs. theta => cls tys
and find a superclass constraint
  forall sc_tvs. sc_theta => sc_inner_pred
we must have a selector
  sel_id :: forall cls_tvs. cls cls_tvs -> forall sc_tvs. sc_theta => sc_inner_pred
and thus build
  g_sc :: forall tvs sc_tvs. theta => sc_theta => sc_inner_pred
  g_sc = /\ tvs. /\ sc_tvs. \ theta_ids. \ sc_theta_ids.
         sel_id tys (g0 tvs theta_ids) sc_tvs sc_theta_ids

Actually, we cheat a bit by eta-reducing: note that sc_theta_ids are both the
last bound variables and the last arguments. This avoids the need to produce
the sc_theta_ids at all. So our final construction is

  g_sc = /\ tvs. /\ sc_tvs. \ theta_ids.
         sel_id tys (g0 tvs theta_ids) sc_tvs

  -}

makeSuperClasses :: [Ct] -> TcS [Ct]
-- Returns strict superclasses, transitively, see Note [The superclasses story]
-- See Note [The superclass story]
-- The loop-breaking here follows Note [Expanding superclasses] in GHC.Tc.Utils.TcType
-- Specifically, for an incoming (C t) constraint, we return all of (C t)'s
--    superclasses, up to /and including/ the first repetition of C
--
-- Example:  class D a => C a
--           class C [a] => D a
-- makeSuperClasses (C x) will return (D x, C [x])
--
-- NB: the incoming constraints have had their cc_pend_sc flag already
--     flipped to False, by isPendingScDict, so we are /obliged/ to at
--     least produce the immediate superclasses
makeSuperClasses :: [Ct] -> TcS [Ct]
makeSuperClasses [Ct]
cts = (Ct -> TcS [Ct]) -> [Ct] -> TcS [Ct]
forall (m :: * -> *) a b. Monad m => (a -> m [b]) -> [a] -> m [b]
concatMapM Ct -> TcS [Ct]
go [Ct]
cts
  where
    go :: Ct -> TcS [Ct]
go (CDictCan { cc_ev :: Ct -> CtEvidence
cc_ev = CtEvidence
ev, cc_class :: Ct -> Class
cc_class = Class
cls, cc_tyargs :: Ct -> [TcType]
cc_tyargs = [TcType]
tys })
      = CtEvidence
-> [TcTyVar] -> [TcType] -> Class -> [TcType] -> TcS [Ct]
mkStrictSuperClasses CtEvidence
ev [] [] Class
cls [TcType]
tys
    go (CQuantCan (QCI { qci_pred :: QCInst -> TcType
qci_pred = TcType
pred, qci_ev :: QCInst -> CtEvidence
qci_ev = CtEvidence
ev }))
      = ASSERT2( isClassPred pred, ppr pred )  -- The cts should all have
                                               -- class pred heads
        CtEvidence
-> [TcTyVar] -> [TcType] -> Class -> [TcType] -> TcS [Ct]
mkStrictSuperClasses CtEvidence
ev [TcTyVar]
tvs [TcType]
theta Class
cls [TcType]
tys
      where
        ([TcTyVar]
tvs, [TcType]
theta, Class
cls, [TcType]
tys) = TcType -> ([TcTyVar], [TcType], Class, [TcType])
tcSplitDFunTy (CtEvidence -> TcType
ctEvPred CtEvidence
ev)
    go Ct
ct = String -> SDoc -> TcS [Ct]
forall a. HasCallStack => String -> SDoc -> a
pprPanic String
"makeSuperClasses" (Ct -> SDoc
forall a. Outputable a => a -> SDoc
ppr Ct
ct)

mkStrictSuperClasses
    :: CtEvidence
    -> [TyVar] -> ThetaType  -- These two args are non-empty only when taking
                             -- superclasses of a /quantified/ constraint
    -> Class -> [Type] -> TcS [Ct]
-- Return constraints for the strict superclasses of
--   ev :: forall as. theta => cls tys
mkStrictSuperClasses :: CtEvidence
-> [TcTyVar] -> [TcType] -> Class -> [TcType] -> TcS [Ct]
mkStrictSuperClasses CtEvidence
ev [TcTyVar]
tvs [TcType]
theta Class
cls [TcType]
tys
  = NameSet
-> CtEvidence
-> [TcTyVar]
-> [TcType]
-> Class
-> [TcType]
-> TcS [Ct]
mk_strict_superclasses (Name -> NameSet
unitNameSet (Class -> Name
className Class
cls))
                           CtEvidence
ev [TcTyVar]
tvs [TcType]
theta Class
cls [TcType]
tys

mk_strict_superclasses :: NameSet -> CtEvidence
                       -> [TyVar] -> ThetaType
                       -> Class -> [Type] -> TcS [Ct]
-- Always return the immediate superclasses of (cls tys);
-- and expand their superclasses, provided none of them are in rec_clss
-- nor are repeated
mk_strict_superclasses :: NameSet
-> CtEvidence
-> [TcTyVar]
-> [TcType]
-> Class
-> [TcType]
-> TcS [Ct]
mk_strict_superclasses NameSet
rec_clss (CtGiven { ctev_evar :: CtEvidence -> TcTyVar
ctev_evar = TcTyVar
evar, ctev_loc :: CtEvidence -> CtLoc
ctev_loc = CtLoc
loc })
                       [TcTyVar]
tvs [TcType]
theta Class
cls [TcType]
tys
  = (TcTyVar -> TcS [Ct]) -> [TcTyVar] -> TcS [Ct]
forall (m :: * -> *) a b. Monad m => (a -> m [b]) -> [a] -> m [b]
concatMapM (CtLoc -> TcTyVar -> TcS [Ct]
do_one_given (CtLoc -> CtLoc
mk_given_loc CtLoc
loc)) ([TcTyVar] -> TcS [Ct]) -> [TcTyVar] -> TcS [Ct]
forall a b. (a -> b) -> a -> b
$
    Class -> [TcTyVar]
classSCSelIds Class
cls
  where
    dict_ids :: [TcTyVar]
dict_ids  = [TcType] -> [TcTyVar]
mkTemplateLocals [TcType]
theta
    size :: TypeSize
size      = [TcType] -> TypeSize
sizeTypes [TcType]
tys

    do_one_given :: CtLoc -> TcTyVar -> TcS [Ct]
do_one_given CtLoc
given_loc TcTyVar
sel_id
      | HasDebugCallStack => TcType -> Bool
TcType -> Bool
isUnliftedType TcType
sc_pred
      , Bool -> Bool
not ([TcTyVar] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [TcTyVar]
tvs Bool -> Bool -> Bool
&& [TcType] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [TcType]
theta)
      = -- See Note [Equality superclasses in quantified constraints]
        [Ct] -> TcS [Ct]
forall (m :: * -> *) a. Monad m => a -> m a
return []
      | Bool
otherwise
      = do { CtEvidence
given_ev <- CtLoc -> (TcType, EvTerm) -> TcS CtEvidence
newGivenEvVar CtLoc
given_loc ((TcType, EvTerm) -> TcS CtEvidence)
-> (TcType, EvTerm) -> TcS CtEvidence
forall a b. (a -> b) -> a -> b
$
                         TcTyVar -> TcType -> (TcType, EvTerm)
mk_given_desc TcTyVar
sel_id TcType
sc_pred
           ; NameSet
-> CtEvidence -> [TcTyVar] -> [TcType] -> TcType -> TcS [Ct]
mk_superclasses NameSet
rec_clss CtEvidence
given_ev [TcTyVar]
tvs [TcType]
theta TcType
sc_pred }
      where
        sc_pred :: TcType
sc_pred = TcTyVar -> [TcType] -> TcType
classMethodInstTy TcTyVar
sel_id [TcType]
tys

      -- See Note [Nested quantified constraint superclasses]
    mk_given_desc :: Id -> PredType -> (PredType, EvTerm)
    mk_given_desc :: TcTyVar -> TcType -> (TcType, EvTerm)
mk_given_desc TcTyVar
sel_id TcType
sc_pred
      = (TcType
swizzled_pred, EvTerm
swizzled_evterm)
      where
        ([TcTyVar]
sc_tvs, TcType
sc_rho)          = TcType -> ([TcTyVar], TcType)
splitForAllTys TcType
sc_pred
        ([Scaled TcType]
sc_theta, TcType
sc_inner_pred) = TcType -> ([Scaled TcType], TcType)
splitFunTys TcType
sc_rho

        all_tvs :: [TcTyVar]
all_tvs       = [TcTyVar]
tvs [TcTyVar] -> [TcTyVar] -> [TcTyVar]
forall a. [a] -> [a] -> [a]
`chkAppend` [TcTyVar]
sc_tvs
        all_theta :: [TcType]
all_theta     = [TcType]
theta [TcType] -> [TcType] -> [TcType]
forall a. [a] -> [a] -> [a]
`chkAppend` ((Scaled TcType -> TcType) -> [Scaled TcType] -> [TcType]
forall a b. (a -> b) -> [a] -> [b]
map Scaled TcType -> TcType
forall a. Scaled a -> a
scaledThing [Scaled TcType]
sc_theta)
        swizzled_pred :: TcType
swizzled_pred = [TcTyVar] -> [TcType] -> TcType -> TcType
mkInfSigmaTy [TcTyVar]
all_tvs [TcType]
all_theta TcType
sc_inner_pred

        -- evar :: forall tvs. theta => cls tys
        -- sel_id :: forall cls_tvs. cls cls_tvs
        --                        -> forall sc_tvs. sc_theta => sc_inner_pred
        -- swizzled_evterm :: forall tvs sc_tvs. theta => sc_theta => sc_inner_pred
        swizzled_evterm :: EvTerm
swizzled_evterm = EvExpr -> EvTerm
EvExpr (EvExpr -> EvTerm) -> EvExpr -> EvTerm
forall a b. (a -> b) -> a -> b
$
          [TcTyVar] -> EvExpr -> EvExpr
forall b. [b] -> Expr b -> Expr b
mkLams [TcTyVar]
all_tvs (EvExpr -> EvExpr) -> EvExpr -> EvExpr
forall a b. (a -> b) -> a -> b
$
          [TcTyVar] -> EvExpr -> EvExpr
forall b. [b] -> Expr b -> Expr b
mkLams [TcTyVar]
dict_ids (EvExpr -> EvExpr) -> EvExpr -> EvExpr
forall a b. (a -> b) -> a -> b
$
          TcTyVar -> EvExpr
forall b. TcTyVar -> Expr b
Var TcTyVar
sel_id
            EvExpr -> [TcType] -> EvExpr
forall b. Expr b -> [TcType] -> Expr b
`mkTyApps` [TcType]
tys
            EvExpr -> EvExpr -> EvExpr
forall b. Expr b -> Expr b -> Expr b
`App` (TcTyVar -> EvExpr
evId TcTyVar
evar EvExpr -> [TcTyVar] -> EvExpr
forall b. Expr b -> [TcTyVar] -> Expr b
`mkVarApps` ([TcTyVar]
tvs [TcTyVar] -> [TcTyVar] -> [TcTyVar]
forall a. [a] -> [a] -> [a]
++ [TcTyVar]
dict_ids))
            EvExpr -> [TcTyVar] -> EvExpr
forall b. Expr b -> [TcTyVar] -> Expr b
`mkVarApps` [TcTyVar]
sc_tvs

    mk_given_loc :: CtLoc -> CtLoc
mk_given_loc CtLoc
loc
       | Class -> Bool
isCTupleClass Class
cls
       = CtLoc
loc   -- For tuple predicates, just take them apart, without
               -- adding their (large) size into the chain.  When we
               -- get down to a base predicate, we'll include its size.
               -- #10335

       | GivenOrigin SkolemInfo
skol_info <- CtLoc -> CtOrigin
ctLocOrigin CtLoc
loc
         -- See Note [Solving superclass constraints] in GHC.Tc.TyCl.Instance
         -- for explantation of this transformation for givens
       = case SkolemInfo
skol_info of
            SkolemInfo
InstSkol -> CtLoc
loc { ctl_origin :: CtOrigin
ctl_origin = SkolemInfo -> CtOrigin
GivenOrigin (TypeSize -> SkolemInfo
InstSC TypeSize
size) }
            InstSC TypeSize
n -> CtLoc
loc { ctl_origin :: CtOrigin
ctl_origin = SkolemInfo -> CtOrigin
GivenOrigin (TypeSize -> SkolemInfo
InstSC (TypeSize
n TypeSize -> TypeSize -> TypeSize
forall a. Ord a => a -> a -> a
`max` TypeSize
size)) }
            SkolemInfo
_        -> CtLoc
loc

       | Bool
otherwise  -- Probably doesn't happen, since this function
       = CtLoc
loc        -- is only used for Givens, but does no harm

mk_strict_superclasses NameSet
rec_clss CtEvidence
ev [TcTyVar]
tvs [TcType]
theta Class
cls [TcType]
tys
  | (TcType -> Bool) -> [TcType] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all TcType -> Bool
noFreeVarsOfType [TcType]
tys
  = [Ct] -> TcS [Ct]
forall (m :: * -> *) a. Monad m => a -> m a
return [] -- Wanteds with no variables yield no deriveds.
              -- See Note [Improvement from Ground Wanteds]

  | Bool
otherwise -- Wanted/Derived case, just add Derived superclasses
              -- that can lead to improvement.
  = ASSERT2( null tvs && null theta, ppr tvs $$ ppr theta )
    (TcType -> TcS [Ct]) -> [TcType] -> TcS [Ct]
forall (m :: * -> *) a b. Monad m => (a -> m [b]) -> [a] -> m [b]
concatMapM TcType -> TcS [Ct]
do_one_derived (Class -> [TcType] -> [TcType]
immSuperClasses Class
cls [TcType]
tys)
  where
    loc :: CtLoc
loc = CtEvidence -> CtLoc
ctEvLoc CtEvidence
ev

    do_one_derived :: TcType -> TcS [Ct]
do_one_derived TcType
sc_pred
      = do { CtEvidence
sc_ev <- CtLoc -> TcType -> TcS CtEvidence
newDerivedNC CtLoc
loc TcType
sc_pred
           ; NameSet
-> CtEvidence -> [TcTyVar] -> [TcType] -> TcType -> TcS [Ct]
mk_superclasses NameSet
rec_clss CtEvidence
sc_ev [] [] TcType
sc_pred }

{- Note [Improvement from Ground Wanteds]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose class C b a => D a b
and consider
  [W] D Int Bool
Is there any point in emitting [D] C Bool Int?  No!  The only point of
emitting superclass constraints for W/D constraints is to get
improvement, extra unifications that result from functional
dependencies.  See Note [Why adding superclasses can help] above.

But no variables means no improvement; case closed.
-}

mk_superclasses :: NameSet -> CtEvidence
                -> [TyVar] -> ThetaType -> PredType -> TcS [Ct]
-- Return this constraint, plus its superclasses, if any
mk_superclasses :: NameSet
-> CtEvidence -> [TcTyVar] -> [TcType] -> TcType -> TcS [Ct]
mk_superclasses NameSet
rec_clss CtEvidence
ev [TcTyVar]
tvs [TcType]
theta TcType
pred
  | ClassPred Class
cls [TcType]
tys <- TcType -> Pred
classifyPredType TcType
pred
  = NameSet
-> CtEvidence
-> [TcTyVar]
-> [TcType]
-> Class
-> [TcType]
-> TcS [Ct]
mk_superclasses_of NameSet
rec_clss CtEvidence
ev [TcTyVar]
tvs [TcType]
theta Class
cls [TcType]
tys

  | Bool
otherwise   -- Superclass is not a class predicate
  = [Ct] -> TcS [Ct]
forall (m :: * -> *) a. Monad m => a -> m a
return [CtEvidence -> Ct
mkNonCanonical CtEvidence
ev]

mk_superclasses_of :: NameSet -> CtEvidence
                   -> [TyVar] -> ThetaType -> Class -> [Type]
                   -> TcS [Ct]
-- Always return this class constraint,
-- and expand its superclasses
mk_superclasses_of :: NameSet
-> CtEvidence
-> [TcTyVar]
-> [TcType]
-> Class
-> [TcType]
-> TcS [Ct]
mk_superclasses_of NameSet
rec_clss CtEvidence
ev [TcTyVar]
tvs [TcType]
theta Class
cls [TcType]
tys
  | Bool
loop_found = do { String -> SDoc -> TcS ()
traceTcS String
"mk_superclasses_of: loop" (Class -> SDoc
forall a. Outputable a => a -> SDoc
ppr Class
cls SDoc -> SDoc -> SDoc
<+> [TcType] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [TcType]
tys)
                    ; [Ct] -> TcS [Ct]
forall (m :: * -> *) a. Monad m => a -> m a
return [Ct
this_ct] }  -- cc_pend_sc of this_ct = True
  | Bool
otherwise  = do { String -> SDoc -> TcS ()
traceTcS String
"mk_superclasses_of" ([SDoc] -> SDoc
vcat [ Class -> SDoc
forall a. Outputable a => a -> SDoc
ppr Class
cls SDoc -> SDoc -> SDoc
<+> [TcType] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [TcType]
tys
                                                          , Bool -> SDoc
forall a. Outputable a => a -> SDoc
ppr (Class -> Bool
isCTupleClass Class
cls)
                                                          , NameSet -> SDoc
forall a. Outputable a => a -> SDoc
ppr NameSet
rec_clss
                                                          ])
                    ; [Ct]
sc_cts <- NameSet
-> CtEvidence
-> [TcTyVar]
-> [TcType]
-> Class
-> [TcType]
-> TcS [Ct]
mk_strict_superclasses NameSet
rec_clss' CtEvidence
ev [TcTyVar]
tvs [TcType]
theta Class
cls [TcType]
tys
                    ; [Ct] -> TcS [Ct]
forall (m :: * -> *) a. Monad m => a -> m a
return (Ct
this_ct Ct -> [Ct] -> [Ct]
forall a. a -> [a] -> [a]
: [Ct]
sc_cts) }
                                   -- cc_pend_sc of this_ct = False
  where
    cls_nm :: Name
cls_nm     = Class -> Name
className Class
cls
    loop_found :: Bool
loop_found = Bool -> Bool
not (Class -> Bool
isCTupleClass Class
cls) Bool -> Bool -> Bool
&& Name
cls_nm Name -> NameSet -> Bool
`elemNameSet` NameSet
rec_clss
                 -- Tuples never contribute to recursion, and can be nested
    rec_clss' :: NameSet
rec_clss'  = NameSet
rec_clss NameSet -> Name -> NameSet
`extendNameSet` Name
cls_nm

    this_ct :: Ct
this_ct | [TcTyVar] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [TcTyVar]
tvs, [TcType] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [TcType]
theta
            = CDictCan :: CtEvidence -> Class -> [TcType] -> Bool -> Ct
CDictCan { cc_ev :: CtEvidence
cc_ev = CtEvidence
ev, cc_class :: Class
cc_class = Class
cls, cc_tyargs :: [TcType]
cc_tyargs = [TcType]
tys
                       , cc_pend_sc :: Bool
cc_pend_sc = Bool
loop_found }
                 -- NB: If there is a loop, we cut off, so we have not
                 --     added the superclasses, hence cc_pend_sc = True
            | Bool
otherwise
            = QCInst -> Ct
CQuantCan (QCI :: CtEvidence -> [TcTyVar] -> TcType -> Bool -> QCInst
QCI { qci_tvs :: [TcTyVar]
qci_tvs = [TcTyVar]
tvs, qci_pred :: TcType
qci_pred = Class -> [TcType] -> TcType
mkClassPred Class
cls [TcType]
tys
                             , qci_ev :: CtEvidence
qci_ev = CtEvidence
ev
                             , qci_pend_sc :: Bool
qci_pend_sc = Bool
loop_found })


{- Note [Equality superclasses in quantified constraints]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider (#15359, #15593, #15625)
  f :: (forall a. theta => a ~ b) => stuff

It's a bit odd to have a local, quantified constraint for `(a~b)`,
but some people want such a thing (see the tickets). And for
Coercible it is definitely useful
  f :: forall m. (forall p q. Coercible p q => Coercible (m p) (m q)))
                 => stuff

Moreover it's not hard to arrange; we just need to look up /equality/
constraints in the quantified-constraint environment, which we do in
GHC.Tc.Solver.Interact.doTopReactOther.

There is a wrinkle though, in the case where 'theta' is empty, so
we have
  f :: (forall a. a~b) => stuff

Now, potentially, the superclass machinery kicks in, in
makeSuperClasses, giving us a a second quantified constraint
       (forall a. a ~# b)
BUT this is an unboxed value!  And nothing has prepared us for
dictionary "functions" that are unboxed.  Actually it does just
about work, but the simplifier ends up with stuff like
   case (/\a. eq_sel d) of df -> ...(df @Int)...
and fails to simplify that any further.  And it doesn't satisfy
isPredTy any more.

So for now we simply decline to take superclasses in the quantified
case.  Instead we have a special case in GHC.Tc.Solver.Interact.doTopReactOther,
which looks for primitive equalities specially in the quantified
constraints.

See also Note [Evidence for quantified constraints] in GHC.Core.Predicate.


************************************************************************
*                                                                      *
*                      Irreducibles canonicalization
*                                                                      *
************************************************************************
-}

canIrred :: CtIrredStatus -> CtEvidence -> TcS (StopOrContinue Ct)
-- Precondition: ty not a tuple and no other evidence form
canIrred :: CtIrredStatus -> CtEvidence -> TcS (StopOrContinue Ct)
canIrred CtIrredStatus
status CtEvidence
ev
  = do { let pred :: TcType
pred = CtEvidence -> TcType
ctEvPred CtEvidence
ev
       ; String -> SDoc -> TcS ()
traceTcS String
"can_pred" (String -> SDoc
text String
"IrredPred = " SDoc -> SDoc -> SDoc
<+> TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
pred)
       ; (TcType
xi,TcCoercion
co) <- FlattenMode -> CtEvidence -> TcType -> TcS (TcType, TcCoercion)
flatten FlattenMode
FM_FlattenAll CtEvidence
ev TcType
pred -- co :: xi ~ pred
       ; CtEvidence
-> TcType -> TcCoercion -> TcS (StopOrContinue CtEvidence)
rewriteEvidence CtEvidence
ev TcType
xi TcCoercion
co TcS (StopOrContinue CtEvidence)
-> (CtEvidence -> TcS (StopOrContinue Ct))
-> TcS (StopOrContinue Ct)
forall a b.
TcS (StopOrContinue a)
-> (a -> TcS (StopOrContinue b)) -> TcS (StopOrContinue b)
`andWhenContinue` \ CtEvidence
new_ev ->
    do { -- Re-classify, in case flattening has improved its shape
       ; case TcType -> Pred
classifyPredType (CtEvidence -> TcType
ctEvPred CtEvidence
new_ev) of
           ClassPred Class
cls [TcType]
tys     -> CtEvidence -> Class -> [TcType] -> TcS (StopOrContinue Ct)
canClassNC CtEvidence
new_ev Class
cls [TcType]
tys
           EqPred EqRel
eq_rel TcType
ty1 TcType
ty2 -> CtEvidence -> EqRel -> TcType -> TcType -> TcS (StopOrContinue Ct)
canEqNC CtEvidence
new_ev EqRel
eq_rel TcType
ty1 TcType
ty2
           Pred
_                     -> Ct -> TcS (StopOrContinue Ct)
forall a. a -> TcS (StopOrContinue a)
continueWith (Ct -> TcS (StopOrContinue Ct)) -> Ct -> TcS (StopOrContinue Ct)
forall a b. (a -> b) -> a -> b
$
                                    CtIrredStatus -> CtEvidence -> Ct
mkIrredCt CtIrredStatus
status CtEvidence
new_ev } }

{- *********************************************************************
*                                                                      *
*                      Quantified predicates
*                                                                      *
********************************************************************* -}

{- Note [Quantified constraints]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The -XQuantifiedConstraints extension allows type-class contexts like this:

  data Rose f x = Rose x (f (Rose f x))

  instance (Eq a, forall b. Eq b => Eq (f b))
        => Eq (Rose f a)  where
    (Rose x1 rs1) == (Rose x2 rs2) = x1==x2 && rs1 == rs2

Note the (forall b. Eq b => Eq (f b)) in the instance contexts.
This quantified constraint is needed to solve the
 [W] (Eq (f (Rose f x)))
constraint which arises form the (==) definition.

The wiki page is
  https://gitlab.haskell.org/ghc/ghc/wikis/quantified-constraints
which in turn contains a link to the GHC Proposal where the change
is specified, and a Haskell Symposium paper about it.

We implement two main extensions to the design in the paper:

 1. We allow a variable in the instance head, e.g.
      f :: forall m a. (forall b. m b) => D (m a)
    Notice the 'm' in the head of the quantified constraint, not
    a class.

 2. We support superclasses to quantified constraints.
    For example (contrived):
      f :: (Ord b, forall b. Ord b => Ord (m b)) => m a -> m a -> Bool
      f x y = x==y
    Here we need (Eq (m a)); but the quantified constraint deals only
    with Ord.  But we can make it work by using its superclass.

Here are the moving parts
  * Language extension {-# LANGUAGE QuantifiedConstraints #-}
    and add it to ghc-boot-th:GHC.LanguageExtensions.Type.Extension

  * A new form of evidence, EvDFun, that is used to discharge
    such wanted constraints

  * checkValidType gets some changes to accept forall-constraints
    only in the right places.

  * Predicate.Pred gets a new constructor ForAllPred, and
    and classifyPredType analyses a PredType to decompose
    the new forall-constraints

  * GHC.Tc.Solver.Monad.InertCans gets an extra field, inert_insts,
    which holds all the Given forall-constraints.  In effect,
    such Given constraints are like local instance decls.

  * When trying to solve a class constraint, via
    GHC.Tc.Solver.Interact.matchInstEnv, use the InstEnv from inert_insts
    so that we include the local Given forall-constraints
    in the lookup.  (See GHC.Tc.Solver.Monad.getInstEnvs.)

  * GHC.Tc.Solver.Canonical.canForAll deals with solving a
    forall-constraint.  See
       Note [Solving a Wanted forall-constraint]

  * We augment the kick-out code to kick out an inert
    forall constraint if it can be rewritten by a new
    type equality; see GHC.Tc.Solver.Monad.kick_out_rewritable

Note that a quantified constraint is never /inferred/
(by GHC.Tc.Solver.simplifyInfer).  A function can only have a
quantified constraint in its type if it is given an explicit
type signature.

-}

canForAllNC :: CtEvidence -> [TyVar] -> TcThetaType -> TcPredType
            -> TcS (StopOrContinue Ct)
canForAllNC :: CtEvidence
-> [TcTyVar] -> [TcType] -> TcType -> TcS (StopOrContinue Ct)
canForAllNC CtEvidence
ev [TcTyVar]
tvs [TcType]
theta TcType
pred
  | CtEvidence -> Bool
isGiven CtEvidence
ev  -- See Note [Eagerly expand given superclasses]
  , Just (Class
cls, [TcType]
tys) <- Maybe (Class, [TcType])
cls_pred_tys_maybe
  = do { [Ct]
sc_cts <- CtEvidence
-> [TcTyVar] -> [TcType] -> Class -> [TcType] -> TcS [Ct]
mkStrictSuperClasses CtEvidence
ev [TcTyVar]
tvs [TcType]
theta Class
cls [TcType]
tys
       ; [Ct] -> TcS ()
emitWork [Ct]
sc_cts
       ; CtEvidence -> Bool -> TcS (StopOrContinue Ct)
canForAll CtEvidence
ev Bool
False }

  | Bool
otherwise
  = CtEvidence -> Bool -> TcS (StopOrContinue Ct)
canForAll CtEvidence
ev (Maybe (Class, [TcType]) -> Bool
forall a. Maybe a -> Bool
isJust Maybe (Class, [TcType])
cls_pred_tys_maybe)

  where
    cls_pred_tys_maybe :: Maybe (Class, [TcType])
cls_pred_tys_maybe = TcType -> Maybe (Class, [TcType])
getClassPredTys_maybe TcType
pred

canForAll :: CtEvidence -> Bool -> TcS (StopOrContinue Ct)
-- We have a constraint (forall as. blah => C tys)
canForAll :: CtEvidence -> Bool -> TcS (StopOrContinue Ct)
canForAll CtEvidence
ev Bool
pend_sc
  = do { -- First rewrite it to apply the current substitution
         -- Do not bother with type-family reductions; we can't
         -- do them under a forall anyway (c.f. Flatten.flatten_one
         -- on a forall type)
         let pred :: TcType
pred = CtEvidence -> TcType
ctEvPred CtEvidence
ev
       ; (TcType
xi,TcCoercion
co) <- FlattenMode -> CtEvidence -> TcType -> TcS (TcType, TcCoercion)
flatten FlattenMode
FM_SubstOnly CtEvidence
ev TcType
pred -- co :: xi ~ pred
       ; CtEvidence
-> TcType -> TcCoercion -> TcS (StopOrContinue CtEvidence)
rewriteEvidence CtEvidence
ev TcType
xi TcCoercion
co TcS (StopOrContinue CtEvidence)
-> (CtEvidence -> TcS (StopOrContinue Ct))
-> TcS (StopOrContinue Ct)
forall a b.
TcS (StopOrContinue a)
-> (a -> TcS (StopOrContinue b)) -> TcS (StopOrContinue b)
`andWhenContinue` \ CtEvidence
new_ev ->

    do { -- Now decompose into its pieces and solve it
         -- (It takes a lot less code to flatten before decomposing.)
       ; case TcType -> Pred
classifyPredType (CtEvidence -> TcType
ctEvPred CtEvidence
new_ev) of
           ForAllPred [TcTyVar]
tvs [TcType]
theta TcType
pred
              -> CtEvidence
-> [TcTyVar]
-> [TcType]
-> TcType
-> Bool
-> TcS (StopOrContinue Ct)
solveForAll CtEvidence
new_ev [TcTyVar]
tvs [TcType]
theta TcType
pred Bool
pend_sc
           Pred
_  -> String -> SDoc -> TcS (StopOrContinue Ct)
forall a. HasCallStack => String -> SDoc -> a
pprPanic String
"canForAll" (CtEvidence -> SDoc
forall a. Outputable a => a -> SDoc
ppr CtEvidence
new_ev)
    } }

solveForAll :: CtEvidence -> [TyVar] -> TcThetaType -> PredType -> Bool
            -> TcS (StopOrContinue Ct)
solveForAll :: CtEvidence
-> [TcTyVar]
-> [TcType]
-> TcType
-> Bool
-> TcS (StopOrContinue Ct)
solveForAll CtEvidence
ev [TcTyVar]
tvs [TcType]
theta TcType
pred Bool
pend_sc
  | CtWanted { ctev_dest :: CtEvidence -> TcEvDest
ctev_dest = TcEvDest
dest } <- CtEvidence
ev
  = -- See Note [Solving a Wanted forall-constraint]
    do { let skol_info :: SkolemInfo
skol_info = SkolemInfo
QuantCtxtSkol
             empty_subst :: TCvSubst
empty_subst = InScopeSet -> TCvSubst
mkEmptyTCvSubst (InScopeSet -> TCvSubst) -> InScopeSet -> TCvSubst
forall a b. (a -> b) -> a -> b
$ VarSet -> InScopeSet
mkInScopeSet (VarSet -> InScopeSet) -> VarSet -> InScopeSet
forall a b. (a -> b) -> a -> b
$
                           [TcType] -> VarSet
tyCoVarsOfTypes (TcType
predTcType -> [TcType] -> [TcType]
forall a. a -> [a] -> [a]
:[TcType]
theta) VarSet -> [TcTyVar] -> VarSet
`delVarSetList` [TcTyVar]
tvs
       ; (TCvSubst
subst, [TcTyVar]
skol_tvs) <- TCvSubst -> [TcTyVar] -> TcS (TCvSubst, [TcTyVar])
tcInstSkolTyVarsX TCvSubst
empty_subst [TcTyVar]
tvs
       ; [TcTyVar]
given_ev_vars <- (TcType -> TcS TcTyVar) -> [TcType] -> TcS [TcTyVar]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM TcType -> TcS TcTyVar
newEvVar (HasCallStack => TCvSubst -> [TcType] -> [TcType]
TCvSubst -> [TcType] -> [TcType]
substTheta TCvSubst
subst [TcType]
theta)

       ; (TcLevel
lvl, (TcTyVar
w_id, Bag Ct
wanteds))
             <- SDoc -> TcS (TcTyVar, Bag Ct) -> TcS (TcLevel, (TcTyVar, Bag Ct))
forall a. SDoc -> TcS a -> TcS (TcLevel, a)
pushLevelNoWorkList (SkolemInfo -> SDoc
forall a. Outputable a => a -> SDoc
ppr SkolemInfo
skol_info) (TcS (TcTyVar, Bag Ct) -> TcS (TcLevel, (TcTyVar, Bag Ct)))
-> TcS (TcTyVar, Bag Ct) -> TcS (TcLevel, (TcTyVar, Bag Ct))
forall a b. (a -> b) -> a -> b
$
                do { CtEvidence
wanted_ev <- CtLoc -> TcType -> TcS CtEvidence
newWantedEvVarNC CtLoc
loc (TcType -> TcS CtEvidence) -> TcType -> TcS CtEvidence
forall a b. (a -> b) -> a -> b
$
                                  HasCallStack => TCvSubst -> TcType -> TcType
TCvSubst -> TcType -> TcType
substTy TCvSubst
subst TcType
pred
                   ; (TcTyVar, Bag Ct) -> TcS (TcTyVar, Bag Ct)
forall (m :: * -> *) a. Monad m => a -> m a
return ( CtEvidence -> TcTyVar
ctEvEvId CtEvidence
wanted_ev
                            , Ct -> Bag Ct
forall a. a -> Bag a
unitBag (CtEvidence -> Ct
mkNonCanonical CtEvidence
wanted_ev)) }

      ; TcEvBinds
ev_binds <- TcLevel
-> SkolemInfo -> [TcTyVar] -> [TcTyVar] -> Bag Ct -> TcS TcEvBinds
emitImplicationTcS TcLevel
lvl SkolemInfo
skol_info [TcTyVar]
skol_tvs
                                       [TcTyVar]
given_ev_vars Bag Ct
wanteds

      ; TcEvDest -> EvTerm -> TcS ()
setWantedEvTerm TcEvDest
dest (EvTerm -> TcS ()) -> EvTerm -> TcS ()
forall a b. (a -> b) -> a -> b
$
        EvFun :: [TcTyVar] -> [TcTyVar] -> TcEvBinds -> TcTyVar -> EvTerm
EvFun { et_tvs :: [TcTyVar]
et_tvs = [TcTyVar]
skol_tvs, et_given :: [TcTyVar]
et_given = [TcTyVar]
given_ev_vars
              , et_binds :: TcEvBinds
et_binds = TcEvBinds
ev_binds, et_body :: TcTyVar
et_body = TcTyVar
w_id }

      ; CtEvidence -> String -> TcS (StopOrContinue Ct)
forall a. CtEvidence -> String -> TcS (StopOrContinue a)
stopWith CtEvidence
ev String
"Wanted forall-constraint" }

  | CtEvidence -> Bool
isGiven CtEvidence
ev   -- See Note [Solving a Given forall-constraint]
  = do { QCInst -> TcS ()
addInertForAll QCInst
qci
       ; CtEvidence -> String -> TcS (StopOrContinue Ct)
forall a. CtEvidence -> String -> TcS (StopOrContinue a)
stopWith CtEvidence
ev String
"Given forall-constraint" }

  | Bool
otherwise
  = do { String -> SDoc -> TcS ()
traceTcS String
"discarding derived forall-constraint" (CtEvidence -> SDoc
forall a. Outputable a => a -> SDoc
ppr CtEvidence
ev)
       ; CtEvidence -> String -> TcS (StopOrContinue Ct)
forall a. CtEvidence -> String -> TcS (StopOrContinue a)
stopWith CtEvidence
ev String
"Derived forall-constraint" }
  where
    loc :: CtLoc
loc = CtEvidence -> CtLoc
ctEvLoc CtEvidence
ev
    qci :: QCInst
qci = QCI :: CtEvidence -> [TcTyVar] -> TcType -> Bool -> QCInst
QCI { qci_ev :: CtEvidence
qci_ev = CtEvidence
ev, qci_tvs :: [TcTyVar]
qci_tvs = [TcTyVar]
tvs
              , qci_pred :: TcType
qci_pred = TcType
pred, qci_pend_sc :: Bool
qci_pend_sc = Bool
pend_sc }

{- Note [Solving a Wanted forall-constraint]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Solving a wanted forall (quantified) constraint
  [W] df :: forall ab. (Eq a, Ord b) => C x a b
is delightfully easy.   Just build an implication constraint
    forall ab. (g1::Eq a, g2::Ord b) => [W] d :: C x a
and discharge df thus:
    df = /\ab. \g1 g2. let <binds> in d
where <binds> is filled in by solving the implication constraint.
All the machinery is to hand; there is little to do.

Note [Solving a Given forall-constraint]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For a Given constraint
  [G] df :: forall ab. (Eq a, Ord b) => C x a b
we just add it to TcS's local InstEnv of known instances,
via addInertForall.  Then, if we look up (C x Int Bool), say,
we'll find a match in the InstEnv.


************************************************************************
*                                                                      *
*        Equalities
*                                                                      *
************************************************************************

Note [Canonicalising equalities]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In order to canonicalise an equality, we look at the structure of the
two types at hand, looking for similarities. A difficulty is that the
types may look dissimilar before flattening but similar after flattening.
However, we don't just want to jump in and flatten right away, because
this might be wasted effort. So, after looking for similarities and failing,
we flatten and then try again. Of course, we don't want to loop, so we
track whether or not we've already flattened.

It is conceivable to do a better job at tracking whether or not a type
is flattened, but this is left as future work. (Mar '15)


Note [Decomposing FunTy]
~~~~~~~~~~~~~~~~~~~~~~~~
can_eq_nc' may attempt to decompose a FunTy that is un-zonked.  This
means that we may very well have a FunTy containing a type of some
unknown kind. For instance, we may have,

    FunTy (a :: k) Int

Where k is a unification variable. So the calls to getRuntimeRep_maybe may
fail (returning Nothing).  In that case we'll fall through, zonk, and try again.
Zonking should fill the variable k, meaning that decomposition will succeed the
second time around.

Also note that we require the AnonArgFlag to match.  This will stop
us decomposing
   (Int -> Bool)  ~  (Show a => blah)
It's as if we treat (->) and (=>) as different type constructors.
-}

canEqNC :: CtEvidence -> EqRel -> Type -> Type -> TcS (StopOrContinue Ct)
canEqNC :: CtEvidence -> EqRel -> TcType -> TcType -> TcS (StopOrContinue Ct)
canEqNC CtEvidence
ev EqRel
eq_rel TcType
ty1 TcType
ty2
  = do { Either (Pair TcType) TcType
result <- TcType -> TcType -> TcS (Either (Pair TcType) TcType)
zonk_eq_types TcType
ty1 TcType
ty2
       ; case Either (Pair TcType) TcType
result of
           Left (Pair TcType
ty1' TcType
ty2') -> Bool
-> CtEvidence
-> EqRel
-> TcType
-> TcType
-> TcType
-> TcType
-> TcS (StopOrContinue Ct)
can_eq_nc Bool
False CtEvidence
ev EqRel
eq_rel TcType
ty1' TcType
ty1 TcType
ty2' TcType
ty2
           Right TcType
ty              -> CtEvidence -> EqRel -> TcType -> TcS (StopOrContinue Ct)
canEqReflexive CtEvidence
ev EqRel
eq_rel TcType
ty }

can_eq_nc
   :: Bool            -- True => both types are flat
   -> CtEvidence
   -> EqRel
   -> Type -> Type    -- LHS, after and before type-synonym expansion, resp
   -> Type -> Type    -- RHS, after and before type-synonym expansion, resp
   -> TcS (StopOrContinue Ct)
can_eq_nc :: Bool
-> CtEvidence
-> EqRel
-> TcType
-> TcType
-> TcType
-> TcType
-> TcS (StopOrContinue Ct)
can_eq_nc Bool
flat CtEvidence
ev EqRel
eq_rel TcType
ty1 TcType
ps_ty1 TcType
ty2 TcType
ps_ty2
  = do { String -> SDoc -> TcS ()
traceTcS String
"can_eq_nc" (SDoc -> TcS ()) -> SDoc -> TcS ()
forall a b. (a -> b) -> a -> b
$
         [SDoc] -> SDoc
vcat [ Bool -> SDoc
forall a. Outputable a => a -> SDoc
ppr Bool
flat, CtEvidence -> SDoc
forall a. Outputable a => a -> SDoc
ppr CtEvidence
ev, EqRel -> SDoc
forall a. Outputable a => a -> SDoc
ppr EqRel
eq_rel, TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
ty1, TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
ps_ty1, TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
ty2, TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
ps_ty2 ]
       ; GlobalRdrEnv
rdr_env <- TcS GlobalRdrEnv
getGlobalRdrEnvTcS
       ; (FamInstEnv, FamInstEnv)
fam_insts <- TcS (FamInstEnv, FamInstEnv)
getFamInstEnvs
       ; Bool
-> GlobalRdrEnv
-> (FamInstEnv, FamInstEnv)
-> CtEvidence
-> EqRel
-> TcType
-> TcType
-> TcType
-> TcType
-> TcS (StopOrContinue Ct)
can_eq_nc' Bool
flat GlobalRdrEnv
rdr_env (FamInstEnv, FamInstEnv)
fam_insts CtEvidence
ev EqRel
eq_rel TcType
ty1 TcType
ps_ty1 TcType
ty2 TcType
ps_ty2 }

can_eq_nc'
   :: Bool           -- True => both input types are flattened
   -> GlobalRdrEnv   -- needed to see which newtypes are in scope
   -> FamInstEnvs    -- needed to unwrap data instances
   -> CtEvidence
   -> EqRel
   -> Type -> Type    -- LHS, after and before type-synonym expansion, resp
   -> Type -> Type    -- RHS, after and before type-synonym expansion, resp
   -> TcS (StopOrContinue Ct)

-- Expand synonyms first; see Note [Type synonyms and canonicalization]
can_eq_nc' :: Bool
-> GlobalRdrEnv
-> (FamInstEnv, FamInstEnv)
-> CtEvidence
-> EqRel
-> TcType
-> TcType
-> TcType
-> TcType
-> TcS (StopOrContinue Ct)
can_eq_nc' Bool
flat GlobalRdrEnv
rdr_env (FamInstEnv, FamInstEnv)
envs CtEvidence
ev EqRel
eq_rel TcType
ty1 TcType
ps_ty1 TcType
ty2 TcType
ps_ty2
  | Just TcType
ty1' <- TcType -> Maybe TcType
tcView TcType
ty1 = Bool
-> GlobalRdrEnv
-> (FamInstEnv, FamInstEnv)
-> CtEvidence
-> EqRel
-> TcType
-> TcType
-> TcType
-> TcType
-> TcS (StopOrContinue Ct)
can_eq_nc' Bool
flat GlobalRdrEnv
rdr_env (FamInstEnv, FamInstEnv)
envs CtEvidence
ev EqRel
eq_rel TcType
ty1' TcType
ps_ty1 TcType
ty2  TcType
ps_ty2
  | Just TcType
ty2' <- TcType -> Maybe TcType
tcView TcType
ty2 = Bool
-> GlobalRdrEnv
-> (FamInstEnv, FamInstEnv)
-> CtEvidence
-> EqRel
-> TcType
-> TcType
-> TcType
-> TcType
-> TcS (StopOrContinue Ct)
can_eq_nc' Bool
flat GlobalRdrEnv
rdr_env (FamInstEnv, FamInstEnv)
envs CtEvidence
ev EqRel
eq_rel TcType
ty1  TcType
ps_ty1 TcType
ty2' TcType
ps_ty2

-- need to check for reflexivity in the ReprEq case.
-- See Note [Eager reflexivity check]
-- Check only when flat because the zonk_eq_types check in canEqNC takes
-- care of the non-flat case.
can_eq_nc' Bool
True GlobalRdrEnv
_rdr_env (FamInstEnv, FamInstEnv)
_envs CtEvidence
ev EqRel
ReprEq TcType
ty1 TcType
_ TcType
ty2 TcType
_
  | TcType
ty1 HasDebugCallStack => TcType -> TcType -> Bool
TcType -> TcType -> Bool
`tcEqType` TcType
ty2
  = CtEvidence -> EqRel -> TcType -> TcS (StopOrContinue Ct)
canEqReflexive CtEvidence
ev EqRel
ReprEq TcType
ty1

-- When working with ReprEq, unwrap newtypes.
-- See Note [Unwrap newtypes first]
-- This must be above the TyVarTy case, in order to guarantee (TyEq:N)
can_eq_nc' Bool
_flat GlobalRdrEnv
rdr_env (FamInstEnv, FamInstEnv)
envs CtEvidence
ev EqRel
eq_rel TcType
ty1 TcType
ps_ty1 TcType
ty2 TcType
ps_ty2
  | EqRel
ReprEq <- EqRel
eq_rel
  , Just ((Bag GlobalRdrElt, TcCoercion), TcType)
stuff1 <- (FamInstEnv, FamInstEnv)
-> GlobalRdrEnv
-> TcType
-> Maybe ((Bag GlobalRdrElt, TcCoercion), TcType)
tcTopNormaliseNewTypeTF_maybe (FamInstEnv, FamInstEnv)
envs GlobalRdrEnv
rdr_env TcType
ty1
  = CtEvidence
-> SwapFlag
-> TcType
-> ((Bag GlobalRdrElt, TcCoercion), TcType)
-> TcType
-> TcType
-> TcS (StopOrContinue Ct)
can_eq_newtype_nc CtEvidence
ev SwapFlag
NotSwapped TcType
ty1 ((Bag GlobalRdrElt, TcCoercion), TcType)
stuff1 TcType
ty2 TcType
ps_ty2

  | EqRel
ReprEq <- EqRel
eq_rel
  , Just ((Bag GlobalRdrElt, TcCoercion), TcType)
stuff2 <- (FamInstEnv, FamInstEnv)
-> GlobalRdrEnv
-> TcType
-> Maybe ((Bag GlobalRdrElt, TcCoercion), TcType)
tcTopNormaliseNewTypeTF_maybe (FamInstEnv, FamInstEnv)
envs GlobalRdrEnv
rdr_env TcType
ty2
  = CtEvidence
-> SwapFlag
-> TcType
-> ((Bag GlobalRdrElt, TcCoercion), TcType)
-> TcType
-> TcType
-> TcS (StopOrContinue Ct)
can_eq_newtype_nc CtEvidence
ev SwapFlag
IsSwapped  TcType
ty2 ((Bag GlobalRdrElt, TcCoercion), TcType)
stuff2 TcType
ty1 TcType
ps_ty1

-- Then, get rid of casts
can_eq_nc' Bool
flat GlobalRdrEnv
_rdr_env (FamInstEnv, FamInstEnv)
_envs CtEvidence
ev EqRel
eq_rel (CastTy TcType
ty1 TcCoercion
co1) TcType
_ TcType
ty2 TcType
ps_ty2
  | Bool -> Bool
not (TcType -> Bool
isTyVarTy TcType
ty2)  -- See (3) in Note [Equalities with incompatible kinds]
  = Bool
-> CtEvidence
-> EqRel
-> SwapFlag
-> TcType
-> TcCoercion
-> TcType
-> TcType
-> TcS (StopOrContinue Ct)
canEqCast Bool
flat CtEvidence
ev EqRel
eq_rel SwapFlag
NotSwapped TcType
ty1 TcCoercion
co1 TcType
ty2 TcType
ps_ty2
can_eq_nc' Bool
flat GlobalRdrEnv
_rdr_env (FamInstEnv, FamInstEnv)
_envs CtEvidence
ev EqRel
eq_rel TcType
ty1 TcType
ps_ty1 (CastTy TcType
ty2 TcCoercion
co2) TcType
_
  | Bool -> Bool
not (TcType -> Bool
isTyVarTy TcType
ty1)  -- See (3) in Note [Equalities with incompatible kinds]
  = Bool
-> CtEvidence
-> EqRel
-> SwapFlag
-> TcType
-> TcCoercion
-> TcType
-> TcType
-> TcS (StopOrContinue Ct)
canEqCast Bool
flat CtEvidence
ev EqRel
eq_rel SwapFlag
IsSwapped TcType
ty2 TcCoercion
co2 TcType
ty1 TcType
ps_ty1

-- NB: pattern match on True: we want only flat types sent to canEqTyVar.
-- See also Note [No top-level newtypes on RHS of representational equalities]
can_eq_nc' Bool
True GlobalRdrEnv
_rdr_env (FamInstEnv, FamInstEnv)
_envs CtEvidence
ev EqRel
eq_rel (TyVarTy TcTyVar
tv1) TcType
ps_ty1 TcType
ty2 TcType
ps_ty2
  = CtEvidence
-> EqRel
-> SwapFlag
-> TcTyVar
-> TcType
-> TcType
-> TcType
-> TcS (StopOrContinue Ct)
canEqTyVar CtEvidence
ev EqRel
eq_rel SwapFlag
NotSwapped TcTyVar
tv1 TcType
ps_ty1 TcType
ty2 TcType
ps_ty2
can_eq_nc' Bool
True GlobalRdrEnv
_rdr_env (FamInstEnv, FamInstEnv)
_envs CtEvidence
ev EqRel
eq_rel TcType
ty1 TcType
ps_ty1 (TyVarTy TcTyVar
tv2) TcType
ps_ty2
  = CtEvidence
-> EqRel
-> SwapFlag
-> TcTyVar
-> TcType
-> TcType
-> TcType
-> TcS (StopOrContinue Ct)
canEqTyVar CtEvidence
ev EqRel
eq_rel SwapFlag
IsSwapped TcTyVar
tv2 TcType
ps_ty2 TcType
ty1 TcType
ps_ty1

----------------------
-- Otherwise try to decompose
----------------------

-- Literals
can_eq_nc' Bool
_flat GlobalRdrEnv
_rdr_env (FamInstEnv, FamInstEnv)
_envs CtEvidence
ev EqRel
eq_rel ty1 :: TcType
ty1@(LitTy TyLit
l1) TcType
_ (LitTy TyLit
l2) TcType
_
 | TyLit
l1 TyLit -> TyLit -> Bool
forall a. Eq a => a -> a -> Bool
== TyLit
l2
  = do { CtEvidence -> EvTerm -> TcS ()
setEvBindIfWanted CtEvidence
ev (TcCoercion -> EvTerm
evCoercion (TcCoercion -> EvTerm) -> TcCoercion -> EvTerm
forall a b. (a -> b) -> a -> b
$ Role -> TcType -> TcCoercion
mkReflCo (EqRel -> Role
eqRelRole EqRel
eq_rel) TcType
ty1)
       ; CtEvidence -> String -> TcS (StopOrContinue Ct)
forall a. CtEvidence -> String -> TcS (StopOrContinue a)
stopWith CtEvidence
ev String
"Equal LitTy" }

-- Decompose FunTy: (s -> t) and (c => t)
-- NB: don't decompose (Int -> blah) ~ (Show a => blah)
can_eq_nc' Bool
_flat GlobalRdrEnv
_rdr_env (FamInstEnv, FamInstEnv)
_envs CtEvidence
ev EqRel
eq_rel
           (FunTy { ft_mult :: TcType -> TcType
ft_mult = TcType
am1, ft_af :: TcType -> AnonArgFlag
ft_af = AnonArgFlag
af1, ft_arg :: TcType -> TcType
ft_arg = TcType
ty1a, ft_res :: TcType -> TcType
ft_res = TcType
ty1b }) TcType
_
           (FunTy { ft_mult :: TcType -> TcType
ft_mult = TcType
am2, ft_af :: TcType -> AnonArgFlag
ft_af = AnonArgFlag
af2, ft_arg :: TcType -> TcType
ft_arg = TcType
ty2a, ft_res :: TcType -> TcType
ft_res = TcType
ty2b }) TcType
_
  | AnonArgFlag
af1 AnonArgFlag -> AnonArgFlag -> Bool
forall a. Eq a => a -> a -> Bool
== AnonArgFlag
af2   -- Don't decompose (Int -> blah) ~ (Show a => blah)
  , Just TcType
ty1a_rep <- HasDebugCallStack => TcType -> Maybe TcType
TcType -> Maybe TcType
getRuntimeRep_maybe TcType
ty1a  -- getRutimeRep_maybe:
  , Just TcType
ty1b_rep <- HasDebugCallStack => TcType -> Maybe TcType
TcType -> Maybe TcType
getRuntimeRep_maybe TcType
ty1b  -- see Note [Decomposing FunTy]
  , Just TcType
ty2a_rep <- HasDebugCallStack => TcType -> Maybe TcType
TcType -> Maybe TcType
getRuntimeRep_maybe TcType
ty2a
  , Just TcType
ty2b_rep <- HasDebugCallStack => TcType -> Maybe TcType
TcType -> Maybe TcType
getRuntimeRep_maybe TcType
ty2b
  = CtEvidence
-> EqRel
-> TyCon
-> [TcType]
-> [TcType]
-> TcS (StopOrContinue Ct)
canDecomposableTyConAppOK CtEvidence
ev EqRel
eq_rel TyCon
funTyCon
                              [TcType
am1, TcType
ty1a_rep, TcType
ty1b_rep, TcType
ty1a, TcType
ty1b]
                              [TcType
am2, TcType
ty2a_rep, TcType
ty2b_rep, TcType
ty2a, TcType
ty2b]

-- Decompose type constructor applications
-- NB: e have expanded type synonyms already
can_eq_nc' Bool
_flat GlobalRdrEnv
_rdr_env (FamInstEnv, FamInstEnv)
_envs CtEvidence
ev EqRel
eq_rel
           (TyConApp TyCon
tc1 [TcType]
tys1) TcType
_
           (TyConApp TyCon
tc2 [TcType]
tys2) TcType
_
  | Bool -> Bool
not (TyCon -> Bool
isTypeFamilyTyCon TyCon
tc1)
  , Bool -> Bool
not (TyCon -> Bool
isTypeFamilyTyCon TyCon
tc2)
  = CtEvidence
-> EqRel
-> TyCon
-> [TcType]
-> TyCon
-> [TcType]
-> TcS (StopOrContinue Ct)
canTyConApp CtEvidence
ev EqRel
eq_rel TyCon
tc1 [TcType]
tys1 TyCon
tc2 [TcType]
tys2

can_eq_nc' Bool
_flat GlobalRdrEnv
_rdr_env (FamInstEnv, FamInstEnv)
_envs CtEvidence
ev EqRel
eq_rel
           s1 :: TcType
s1@(ForAllTy {}) TcType
_ s2 :: TcType
s2@(ForAllTy {}) TcType
_
  = CtEvidence -> EqRel -> TcType -> TcType -> TcS (StopOrContinue Ct)
can_eq_nc_forall CtEvidence
ev EqRel
eq_rel TcType
s1 TcType
s2

-- See Note [Canonicalising type applications] about why we require flat types
can_eq_nc' Bool
True GlobalRdrEnv
_rdr_env (FamInstEnv, FamInstEnv)
_envs CtEvidence
ev EqRel
eq_rel (AppTy TcType
t1 TcType
s1) TcType
_ TcType
ty2 TcType
_
  | EqRel
NomEq <- EqRel
eq_rel
  , Just (TcType
t2, TcType
s2) <- TcType -> Maybe (TcType, TcType)
tcSplitAppTy_maybe TcType
ty2
  = CtEvidence
-> TcType -> TcType -> TcType -> TcType -> TcS (StopOrContinue Ct)
can_eq_app CtEvidence
ev TcType
t1 TcType
s1 TcType
t2 TcType
s2
can_eq_nc' Bool
True GlobalRdrEnv
_rdr_env (FamInstEnv, FamInstEnv)
_envs CtEvidence
ev EqRel
eq_rel TcType
ty1 TcType
_ (AppTy TcType
t2 TcType
s2) TcType
_
  | EqRel
NomEq <- EqRel
eq_rel
  , Just (TcType
t1, TcType
s1) <- TcType -> Maybe (TcType, TcType)
tcSplitAppTy_maybe TcType
ty1
  = CtEvidence
-> TcType -> TcType -> TcType -> TcType -> TcS (StopOrContinue Ct)
can_eq_app CtEvidence
ev TcType
t1 TcType
s1 TcType
t2 TcType
s2

-- No similarity in type structure detected. Flatten and try again.
can_eq_nc' Bool
False GlobalRdrEnv
rdr_env (FamInstEnv, FamInstEnv)
envs CtEvidence
ev EqRel
eq_rel TcType
_ TcType
ps_ty1 TcType
_ TcType
ps_ty2
  = do { (TcType
xi1, TcCoercion
co1) <- FlattenMode -> CtEvidence -> TcType -> TcS (TcType, TcCoercion)
flatten FlattenMode
FM_FlattenAll CtEvidence
ev TcType
ps_ty1
       ; (TcType
xi2, TcCoercion
co2) <- FlattenMode -> CtEvidence -> TcType -> TcS (TcType, TcCoercion)
flatten FlattenMode
FM_FlattenAll CtEvidence
ev TcType
ps_ty2
       ; CtEvidence
new_ev <- CtEvidence
-> SwapFlag
-> TcType
-> TcType
-> TcCoercion
-> TcCoercion
-> TcS CtEvidence
rewriteEqEvidence CtEvidence
ev SwapFlag
NotSwapped TcType
xi1 TcType
xi2 TcCoercion
co1 TcCoercion
co2
       ; Bool
-> GlobalRdrEnv
-> (FamInstEnv, FamInstEnv)
-> CtEvidence
-> EqRel
-> TcType
-> TcType
-> TcType
-> TcType
-> TcS (StopOrContinue Ct)
can_eq_nc' Bool
True GlobalRdrEnv
rdr_env (FamInstEnv, FamInstEnv)
envs CtEvidence
new_ev EqRel
eq_rel TcType
xi1 TcType
xi1 TcType
xi2 TcType
xi2 }

-- We've flattened and the types don't match. Give up.
can_eq_nc' Bool
True GlobalRdrEnv
_rdr_env (FamInstEnv, FamInstEnv)
_envs CtEvidence
ev EqRel
eq_rel TcType
_ TcType
ps_ty1 TcType
_ TcType
ps_ty2
  = do { String -> SDoc -> TcS ()
traceTcS String
"can_eq_nc' catch-all case" (TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
ps_ty1 SDoc -> SDoc -> SDoc
$$ TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
ps_ty2)
       ; case EqRel
eq_rel of -- See Note [Unsolved equalities]
            EqRel
ReprEq -> Ct -> TcS (StopOrContinue Ct)
forall a. a -> TcS (StopOrContinue a)
continueWith (CtIrredStatus -> CtEvidence -> Ct
mkIrredCt CtIrredStatus
OtherCIS CtEvidence
ev)
            EqRel
NomEq  -> Ct -> TcS (StopOrContinue Ct)
forall a. a -> TcS (StopOrContinue a)
continueWith (CtIrredStatus -> CtEvidence -> Ct
mkIrredCt CtIrredStatus
InsolubleCIS CtEvidence
ev) }
          -- No need to call canEqFailure/canEqHardFailure because they
          -- flatten, and the types involved here are already flat

{- Note [Unsolved equalities]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If we have an unsolved equality like
  (a b ~R# Int)
that is not necessarily insoluble!  Maybe 'a' will turn out to be a newtype.
So we want to make it a potentially-soluble Irred not an insoluble one.
Missing this point is what caused #15431
-}

---------------------------------
can_eq_nc_forall :: CtEvidence -> EqRel
                 -> Type -> Type    -- LHS and RHS
                 -> TcS (StopOrContinue Ct)
-- (forall as. phi1) ~ (forall bs. phi2)
-- Check for length match of as, bs
-- Then build an implication constraint: forall as. phi1 ~ phi2[as/bs]
-- But remember also to unify the kinds of as and bs
--  (this is the 'go' loop), and actually substitute phi2[as |> cos / bs]
-- Remember also that we might have forall z (a:z). blah
--  so we must proceed one binder at a time (#13879)

can_eq_nc_forall :: CtEvidence -> EqRel -> TcType -> TcType -> TcS (StopOrContinue Ct)
can_eq_nc_forall CtEvidence
ev EqRel
eq_rel TcType
s1 TcType
s2
 | CtWanted { ctev_loc :: CtEvidence -> CtLoc
ctev_loc = CtLoc
loc, ctev_dest :: CtEvidence -> TcEvDest
ctev_dest = TcEvDest
orig_dest } <- CtEvidence
ev
 = do { let free_tvs :: VarSet
free_tvs       = [TcType] -> VarSet
tyCoVarsOfTypes [TcType
s1,TcType
s2]
            ([TyVarBinder]
bndrs1, TcType
phi1) = TcType -> ([TyVarBinder], TcType)
tcSplitForAllVarBndrs TcType
s1
            ([TyVarBinder]
bndrs2, TcType
phi2) = TcType -> ([TyVarBinder], TcType)
tcSplitForAllVarBndrs TcType
s2
      ; if Bool -> Bool
not ([TyVarBinder] -> [TyVarBinder] -> Bool
forall a b. [a] -> [b] -> Bool
equalLength [TyVarBinder]
bndrs1 [TyVarBinder]
bndrs2)
        then do { String -> SDoc -> TcS ()
traceTcS String
"Forall failure" (SDoc -> TcS ()) -> SDoc -> TcS ()
forall a b. (a -> b) -> a -> b
$
                     [SDoc] -> SDoc
vcat [ TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
s1, TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
s2, [TyVarBinder] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [TyVarBinder]
bndrs1, [TyVarBinder] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [TyVarBinder]
bndrs2
                          , [ArgFlag] -> SDoc
forall a. Outputable a => a -> SDoc
ppr ((TyVarBinder -> ArgFlag) -> [TyVarBinder] -> [ArgFlag]
forall a b. (a -> b) -> [a] -> [b]
map TyVarBinder -> ArgFlag
forall tv argf. VarBndr tv argf -> argf
binderArgFlag [TyVarBinder]
bndrs1)
                          , [ArgFlag] -> SDoc
forall a. Outputable a => a -> SDoc
ppr ((TyVarBinder -> ArgFlag) -> [TyVarBinder] -> [ArgFlag]
forall a b. (a -> b) -> [a] -> [b]
map TyVarBinder -> ArgFlag
forall tv argf. VarBndr tv argf -> argf
binderArgFlag [TyVarBinder]
bndrs2) ]
                ; CtEvidence -> TcType -> TcType -> TcS (StopOrContinue Ct)
canEqHardFailure CtEvidence
ev TcType
s1 TcType
s2 }
        else
   do { String -> SDoc -> TcS ()
traceTcS String
"Creating implication for polytype equality" (SDoc -> TcS ()) -> SDoc -> TcS ()
forall a b. (a -> b) -> a -> b
$ CtEvidence -> SDoc
forall a. Outputable a => a -> SDoc
ppr CtEvidence
ev
      ; let empty_subst1 :: TCvSubst
empty_subst1 = InScopeSet -> TCvSubst
mkEmptyTCvSubst (InScopeSet -> TCvSubst) -> InScopeSet -> TCvSubst
forall a b. (a -> b) -> a -> b
$ VarSet -> InScopeSet
mkInScopeSet VarSet
free_tvs
      ; (TCvSubst
subst1, [TcTyVar]
skol_tvs) <- TCvSubst -> [TcTyVar] -> TcS (TCvSubst, [TcTyVar])
tcInstSkolTyVarsX TCvSubst
empty_subst1 ([TcTyVar] -> TcS (TCvSubst, [TcTyVar]))
-> [TcTyVar] -> TcS (TCvSubst, [TcTyVar])
forall a b. (a -> b) -> a -> b
$
                              [TyVarBinder] -> [TcTyVar]
forall tv argf. [VarBndr tv argf] -> [tv]
binderVars [TyVarBinder]
bndrs1

      ; let skol_info :: SkolemInfo
skol_info = TcType -> SkolemInfo
UnifyForAllSkol TcType
phi1
            phi1' :: TcType
phi1' = HasCallStack => TCvSubst -> TcType -> TcType
TCvSubst -> TcType -> TcType
substTy TCvSubst
subst1 TcType
phi1

            -- Unify the kinds, extend the substitution
            go :: [TcTyVar] -> TCvSubst -> [TyVarBinder]
               -> TcS (TcCoercion, Cts)
            go :: [TcTyVar] -> TCvSubst -> [TyVarBinder] -> TcS (TcCoercion, Bag Ct)
go (TcTyVar
skol_tv:[TcTyVar]
skol_tvs) TCvSubst
subst (TyVarBinder
bndr2:[TyVarBinder]
bndrs2)
              = do { let tv2 :: TcTyVar
tv2 = TyVarBinder -> TcTyVar
forall tv argf. VarBndr tv argf -> tv
binderVar TyVarBinder
bndr2
                   ; (TcCoercion
kind_co, Bag Ct
wanteds1) <- CtLoc -> Role -> TcType -> TcType -> TcS (TcCoercion, Bag Ct)
unify CtLoc
loc Role
Nominal (TcTyVar -> TcType
tyVarKind TcTyVar
skol_tv)
                                                  (HasCallStack => TCvSubst -> TcType -> TcType
TCvSubst -> TcType -> TcType
substTy TCvSubst
subst (TcTyVar -> TcType
tyVarKind TcTyVar
tv2))
                   ; let subst' :: TCvSubst
subst' = TCvSubst -> TcTyVar -> TcType -> TCvSubst
extendTvSubstAndInScope TCvSubst
subst TcTyVar
tv2
                                       (TcType -> TcCoercion -> TcType
mkCastTy (TcTyVar -> TcType
mkTyVarTy TcTyVar
skol_tv) TcCoercion
kind_co)
                         -- skol_tv is already in the in-scope set, but the
                         -- free vars of kind_co are not; hence "...AndInScope"
                   ; (TcCoercion
co, Bag Ct
wanteds2) <- [TcTyVar] -> TCvSubst -> [TyVarBinder] -> TcS (TcCoercion, Bag Ct)
go [TcTyVar]
skol_tvs TCvSubst
subst' [TyVarBinder]
bndrs2
                   ; (TcCoercion, Bag Ct) -> TcS (TcCoercion, Bag Ct)
forall (m :: * -> *) a. Monad m => a -> m a
return ( TcTyVar -> TcCoercion -> TcCoercion -> TcCoercion
mkTcForAllCo TcTyVar
skol_tv TcCoercion
kind_co TcCoercion
co
                            , Bag Ct
wanteds1 Bag Ct -> Bag Ct -> Bag Ct
forall a. Bag a -> Bag a -> Bag a
`unionBags` Bag Ct
wanteds2 ) }

            -- Done: unify phi1 ~ phi2
            go [] TCvSubst
subst [TyVarBinder]
bndrs2
              = ASSERT( null bndrs2 )
                CtLoc -> Role -> TcType -> TcType -> TcS (TcCoercion, Bag Ct)
unify CtLoc
loc (EqRel -> Role
eqRelRole EqRel
eq_rel) TcType
phi1' (TCvSubst -> TcType -> TcType
substTyUnchecked TCvSubst
subst TcType
phi2)

            go [TcTyVar]
_ TCvSubst
_ [TyVarBinder]
_ = String -> TcS (TcCoercion, Bag Ct)
forall a. String -> a
panic String
"cna_eq_nc_forall"  -- case (s:ss) []

            empty_subst2 :: TCvSubst
empty_subst2 = InScopeSet -> TCvSubst
mkEmptyTCvSubst (TCvSubst -> InScopeSet
getTCvInScope TCvSubst
subst1)

      ; (TcLevel
lvl, (TcCoercion
all_co, Bag Ct
wanteds)) <- SDoc
-> TcS (TcCoercion, Bag Ct) -> TcS (TcLevel, (TcCoercion, Bag Ct))
forall a. SDoc -> TcS a -> TcS (TcLevel, a)
pushLevelNoWorkList (SkolemInfo -> SDoc
forall a. Outputable a => a -> SDoc
ppr SkolemInfo
skol_info) (TcS (TcCoercion, Bag Ct) -> TcS (TcLevel, (TcCoercion, Bag Ct)))
-> TcS (TcCoercion, Bag Ct) -> TcS (TcLevel, (TcCoercion, Bag Ct))
forall a b. (a -> b) -> a -> b
$
                                    [TcTyVar] -> TCvSubst -> [TyVarBinder] -> TcS (TcCoercion, Bag Ct)
go [TcTyVar]
skol_tvs TCvSubst
empty_subst2 [TyVarBinder]
bndrs2
      ; TcLevel -> SkolemInfo -> [TcTyVar] -> Bag Ct -> TcS ()
emitTvImplicationTcS TcLevel
lvl SkolemInfo
skol_info [TcTyVar]
skol_tvs Bag Ct
wanteds

      ; TcEvDest -> TcCoercion -> TcS ()
setWantedEq TcEvDest
orig_dest TcCoercion
all_co
      ; CtEvidence -> String -> TcS (StopOrContinue Ct)
forall a. CtEvidence -> String -> TcS (StopOrContinue a)
stopWith CtEvidence
ev String
"Deferred polytype equality" } }

 | Bool
otherwise
 = do { String -> SDoc -> TcS ()
traceTcS String
"Omitting decomposition of given polytype equality" (SDoc -> TcS ()) -> SDoc -> TcS ()
forall a b. (a -> b) -> a -> b
$
        TcType -> TcType -> SDoc
pprEq TcType
s1 TcType
s2    -- See Note [Do not decompose given polytype equalities]
      ; CtEvidence -> String -> TcS (StopOrContinue Ct)
forall a. CtEvidence -> String -> TcS (StopOrContinue a)
stopWith CtEvidence
ev String
"Discard given polytype equality" }

 where
    unify :: CtLoc -> Role -> TcType -> TcType -> TcS (TcCoercion, Cts)
    -- This version returns the wanted constraint rather
    -- than putting it in the work list
    unify :: CtLoc -> Role -> TcType -> TcType -> TcS (TcCoercion, Bag Ct)
unify CtLoc
loc Role
role TcType
ty1 TcType
ty2
      | TcType
ty1 HasDebugCallStack => TcType -> TcType -> Bool
TcType -> TcType -> Bool
`tcEqType` TcType
ty2
      = (TcCoercion, Bag Ct) -> TcS (TcCoercion, Bag Ct)
forall (m :: * -> *) a. Monad m => a -> m a
return (Role -> TcType -> TcCoercion
mkTcReflCo Role
role TcType
ty1, Bag Ct
forall a. Bag a
emptyBag)
      | Bool
otherwise
      = do { (CtEvidence
wanted, TcCoercion
co) <- CtLoc -> Role -> TcType -> TcType -> TcS (CtEvidence, TcCoercion)
newWantedEq CtLoc
loc Role
role TcType
ty1 TcType
ty2
           ; (TcCoercion, Bag Ct) -> TcS (TcCoercion, Bag Ct)
forall (m :: * -> *) a. Monad m => a -> m a
return (TcCoercion
co, Ct -> Bag Ct
forall a. a -> Bag a
unitBag (CtEvidence -> Ct
mkNonCanonical CtEvidence
wanted)) }

---------------------------------
-- | Compare types for equality, while zonking as necessary. Gives up
-- as soon as it finds that two types are not equal.
-- This is quite handy when some unification has made two
-- types in an inert Wanted to be equal. We can discover the equality without
-- flattening, which is sometimes very expensive (in the case of type functions).
-- In particular, this function makes a ~20% improvement in test case
-- perf/compiler/T5030.
--
-- Returns either the (partially zonked) types in the case of
-- inequality, or the one type in the case of equality. canEqReflexive is
-- a good next step in the 'Right' case. Returning 'Left' is always safe.
--
-- NB: This does *not* look through type synonyms. In fact, it treats type
-- synonyms as rigid constructors. In the future, it might be convenient
-- to look at only those arguments of type synonyms that actually appear
-- in the synonym RHS. But we're not there yet.
zonk_eq_types :: TcType -> TcType -> TcS (Either (Pair TcType) TcType)
zonk_eq_types :: TcType -> TcType -> TcS (Either (Pair TcType) TcType)
zonk_eq_types = TcType -> TcType -> TcS (Either (Pair TcType) TcType)
go
  where
    go :: TcType -> TcType -> TcS (Either (Pair TcType) TcType)
go (TyVarTy TcTyVar
tv1) (TyVarTy TcTyVar
tv2) = TcTyVar -> TcTyVar -> TcS (Either (Pair TcType) TcType)
tyvar_tyvar TcTyVar
tv1 TcTyVar
tv2
    go (TyVarTy TcTyVar
tv1) TcType
ty2           = SwapFlag -> TcTyVar -> TcType -> TcS (Either (Pair TcType) TcType)
tyvar SwapFlag
NotSwapped TcTyVar
tv1 TcType
ty2
    go TcType
ty1 (TyVarTy TcTyVar
tv2)           = SwapFlag -> TcTyVar -> TcType -> TcS (Either (Pair TcType) TcType)
tyvar SwapFlag
IsSwapped  TcTyVar
tv2 TcType
ty1

    -- We handle FunTys explicitly here despite the fact that they could also be
    -- treated as an application. Why? Well, for one it's cheaper to just look
    -- at two types (the argument and result types) than four (the argument,
    -- result, and their RuntimeReps). Also, we haven't completely zonked yet,
    -- so we may run into an unzonked type variable while trying to compute the
    -- RuntimeReps of the argument and result types. This can be observed in
    -- testcase tc269.
    go TcType
ty1 TcType
ty2
      | Just (Scaled TcType
w1 TcType
arg1, TcType
res1) <- Maybe (Scaled TcType, TcType)
split1
      , Just (Scaled TcType
w2 TcType
arg2, TcType
res2) <- Maybe (Scaled TcType, TcType)
split2
      , TcType -> TcType -> Bool
eqType TcType
w1 TcType
w2
      = do { Either (Pair TcType) TcType
res_a <- TcType -> TcType -> TcS (Either (Pair TcType) TcType)
go TcType
arg1 TcType
arg2
           ; Either (Pair TcType) TcType
res_b <- TcType -> TcType -> TcS (Either (Pair TcType) TcType)
go TcType
res1 TcType
res2
           ; Either (Pair TcType) TcType -> TcS (Either (Pair TcType) TcType)
forall (m :: * -> *) a. Monad m => a -> m a
return (Either (Pair TcType) TcType -> TcS (Either (Pair TcType) TcType))
-> Either (Pair TcType) TcType -> TcS (Either (Pair TcType) TcType)
forall a b. (a -> b) -> a -> b
$ (TcType -> TcType -> TcType)
-> Either (Pair TcType) TcType
-> Either (Pair TcType) TcType
-> Either (Pair TcType) TcType
forall a b c.
(a -> b -> c)
-> Either (Pair b) b -> Either (Pair a) a -> Either (Pair c) c
combine_rev (TcType -> TcType -> TcType -> TcType
mkVisFunTy TcType
w1) Either (Pair TcType) TcType
res_b Either (Pair TcType) TcType
res_a
           }
      | Maybe (Scaled TcType, TcType) -> Bool
forall a. Maybe a -> Bool
isJust Maybe (Scaled TcType, TcType)
split1 Bool -> Bool -> Bool
|| Maybe (Scaled TcType, TcType) -> Bool
forall a. Maybe a -> Bool
isJust Maybe (Scaled TcType, TcType)
split2
      = TcType -> TcType -> TcS (Either (Pair TcType) TcType)
forall {m :: * -> *} {a} {b}.
Monad m =>
a -> a -> m (Either (Pair a) b)
bale_out TcType
ty1 TcType
ty2
      where
        split1 :: Maybe (Scaled TcType, TcType)
split1 = TcType -> Maybe (Scaled TcType, TcType)
tcSplitFunTy_maybe TcType
ty1
        split2 :: Maybe (Scaled TcType, TcType)
split2 = TcType -> Maybe (Scaled TcType, TcType)
tcSplitFunTy_maybe TcType
ty2

    go TcType
ty1 TcType
ty2
      | Just (TyCon
tc1, [TcType]
tys1) <- HasDebugCallStack => TcType -> Maybe (TyCon, [TcType])
TcType -> Maybe (TyCon, [TcType])
repSplitTyConApp_maybe TcType
ty1
      , Just (TyCon
tc2, [TcType]
tys2) <- HasDebugCallStack => TcType -> Maybe (TyCon, [TcType])
TcType -> Maybe (TyCon, [TcType])
repSplitTyConApp_maybe TcType
ty2
      = if TyCon
tc1 TyCon -> TyCon -> Bool
forall a. Eq a => a -> a -> Bool
== TyCon
tc2 Bool -> Bool -> Bool
&& [TcType]
tys1 [TcType] -> [TcType] -> Bool
forall a b. [a] -> [b] -> Bool
`equalLength` [TcType]
tys2
          -- Crucial to check for equal-length args, because
          -- we cannot assume that the two args to 'go' have
          -- the same kind.  E.g go (Proxy *      (Maybe Int))
          --                        (Proxy (*->*) Maybe)
          -- We'll call (go (Maybe Int) Maybe)
          -- See #13083
        then TyCon -> [TcType] -> [TcType] -> TcS (Either (Pair TcType) TcType)
tycon TyCon
tc1 [TcType]
tys1 [TcType]
tys2
        else TcType -> TcType -> TcS (Either (Pair TcType) TcType)
forall {m :: * -> *} {a} {b}.
Monad m =>
a -> a -> m (Either (Pair a) b)
bale_out TcType
ty1 TcType
ty2

    go TcType
ty1 TcType
ty2
      | Just (TcType
ty1a, TcType
ty1b) <- TcType -> Maybe (TcType, TcType)
tcRepSplitAppTy_maybe TcType
ty1
      , Just (TcType
ty2a, TcType
ty2b) <- TcType -> Maybe (TcType, TcType)
tcRepSplitAppTy_maybe TcType
ty2
      = do { Either (Pair TcType) TcType
res_a <- TcType -> TcType -> TcS (Either (Pair TcType) TcType)
go TcType
ty1a TcType
ty2a
           ; Either (Pair TcType) TcType
res_b <- TcType -> TcType -> TcS (Either (Pair TcType) TcType)
go TcType
ty1b TcType
ty2b
           ; Either (Pair TcType) TcType -> TcS (Either (Pair TcType) TcType)
forall (m :: * -> *) a. Monad m => a -> m a
return (Either (Pair TcType) TcType -> TcS (Either (Pair TcType) TcType))
-> Either (Pair TcType) TcType -> TcS (Either (Pair TcType) TcType)
forall a b. (a -> b) -> a -> b
$ (TcType -> TcType -> TcType)
-> Either (Pair TcType) TcType
-> Either (Pair TcType) TcType
-> Either (Pair TcType) TcType
forall a b c.
(a -> b -> c)
-> Either (Pair b) b -> Either (Pair a) a -> Either (Pair c) c
combine_rev TcType -> TcType -> TcType
mkAppTy Either (Pair TcType) TcType
res_b Either (Pair TcType) TcType
res_a }

    go ty1 :: TcType
ty1@(LitTy TyLit
lit1) (LitTy TyLit
lit2)
      | TyLit
lit1 TyLit -> TyLit -> Bool
forall a. Eq a => a -> a -> Bool
== TyLit
lit2
      = Either (Pair TcType) TcType -> TcS (Either (Pair TcType) TcType)
forall (m :: * -> *) a. Monad m => a -> m a
return (TcType -> Either (Pair TcType) TcType
forall a b. b -> Either a b
Right TcType
ty1)

    go TcType
ty1 TcType
ty2 = TcType -> TcType -> TcS (Either (Pair TcType) TcType)
forall {m :: * -> *} {a} {b}.
Monad m =>
a -> a -> m (Either (Pair a) b)
bale_out TcType
ty1 TcType
ty2
      -- We don't handle more complex forms here

    bale_out :: a -> a -> m (Either (Pair a) b)
bale_out a
ty1 a
ty2 = Either (Pair a) b -> m (Either (Pair a) b)
forall (m :: * -> *) a. Monad m => a -> m a
return (Either (Pair a) b -> m (Either (Pair a) b))
-> Either (Pair a) b -> m (Either (Pair a) b)
forall a b. (a -> b) -> a -> b
$ Pair a -> Either (Pair a) b
forall a b. a -> Either a b
Left (a -> a -> Pair a
forall a. a -> a -> Pair a
Pair a
ty1 a
ty2)

    tyvar :: SwapFlag -> TcTyVar -> TcType
          -> TcS (Either (Pair TcType) TcType)
      -- Try to do as little as possible, as anything we do here is redundant
      -- with flattening. In particular, no need to zonk kinds. That's why
      -- we don't use the already-defined zonking functions
    tyvar :: SwapFlag -> TcTyVar -> TcType -> TcS (Either (Pair TcType) TcType)
tyvar SwapFlag
swapped TcTyVar
tv TcType
ty
      = case TcTyVar -> TcTyVarDetails
tcTyVarDetails TcTyVar
tv of
          MetaTv { mtv_ref :: TcTyVarDetails -> IORef MetaDetails
mtv_ref = IORef MetaDetails
ref }
            -> do { MetaDetails
cts <- IORef MetaDetails -> TcS MetaDetails
forall a. TcRef a -> TcS a
readTcRef IORef MetaDetails
ref
                  ; case MetaDetails
cts of
                      MetaDetails
Flexi        -> TcS (Either (Pair TcType) TcType)
forall {b}. TcS (Either (Pair TcType) b)
give_up
                      Indirect TcType
ty' -> do { TcTyVar -> TcType -> TcS ()
forall {a} {a}. (Outputable a, Outputable a) => a -> a -> TcS ()
trace_indirect TcTyVar
tv TcType
ty'
                                         ; SwapFlag
-> (TcType -> TcType -> TcS (Either (Pair TcType) TcType))
-> TcType
-> TcType
-> TcS (Either (Pair TcType) TcType)
forall a b. SwapFlag -> (a -> a -> b) -> a -> a -> b
unSwap SwapFlag
swapped TcType -> TcType -> TcS (Either (Pair TcType) TcType)
go TcType
ty' TcType
ty } }
          TcTyVarDetails
_ -> TcS (Either (Pair TcType) TcType)
forall {b}. TcS (Either (Pair TcType) b)
give_up
      where
        give_up :: TcS (Either (Pair TcType) b)
give_up = Either (Pair TcType) b -> TcS (Either (Pair TcType) b)
forall (m :: * -> *) a. Monad m => a -> m a
return (Either (Pair TcType) b -> TcS (Either (Pair TcType) b))
-> Either (Pair TcType) b -> TcS (Either (Pair TcType) b)
forall a b. (a -> b) -> a -> b
$ Pair TcType -> Either (Pair TcType) b
forall a b. a -> Either a b
Left (Pair TcType -> Either (Pair TcType) b)
-> Pair TcType -> Either (Pair TcType) b
forall a b. (a -> b) -> a -> b
$ SwapFlag
-> (TcType -> TcType -> Pair TcType)
-> TcType
-> TcType
-> Pair TcType
forall a b. SwapFlag -> (a -> a -> b) -> a -> a -> b
unSwap SwapFlag
swapped TcType -> TcType -> Pair TcType
forall a. a -> a -> Pair a
Pair (TcTyVar -> TcType
mkTyVarTy TcTyVar
tv) TcType
ty

    tyvar_tyvar :: TcTyVar -> TcTyVar -> TcS (Either (Pair TcType) TcType)
tyvar_tyvar TcTyVar
tv1 TcTyVar
tv2
      | TcTyVar
tv1 TcTyVar -> TcTyVar -> Bool
forall a. Eq a => a -> a -> Bool
== TcTyVar
tv2 = Either (Pair TcType) TcType -> TcS (Either (Pair TcType) TcType)
forall (m :: * -> *) a. Monad m => a -> m a
return (TcType -> Either (Pair TcType) TcType
forall a b. b -> Either a b
Right (TcTyVar -> TcType
mkTyVarTy TcTyVar
tv1))
      | Bool
otherwise  = do { (TcType
ty1', Bool
progress1) <- TcTyVar -> TcS (TcType, Bool)
quick_zonk TcTyVar
tv1
                        ; (TcType
ty2', Bool
progress2) <- TcTyVar -> TcS (TcType, Bool)
quick_zonk TcTyVar
tv2
                        ; if Bool
progress1 Bool -> Bool -> Bool
|| Bool
progress2
                          then TcType -> TcType -> TcS (Either (Pair TcType) TcType)
go TcType
ty1' TcType
ty2'
                          else Either (Pair TcType) TcType -> TcS (Either (Pair TcType) TcType)
forall (m :: * -> *) a. Monad m => a -> m a
return (Either (Pair TcType) TcType -> TcS (Either (Pair TcType) TcType))
-> Either (Pair TcType) TcType -> TcS (Either (Pair TcType) TcType)
forall a b. (a -> b) -> a -> b
$ Pair TcType -> Either (Pair TcType) TcType
forall a b. a -> Either a b
Left (TcType -> TcType -> Pair TcType
forall a. a -> a -> Pair a
Pair (TcTyVar -> TcType
TyVarTy TcTyVar
tv1) (TcTyVar -> TcType
TyVarTy TcTyVar
tv2)) }

    trace_indirect :: a -> a -> TcS ()
trace_indirect a
tv a
ty
       = String -> SDoc -> TcS ()
traceTcS String
"Following filled tyvar (zonk_eq_types)"
                  (a -> SDoc
forall a. Outputable a => a -> SDoc
ppr a
tv SDoc -> SDoc -> SDoc
<+> SDoc
equals SDoc -> SDoc -> SDoc
<+> a -> SDoc
forall a. Outputable a => a -> SDoc
ppr a
ty)

    quick_zonk :: TcTyVar -> TcS (TcType, Bool)
quick_zonk TcTyVar
tv = case TcTyVar -> TcTyVarDetails
tcTyVarDetails TcTyVar
tv of
      MetaTv { mtv_ref :: TcTyVarDetails -> IORef MetaDetails
mtv_ref = IORef MetaDetails
ref }
        -> do { MetaDetails
cts <- IORef MetaDetails -> TcS MetaDetails
forall a. TcRef a -> TcS a
readTcRef IORef MetaDetails
ref
              ; case MetaDetails
cts of
                  MetaDetails
Flexi        -> (TcType, Bool) -> TcS (TcType, Bool)
forall (m :: * -> *) a. Monad m => a -> m a
return (TcTyVar -> TcType
TyVarTy TcTyVar
tv, Bool
False)
                  Indirect TcType
ty' -> do { TcTyVar -> TcType -> TcS ()
forall {a} {a}. (Outputable a, Outputable a) => a -> a -> TcS ()
trace_indirect TcTyVar
tv TcType
ty'
                                     ; (TcType, Bool) -> TcS (TcType, Bool)
forall (m :: * -> *) a. Monad m => a -> m a
return (TcType
ty', Bool
True) } }
      TcTyVarDetails
_ -> (TcType, Bool) -> TcS (TcType, Bool)
forall (m :: * -> *) a. Monad m => a -> m a
return (TcTyVar -> TcType
TyVarTy TcTyVar
tv, Bool
False)

      -- This happens for type families, too. But recall that failure
      -- here just means to try harder, so it's OK if the type function
      -- isn't injective.
    tycon :: TyCon -> [TcType] -> [TcType]
          -> TcS (Either (Pair TcType) TcType)
    tycon :: TyCon -> [TcType] -> [TcType] -> TcS (Either (Pair TcType) TcType)
tycon TyCon
tc [TcType]
tys1 [TcType]
tys2
      = do { [Either (Pair TcType) TcType]
results <- (TcType -> TcType -> TcS (Either (Pair TcType) TcType))
-> [TcType] -> [TcType] -> TcS [Either (Pair TcType) TcType]
forall (m :: * -> *) a b c.
Applicative m =>
(a -> b -> m c) -> [a] -> [b] -> m [c]
zipWithM TcType -> TcType -> TcS (Either (Pair TcType) TcType)
go [TcType]
tys1 [TcType]
tys2
           ; Either (Pair TcType) TcType -> TcS (Either (Pair TcType) TcType)
forall (m :: * -> *) a. Monad m => a -> m a
return (Either (Pair TcType) TcType -> TcS (Either (Pair TcType) TcType))
-> Either (Pair TcType) TcType -> TcS (Either (Pair TcType) TcType)
forall a b. (a -> b) -> a -> b
$ case [Either (Pair TcType) TcType] -> Either (Pair [TcType]) [TcType]
combine_results [Either (Pair TcType) TcType]
results of
               Left Pair [TcType]
tys  -> Pair TcType -> Either (Pair TcType) TcType
forall a b. a -> Either a b
Left (TyCon -> [TcType] -> TcType
mkTyConApp TyCon
tc ([TcType] -> TcType) -> Pair [TcType] -> Pair TcType
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Pair [TcType]
tys)
               Right [TcType]
tys -> TcType -> Either (Pair TcType) TcType
forall a b. b -> Either a b
Right (TyCon -> [TcType] -> TcType
mkTyConApp TyCon
tc [TcType]
tys) }

    combine_results :: [Either (Pair TcType) TcType]
                    -> Either (Pair [TcType]) [TcType]
    combine_results :: [Either (Pair TcType) TcType] -> Either (Pair [TcType]) [TcType]
combine_results = (Pair [TcType] -> Pair [TcType])
-> ([TcType] -> [TcType])
-> Either (Pair [TcType]) [TcType]
-> Either (Pair [TcType]) [TcType]
forall (p :: * -> * -> *) a b c d.
Bifunctor p =>
(a -> b) -> (c -> d) -> p a c -> p b d
bimap (([TcType] -> [TcType]) -> Pair [TcType] -> Pair [TcType]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap [TcType] -> [TcType]
forall a. [a] -> [a]
reverse) [TcType] -> [TcType]
forall a. [a] -> [a]
reverse (Either (Pair [TcType]) [TcType]
 -> Either (Pair [TcType]) [TcType])
-> ([Either (Pair TcType) TcType]
    -> Either (Pair [TcType]) [TcType])
-> [Either (Pair TcType) TcType]
-> Either (Pair [TcType]) [TcType]
forall b c a. (b -> c) -> (a -> b) -> a -> c
.
                      (Either (Pair [TcType]) [TcType]
 -> Either (Pair TcType) TcType -> Either (Pair [TcType]) [TcType])
-> Either (Pair [TcType]) [TcType]
-> [Either (Pair TcType) TcType]
-> Either (Pair [TcType]) [TcType]
forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
foldl' ((TcType -> [TcType] -> [TcType])
-> Either (Pair [TcType]) [TcType]
-> Either (Pair TcType) TcType
-> Either (Pair [TcType]) [TcType]
forall a b c.
(a -> b -> c)
-> Either (Pair b) b -> Either (Pair a) a -> Either (Pair c) c
combine_rev (:)) ([TcType] -> Either (Pair [TcType]) [TcType]
forall a b. b -> Either a b
Right [])

      -- combine (in reverse) a new result onto an already-combined result
    combine_rev :: (a -> b -> c)
                -> Either (Pair b) b
                -> Either (Pair a) a
                -> Either (Pair c) c
    combine_rev :: forall a b c.
(a -> b -> c)
-> Either (Pair b) b -> Either (Pair a) a -> Either (Pair c) c
combine_rev a -> b -> c
f (Left Pair b
list) (Left Pair a
elt) = Pair c -> Either (Pair c) c
forall a b. a -> Either a b
Left (a -> b -> c
f (a -> b -> c) -> Pair a -> Pair (b -> c)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Pair a
elt     Pair (b -> c) -> Pair b -> Pair c
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> Pair b
list)
    combine_rev a -> b -> c
f (Left Pair b
list) (Right a
ty) = Pair c -> Either (Pair c) c
forall a b. a -> Either a b
Left (a -> b -> c
f (a -> b -> c) -> Pair a -> Pair (b -> c)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> a -> Pair a
forall (f :: * -> *) a. Applicative f => a -> f a
pure a
ty Pair (b -> c) -> Pair b -> Pair c
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> Pair b
list)
    combine_rev a -> b -> c
f (Right b
tys) (Left Pair a
elt) = Pair c -> Either (Pair c) c
forall a b. a -> Either a b
Left (a -> b -> c
f (a -> b -> c) -> Pair a -> Pair (b -> c)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Pair a
elt     Pair (b -> c) -> Pair b -> Pair c
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> b -> Pair b
forall (f :: * -> *) a. Applicative f => a -> f a
pure b
tys)
    combine_rev a -> b -> c
f (Right b
tys) (Right a
ty) = c -> Either (Pair c) c
forall a b. b -> Either a b
Right (a -> b -> c
f a
ty b
tys)

{- See Note [Unwrap newtypes first]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
  newtype N m a = MkN (m a)
Then N will get a conservative, Nominal role for its second parameter 'a',
because it appears as an argument to the unknown 'm'. Now consider
  [W] N Maybe a  ~R#  N Maybe b

If we decompose, we'll get
  [W] a ~N# b

But if instead we unwrap we'll get
  [W] Maybe a ~R# Maybe b
which in turn gives us
  [W] a ~R# b
which is easier to satisfy.

Bottom line: unwrap newtypes before decomposing them!
c.f. #9123 comment:52,53 for a compelling example.

Note [Newtypes can blow the stack]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose we have

  newtype X = MkX (Int -> X)
  newtype Y = MkY (Int -> Y)

and now wish to prove

  [W] X ~R Y

This Wanted will loop, expanding out the newtypes ever deeper looking
for a solid match or a solid discrepancy. Indeed, there is something
appropriate to this looping, because X and Y *do* have the same representation,
in the limit -- they're both (Fix ((->) Int)). However, no finitely-sized
coercion will ever witness it. This loop won't actually cause GHC to hang,
though, because we check our depth when unwrapping newtypes.

Note [Eager reflexivity check]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose we have

  newtype X = MkX (Int -> X)

and

  [W] X ~R X

Naively, we would start unwrapping X and end up in a loop. Instead,
we do this eager reflexivity check. This is necessary only for representational
equality because the flattener technology deals with the similar case
(recursive type families) for nominal equality.

Note that this check does not catch all cases, but it will catch the cases
we're most worried about, types like X above that are actually inhabited.

Here's another place where this reflexivity check is key:
Consider trying to prove (f a) ~R (f a). The AppTys in there can't
be decomposed, because representational equality isn't congruent with respect
to AppTy. So, when canonicalising the equality above, we get stuck and
would normally produce a CIrredCan. However, we really do want to
be able to solve (f a) ~R (f a). So, in the representational case only,
we do a reflexivity check.

(This would be sound in the nominal case, but unnecessary, and I [Richard
E.] am worried that it would slow down the common case.)
-}

------------------------
-- | We're able to unwrap a newtype. Update the bits accordingly.
can_eq_newtype_nc :: CtEvidence           -- ^ :: ty1 ~ ty2
                  -> SwapFlag
                  -> TcType                                    -- ^ ty1
                  -> ((Bag GlobalRdrElt, TcCoercion), TcType)  -- ^ :: ty1 ~ ty1'
                  -> TcType               -- ^ ty2
                  -> TcType               -- ^ ty2, with type synonyms
                  -> TcS (StopOrContinue Ct)
can_eq_newtype_nc :: CtEvidence
-> SwapFlag
-> TcType
-> ((Bag GlobalRdrElt, TcCoercion), TcType)
-> TcType
-> TcType
-> TcS (StopOrContinue Ct)
can_eq_newtype_nc CtEvidence
ev SwapFlag
swapped TcType
ty1 ((Bag GlobalRdrElt
gres, TcCoercion
co), TcType
ty1') TcType
ty2 TcType
ps_ty2
  = do { String -> SDoc -> TcS ()
traceTcS String
"can_eq_newtype_nc" (SDoc -> TcS ()) -> SDoc -> TcS ()
forall a b. (a -> b) -> a -> b
$
         [SDoc] -> SDoc
vcat [ CtEvidence -> SDoc
forall a. Outputable a => a -> SDoc
ppr CtEvidence
ev, SwapFlag -> SDoc
forall a. Outputable a => a -> SDoc
ppr SwapFlag
swapped, TcCoercion -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcCoercion
co, Bag GlobalRdrElt -> SDoc
forall a. Outputable a => a -> SDoc
ppr Bag GlobalRdrElt
gres, TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
ty1', TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
ty2 ]

         -- check for blowing our stack:
         -- See Note [Newtypes can blow the stack]
       ; CtLoc -> TcType -> TcS ()
checkReductionDepth (CtEvidence -> CtLoc
ctEvLoc CtEvidence
ev) TcType
ty1

         -- Next, we record uses of newtype constructors, since coercing
         -- through newtypes is tantamount to using their constructors.
       ; [GlobalRdrElt] -> TcS ()
addUsedGREs [GlobalRdrElt]
gre_list
         -- If a newtype constructor was imported, don't warn about not
         -- importing it...
       ; (Name -> TcS ()) -> [Name] -> TcS ()
forall (t :: * -> *) (f :: * -> *) a b.
(Foldable t, Applicative f) =>
(a -> f b) -> t a -> f ()
traverse_ Name -> TcS ()
keepAlive ([Name] -> TcS ()) -> [Name] -> TcS ()
forall a b. (a -> b) -> a -> b
$ (GlobalRdrElt -> Name) -> [GlobalRdrElt] -> [Name]
forall a b. (a -> b) -> [a] -> [b]
map GlobalRdrElt -> Name
gre_name [GlobalRdrElt]
gre_list
         -- ...and similarly, if a newtype constructor was defined in the same
         -- module, don't warn about it being unused.
         -- See Note [Tracking unused binding and imports] in GHC.Tc.Utils.

       ; CtEvidence
new_ev <- CtEvidence
-> SwapFlag
-> TcType
-> TcType
-> TcCoercion
-> TcCoercion
-> TcS CtEvidence
rewriteEqEvidence CtEvidence
ev SwapFlag
swapped TcType
ty1' TcType
ps_ty2
                                     (TcCoercion -> TcCoercion
mkTcSymCo TcCoercion
co) (Role -> TcType -> TcCoercion
mkTcReflCo Role
Representational TcType
ps_ty2)
       ; Bool
-> CtEvidence
-> EqRel
-> TcType
-> TcType
-> TcType
-> TcType
-> TcS (StopOrContinue Ct)
can_eq_nc Bool
False CtEvidence
new_ev EqRel
ReprEq TcType
ty1' TcType
ty1' TcType
ty2 TcType
ps_ty2 }
  where
    gre_list :: [GlobalRdrElt]
gre_list = Bag GlobalRdrElt -> [GlobalRdrElt]
forall a. Bag a -> [a]
bagToList Bag GlobalRdrElt
gres

---------
-- ^ Decompose a type application.
-- All input types must be flat. See Note [Canonicalising type applications]
-- Nominal equality only!
can_eq_app :: CtEvidence       -- :: s1 t1 ~N s2 t2
           -> Xi -> Xi         -- s1 t1
           -> Xi -> Xi         -- s2 t2
           -> TcS (StopOrContinue Ct)

-- AppTys only decompose for nominal equality, so this case just leads
-- to an irreducible constraint; see typecheck/should_compile/T10494
-- See Note [Decomposing equality], note {4}
can_eq_app :: CtEvidence
-> TcType -> TcType -> TcType -> TcType -> TcS (StopOrContinue Ct)
can_eq_app CtEvidence
ev TcType
s1 TcType
t1 TcType
s2 TcType
t2
  | CtDerived {} <- CtEvidence
ev
  = do { CtLoc -> [Role] -> [TcType] -> [TcType] -> TcS ()
unifyDeriveds CtLoc
loc [Role
Nominal, Role
Nominal] [TcType
s1, TcType
t1] [TcType
s2, TcType
t2]
       ; CtEvidence -> String -> TcS (StopOrContinue Ct)
forall a. CtEvidence -> String -> TcS (StopOrContinue a)
stopWith CtEvidence
ev String
"Decomposed [D] AppTy" }

  | CtWanted { ctev_dest :: CtEvidence -> TcEvDest
ctev_dest = TcEvDest
dest } <- CtEvidence
ev
  = do { TcCoercion
co_s <- CtLoc -> Role -> TcType -> TcType -> TcS TcCoercion
unifyWanted CtLoc
loc Role
Nominal TcType
s1 TcType
s2
       ; let arg_loc :: CtLoc
arg_loc
               | TcType -> Bool
isNextArgVisible TcType
s1 = CtLoc
loc
               | Bool
otherwise           = CtLoc -> (CtOrigin -> CtOrigin) -> CtLoc
updateCtLocOrigin CtLoc
loc CtOrigin -> CtOrigin
toInvisibleOrigin
       ; TcCoercion
co_t <- CtLoc -> Role -> TcType -> TcType -> TcS TcCoercion
unifyWanted CtLoc
arg_loc Role
Nominal TcType
t1 TcType
t2
       ; let co :: TcCoercion
co = TcCoercion -> TcCoercion -> TcCoercion
mkAppCo TcCoercion
co_s TcCoercion
co_t
       ; TcEvDest -> TcCoercion -> TcS ()
setWantedEq TcEvDest
dest TcCoercion
co
       ; CtEvidence -> String -> TcS (StopOrContinue Ct)
forall a. CtEvidence -> String -> TcS (StopOrContinue a)
stopWith CtEvidence
ev String
"Decomposed [W] AppTy" }

    -- If there is a ForAll/(->) mismatch, the use of the Left coercion
    -- below is ill-typed, potentially leading to a panic in splitTyConApp
    -- Test case: typecheck/should_run/Typeable1
    -- We could also include this mismatch check above (for W and D), but it's slow
    -- and we'll get a better error message not doing it
  | TcType
s1k TcType -> TcType -> Bool
`mismatches` TcType
s2k
  = CtEvidence -> TcType -> TcType -> TcS (StopOrContinue Ct)
canEqHardFailure CtEvidence
ev (TcType
s1 TcType -> TcType -> TcType
`mkAppTy` TcType
t1) (TcType
s2 TcType -> TcType -> TcType
`mkAppTy` TcType
t2)

  | CtGiven { ctev_evar :: CtEvidence -> TcTyVar
ctev_evar = TcTyVar
evar } <- CtEvidence
ev
  = do { let co :: TcCoercion
co   = TcTyVar -> TcCoercion
mkTcCoVarCo TcTyVar
evar
             co_s :: TcCoercion
co_s = LeftOrRight -> TcCoercion -> TcCoercion
mkTcLRCo LeftOrRight
CLeft  TcCoercion
co
             co_t :: TcCoercion
co_t = LeftOrRight -> TcCoercion -> TcCoercion
mkTcLRCo LeftOrRight
CRight TcCoercion
co
       ; CtEvidence
evar_s <- CtLoc -> (TcType, EvTerm) -> TcS CtEvidence
newGivenEvVar CtLoc
loc ( CtEvidence -> TcType -> TcType -> TcType
mkTcEqPredLikeEv CtEvidence
ev TcType
s1 TcType
s2
                                     , TcCoercion -> EvTerm
evCoercion TcCoercion
co_s )
       ; CtEvidence
evar_t <- CtLoc -> (TcType, EvTerm) -> TcS CtEvidence
newGivenEvVar CtLoc
loc ( CtEvidence -> TcType -> TcType -> TcType
mkTcEqPredLikeEv CtEvidence
ev TcType
t1 TcType
t2
                                     , TcCoercion -> EvTerm
evCoercion TcCoercion
co_t )
       ; [CtEvidence] -> TcS ()
emitWorkNC [CtEvidence
evar_t]
       ; CtEvidence -> EqRel -> TcType -> TcType -> TcS (StopOrContinue Ct)
canEqNC CtEvidence
evar_s EqRel
NomEq TcType
s1 TcType
s2 }

  where
    loc :: CtLoc
loc = CtEvidence -> CtLoc
ctEvLoc CtEvidence
ev

    s1k :: TcType
s1k = HasDebugCallStack => TcType -> TcType
TcType -> TcType
tcTypeKind TcType
s1
    s2k :: TcType
s2k = HasDebugCallStack => TcType -> TcType
TcType -> TcType
tcTypeKind TcType
s2

    TcType
k1 mismatches :: TcType -> TcType -> Bool
`mismatches` TcType
k2
      =  TcType -> Bool
isForAllTy TcType
k1 Bool -> Bool -> Bool
&& Bool -> Bool
not (TcType -> Bool
isForAllTy TcType
k2)
      Bool -> Bool -> Bool
|| Bool -> Bool
not (TcType -> Bool
isForAllTy TcType
k1) Bool -> Bool -> Bool
&& TcType -> Bool
isForAllTy TcType
k2

-----------------------
-- | Break apart an equality over a casted type
-- looking like   (ty1 |> co1) ~ ty2   (modulo a swap-flag)
canEqCast :: Bool         -- are both types flat?
          -> CtEvidence
          -> EqRel
          -> SwapFlag
          -> TcType -> Coercion   -- LHS (res. RHS), ty1 |> co1
          -> TcType -> TcType     -- RHS (res. LHS), ty2 both normal and pretty
          -> TcS (StopOrContinue Ct)
canEqCast :: Bool
-> CtEvidence
-> EqRel
-> SwapFlag
-> TcType
-> TcCoercion
-> TcType
-> TcType
-> TcS (StopOrContinue Ct)
canEqCast Bool
flat CtEvidence
ev EqRel
eq_rel SwapFlag
swapped TcType
ty1 TcCoercion
co1 TcType
ty2 TcType
ps_ty2
  = do { String -> SDoc -> TcS ()
traceTcS String
"Decomposing cast" ([SDoc] -> SDoc
vcat [ CtEvidence -> SDoc
forall a. Outputable a => a -> SDoc
ppr CtEvidence
ev
                                           , TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
ty1 SDoc -> SDoc -> SDoc
<+> String -> SDoc
text String
"|>" SDoc -> SDoc -> SDoc
<+> TcCoercion -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcCoercion
co1
                                           , TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
ps_ty2 ])
       ; CtEvidence
new_ev <- CtEvidence
-> SwapFlag
-> TcType
-> TcType
-> TcCoercion
-> TcCoercion
-> TcS CtEvidence
rewriteEqEvidence CtEvidence
ev SwapFlag
swapped TcType
ty1 TcType
ps_ty2
                                     (Role -> TcType -> TcCoercion -> TcCoercion
mkTcGReflRightCo Role
role TcType
ty1 TcCoercion
co1)
                                     (Role -> TcType -> TcCoercion
mkTcReflCo Role
role TcType
ps_ty2)
       ; Bool
-> CtEvidence
-> EqRel
-> TcType
-> TcType
-> TcType
-> TcType
-> TcS (StopOrContinue Ct)
can_eq_nc Bool
flat CtEvidence
new_ev EqRel
eq_rel TcType
ty1 TcType
ty1 TcType
ty2 TcType
ps_ty2 }
  where
    role :: Role
role = EqRel -> Role
eqRelRole EqRel
eq_rel

------------------------
canTyConApp :: CtEvidence -> EqRel
            -> TyCon -> [TcType]
            -> TyCon -> [TcType]
            -> TcS (StopOrContinue Ct)
-- See Note [Decomposing TyConApps]
-- Neither tc1 nor tc2 is a saturated funTyCon
canTyConApp :: CtEvidence
-> EqRel
-> TyCon
-> [TcType]
-> TyCon
-> [TcType]
-> TcS (StopOrContinue Ct)
canTyConApp CtEvidence
ev EqRel
eq_rel TyCon
tc1 [TcType]
tys1 TyCon
tc2 [TcType]
tys2
  | TyCon
tc1 TyCon -> TyCon -> Bool
forall a. Eq a => a -> a -> Bool
== TyCon
tc2
  , [TcType]
tys1 [TcType] -> [TcType] -> Bool
forall a b. [a] -> [b] -> Bool
`equalLength` [TcType]
tys2
  = do { InertSet
inerts <- TcS InertSet
getTcSInerts
       ; if InertSet -> Bool
can_decompose InertSet
inerts
         then CtEvidence
-> EqRel
-> TyCon
-> [TcType]
-> [TcType]
-> TcS (StopOrContinue Ct)
canDecomposableTyConAppOK CtEvidence
ev EqRel
eq_rel TyCon
tc1 [TcType]
tys1 [TcType]
tys2
         else CtEvidence -> EqRel -> TcType -> TcType -> TcS (StopOrContinue Ct)
canEqFailure CtEvidence
ev EqRel
eq_rel TcType
ty1 TcType
ty2 }

  -- See Note [Skolem abstract data] (at tyConSkolem)
  | TyCon -> Bool
tyConSkolem TyCon
tc1 Bool -> Bool -> Bool
|| TyCon -> Bool
tyConSkolem TyCon
tc2
  = do { String -> SDoc -> TcS ()
traceTcS String
"canTyConApp: skolem abstract" (TyCon -> SDoc
forall a. Outputable a => a -> SDoc
ppr TyCon
tc1 SDoc -> SDoc -> SDoc
$$ TyCon -> SDoc
forall a. Outputable a => a -> SDoc
ppr TyCon
tc2)
       ; Ct -> TcS (StopOrContinue Ct)
forall a. a -> TcS (StopOrContinue a)
continueWith (CtIrredStatus -> CtEvidence -> Ct
mkIrredCt CtIrredStatus
OtherCIS CtEvidence
ev) }

  -- Fail straight away for better error messages
  -- See Note [Use canEqFailure in canDecomposableTyConApp]
  | EqRel
eq_rel EqRel -> EqRel -> Bool
forall a. Eq a => a -> a -> Bool
== EqRel
ReprEq Bool -> Bool -> Bool
&& Bool -> Bool
not (TyCon -> Role -> Bool
isGenerativeTyCon TyCon
tc1 Role
Representational Bool -> Bool -> Bool
&&
                             TyCon -> Role -> Bool
isGenerativeTyCon TyCon
tc2 Role
Representational)
  = CtEvidence -> EqRel -> TcType -> TcType -> TcS (StopOrContinue Ct)
canEqFailure CtEvidence
ev EqRel
eq_rel TcType
ty1 TcType
ty2
  | Bool
otherwise
  = CtEvidence -> TcType -> TcType -> TcS (StopOrContinue Ct)
canEqHardFailure CtEvidence
ev TcType
ty1 TcType
ty2
  where
    -- Reconstruct the types for error messages. This would do
    -- the wrong thing (from a pretty printing point of view)
    -- for functions, because we've lost the AnonArgFlag; but
    -- in fact we never call canTyConApp on a saturated FunTyCon
    ty1 :: TcType
ty1 = TyCon -> [TcType] -> TcType
mkTyConApp TyCon
tc1 [TcType]
tys1
    ty2 :: TcType
ty2 = TyCon -> [TcType] -> TcType
mkTyConApp TyCon
tc2 [TcType]
tys2

    loc :: CtLoc
loc  = CtEvidence -> CtLoc
ctEvLoc CtEvidence
ev
    pred :: TcType
pred = CtEvidence -> TcType
ctEvPred CtEvidence
ev

     -- See Note [Decomposing equality]
    can_decompose :: InertSet -> Bool
can_decompose InertSet
inerts
      =  TyCon -> Role -> Bool
isInjectiveTyCon TyCon
tc1 (EqRel -> Role
eqRelRole EqRel
eq_rel)
      Bool -> Bool -> Bool
|| (CtEvidence -> CtFlavour
ctEvFlavour CtEvidence
ev CtFlavour -> CtFlavour -> Bool
forall a. Eq a => a -> a -> Bool
/= CtFlavour
Given Bool -> Bool -> Bool
&& Bag Ct -> Bool
forall a. Bag a -> Bool
isEmptyBag (CtLoc -> TcType -> InertSet -> Bag Ct
matchableGivens CtLoc
loc TcType
pred InertSet
inerts))

{-
Note [Use canEqFailure in canDecomposableTyConApp]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We must use canEqFailure, not canEqHardFailure here, because there is
the possibility of success if working with a representational equality.
Here is one case:

  type family TF a where TF Char = Bool
  data family DF a
  newtype instance DF Bool = MkDF Int

Suppose we are canonicalising (Int ~R DF (TF a)), where we don't yet
know `a`. This is *not* a hard failure, because we might soon learn
that `a` is, in fact, Char, and then the equality succeeds.

Here is another case:

  [G] Age ~R Int

where Age's constructor is not in scope. We don't want to report
an "inaccessible code" error in the context of this Given!

For example, see typecheck/should_compile/T10493, repeated here:

  import Data.Ord (Down)  -- no constructor

  foo :: Coercible (Down Int) Int => Down Int -> Int
  foo = coerce

That should compile, but only because we use canEqFailure and not
canEqHardFailure.

Note [Decomposing equality]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
If we have a constraint (of any flavour and role) that looks like
T tys1 ~ T tys2, what can we conclude about tys1 and tys2? The answer,
of course, is "it depends". This Note spells it all out.

In this Note, "decomposition" refers to taking the constraint
  [fl] (T tys1 ~X T tys2)
(for some flavour fl and some role X) and replacing it with
  [fls'] (tys1 ~Xs' tys2)
where that notation indicates a list of new constraints, where the
new constraints may have different flavours and different roles.

The key property to consider is injectivity. When decomposing a Given the
decomposition is sound if and only if T is injective in all of its type
arguments. When decomposing a Wanted, the decomposition is sound (assuming the
correct roles in the produced equality constraints), but it may be a guess --
that is, an unforced decision by the constraint solver. Decomposing Wanteds
over injective TyCons does not entail guessing. But sometimes we want to
decompose a Wanted even when the TyCon involved is not injective! (See below.)

So, in broad strokes, we want this rule:

(*) Decompose a constraint (T tys1 ~X T tys2) if and only if T is injective
at role X.

Pursuing the details requires exploring three axes:
* Flavour: Given vs. Derived vs. Wanted
* Role: Nominal vs. Representational
* TyCon species: datatype vs. newtype vs. data family vs. type family vs. type variable

(So a type variable isn't a TyCon, but it's convenient to put the AppTy case
in the same table.)

Right away, we can say that Derived behaves just as Wanted for the purposes
of decomposition. The difference between Derived and Wanted is the handling of
evidence. Since decomposition in these cases isn't a matter of soundness but of
guessing, we want the same behavior regardless of evidence.

Here is a table (discussion following) detailing where decomposition of
   (T s1 ... sn) ~r (T t1 .. tn)
is allowed.  The first four lines (Data types ... type family) refer
to TyConApps with various TyCons T; the last line is for AppTy, where
there is presumably a type variable at the head, so it's actually
   (s s1 ... sn) ~r (t t1 .. tn)

NOMINAL               GIVEN                       WANTED

Datatype               YES                         YES
Newtype                YES                         YES
Data family            YES                         YES
Type family            YES, in injective args{1}   YES, in injective args{1}
Type variable          YES                         YES

REPRESENTATIONAL      GIVEN                       WANTED

Datatype               YES                         YES
Newtype                NO{2}                      MAYBE{2}
Data family            NO{3}                      MAYBE{3}
Type family             NO                          NO
Type variable          NO{4}                       NO{4}

{1}: Type families can be injective in some, but not all, of their arguments,
so we want to do partial decomposition. This is quite different than the way
other decomposition is done, where the decomposed equalities replace the original
one. We thus proceed much like we do with superclasses: emitting new Givens
when "decomposing" a partially-injective type family Given and new Deriveds
when "decomposing" a partially-injective type family Wanted. (As of the time of
writing, 13 June 2015, the implementation of injective type families has not
been merged, but it should be soon. Please delete this parenthetical if the
implementation is indeed merged.)

{2}: See Note [Decomposing newtypes at representational role]

{3}: Because of the possibility of newtype instances, we must treat
data families like newtypes. See also Note [Decomposing newtypes at
representational role]. See #10534 and test case
typecheck/should_fail/T10534.

{4}: Because type variables can stand in for newtypes, we conservatively do not
decompose AppTys over representational equality.

In the implementation of can_eq_nc and friends, we don't directly pattern
match using lines like in the tables above, as those tables don't cover
all cases (what about PrimTyCon? tuples?). Instead we just ask about injectivity,
boiling the tables above down to rule (*). The exceptions to rule (*) are for
injective type families, which are handled separately from other decompositions,
and the MAYBE entries above.

Note [Decomposing newtypes at representational role]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This note discusses the 'newtype' line in the REPRESENTATIONAL table
in Note [Decomposing equality]. (At nominal role, newtypes are fully
decomposable.)

Here is a representative example of why representational equality over
newtypes is tricky:

  newtype Nt a = Mk Bool         -- NB: a is not used in the RHS,
  type role Nt representational  -- but the user gives it an R role anyway

If we have [W] Nt alpha ~R Nt beta, we *don't* want to decompose to
[W] alpha ~R beta, because it's possible that alpha and beta aren't
representationally equal. Here's another example.

  newtype Nt a = MkNt (Id a)
  type family Id a where Id a = a

  [W] Nt Int ~R Nt Age

Because of its use of a type family, Nt's parameter will get inferred to have
a nominal role. Thus, decomposing the wanted will yield [W] Int ~N Age, which
is unsatisfiable. Unwrapping, though, leads to a solution.

Conclusion:
 * Unwrap newtypes before attempting to decompose them.
   This is done in can_eq_nc'.

It all comes from the fact that newtypes aren't necessarily injective
w.r.t. representational equality.

Furthermore, as explained in Note [NthCo and newtypes] in GHC.Core.TyCo.Rep, we can't use
NthCo on representational coercions over newtypes. NthCo comes into play
only when decomposing givens.

Conclusion:
 * Do not decompose [G] N s ~R N t

Is it sensible to decompose *Wanted* constraints over newtypes?  Yes!
It's the only way we could ever prove (IO Int ~R IO Age), recalling
that IO is a newtype.

However we must be careful.  Consider

  type role Nt representational

  [G] Nt a ~R Nt b       (1)
  [W] NT alpha ~R Nt b   (2)
  [W] alpha ~ a          (3)

If we focus on (3) first, we'll substitute in (2), and now it's
identical to the given (1), so we succeed.  But if we focus on (2)
first, and decompose it, we'll get (alpha ~R b), which is not soluble.
This is exactly like the question of overlapping Givens for class
constraints: see Note [Instance and Given overlap] in GHC.Tc.Solver.Interact.

Conclusion:
  * Decompose [W] N s ~R N t  iff there no given constraint that could
    later solve it.

-}

canDecomposableTyConAppOK :: CtEvidence -> EqRel
                          -> TyCon -> [TcType] -> [TcType]
                          -> TcS (StopOrContinue Ct)
-- Precondition: tys1 and tys2 are the same length, hence "OK"
canDecomposableTyConAppOK :: CtEvidence
-> EqRel
-> TyCon
-> [TcType]
-> [TcType]
-> TcS (StopOrContinue Ct)
canDecomposableTyConAppOK CtEvidence
ev EqRel
eq_rel TyCon
tc [TcType]
tys1 [TcType]
tys2
  = ASSERT( tys1 `equalLength` tys2 )
    do { String -> SDoc -> TcS ()
traceTcS String
"canDecomposableTyConAppOK"
                  (CtEvidence -> SDoc
forall a. Outputable a => a -> SDoc
ppr CtEvidence
ev SDoc -> SDoc -> SDoc
$$ EqRel -> SDoc
forall a. Outputable a => a -> SDoc
ppr EqRel
eq_rel SDoc -> SDoc -> SDoc
$$ TyCon -> SDoc
forall a. Outputable a => a -> SDoc
ppr TyCon
tc SDoc -> SDoc -> SDoc
$$ [TcType] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [TcType]
tys1 SDoc -> SDoc -> SDoc
$$ [TcType] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [TcType]
tys2)
       ; case CtEvidence
ev of
           CtDerived {}
             -> CtLoc -> [Role] -> [TcType] -> [TcType] -> TcS ()
unifyDeriveds CtLoc
loc [Role]
tc_roles [TcType]
tys1 [TcType]
tys2

           CtWanted { ctev_dest :: CtEvidence -> TcEvDest
ctev_dest = TcEvDest
dest }
                  -- new_locs and tc_roles are both infinite, so
                  -- we are guaranteed that cos has the same length
                  -- as tys1 and tys2
             -> do { [TcCoercion]
cos <- (CtLoc -> Role -> TcType -> TcType -> TcS TcCoercion)
-> [CtLoc] -> [Role] -> [TcType] -> [TcType] -> TcS [TcCoercion]
forall (m :: * -> *) a b c d e.
Monad m =>
(a -> b -> c -> d -> m e) -> [a] -> [b] -> [c] -> [d] -> m [e]
zipWith4M CtLoc -> Role -> TcType -> TcType -> TcS TcCoercion
unifyWanted [CtLoc]
new_locs [Role]
tc_roles [TcType]
tys1 [TcType]
tys2
                   ; TcEvDest -> TcCoercion -> TcS ()
setWantedEq TcEvDest
dest (HasDebugCallStack => Role -> TyCon -> [TcCoercion] -> TcCoercion
Role -> TyCon -> [TcCoercion] -> TcCoercion
mkTyConAppCo Role
role TyCon
tc [TcCoercion]
cos) }

           CtGiven { ctev_evar :: CtEvidence -> TcTyVar
ctev_evar = TcTyVar
evar }
             -> do { let ev_co :: TcCoercion
ev_co = TcTyVar -> TcCoercion
mkCoVarCo TcTyVar
evar
                   ; [CtEvidence]
given_evs <- CtLoc -> [(TcType, EvTerm)] -> TcS [CtEvidence]
newGivenEvVars CtLoc
loc ([(TcType, EvTerm)] -> TcS [CtEvidence])
-> [(TcType, EvTerm)] -> TcS [CtEvidence]
forall a b. (a -> b) -> a -> b
$
                                  [ ( Role -> TcType -> TcType -> TcType
mkPrimEqPredRole Role
r TcType
ty1 TcType
ty2
                                    , TcCoercion -> EvTerm
evCoercion (TcCoercion -> EvTerm) -> TcCoercion -> EvTerm
forall a b. (a -> b) -> a -> b
$ HasDebugCallStack => Role -> Int -> TcCoercion -> TcCoercion
Role -> Int -> TcCoercion -> TcCoercion
mkNthCo Role
r Int
i TcCoercion
ev_co )
                                  | (Role
r, TcType
ty1, TcType
ty2, Int
i) <- [Role]
-> [TcType] -> [TcType] -> [Int] -> [(Role, TcType, TcType, Int)]
forall a b c d. [a] -> [b] -> [c] -> [d] -> [(a, b, c, d)]
zip4 [Role]
tc_roles [TcType]
tys1 [TcType]
tys2 [Int
0..]
                                  , Role
r Role -> Role -> Bool
forall a. Eq a => a -> a -> Bool
/= Role
Phantom
                                  , Bool -> Bool
not (TcType -> Bool
isCoercionTy TcType
ty1) Bool -> Bool -> Bool
&& Bool -> Bool
not (TcType -> Bool
isCoercionTy TcType
ty2) ]
                   ; [CtEvidence] -> TcS ()
emitWorkNC [CtEvidence]
given_evs }

    ; CtEvidence -> String -> TcS (StopOrContinue Ct)
forall a. CtEvidence -> String -> TcS (StopOrContinue a)
stopWith CtEvidence
ev String
"Decomposed TyConApp" }

  where
    loc :: CtLoc
loc        = CtEvidence -> CtLoc
ctEvLoc CtEvidence
ev
    role :: Role
role       = EqRel -> Role
eqRelRole EqRel
eq_rel

      -- infinite, as tyConRolesX returns an infinite tail of Nominal
    tc_roles :: [Role]
tc_roles   = Role -> TyCon -> [Role]
tyConRolesX Role
role TyCon
tc

      -- Add nuances to the location during decomposition:
      --  * if the argument is a kind argument, remember this, so that error
      --    messages say "kind", not "type". This is determined based on whether
      --    the corresponding tyConBinder is named (that is, dependent)
      --  * if the argument is invisible, note this as well, again by
      --    looking at the corresponding binder
      -- For oversaturated tycons, we need the (repeat loc) tail, which doesn't
      -- do either of these changes. (Forgetting to do so led to #16188)
      --
      -- NB: infinite in length
    new_locs :: [CtLoc]
new_locs = [ CtLoc
new_loc
               | TyConBinder
bndr <- TyCon -> [TyConBinder]
tyConBinders TyCon
tc
               , let new_loc0 :: CtLoc
new_loc0 | TyConBinder -> Bool
isNamedTyConBinder TyConBinder
bndr = CtLoc -> CtLoc
toKindLoc CtLoc
loc
                              | Bool
otherwise               = CtLoc
loc
                     new_loc :: CtLoc
new_loc  | TyConBinder -> Bool
forall tv. VarBndr tv TyConBndrVis -> Bool
isVisibleTyConBinder TyConBinder
bndr
                              = CtLoc -> (CtOrigin -> CtOrigin) -> CtLoc
updateCtLocOrigin CtLoc
new_loc0 CtOrigin -> CtOrigin
toInvisibleOrigin
                              | Bool
otherwise
                              = CtLoc
new_loc0 ]
               [CtLoc] -> [CtLoc] -> [CtLoc]
forall a. [a] -> [a] -> [a]
++ CtLoc -> [CtLoc]
forall a. a -> [a]
repeat CtLoc
loc

-- | Call when canonicalizing an equality fails, but if the equality is
-- representational, there is some hope for the future.
-- Examples in Note [Use canEqFailure in canDecomposableTyConApp]
canEqFailure :: CtEvidence -> EqRel
             -> TcType -> TcType -> TcS (StopOrContinue Ct)
canEqFailure :: CtEvidence -> EqRel -> TcType -> TcType -> TcS (StopOrContinue Ct)
canEqFailure CtEvidence
ev EqRel
NomEq TcType
ty1 TcType
ty2
  = CtEvidence -> TcType -> TcType -> TcS (StopOrContinue Ct)
canEqHardFailure CtEvidence
ev TcType
ty1 TcType
ty2
canEqFailure CtEvidence
ev EqRel
ReprEq TcType
ty1 TcType
ty2
  = do { (TcType
xi1, TcCoercion
co1) <- FlattenMode -> CtEvidence -> TcType -> TcS (TcType, TcCoercion)
flatten FlattenMode
FM_FlattenAll CtEvidence
ev TcType
ty1
       ; (TcType
xi2, TcCoercion
co2) <- FlattenMode -> CtEvidence -> TcType -> TcS (TcType, TcCoercion)
flatten FlattenMode
FM_FlattenAll CtEvidence
ev TcType
ty2
            -- We must flatten the types before putting them in the
            -- inert set, so that we are sure to kick them out when
            -- new equalities become available
       ; String -> SDoc -> TcS ()
traceTcS String
"canEqFailure with ReprEq" (SDoc -> TcS ()) -> SDoc -> TcS ()
forall a b. (a -> b) -> a -> b
$
         [SDoc] -> SDoc
vcat [ CtEvidence -> SDoc
forall a. Outputable a => a -> SDoc
ppr CtEvidence
ev, TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
ty1, TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
ty2, TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
xi1, TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
xi2 ]
       ; CtEvidence
new_ev <- CtEvidence
-> SwapFlag
-> TcType
-> TcType
-> TcCoercion
-> TcCoercion
-> TcS CtEvidence
rewriteEqEvidence CtEvidence
ev SwapFlag
NotSwapped TcType
xi1 TcType
xi2 TcCoercion
co1 TcCoercion
co2
       ; Ct -> TcS (StopOrContinue Ct)
forall a. a -> TcS (StopOrContinue a)
continueWith (CtIrredStatus -> CtEvidence -> Ct
mkIrredCt CtIrredStatus
OtherCIS CtEvidence
new_ev) }

-- | Call when canonicalizing an equality fails with utterly no hope.
canEqHardFailure :: CtEvidence
                 -> TcType -> TcType -> TcS (StopOrContinue Ct)
-- See Note [Make sure that insolubles are fully rewritten]
canEqHardFailure :: CtEvidence -> TcType -> TcType -> TcS (StopOrContinue Ct)
canEqHardFailure CtEvidence
ev TcType
ty1 TcType
ty2
  = do { String -> SDoc -> TcS ()
traceTcS String
"canEqHardFailure" (TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
ty1 SDoc -> SDoc -> SDoc
$$ TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
ty2)
       ; (TcType
s1, TcCoercion
co1) <- FlattenMode -> CtEvidence -> TcType -> TcS (TcType, TcCoercion)
flatten FlattenMode
FM_SubstOnly CtEvidence
ev TcType
ty1
       ; (TcType
s2, TcCoercion
co2) <- FlattenMode -> CtEvidence -> TcType -> TcS (TcType, TcCoercion)
flatten FlattenMode
FM_SubstOnly CtEvidence
ev TcType
ty2
       ; CtEvidence
new_ev <- CtEvidence
-> SwapFlag
-> TcType
-> TcType
-> TcCoercion
-> TcCoercion
-> TcS CtEvidence
rewriteEqEvidence CtEvidence
ev SwapFlag
NotSwapped TcType
s1 TcType
s2 TcCoercion
co1 TcCoercion
co2
       ; Ct -> TcS (StopOrContinue Ct)
forall a. a -> TcS (StopOrContinue a)
continueWith (CtIrredStatus -> CtEvidence -> Ct
mkIrredCt CtIrredStatus
InsolubleCIS CtEvidence
new_ev) }

{-
Note [Decomposing TyConApps]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If we see (T s1 t1 ~ T s2 t2), then we can just decompose to
  (s1 ~ s2, t1 ~ t2)
and push those back into the work list.  But if
  s1 = K k1    s2 = K k2
then we will just decomopose s1~s2, and it might be better to
do so on the spot.  An important special case is where s1=s2,
and we get just Refl.

So canDecomposableTyCon is a fast-path decomposition that uses
unifyWanted etc to short-cut that work.

Note [Canonicalising type applications]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Given (s1 t1) ~ ty2, how should we proceed?
The simple things is to see if ty2 is of form (s2 t2), and
decompose.  By this time s1 and s2 can't be saturated type
function applications, because those have been dealt with
by an earlier equation in can_eq_nc, so it is always sound to
decompose.

However, over-eager decomposition gives bad error messages
for things like
   a b ~ Maybe c
   e f ~ p -> q
Suppose (in the first example) we already know a~Array.  Then if we
decompose the application eagerly, yielding
   a ~ Maybe
   b ~ c
we get an error        "Can't match Array ~ Maybe",
but we'd prefer to get "Can't match Array b ~ Maybe c".

So instead can_eq_wanted_app flattens the LHS and RHS, in the hope of
replacing (a b) by (Array b), before using try_decompose_app to
decompose it.

Note [Make sure that insolubles are fully rewritten]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When an equality fails, we still want to rewrite the equality
all the way down, so that it accurately reflects
 (a) the mutable reference substitution in force at start of solving
 (b) any ty-binds in force at this point in solving
See Note [Rewrite insolubles] in GHC.Tc.Solver.Monad.
And if we don't do this there is a bad danger that
GHC.Tc.Solver.applyTyVarDefaulting will find a variable
that has in fact been substituted.

Note [Do not decompose Given polytype equalities]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider [G] (forall a. t1 ~ forall a. t2).  Can we decompose this?
No -- what would the evidence look like?  So instead we simply discard
this given evidence.


Note [Combining insoluble constraints]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
As this point we have an insoluble constraint, like Int~Bool.

 * If it is Wanted, delete it from the cache, so that subsequent
   Int~Bool constraints give rise to separate error messages

 * But if it is Derived, DO NOT delete from cache.  A class constraint
   may get kicked out of the inert set, and then have its functional
   dependency Derived constraints generated a second time. In that
   case we don't want to get two (or more) error messages by
   generating two (or more) insoluble fundep constraints from the same
   class constraint.

Note [No top-level newtypes on RHS of representational equalities]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose we're in this situation:

 work item:  [W] c1 : a ~R b
     inert:  [G] c2 : b ~R Id a

where
  newtype Id a = Id a

We want to make sure canEqTyVar sees [W] a ~R a, after b is flattened
and the Id newtype is unwrapped. This is assured by requiring only flat
types in canEqTyVar *and* having the newtype-unwrapping check above
the tyvar check in can_eq_nc.

Note [Occurs check error]
~~~~~~~~~~~~~~~~~~~~~~~~~
If we have an occurs check error, are we necessarily hosed? Say our
tyvar is tv1 and the type it appears in is xi2. Because xi2 is function
free, then if we're computing w.r.t. nominal equality, then, yes, we're
hosed. Nothing good can come from (a ~ [a]). If we're computing w.r.t.
representational equality, this is a little subtler. Once again, (a ~R [a])
is a bad thing, but (a ~R N a) for a newtype N might be just fine. This
means also that (a ~ b a) might be fine, because `b` might become a newtype.

So, we must check: does tv1 appear in xi2 under any type constructor
that is generative w.r.t. representational equality? That's what
isInsolubleOccursCheck does.

See also #10715, which induced this addition.

Note [canCFunEqCan]
~~~~~~~~~~~~~~~~~~~
Flattening the arguments to a type family can change the kind of the type
family application. As an easy example, consider (Any k) where (k ~ Type)
is in the inert set. The original (Any k :: k) becomes (Any Type :: Type).
The problem here is that the fsk in the CFunEqCan will have the old kind.

The solution is to come up with a new fsk/fmv of the right kind. For
givens, this is easy: just introduce a new fsk and update the flat-cache
with the new one. For wanteds, we want to solve the old one if favor of
the new one, so we use dischargeFmv. This also kicks out constraints
from the inert set; this behavior is correct, as the kind-change may
allow more constraints to be solved.

We use `isTcReflexiveCo`, to ensure that we only use the hetero-kinded case
if we really need to.  Of course `flattenArgsNom` should return `Refl`
whenever possible, but #15577 was an infinite loop because even
though the coercion was homo-kinded, `kind_co` was not `Refl`, so we
made a new (identical) CFunEqCan, and then the entire process repeated.
-}

canCFunEqCan :: CtEvidence
             -> TyCon -> [TcType]   -- LHS
             -> TcTyVar             -- RHS
             -> TcS (StopOrContinue Ct)
-- ^ Canonicalise a CFunEqCan.  We know that
--     the arg types are already flat,
-- and the RHS is a fsk, which we must *not* substitute.
-- So just substitute in the LHS
canCFunEqCan :: CtEvidence
-> TyCon -> [TcType] -> TcTyVar -> TcS (StopOrContinue Ct)
canCFunEqCan CtEvidence
ev TyCon
fn [TcType]
tys TcTyVar
fsk
  = do { ([TcType]
tys', [TcCoercion]
cos, TcCoercion
kind_co) <- CtEvidence
-> TyCon -> [TcType] -> TcS ([TcType], [TcCoercion], TcCoercion)
flattenArgsNom CtEvidence
ev TyCon
fn [TcType]
tys
                        -- cos :: tys' ~ tys

       ; let lhs_co :: TcCoercion
lhs_co  = Role -> TyCon -> [TcCoercion] -> TcCoercion
mkTcTyConAppCo Role
Nominal TyCon
fn [TcCoercion]
cos
                        -- :: F tys' ~ F tys
             new_lhs :: TcType
new_lhs = TyCon -> [TcType] -> TcType
mkTyConApp TyCon
fn [TcType]
tys'

             flav :: CtFlavour
flav    = CtEvidence -> CtFlavour
ctEvFlavour CtEvidence
ev
       ; (CtEvidence
ev', TcTyVar
fsk')
           <- if TcCoercion -> Bool
isTcReflexiveCo TcCoercion
kind_co   -- See Note [canCFunEqCan]
              then do { String -> SDoc -> TcS ()
traceTcS String
"canCFunEqCan: refl" (TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
new_lhs)
                      ; let fsk_ty :: TcType
fsk_ty = TcTyVar -> TcType
mkTyVarTy TcTyVar
fsk
                      ; CtEvidence
ev' <- CtEvidence
-> SwapFlag
-> TcType
-> TcType
-> TcCoercion
-> TcCoercion
-> TcS CtEvidence
rewriteEqEvidence CtEvidence
ev SwapFlag
NotSwapped TcType
new_lhs TcType
fsk_ty
                                                 TcCoercion
lhs_co (TcType -> TcCoercion
mkTcNomReflCo TcType
fsk_ty)
                      ; (CtEvidence, TcTyVar) -> TcS (CtEvidence, TcTyVar)
forall (m :: * -> *) a. Monad m => a -> m a
return (CtEvidence
ev', TcTyVar
fsk) }
              else do { String -> SDoc -> TcS ()
traceTcS String
"canCFunEqCan: non-refl" (SDoc -> TcS ()) -> SDoc -> TcS ()
forall a b. (a -> b) -> a -> b
$
                        [SDoc] -> SDoc
vcat [ String -> SDoc
text String
"Kind co:" SDoc -> SDoc -> SDoc
<+> TcCoercion -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcCoercion
kind_co
                             , String -> SDoc
text String
"RHS:" SDoc -> SDoc -> SDoc
<+> TcTyVar -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcTyVar
fsk SDoc -> SDoc -> SDoc
<+> SDoc
dcolon SDoc -> SDoc -> SDoc
<+> TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr (TcTyVar -> TcType
tyVarKind TcTyVar
fsk)
                             , String -> SDoc
text String
"LHS:" SDoc -> SDoc -> SDoc
<+> SDoc -> Int -> SDoc -> SDoc
hang (TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr (TyCon -> [TcType] -> TcType
mkTyConApp TyCon
fn [TcType]
tys))
                                                  Int
2 (SDoc
dcolon SDoc -> SDoc -> SDoc
<+> TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr (HasDebugCallStack => TcType -> TcType
TcType -> TcType
tcTypeKind (TyCon -> [TcType] -> TcType
mkTyConApp TyCon
fn [TcType]
tys)))
                             , String -> SDoc
text String
"New LHS" SDoc -> SDoc -> SDoc
<+> SDoc -> Int -> SDoc -> SDoc
hang (TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
new_lhs)
                                                     Int
2 (SDoc
dcolon SDoc -> SDoc -> SDoc
<+> TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr (HasDebugCallStack => TcType -> TcType
TcType -> TcType
tcTypeKind TcType
new_lhs)) ]
                      ; (CtEvidence
ev', TcCoercion
new_co, TcTyVar
new_fsk)
                          <- CtFlavour
-> CtLoc
-> TyCon
-> [TcType]
-> TcS (CtEvidence, TcCoercion, TcTyVar)
newFlattenSkolem CtFlavour
flav (CtEvidence -> CtLoc
ctEvLoc CtEvidence
ev) TyCon
fn [TcType]
tys'
                      ; let xi :: TcType
xi = TcTyVar -> TcType
mkTyVarTy TcTyVar
new_fsk TcType -> TcCoercion -> TcType
`mkCastTy` TcCoercion
kind_co
                               -- sym lhs_co :: F tys ~ F tys'
                               -- new_co     :: F tys' ~ new_fsk
                               -- co         :: F tys ~ (new_fsk |> kind_co)
                            co :: TcCoercion
co = TcCoercion -> TcCoercion
mkTcSymCo TcCoercion
lhs_co TcCoercion -> TcCoercion -> TcCoercion
`mkTcTransCo`
                                 Role -> TcType -> TcCoercion -> TcCoercion -> TcCoercion
mkTcCoherenceRightCo Role
Nominal
                                                      (TcTyVar -> TcType
mkTyVarTy TcTyVar
new_fsk)
                                                      TcCoercion
kind_co
                                                      TcCoercion
new_co

                      ; String -> SDoc -> TcS ()
traceTcS String
"Discharging fmv/fsk due to hetero flattening" (CtEvidence -> SDoc
forall a. Outputable a => a -> SDoc
ppr CtEvidence
ev)
                      ; CtEvidence -> TcTyVar -> TcCoercion -> TcType -> TcS ()
dischargeFunEq CtEvidence
ev TcTyVar
fsk TcCoercion
co TcType
xi
                      ; (CtEvidence, TcTyVar) -> TcS (CtEvidence, TcTyVar)
forall (m :: * -> *) a. Monad m => a -> m a
return (CtEvidence
ev', TcTyVar
new_fsk) }

       ; TyCon -> [TcType] -> (TcCoercion, TcType, CtFlavour) -> TcS ()
extendFlatCache TyCon
fn [TcType]
tys' (HasDebugCallStack => CtEvidence -> TcCoercion
CtEvidence -> TcCoercion
ctEvCoercion CtEvidence
ev', TcTyVar -> TcType
mkTyVarTy TcTyVar
fsk', CtEvidence -> CtFlavour
ctEvFlavour CtEvidence
ev')
       ; Ct -> TcS (StopOrContinue Ct)
forall a. a -> TcS (StopOrContinue a)
continueWith (CFunEqCan :: CtEvidence -> TyCon -> [TcType] -> TcTyVar -> Ct
CFunEqCan { cc_ev :: CtEvidence
cc_ev = CtEvidence
ev', cc_fun :: TyCon
cc_fun = TyCon
fn
                                 , cc_tyargs :: [TcType]
cc_tyargs = [TcType]
tys', cc_fsk :: TcTyVar
cc_fsk = TcTyVar
fsk' }) }

---------------------
canEqTyVar :: CtEvidence          -- ev :: lhs ~ rhs
           -> EqRel -> SwapFlag
           -> TcTyVar               -- tv1
           -> TcType                -- lhs: pretty lhs, already flat
           -> TcType -> TcType      -- rhs: already flat
           -> TcS (StopOrContinue Ct)
canEqTyVar :: CtEvidence
-> EqRel
-> SwapFlag
-> TcTyVar
-> TcType
-> TcType
-> TcType
-> TcS (StopOrContinue Ct)
canEqTyVar CtEvidence
ev EqRel
eq_rel SwapFlag
swapped TcTyVar
tv1 TcType
ps_xi1 TcType
xi2 TcType
ps_xi2
  | TcType
k1 HasDebugCallStack => TcType -> TcType -> Bool
TcType -> TcType -> Bool
`tcEqType` TcType
k2
  = CtEvidence
-> EqRel
-> SwapFlag
-> TcTyVar
-> TcType
-> TcType
-> TcType
-> TcS (StopOrContinue Ct)
canEqTyVarHomo CtEvidence
ev EqRel
eq_rel SwapFlag
swapped TcTyVar
tv1 TcType
ps_xi1 TcType
xi2 TcType
ps_xi2

  | Bool
otherwise
  = CtEvidence
-> EqRel
-> SwapFlag
-> TcTyVar
-> TcType
-> TcType
-> TcType
-> TcType
-> TcType
-> TcS (StopOrContinue Ct)
canEqTyVarHetero CtEvidence
ev EqRel
eq_rel SwapFlag
swapped TcTyVar
tv1 TcType
ps_xi1 TcType
k1 TcType
xi2 TcType
ps_xi2 TcType
k2

  where
    k1 :: TcType
k1 = TcTyVar -> TcType
tyVarKind TcTyVar
tv1
    k2 :: TcType
k2 = HasDebugCallStack => TcType -> TcType
TcType -> TcType
tcTypeKind TcType
xi2

canEqTyVarHetero :: CtEvidence         -- :: (tv1 :: ki1) ~ (xi2 :: ki2)
                 -> EqRel -> SwapFlag
                 -> TcTyVar -> TcType  -- tv1, pretty tv1
                 -> TcKind             -- ki1
                 -> TcType -> TcType   -- xi2, pretty xi2 :: ki2
                 -> TcKind             -- ki2
                 -> TcS (StopOrContinue Ct)
canEqTyVarHetero :: CtEvidence
-> EqRel
-> SwapFlag
-> TcTyVar
-> TcType
-> TcType
-> TcType
-> TcType
-> TcType
-> TcS (StopOrContinue Ct)
canEqTyVarHetero CtEvidence
ev EqRel
eq_rel SwapFlag
swapped TcTyVar
tv1 TcType
ps_tv1 TcType
ki1 TcType
xi2 TcType
ps_xi2 TcType
ki2
  -- See Note [Equalities with incompatible kinds]
  = do { TcCoercion
kind_co <- TcS TcCoercion
emit_kind_co   -- :: ki2 ~N ki1

       ; let  -- kind_co :: (ki2 :: *) ~N (ki1 :: *)   (whether swapped or not)
              -- co1     :: kind(tv1) ~N ki1
             rhs' :: TcType
rhs'    = TcType
xi2    TcType -> TcCoercion -> TcType
`mkCastTy` TcCoercion
kind_co   -- :: ki1
             ps_rhs' :: TcType
ps_rhs' = TcType
ps_xi2 TcType -> TcCoercion -> TcType
`mkCastTy` TcCoercion
kind_co   -- :: ki1
             rhs_co :: TcCoercion
rhs_co  = Role -> TcType -> TcCoercion -> TcCoercion
mkTcGReflLeftCo Role
role TcType
xi2 TcCoercion
kind_co
               -- rhs_co :: (xi2 |> kind_co) ~ xi2

             lhs' :: TcType
lhs'   = TcTyVar -> TcType
mkTyVarTy TcTyVar
tv1  -- same as old lhs
             lhs_co :: TcCoercion
lhs_co = Role -> TcType -> TcCoercion
mkTcReflCo Role
role TcType
lhs'

       ; String -> SDoc -> TcS ()
traceTcS String
"Hetero equality gives rise to kind equality"
           (TcCoercion -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcCoercion
kind_co SDoc -> SDoc -> SDoc
<+> SDoc
dcolon SDoc -> SDoc -> SDoc
<+> [SDoc] -> SDoc
sep [ TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
ki2, String -> SDoc
text String
"~#", TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
ki1 ])
       ; CtEvidence
type_ev <- CtEvidence
-> SwapFlag
-> TcType
-> TcType
-> TcCoercion
-> TcCoercion
-> TcS CtEvidence
rewriteEqEvidence CtEvidence
ev SwapFlag
swapped TcType
lhs' TcType
rhs' TcCoercion
lhs_co TcCoercion
rhs_co

          -- rewriteEqEvidence carries out the swap, so we're NotSwapped any more
       ; CtEvidence
-> EqRel
-> SwapFlag
-> TcTyVar
-> TcType
-> TcType
-> TcType
-> TcS (StopOrContinue Ct)
canEqTyVarHomo CtEvidence
type_ev EqRel
eq_rel SwapFlag
NotSwapped TcTyVar
tv1 TcType
ps_tv1 TcType
rhs' TcType
ps_rhs' }
  where
    emit_kind_co :: TcS CoercionN
    emit_kind_co :: TcS TcCoercion
emit_kind_co
      | CtGiven { ctev_evar :: CtEvidence -> TcTyVar
ctev_evar = TcTyVar
evar } <- CtEvidence
ev
      = do { let kind_co :: TcCoercion
kind_co = TcCoercion -> TcCoercion
maybe_sym (TcCoercion -> TcCoercion) -> TcCoercion -> TcCoercion
forall a b. (a -> b) -> a -> b
$ TcCoercion -> TcCoercion
mkTcKindCo (TcTyVar -> TcCoercion
mkTcCoVarCo TcTyVar
evar)  -- :: k2 ~ k1
           ; CtEvidence
kind_ev <- CtLoc -> (TcType, EvTerm) -> TcS CtEvidence
newGivenEvVar CtLoc
kind_loc (TcType
kind_pty, TcCoercion -> EvTerm
evCoercion TcCoercion
kind_co)
           ; [CtEvidence] -> TcS ()
emitWorkNC [CtEvidence
kind_ev]
           ; TcCoercion -> TcS TcCoercion
forall (m :: * -> *) a. Monad m => a -> m a
return (HasDebugCallStack => CtEvidence -> TcCoercion
CtEvidence -> TcCoercion
ctEvCoercion CtEvidence
kind_ev) }

      | Bool
otherwise
      = CtLoc -> Role -> TcType -> TcType -> TcS TcCoercion
unifyWanted CtLoc
kind_loc Role
Nominal TcType
ki2 TcType
ki1

    loc :: CtLoc
loc      = CtEvidence -> CtLoc
ctev_loc CtEvidence
ev
    role :: Role
role     = EqRel -> Role
eqRelRole EqRel
eq_rel
    kind_loc :: CtLoc
kind_loc = TcType -> TcType -> CtLoc -> CtLoc
mkKindLoc (TcTyVar -> TcType
mkTyVarTy TcTyVar
tv1) TcType
xi2 CtLoc
loc
    kind_pty :: TcType
kind_pty = TcType -> TcType -> TcType -> TcType -> TcType
mkHeteroPrimEqPred TcType
liftedTypeKind TcType
liftedTypeKind TcType
ki2 TcType
ki1

    maybe_sym :: TcCoercion -> TcCoercion
maybe_sym = case SwapFlag
swapped of
          SwapFlag
IsSwapped  -> TcCoercion -> TcCoercion
forall a. a -> a
id         -- if the input is swapped, then we already
                                   -- will have k2 ~ k1
          SwapFlag
NotSwapped -> TcCoercion -> TcCoercion
mkTcSymCo

-- guaranteed that tcTypeKind lhs == tcTypeKind rhs
canEqTyVarHomo :: CtEvidence
               -> EqRel -> SwapFlag
               -> TcTyVar                -- lhs: tv1
               -> TcType                 -- pretty lhs, flat
               -> TcType -> TcType       -- rhs, flat
               -> TcS (StopOrContinue Ct)
canEqTyVarHomo :: CtEvidence
-> EqRel
-> SwapFlag
-> TcTyVar
-> TcType
-> TcType
-> TcType
-> TcS (StopOrContinue Ct)
canEqTyVarHomo CtEvidence
ev EqRel
eq_rel SwapFlag
swapped TcTyVar
tv1 TcType
ps_xi1 TcType
xi2 TcType
_
  | Just (TcTyVar
tv2, TcCoercion
_) <- TcType -> Maybe (TcTyVar, TcCoercion)
tcGetCastedTyVar_maybe TcType
xi2
  , TcTyVar
tv1 TcTyVar -> TcTyVar -> Bool
forall a. Eq a => a -> a -> Bool
== TcTyVar
tv2
  = CtEvidence -> EqRel -> TcType -> TcS (StopOrContinue Ct)
canEqReflexive CtEvidence
ev EqRel
eq_rel (TcTyVar -> TcType
mkTyVarTy TcTyVar
tv1)
    -- we don't need to check co because it must be reflexive

    -- this guarantees (TyEq:TV)
  | Just (TcTyVar
tv2, TcCoercion
co2) <- TcType -> Maybe (TcTyVar, TcCoercion)
tcGetCastedTyVar_maybe TcType
xi2
  , Bool -> TcTyVar -> TcTyVar -> Bool
swapOverTyVars (CtEvidence -> Bool
isGiven CtEvidence
ev) TcTyVar
tv1 TcTyVar
tv2
  = do { String -> SDoc -> TcS ()
traceTcS String
"canEqTyVar swapOver" (TcTyVar -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcTyVar
tv1 SDoc -> SDoc -> SDoc
$$ TcTyVar -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcTyVar
tv2 SDoc -> SDoc -> SDoc
$$ SwapFlag -> SDoc
forall a. Outputable a => a -> SDoc
ppr SwapFlag
swapped)
       ; let role :: Role
role    = EqRel -> Role
eqRelRole EqRel
eq_rel
             sym_co2 :: TcCoercion
sym_co2 = TcCoercion -> TcCoercion
mkTcSymCo TcCoercion
co2
             ty1 :: TcType
ty1     = TcTyVar -> TcType
mkTyVarTy TcTyVar
tv1
             new_lhs :: TcType
new_lhs = TcType
ty1 TcType -> TcCoercion -> TcType
`mkCastTy` TcCoercion
sym_co2
             lhs_co :: TcCoercion
lhs_co  = Role -> TcType -> TcCoercion -> TcCoercion
mkTcGReflLeftCo Role
role TcType
ty1 TcCoercion
sym_co2

             new_rhs :: TcType
new_rhs = TcTyVar -> TcType
mkTyVarTy TcTyVar
tv2
             rhs_co :: TcCoercion
rhs_co  = Role -> TcType -> TcCoercion -> TcCoercion
mkTcGReflRightCo Role
role TcType
new_rhs TcCoercion
co2

       ; CtEvidence
new_ev <- CtEvidence
-> SwapFlag
-> TcType
-> TcType
-> TcCoercion
-> TcCoercion
-> TcS CtEvidence
rewriteEqEvidence CtEvidence
ev SwapFlag
swapped TcType
new_lhs TcType
new_rhs TcCoercion
lhs_co TcCoercion
rhs_co

       ; DynFlags
dflags <- TcS DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags
       ; DynFlags
-> CtEvidence
-> EqRel
-> SwapFlag
-> TcTyVar
-> TcType
-> TcS (StopOrContinue Ct)
canEqTyVar2 DynFlags
dflags CtEvidence
new_ev EqRel
eq_rel SwapFlag
IsSwapped TcTyVar
tv2 (TcType
ps_xi1 TcType -> TcCoercion -> TcType
`mkCastTy` TcCoercion
sym_co2) }

canEqTyVarHomo CtEvidence
ev EqRel
eq_rel SwapFlag
swapped TcTyVar
tv1 TcType
_ TcType
_ TcType
ps_xi2
  = do { DynFlags
dflags <- TcS DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags
       ; DynFlags
-> CtEvidence
-> EqRel
-> SwapFlag
-> TcTyVar
-> TcType
-> TcS (StopOrContinue Ct)
canEqTyVar2 DynFlags
dflags CtEvidence
ev EqRel
eq_rel SwapFlag
swapped TcTyVar
tv1 TcType
ps_xi2 }

-- The RHS here is either not a casted tyvar, or it's a tyvar but we want
-- to rewrite the LHS to the RHS (as per swapOverTyVars)
canEqTyVar2 :: DynFlags
            -> CtEvidence   -- lhs ~ rhs (or, if swapped, orhs ~ olhs)
            -> EqRel
            -> SwapFlag
            -> TcTyVar                  -- lhs = tv, flat
            -> TcType                   -- rhs, flat
            -> TcS (StopOrContinue Ct)
-- LHS is an inert type variable,
-- and RHS is fully rewritten, but with type synonyms
-- preserved as much as possible
-- guaranteed that tyVarKind lhs == typeKind rhs, for (TyEq:K)
-- the "flat" requirement guarantees (TyEq:AFF)
-- (TyEq:N) is checked in can_eq_nc', and (TyEq:TV) is handled in canEqTyVarHomo
canEqTyVar2 :: DynFlags
-> CtEvidence
-> EqRel
-> SwapFlag
-> TcTyVar
-> TcType
-> TcS (StopOrContinue Ct)
canEqTyVar2 DynFlags
dflags CtEvidence
ev EqRel
eq_rel SwapFlag
swapped TcTyVar
tv1 TcType
rhs
    -- this next line checks also for coercion holes; see
    -- Note [Equalities with incompatible kinds]
  | MTVU_OK TcType
rhs' <- MetaTyVarUpdateResult TcType
mtvu  -- No occurs check
     -- Must do the occurs check even on tyvar/tyvar
     -- equalities, in case have  x ~ (y :: ..x...)
     -- #12593
     -- guarantees (TyEq:OC), (TyEq:F), and (TyEq:H)
  = do { CtEvidence
new_ev <- CtEvidence
-> SwapFlag
-> TcType
-> TcType
-> TcCoercion
-> TcCoercion
-> TcS CtEvidence
rewriteEqEvidence CtEvidence
ev SwapFlag
swapped TcType
lhs TcType
rhs' TcCoercion
rewrite_co1 TcCoercion
rewrite_co2
       ; Ct -> TcS (StopOrContinue Ct)
forall a. a -> TcS (StopOrContinue a)
continueWith (CTyEqCan :: CtEvidence -> TcTyVar -> TcType -> EqRel -> Ct
CTyEqCan { cc_ev :: CtEvidence
cc_ev = CtEvidence
new_ev, cc_tyvar :: TcTyVar
cc_tyvar = TcTyVar
tv1
                                , cc_rhs :: TcType
cc_rhs = TcType
rhs', cc_eq_rel :: EqRel
cc_eq_rel = EqRel
eq_rel }) }

  | Bool
otherwise  -- For some reason (occurs check, or forall) we can't unify
               -- We must not use it for further rewriting!
  = do { String -> SDoc -> TcS ()
traceTcS String
"canEqTyVar2 can't unify" (TcTyVar -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcTyVar
tv1 SDoc -> SDoc -> SDoc
$$ TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
rhs)
       ; CtEvidence
new_ev <- CtEvidence
-> SwapFlag
-> TcType
-> TcType
-> TcCoercion
-> TcCoercion
-> TcS CtEvidence
rewriteEqEvidence CtEvidence
ev SwapFlag
swapped TcType
lhs TcType
rhs TcCoercion
rewrite_co1 TcCoercion
rewrite_co2
       ; let status :: CtIrredStatus
status | EqRel -> TcTyVar -> TcType -> Bool
isInsolubleOccursCheck EqRel
eq_rel TcTyVar
tv1 TcType
rhs
                    = CtIrredStatus
InsolubleCIS
             -- If we have a ~ [a], it is not canonical, and in particular
             -- we don't want to rewrite existing inerts with it, otherwise
             -- we'd risk divergence in the constraint solver

                    | MetaTyVarUpdateResult TcType
MTVU_HoleBlocker <- MetaTyVarUpdateResult TcType
mtvu
                    = CtIrredStatus
BlockedCIS
             -- This is the case detailed in
             -- Note [Equalities with incompatible kinds]

                    | Bool
otherwise
                    = CtIrredStatus
OtherCIS
             -- A representational equality with an occurs-check problem isn't
             -- insoluble! For example:
             --   a ~R b a
             -- We might learn that b is the newtype Id.
             -- But, the occurs-check certainly prevents the equality from being
             -- canonical, and we might loop if we were to use it in rewriting.

       ; Ct -> TcS (StopOrContinue Ct)
forall a. a -> TcS (StopOrContinue a)
continueWith (CtIrredStatus -> CtEvidence -> Ct
mkIrredCt CtIrredStatus
status CtEvidence
new_ev) }
  where
    mtvu :: MetaTyVarUpdateResult TcType
mtvu = DynFlags -> TcTyVar -> TcType -> MetaTyVarUpdateResult TcType
metaTyVarUpdateOK DynFlags
dflags TcTyVar
tv1 TcType
rhs

    role :: Role
role = EqRel -> Role
eqRelRole EqRel
eq_rel

    lhs :: TcType
lhs = TcTyVar -> TcType
mkTyVarTy TcTyVar
tv1

    rewrite_co1 :: TcCoercion
rewrite_co1  = Role -> TcType -> TcCoercion
mkTcReflCo Role
role TcType
lhs
    rewrite_co2 :: TcCoercion
rewrite_co2  = Role -> TcType -> TcCoercion
mkTcReflCo Role
role TcType
rhs

-- | Solve a reflexive equality constraint
canEqReflexive :: CtEvidence    -- ty ~ ty
               -> EqRel
               -> TcType        -- ty
               -> TcS (StopOrContinue Ct)   -- always Stop
canEqReflexive :: CtEvidence -> EqRel -> TcType -> TcS (StopOrContinue Ct)
canEqReflexive CtEvidence
ev EqRel
eq_rel TcType
ty
  = do { CtEvidence -> EvTerm -> TcS ()
setEvBindIfWanted CtEvidence
ev (TcCoercion -> EvTerm
evCoercion (TcCoercion -> EvTerm) -> TcCoercion -> EvTerm
forall a b. (a -> b) -> a -> b
$
                               Role -> TcType -> TcCoercion
mkTcReflCo (EqRel -> Role
eqRelRole EqRel
eq_rel) TcType
ty)
       ; CtEvidence -> String -> TcS (StopOrContinue Ct)
forall a. CtEvidence -> String -> TcS (StopOrContinue a)
stopWith CtEvidence
ev String
"Solved by reflexivity" }

{- Note [Equalities with incompatible kinds]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
What do we do when we have an equality

  (tv :: k1) ~ (rhs :: k2)

where k1 and k2 differ? Easy: we create a coercion that relates k1 and
k2 and use this to cast. To wit, from

  [X] (tv :: k1) ~ (rhs :: k2)

we go to

  [noDerived X] co :: k2 ~ k1
  [X]           (tv :: k1) ~ ((rhs |> co) :: k1)

where

  noDerived G = G
  noDerived _ = W

Wrinkles:

 (1) The noDerived step is because Derived equalities have no evidence.
     And yet we absolutely need evidence to be able to proceed here.
     Given evidence will use the KindCo coercion; Wanted evidence will
     be a coercion hole. Even a Derived hetero equality begets a Wanted
     kind equality.

 (2) Though it would be sound to do so, we must not mark the rewritten Wanted
       [W] (tv :: k1) ~ ((rhs |> co) :: k1)
     as canonical in the inert set. In particular, we must not unify tv.
     If we did, the Wanted becomes a Given (effectively), and then can
     rewrite other Wanteds. But that's bad: See Note [Wanteds to not rewrite Wanteds]
     in GHC.Tc.Types.Constraint. The problem is about poor error messages. See #11198 for
     tales of destruction.

     So, we have an invariant on CTyEqCan (TyEq:H) that the RHS does not have
     any coercion holes. This is checked in metaTyVarUpdateOK. We also
     must be sure to kick out any constraints that mention coercion holes
     when those holes get filled in.

     (2a) We don't want to do this for CoercionHoles that witness
          CFunEqCans (that are produced by the flattener), as these will disappear
          once we unflatten. So we remember in the CoercionHole structure
          whether the presence of the hole should block substitution or not.
          A bit gross, this.

     (2b) We must now absolutely make sure to kick out any constraints that
          mention a newly-filled-in coercion hole. This is done in
          kickOutAfterFillingCoercionHole.

 (3) Suppose we have [W] (a :: k1) ~ (rhs :: k2). We duly follow the
     algorithm detailed here, producing [W] co :: k2 ~ k1, and adding
     [W] (a :: k1) ~ ((rhs |> co) :: k1) to the irreducibles. Some time
     later, we solve co, and fill in co's coercion hole. This kicks out
     the irreducible as described in (2b).
     But now, during canonicalization, we see the cast
     and remove it, in canEqCast. By the time we get into canEqTyVar, the equality
     is heterogeneous again, and the process repeats.

     To avoid this, we don't strip casts off a type if the other type
     in the equality is a tyvar. And this is an improvement regardless:
     because tyvars can, generally, unify with casted types, there's no
     reason to go through the work of stripping off the cast when the
     cast appears opposite a tyvar. This is implemented in the cast case
     of can_eq_nc'.

 (4) Reporting an error for a constraint that is blocked only because
     of wrinkle (2) is hard: what would we say to users? And we don't
     really need to report, because if a constraint is blocked, then
     there is unsolved wanted blocking it; that unsolved wanted will
     be reported. We thus push such errors to the bottom of the queue
     in the error-reporting code; they should never be printed.

     (4a) It would seem possible to do this filtering just based on the
          presence of a blocking coercion hole. However, this is no good,
          as it suppresses e.g. no-instance-found errors. We thus record
          a CtIrredStatus in CIrredCan and filter based on this status.
          This happened in T14584. An alternative approach is to expressly
          look for *equalities* with blocking coercion holes, but actually
          recording the blockage in a status field seems nicer.

     (4b) The error message might be printed with -fdefer-type-errors,
          so it still must exist. This is the only reason why there is
          a message at all. Otherwise, we could simply do nothing.

Historical note:

We used to do this via emitting a Derived kind equality and then parking
the heterogeneous equality as irreducible. But this new approach is much
more direct. And it doesn't produce duplicate Deriveds (as the old one did).

Note [Type synonyms and canonicalization]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We treat type synonym applications as xi types, that is, they do not
count as type function applications.  However, we do need to be a bit
careful with type synonyms: like type functions they may not be
generative or injective.  However, unlike type functions, they are
parametric, so there is no problem in expanding them whenever we see
them, since we do not need to know anything about their arguments in
order to expand them; this is what justifies not having to treat them
as specially as type function applications.  The thing that causes
some subtleties is that we prefer to leave type synonym applications
*unexpanded* whenever possible, in order to generate better error
messages.

If we encounter an equality constraint with type synonym applications
on both sides, or a type synonym application on one side and some sort
of type application on the other, we simply must expand out the type
synonyms in order to continue decomposing the equality constraint into
primitive equality constraints.  For example, suppose we have

  type F a = [Int]

and we encounter the equality

  F a ~ [b]

In order to continue we must expand F a into [Int], giving us the
equality

  [Int] ~ [b]

which we can then decompose into the more primitive equality
constraint

  Int ~ b.

However, if we encounter an equality constraint with a type synonym
application on one side and a variable on the other side, we should
NOT (necessarily) expand the type synonym, since for the purpose of
good error messages we want to leave type synonyms unexpanded as much
as possible.  Hence the ps_xi1, ps_xi2 argument passed to canEqTyVar.

-}

{-
************************************************************************
*                                                                      *
                  Evidence transformation
*                                                                      *
************************************************************************
-}

data StopOrContinue a
  = ContinueWith a    -- The constraint was not solved, although it may have
                      --   been rewritten

  | Stop CtEvidence   -- The (rewritten) constraint was solved
         SDoc         -- Tells how it was solved
                      -- Any new sub-goals have been put on the work list
  deriving ((forall a b. (a -> b) -> StopOrContinue a -> StopOrContinue b)
-> (forall a b. a -> StopOrContinue b -> StopOrContinue a)
-> Functor StopOrContinue
forall a b. a -> StopOrContinue b -> StopOrContinue a
forall a b. (a -> b) -> StopOrContinue a -> StopOrContinue b
forall (f :: * -> *).
(forall a b. (a -> b) -> f a -> f b)
-> (forall a b. a -> f b -> f a) -> Functor f
<$ :: forall a b. a -> StopOrContinue b -> StopOrContinue a
$c<$ :: forall a b. a -> StopOrContinue b -> StopOrContinue a
fmap :: forall a b. (a -> b) -> StopOrContinue a -> StopOrContinue b
$cfmap :: forall a b. (a -> b) -> StopOrContinue a -> StopOrContinue b
Functor)

instance Outputable a => Outputable (StopOrContinue a) where
  ppr :: StopOrContinue a -> SDoc
ppr (Stop CtEvidence
ev SDoc
s)      = String -> SDoc
text String
"Stop" SDoc -> SDoc -> SDoc
<> SDoc -> SDoc
parens SDoc
s SDoc -> SDoc -> SDoc
<+> CtEvidence -> SDoc
forall a. Outputable a => a -> SDoc
ppr CtEvidence
ev
  ppr (ContinueWith a
w) = String -> SDoc
text String
"ContinueWith" SDoc -> SDoc -> SDoc
<+> a -> SDoc
forall a. Outputable a => a -> SDoc
ppr a
w

continueWith :: a -> TcS (StopOrContinue a)
continueWith :: forall a. a -> TcS (StopOrContinue a)
continueWith = StopOrContinue a -> TcS (StopOrContinue a)
forall (m :: * -> *) a. Monad m => a -> m a
return (StopOrContinue a -> TcS (StopOrContinue a))
-> (a -> StopOrContinue a) -> a -> TcS (StopOrContinue a)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. a -> StopOrContinue a
forall a. a -> StopOrContinue a
ContinueWith

stopWith :: CtEvidence -> String -> TcS (StopOrContinue a)
stopWith :: forall a. CtEvidence -> String -> TcS (StopOrContinue a)
stopWith CtEvidence
ev String
s = StopOrContinue a -> TcS (StopOrContinue a)
forall (m :: * -> *) a. Monad m => a -> m a
return (CtEvidence -> SDoc -> StopOrContinue a
forall a. CtEvidence -> SDoc -> StopOrContinue a
Stop CtEvidence
ev (String -> SDoc
text String
s))

andWhenContinue :: TcS (StopOrContinue a)
                -> (a -> TcS (StopOrContinue b))
                -> TcS (StopOrContinue b)
andWhenContinue :: forall a b.
TcS (StopOrContinue a)
-> (a -> TcS (StopOrContinue b)) -> TcS (StopOrContinue b)
andWhenContinue TcS (StopOrContinue a)
tcs1 a -> TcS (StopOrContinue b)
tcs2
  = do { StopOrContinue a
r <- TcS (StopOrContinue a)
tcs1
       ; case StopOrContinue a
r of
           Stop CtEvidence
ev SDoc
s       -> StopOrContinue b -> TcS (StopOrContinue b)
forall (m :: * -> *) a. Monad m => a -> m a
return (CtEvidence -> SDoc -> StopOrContinue b
forall a. CtEvidence -> SDoc -> StopOrContinue a
Stop CtEvidence
ev SDoc
s)
           ContinueWith a
ct -> a -> TcS (StopOrContinue b)
tcs2 a
ct }
infixr 0 `andWhenContinue`    -- allow chaining with ($)

rewriteEvidence :: CtEvidence   -- old evidence
                -> TcPredType   -- new predicate
                -> TcCoercion   -- Of type :: new predicate ~ <type of old evidence>
                -> TcS (StopOrContinue CtEvidence)
-- Returns Just new_ev iff either (i)  'co' is reflexivity
--                             or (ii) 'co' is not reflexivity, and 'new_pred' not cached
-- In either case, there is nothing new to do with new_ev
{-
     rewriteEvidence old_ev new_pred co
Main purpose: create new evidence for new_pred;
              unless new_pred is cached already
* Returns a new_ev : new_pred, with same wanted/given/derived flag as old_ev
* If old_ev was wanted, create a binding for old_ev, in terms of new_ev
* If old_ev was given, AND not cached, create a binding for new_ev, in terms of old_ev
* Returns Nothing if new_ev is already cached

        Old evidence    New predicate is               Return new evidence
        flavour                                        of same flavor
        -------------------------------------------------------------------
        Wanted          Already solved or in inert     Nothing
        or Derived      Not                            Just new_evidence

        Given           Already in inert               Nothing
                        Not                            Just new_evidence

Note [Rewriting with Refl]
~~~~~~~~~~~~~~~~~~~~~~~~~~
If the coercion is just reflexivity then you may re-use the same
variable.  But be careful!  Although the coercion is Refl, new_pred
may reflect the result of unification alpha := ty, so new_pred might
not _look_ the same as old_pred, and it's vital to proceed from now on
using new_pred.

qThe flattener preserves type synonyms, so they should appear in new_pred
as well as in old_pred; that is important for good error messages.
 -}


rewriteEvidence :: CtEvidence
-> TcType -> TcCoercion -> TcS (StopOrContinue CtEvidence)
rewriteEvidence old_ev :: CtEvidence
old_ev@(CtDerived {}) TcType
new_pred TcCoercion
_co
  = -- If derived, don't even look at the coercion.
    -- This is very important, DO NOT re-order the equations for
    -- rewriteEvidence to put the isTcReflCo test first!
    -- Why?  Because for *Derived* constraints, c, the coercion, which
    -- was produced by flattening, may contain suspended calls to
    -- (ctEvExpr c), which fails for Derived constraints.
    -- (Getting this wrong caused #7384.)
    CtEvidence -> TcS (StopOrContinue CtEvidence)
forall a. a -> TcS (StopOrContinue a)
continueWith (CtEvidence
old_ev { ctev_pred :: TcType
ctev_pred = TcType
new_pred })

rewriteEvidence CtEvidence
old_ev TcType
new_pred TcCoercion
co
  | TcCoercion -> Bool
isTcReflCo TcCoercion
co -- See Note [Rewriting with Refl]
  = CtEvidence -> TcS (StopOrContinue CtEvidence)
forall a. a -> TcS (StopOrContinue a)
continueWith (CtEvidence
old_ev { ctev_pred :: TcType
ctev_pred = TcType
new_pred })

rewriteEvidence ev :: CtEvidence
ev@(CtGiven { ctev_evar :: CtEvidence -> TcTyVar
ctev_evar = TcTyVar
old_evar, ctev_loc :: CtEvidence -> CtLoc
ctev_loc = CtLoc
loc }) TcType
new_pred TcCoercion
co
  = do { CtEvidence
new_ev <- CtLoc -> (TcType, EvTerm) -> TcS CtEvidence
newGivenEvVar CtLoc
loc (TcType
new_pred, EvTerm
new_tm)
       ; CtEvidence -> TcS (StopOrContinue CtEvidence)
forall a. a -> TcS (StopOrContinue a)
continueWith CtEvidence
new_ev }
  where
    -- mkEvCast optimises ReflCo
    new_tm :: EvTerm
new_tm = EvExpr -> TcCoercion -> EvTerm
mkEvCast (TcTyVar -> EvExpr
evId TcTyVar
old_evar) (Role -> Role -> TcCoercion -> TcCoercion
tcDowngradeRole Role
Representational
                                                       (CtEvidence -> Role
ctEvRole CtEvidence
ev)
                                                       (TcCoercion -> TcCoercion
mkTcSymCo TcCoercion
co))

rewriteEvidence ev :: CtEvidence
ev@(CtWanted { ctev_dest :: CtEvidence -> TcEvDest
ctev_dest = TcEvDest
dest
                             , ctev_nosh :: CtEvidence -> ShadowInfo
ctev_nosh = ShadowInfo
si
                             , ctev_loc :: CtEvidence -> CtLoc
ctev_loc = CtLoc
loc }) TcType
new_pred TcCoercion
co
  = do { MaybeNew
mb_new_ev <- ShadowInfo -> CtLoc -> TcType -> TcS MaybeNew
newWanted_SI ShadowInfo
si CtLoc
loc TcType
new_pred
               -- The "_SI" variant ensures that we make a new Wanted
               -- with the same shadow-info as the existing one
               -- with the same shadow-info as the existing one (#16735)
       ; MASSERT( tcCoercionRole co == ctEvRole ev )
       ; TcEvDest -> EvTerm -> TcS ()
setWantedEvTerm TcEvDest
dest
            (EvExpr -> TcCoercion -> EvTerm
mkEvCast (MaybeNew -> EvExpr
getEvExpr MaybeNew
mb_new_ev)
                      (Role -> Role -> TcCoercion -> TcCoercion
tcDowngradeRole Role
Representational (CtEvidence -> Role
ctEvRole CtEvidence
ev) TcCoercion
co))
       ; case MaybeNew
mb_new_ev of
            Fresh  CtEvidence
new_ev -> CtEvidence -> TcS (StopOrContinue CtEvidence)
forall a. a -> TcS (StopOrContinue a)
continueWith CtEvidence
new_ev
            Cached EvExpr
_      -> CtEvidence -> String -> TcS (StopOrContinue CtEvidence)
forall a. CtEvidence -> String -> TcS (StopOrContinue a)
stopWith CtEvidence
ev String
"Cached wanted" }


rewriteEqEvidence :: CtEvidence         -- Old evidence :: olhs ~ orhs (not swapped)
                                        --              or orhs ~ olhs (swapped)
                  -> SwapFlag
                  -> TcType -> TcType   -- New predicate  nlhs ~ nrhs
                  -> TcCoercion         -- lhs_co, of type :: nlhs ~ olhs
                  -> TcCoercion         -- rhs_co, of type :: nrhs ~ orhs
                  -> TcS CtEvidence     -- Of type nlhs ~ nrhs
-- For (rewriteEqEvidence (Given g olhs orhs) False nlhs nrhs lhs_co rhs_co)
-- we generate
-- If not swapped
--      g1 : nlhs ~ nrhs = lhs_co ; g ; sym rhs_co
-- If 'swapped'
--      g1 : nlhs ~ nrhs = lhs_co ; Sym g ; sym rhs_co
--
-- For (Wanted w) we do the dual thing.
-- New  w1 : nlhs ~ nrhs
-- If not swapped
--      w : olhs ~ orhs = sym lhs_co ; w1 ; rhs_co
-- If swapped
--      w : orhs ~ olhs = sym rhs_co ; sym w1 ; lhs_co
--
-- It's all a form of rewwriteEvidence, specialised for equalities
rewriteEqEvidence :: CtEvidence
-> SwapFlag
-> TcType
-> TcType
-> TcCoercion
-> TcCoercion
-> TcS CtEvidence
rewriteEqEvidence CtEvidence
old_ev SwapFlag
swapped TcType
nlhs TcType
nrhs TcCoercion
lhs_co TcCoercion
rhs_co
  | CtDerived {} <- CtEvidence
old_ev  -- Don't force the evidence for a Derived
  = CtEvidence -> TcS CtEvidence
forall (m :: * -> *) a. Monad m => a -> m a
return (CtEvidence
old_ev { ctev_pred :: TcType
ctev_pred = TcType
new_pred })

  | SwapFlag
NotSwapped <- SwapFlag
swapped
  , TcCoercion -> Bool
isTcReflCo TcCoercion
lhs_co      -- See Note [Rewriting with Refl]
  , TcCoercion -> Bool
isTcReflCo TcCoercion
rhs_co
  = CtEvidence -> TcS CtEvidence
forall (m :: * -> *) a. Monad m => a -> m a
return (CtEvidence
old_ev { ctev_pred :: TcType
ctev_pred = TcType
new_pred })

  | CtGiven { ctev_evar :: CtEvidence -> TcTyVar
ctev_evar = TcTyVar
old_evar } <- CtEvidence
old_ev
  = do { let new_tm :: EvTerm
new_tm = TcCoercion -> EvTerm
evCoercion (TcCoercion
lhs_co
                                  TcCoercion -> TcCoercion -> TcCoercion
`mkTcTransCo` SwapFlag -> TcCoercion -> TcCoercion
maybeSym SwapFlag
swapped (TcTyVar -> TcCoercion
mkTcCoVarCo TcTyVar
old_evar)
                                  TcCoercion -> TcCoercion -> TcCoercion
`mkTcTransCo` TcCoercion -> TcCoercion
mkTcSymCo TcCoercion
rhs_co)
       ; CtLoc -> (TcType, EvTerm) -> TcS CtEvidence
newGivenEvVar CtLoc
loc' (TcType
new_pred, EvTerm
new_tm) }

  | CtWanted { ctev_dest :: CtEvidence -> TcEvDest
ctev_dest = TcEvDest
dest, ctev_nosh :: CtEvidence -> ShadowInfo
ctev_nosh = ShadowInfo
si } <- CtEvidence
old_ev
  = case TcEvDest
dest of
      HoleDest CoercionHole
hole ->
        do { (CtEvidence
new_ev, TcCoercion
hole_co) <- BlockSubstFlag
-> ShadowInfo
-> CtLoc
-> Role
-> TcType
-> TcType
-> TcS (CtEvidence, TcCoercion)
newWantedEq_SI (CoercionHole -> BlockSubstFlag
ch_blocker CoercionHole
hole) ShadowInfo
si CtLoc
loc'
                                                 (CtEvidence -> Role
ctEvRole CtEvidence
old_ev) TcType
nlhs TcType
nrhs
                   -- The "_SI" variant ensures that we make a new Wanted
                   -- with the same shadow-info as the existing one (#16735)
           ; let co :: TcCoercion
co = SwapFlag -> TcCoercion -> TcCoercion
maybeSym SwapFlag
swapped (TcCoercion -> TcCoercion) -> TcCoercion -> TcCoercion
forall a b. (a -> b) -> a -> b
$
                      TcCoercion -> TcCoercion
mkSymCo TcCoercion
lhs_co
                      TcCoercion -> TcCoercion -> TcCoercion
`mkTransCo` TcCoercion
hole_co
                      TcCoercion -> TcCoercion -> TcCoercion
`mkTransCo` TcCoercion
rhs_co
           ; TcEvDest -> TcCoercion -> TcS ()
setWantedEq TcEvDest
dest TcCoercion
co
           ; String -> SDoc -> TcS ()
traceTcS String
"rewriteEqEvidence" ([SDoc] -> SDoc
vcat [CtEvidence -> SDoc
forall a. Outputable a => a -> SDoc
ppr CtEvidence
old_ev, TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
nlhs, TcType -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcType
nrhs, TcCoercion -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcCoercion
co])
           ; CtEvidence -> TcS CtEvidence
forall (m :: * -> *) a. Monad m => a -> m a
return CtEvidence
new_ev }

      TcEvDest
_ -> String -> TcS CtEvidence
forall a. String -> a
panic String
"rewriteEqEvidence"

#if __GLASGOW_HASKELL__ <= 810
  | otherwise
  = panic "rewriteEvidence"
#endif
  where
    new_pred :: TcType
new_pred = CtEvidence -> TcType -> TcType -> TcType
mkTcEqPredLikeEv CtEvidence
old_ev TcType
nlhs TcType
nrhs

      -- equality is like a type class. Bumping the depth is necessary because
      -- of recursive newtypes, where "reducing" a newtype can actually make
      -- it bigger. See Note [Newtypes can blow the stack].
    loc :: CtLoc
loc      = CtEvidence -> CtLoc
ctEvLoc CtEvidence
old_ev
    loc' :: CtLoc
loc'     = CtLoc -> CtLoc
bumpCtLocDepth CtLoc
loc

{- Note [unifyWanted and unifyDerived]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When decomposing equalities we often create new wanted constraints for
(s ~ t).  But what if s=t?  Then it'd be faster to return Refl right away.
Similar remarks apply for Derived.

Rather than making an equality test (which traverses the structure of the
type, perhaps fruitlessly), unifyWanted traverses the common structure, and
bales out when it finds a difference by creating a new Wanted constraint.
But where it succeeds in finding common structure, it just builds a coercion
to reflect it.
-}

unifyWanted :: CtLoc -> Role
            -> TcType -> TcType -> TcS Coercion
-- Return coercion witnessing the equality of the two types,
-- emitting new work equalities where necessary to achieve that
-- Very good short-cut when the two types are equal, or nearly so
-- See Note [unifyWanted and unifyDerived]
-- The returned coercion's role matches the input parameter
unifyWanted :: CtLoc -> Role -> TcType -> TcType -> TcS TcCoercion
unifyWanted CtLoc
loc Role
Phantom TcType
ty1 TcType
ty2
  = do { TcCoercion
kind_co <- CtLoc -> Role -> TcType -> TcType -> TcS TcCoercion
unifyWanted CtLoc
loc Role
Nominal (HasDebugCallStack => TcType -> TcType
TcType -> TcType
tcTypeKind TcType
ty1) (HasDebugCallStack => TcType -> TcType
TcType -> TcType
tcTypeKind TcType
ty2)
       ; TcCoercion -> TcS TcCoercion
forall (m :: * -> *) a. Monad m => a -> m a
return (TcCoercion -> TcType -> TcType -> TcCoercion
mkPhantomCo TcCoercion
kind_co TcType
ty1 TcType
ty2) }

unifyWanted CtLoc
loc Role
role TcType
orig_ty1 TcType
orig_ty2
  = TcType -> TcType -> TcS TcCoercion
go TcType
orig_ty1 TcType
orig_ty2
  where
    go :: TcType -> TcType -> TcS TcCoercion
go TcType
ty1 TcType
ty2 | Just TcType
ty1' <- TcType -> Maybe TcType
tcView TcType
ty1 = TcType -> TcType -> TcS TcCoercion
go TcType
ty1' TcType
ty2
    go TcType
ty1 TcType
ty2 | Just TcType
ty2' <- TcType -> Maybe TcType
tcView TcType
ty2 = TcType -> TcType -> TcS TcCoercion
go TcType
ty1 TcType
ty2'

    go (FunTy AnonArgFlag
_ TcType
w1 TcType
s1 TcType
t1) (FunTy AnonArgFlag
_ TcType
w2 TcType
s2 TcType
t2)
      = do { TcCoercion
co_s <- CtLoc -> Role -> TcType -> TcType -> TcS TcCoercion
unifyWanted CtLoc
loc Role
role TcType
s1 TcType
s2
           ; TcCoercion
co_t <- CtLoc -> Role -> TcType -> TcType -> TcS TcCoercion
unifyWanted CtLoc
loc Role
role TcType
t1 TcType
t2
           ; TcCoercion
co_w <- CtLoc -> Role -> TcType -> TcType -> TcS TcCoercion
unifyWanted CtLoc
loc Role
Nominal TcType
w1 TcType
w2
           ; TcCoercion -> TcS TcCoercion
forall (m :: * -> *) a. Monad m => a -> m a
return (Role -> TcCoercion -> TcCoercion -> TcCoercion -> TcCoercion
mkFunCo Role
role TcCoercion
co_w TcCoercion
co_s TcCoercion
co_t) }
    go (TyConApp TyCon
tc1 [TcType]
tys1) (TyConApp TyCon
tc2 [TcType]
tys2)
      | TyCon
tc1 TyCon -> TyCon -> Bool
forall a. Eq a => a -> a -> Bool
== TyCon
tc2, [TcType]
tys1 [TcType] -> [TcType] -> Bool
forall a b. [a] -> [b] -> Bool
`equalLength` [TcType]
tys2
      , TyCon -> Role -> Bool
isInjectiveTyCon TyCon
tc1 Role
role -- don't look under newtypes at Rep equality
      = do { [TcCoercion]
cos <- (Role -> TcType -> TcType -> TcS TcCoercion)
-> [Role] -> [TcType] -> [TcType] -> TcS [TcCoercion]
forall (m :: * -> *) a b c d.
Monad m =>
(a -> b -> c -> m d) -> [a] -> [b] -> [c] -> m [d]
zipWith3M (CtLoc -> Role -> TcType -> TcType -> TcS TcCoercion
unifyWanted CtLoc
loc)
                              (Role -> TyCon -> [Role]
tyConRolesX Role
role TyCon
tc1) [TcType]
tys1 [TcType]
tys2
           ; TcCoercion -> TcS TcCoercion
forall (m :: * -> *) a. Monad m => a -> m a
return (HasDebugCallStack => Role -> TyCon -> [TcCoercion] -> TcCoercion
Role -> TyCon -> [TcCoercion] -> TcCoercion
mkTyConAppCo Role
role TyCon
tc1 [TcCoercion]
cos) }

    go ty1 :: TcType
ty1@(TyVarTy TcTyVar
tv) TcType
ty2
      = do { Maybe TcType
mb_ty <- TcTyVar -> TcS (Maybe TcType)
isFilledMetaTyVar_maybe TcTyVar
tv
           ; case Maybe TcType
mb_ty of
                Just TcType
ty1' -> TcType -> TcType -> TcS TcCoercion
go TcType
ty1' TcType
ty2
                Maybe TcType
Nothing   -> TcType -> TcType -> TcS TcCoercion
bale_out TcType
ty1 TcType
ty2}
    go TcType
ty1 ty2 :: TcType
ty2@(TyVarTy TcTyVar
tv)
      = do { Maybe TcType
mb_ty <- TcTyVar -> TcS (Maybe TcType)
isFilledMetaTyVar_maybe TcTyVar
tv
           ; case Maybe TcType
mb_ty of
                Just TcType
ty2' -> TcType -> TcType -> TcS TcCoercion
go TcType
ty1 TcType
ty2'
                Maybe TcType
Nothing   -> TcType -> TcType -> TcS TcCoercion
bale_out TcType
ty1 TcType
ty2 }

    go ty1 :: TcType
ty1@(CoercionTy {}) (CoercionTy {})
      = TcCoercion -> TcS TcCoercion
forall (m :: * -> *) a. Monad m => a -> m a
return (Role -> TcType -> TcCoercion
mkReflCo Role
role TcType
ty1) -- we just don't care about coercions!

    go TcType
ty1 TcType
ty2 = TcType -> TcType -> TcS TcCoercion
bale_out TcType
ty1 TcType
ty2

    bale_out :: TcType -> TcType -> TcS TcCoercion
bale_out TcType
ty1 TcType
ty2
       | TcType
ty1 HasDebugCallStack => TcType -> TcType -> Bool
TcType -> TcType -> Bool
`tcEqType` TcType
ty2 = TcCoercion -> TcS TcCoercion
forall (m :: * -> *) a. Monad m => a -> m a
return (Role -> TcType -> TcCoercion
mkTcReflCo Role
role TcType
ty1)
        -- Check for equality; e.g. a ~ a, or (m a) ~ (m a)
       | Bool
otherwise = CtLoc -> Role -> TcType -> TcType -> TcS TcCoercion
emitNewWantedEq CtLoc
loc Role
role TcType
orig_ty1 TcType
orig_ty2

unifyDeriveds :: CtLoc -> [Role] -> [TcType] -> [TcType] -> TcS ()
-- See Note [unifyWanted and unifyDerived]
unifyDeriveds :: CtLoc -> [Role] -> [TcType] -> [TcType] -> TcS ()
unifyDeriveds CtLoc
loc [Role]
roles [TcType]
tys1 [TcType]
tys2 = (Role -> TcType -> TcType -> TcS ())
-> [Role] -> [TcType] -> [TcType] -> TcS ()
forall (m :: * -> *) a b c d.
Monad m =>
(a -> b -> c -> m d) -> [a] -> [b] -> [c] -> m ()
zipWith3M_ (CtLoc -> Role -> TcType -> TcType -> TcS ()
unify_derived CtLoc
loc) [Role]
roles [TcType]
tys1 [TcType]
tys2

unifyDerived :: CtLoc -> Role -> Pair TcType -> TcS ()
-- See Note [unifyWanted and unifyDerived]
unifyDerived :: CtLoc -> Role -> Pair TcType -> TcS ()
unifyDerived CtLoc
loc Role
role (Pair TcType
ty1 TcType
ty2) = CtLoc -> Role -> TcType -> TcType -> TcS ()
unify_derived CtLoc
loc Role
role TcType
ty1 TcType
ty2

unify_derived :: CtLoc -> Role -> TcType -> TcType -> TcS ()
-- Create new Derived and put it in the work list
-- Should do nothing if the two types are equal
-- See Note [unifyWanted and unifyDerived]
unify_derived :: CtLoc -> Role -> TcType -> TcType -> TcS ()
unify_derived CtLoc
_   Role
Phantom TcType
_        TcType
_        = () -> TcS ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()
unify_derived CtLoc
loc Role
role    TcType
orig_ty1 TcType
orig_ty2
  = TcType -> TcType -> TcS ()
go TcType
orig_ty1 TcType
orig_ty2
  where
    go :: TcType -> TcType -> TcS ()
go TcType
ty1 TcType
ty2 | Just TcType
ty1' <- TcType -> Maybe TcType
tcView TcType
ty1 = TcType -> TcType -> TcS ()
go TcType
ty1' TcType
ty2
    go TcType
ty1 TcType
ty2 | Just TcType
ty2' <- TcType -> Maybe TcType
tcView TcType
ty2 = TcType -> TcType -> TcS ()
go TcType
ty1 TcType
ty2'

    go (FunTy AnonArgFlag
_ TcType
w1 TcType
s1 TcType
t1) (FunTy AnonArgFlag
_ TcType
w2 TcType
s2 TcType
t2)
      = do { CtLoc -> Role -> TcType -> TcType -> TcS ()
unify_derived CtLoc
loc Role
role TcType
s1 TcType
s2
           ; CtLoc -> Role -> TcType -> TcType -> TcS ()
unify_derived CtLoc
loc Role
role TcType
t1 TcType
t2
           ; CtLoc -> Role -> TcType -> TcType -> TcS ()
unify_derived CtLoc
loc Role
Nominal TcType
w1 TcType
w2 }
    go (TyConApp TyCon
tc1 [TcType]
tys1) (TyConApp TyCon
tc2 [TcType]
tys2)
      | TyCon
tc1 TyCon -> TyCon -> Bool
forall a. Eq a => a -> a -> Bool
== TyCon
tc2, [TcType]
tys1 [TcType] -> [TcType] -> Bool
forall a b. [a] -> [b] -> Bool
`equalLength` [TcType]
tys2
      , TyCon -> Role -> Bool
isInjectiveTyCon TyCon
tc1 Role
role
      = CtLoc -> [Role] -> [TcType] -> [TcType] -> TcS ()
unifyDeriveds CtLoc
loc (Role -> TyCon -> [Role]
tyConRolesX Role
role TyCon
tc1) [TcType]
tys1 [TcType]
tys2
    go ty1 :: TcType
ty1@(TyVarTy TcTyVar
tv) TcType
ty2
      = do { Maybe TcType
mb_ty <- TcTyVar -> TcS (Maybe TcType)
isFilledMetaTyVar_maybe TcTyVar
tv
           ; case Maybe TcType
mb_ty of
                Just TcType
ty1' -> TcType -> TcType -> TcS ()
go TcType
ty1' TcType
ty2
                Maybe TcType
Nothing   -> TcType -> TcType -> TcS ()
bale_out TcType
ty1 TcType
ty2 }
    go TcType
ty1 ty2 :: TcType
ty2@(TyVarTy TcTyVar
tv)
      = do { Maybe TcType
mb_ty <- TcTyVar -> TcS (Maybe TcType)
isFilledMetaTyVar_maybe TcTyVar
tv
           ; case Maybe TcType
mb_ty of
                Just TcType
ty2' -> TcType -> TcType -> TcS ()
go TcType
ty1 TcType
ty2'
                Maybe TcType
Nothing   -> TcType -> TcType -> TcS ()
bale_out TcType
ty1 TcType
ty2 }
    go TcType
ty1 TcType
ty2 = TcType -> TcType -> TcS ()
bale_out TcType
ty1 TcType
ty2

    bale_out :: TcType -> TcType -> TcS ()
bale_out TcType
ty1 TcType
ty2
       | TcType
ty1 HasDebugCallStack => TcType -> TcType -> Bool
TcType -> TcType -> Bool
`tcEqType` TcType
ty2 = () -> TcS ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()
        -- Check for equality; e.g. a ~ a, or (m a) ~ (m a)
       | Bool
otherwise = CtLoc -> Role -> TcType -> TcType -> TcS ()
emitNewDerivedEq CtLoc
loc Role
role TcType
orig_ty1 TcType
orig_ty2

maybeSym :: SwapFlag -> TcCoercion -> TcCoercion
maybeSym :: SwapFlag -> TcCoercion -> TcCoercion
maybeSym SwapFlag
IsSwapped  TcCoercion
co = TcCoercion -> TcCoercion
mkTcSymCo TcCoercion
co
maybeSym SwapFlag
NotSwapped TcCoercion
co = TcCoercion
co