TcCanonical.hs 79 KB
Newer Older
1 2
{-# LANGUAGE CPP #-}

3
module TcCanonical(
4 5
     canonicalize,
     unifyDerived,
6
     makeSuperClasses, mkGivensWithSuperClasses,
7 8
     StopOrContinue(..), stopWith, continueWith
  ) where
9 10 11 12 13

#include "HsVersions.h"

import TcRnTypes
import TcType
14
import Type
15 16
import TcFlatten
import TcSMonad
17
import TcEvidence
18 19
import Class
import TyCon
20
import TyCoRep   -- cleverly decomposes types, good for completeness checking
21 22 23
import Coercion
import FamInstEnv ( FamInstEnvs )
import FamInst ( tcTopNormaliseNewTypeTF_maybe )
24
import Var
25
import Name( isSystemName )
26
import OccName( OccName )
27
import Outputable
28
import DynFlags( DynFlags )
29
import VarSet
30
import NameSet
31
import RdrName
32

33
import Pair
34
import Util
35
import Bag
36 37 38
import MonadUtils
import Control.Monad
import Data.List  ( zip4, foldl' )
39
import BasicTypes
40

41 42
import Data.Bifunctor ( bimap )

Austin Seipp's avatar
Austin Seipp committed
43 44 45 46 47 48
{-
************************************************************************
*                                                                      *
*                      The Canonicaliser                               *
*                                                                      *
************************************************************************
49

50 51
Note [Canonicalization]
~~~~~~~~~~~~~~~~~~~~~~~
52

53
Canonicalization converts a simple constraint to a canonical form. It is
54 55 56
unary (i.e. treats individual constraints one at a time), does not do
any zonking, but lives in TcS monad because it needs to create fresh
variables (for flattening) and consult the inerts (for efficiency).
57

58
The execution plan for canonicalization is the following:
Simon Peyton Jones's avatar
Simon Peyton Jones committed
59 60

  1) Decomposition of equalities happens as necessary until we reach a
61
     variable or type family in one side. There is no decomposition step
Simon Peyton Jones's avatar
Simon Peyton Jones committed
62
     for other forms of constraints.
63

Simon Peyton Jones's avatar
Simon Peyton Jones committed
64 65 66 67
  2) If, when we decompose, we discover a variable on the head then we
     look at inert_eqs from the current inert for a substitution for this
     variable and contine decomposing. Hence we lazily apply the inert
     substitution if it is needed.
68

69 70
  3) If no more decomposition is possible, we deeply apply the substitution
     from the inert_eqs and continue with flattening.
71

Simon Peyton Jones's avatar
Simon Peyton Jones committed
72 73 74 75 76
  4) During flattening, we examine whether we have already flattened some
     function application by looking at all the CTyFunEqs with the same
     function in the inert set. The reason for deeply applying the inert
     substitution at step (3) is to maximise our chances of matching an
     already flattened family application in the inert.
77

Simon Peyton Jones's avatar
Simon Peyton Jones committed
78 79
The net result is that a constraint coming out of the canonicalization
phase cannot be rewritten any further from the inerts (but maybe /it/ can
80 81
rewrite an inert or still interact with an inert in a further phase in the
simplifier.
dimitris's avatar
dimitris committed
82

83
Note [Caching for canonicals]
Simon Peyton Jones's avatar
Simon Peyton Jones committed
84
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
85 86 87 88
Our plan with pre-canonicalization is to be able to solve a constraint
really fast from existing bindings in TcEvBinds. So one may think that
the condition (isCNonCanonical) is not necessary.  However consider
the following setup:
89

Simon Peyton Jones's avatar
Simon Peyton Jones committed
90 91
InertSet = { [W] d1 : Num t }
WorkList = { [W] d2 : Num t, [W] c : t ~ Int}
92

93 94 95 96 97
Now, we prioritize equalities, but in our concrete example
(should_run/mc17.hs) the first (d2) constraint is dealt with first,
because (t ~ Int) is an equality that only later appears in the
worklist since it is pulled out from a nested implication
constraint. So, let's examine what happens:
Simon Peyton Jones's avatar
Simon Peyton Jones committed
98

99 100
   - We encounter work item (d2 : Num t)

Simon Peyton Jones's avatar
Simon Peyton Jones committed
101
   - Nothing is yet in EvBinds, so we reach the interaction with inerts
102
     and set:
Simon Peyton Jones's avatar
Simon Peyton Jones committed
103
              d2 := d1
104 105
    and we discard d2 from the worklist. The inert set remains unaffected.

106 107 108
   - Now the equation ([W] c : t ~ Int) is encountered and kicks-out
     (d1 : Num t) from the inerts.  Then that equation gets
     spontaneously solved, perhaps. We end up with:
109
        InertSet : { [G] c : t ~ Int }
Simon Peyton Jones's avatar
Simon Peyton Jones committed
110
        WorkList : { [W] d1 : Num t}
111

112 113
   - Now we examine (d1), we observe that there is a binding for (Num
     t) in the evidence binds and we set:
Simon Peyton Jones's avatar
Simon Peyton Jones committed
114
             d1 := d2
115 116
     and end up in a loop!

117 118 119 120 121 122 123 124
Now, the constraints that get kicked out from the inert set are always
Canonical, so by restricting the use of the pre-canonicalizer to
NonCanonical constraints we eliminate this danger. Moreover, for
canonical constraints we already have good caching mechanisms
(effectively the interaction solver) and we are interested in reducing
things like superclasses of the same non-canonical constraint being
generated hence I don't expect us to lose a lot by introducing the
(isCNonCanonical) restriction.
125

126 127 128 129 130 131 132
A similar situation can arise in TcSimplify, at the end of the
solve_wanteds function, where constraints from the inert set are
returned as new work -- our substCt ensures however that if they are
not rewritten by subst, they remain canonical and hence we will not
attempt to solve them from the EvBinds. If on the other hand they did
get rewritten and are now non-canonical they will still not match the
EvBinds, so we are again good.
Austin Seipp's avatar
Austin Seipp committed
133
-}
134

135 136 137
-- Top-level canonicalization
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

138
canonicalize :: Ct -> TcS (StopOrContinue Ct)
139
canonicalize ct@(CNonCanonical { cc_ev = ev })
140
  = do { traceTcS "canonicalize (non-canonical)" (ppr ct)
141
       ; {-# SCC "canEvVar" #-}
142
         canEvNC ev }
143

144 145
canonicalize (CDictCan { cc_ev = ev, cc_class  = cls
                       , cc_tyargs = xis, cc_pend_sc = pend_sc })
146
  = {-# SCC "canClass" #-}
147 148
    canClass ev cls xis pend_sc

149
canonicalize (CTyEqCan { cc_ev = ev
150
                       , cc_tyvar  = tv
151 152
                       , cc_rhs    = xi
                       , cc_eq_rel = eq_rel })
153
  = {-# SCC "canEqLeafTyVarEq" #-}
154 155 156
    canEqNC ev eq_rel (mkTyVarTy tv) 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
157

158
canonicalize (CFunEqCan { cc_ev = ev
159 160
                        , cc_fun    = fn
                        , cc_tyargs = xis1
161
                        , cc_fsk    = fsk })
Simon Peyton Jones's avatar
Simon Peyton Jones committed
162
  = {-# SCC "canEqLeafFunEq" #-}
163
    canCFunEqCan ev fn xis1 fsk
164

165 166
canonicalize (CIrredEvCan { cc_ev = ev })
  = canIrred ev
thomasw's avatar
thomasw committed
167 168
canonicalize (CHoleCan { cc_ev = ev, cc_occ = occ, cc_hole = hole })
  = canHole ev occ hole
169

170
canEvNC :: CtEvidence -> TcS (StopOrContinue Ct)
Simon Peyton Jones's avatar
Simon Peyton Jones committed
171
-- Called only for non-canonical EvVars
172
canEvNC ev
173
  = case classifyPredType (ctEvPred ev) of
174 175 176 177 178 179
      ClassPred cls tys     -> do traceTcS "canEvNC:cls" (ppr cls <+> ppr tys)
                                  canClassNC ev cls tys
      EqPred eq_rel ty1 ty2 -> do traceTcS "canEvNC:eq" (ppr ty1 $$ ppr ty2)
                                  canEqNC    ev eq_rel ty1 ty2
      IrredPred {}          -> do traceTcS "canEvNC:irred" (ppr (ctEvPred ev))
                                  canIrred   ev
Austin Seipp's avatar
Austin Seipp committed
180 181 182 183 184 185 186
{-
************************************************************************
*                                                                      *
*                      Class Canonicalization
*                                                                      *
************************************************************************
-}
187

188
canClassNC :: CtEvidence -> Class -> [Type] -> TcS (StopOrContinue Ct)
Simon Peyton Jones's avatar
Simon Peyton Jones committed
189
-- Precondition: EvVar is class evidence
190 191 192
canClassNC ev cls tys = canClass ev cls tys (has_scs cls)
  where
    has_scs cls = not (null (classSCTheta cls))
193

194 195
canClass :: CtEvidence -> Class -> [Type] -> Bool -> TcS (StopOrContinue Ct)
-- Precondition: EvVar is class evidence
196

197
canClass ev cls tys pend_sc
198 199
  =   -- all classes do *nominal* matching
    ASSERT2( ctEvRole ev == Nominal, ppr ev $$ ppr cls $$ ppr tys )
200
    do { (xis, cos) <- flattenManyNom ev tys
Joachim Breitner's avatar
Joachim Breitner committed
201
       ; let co = mkTcTyConAppCo Nominal (classTyCon cls) cos
202
             xi = mkClassPred cls xis
203
             mk_ct new_ev = CDictCan { cc_ev = new_ev
204 205 206
                                     , cc_tyargs = xis
                                     , cc_class = cls
                                     , cc_pend_sc = pend_sc }
207
       ; mb <- rewriteEvidence ev xi co
208
       ; traceTcS "canClass" (vcat [ ppr ev
Simon Peyton Jones's avatar
Simon Peyton Jones committed
209
                                   , ppr xi, ppr mb ])
210
       ; return (fmap mk_ct mb) }
dimitris's avatar
dimitris committed
211

212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
{- Note [The superclass story]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We need to add superclass constraints for two reasons:

* For givens, they give us a route to 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, 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 Wanted 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 generateing a Derived (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 (Trac #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. Generate superclasses for given (but not wanted) constraints;
   see Note [Aggressively expand given superclasses].  However
   stop if you encounter the same class twice.  That is, expand
   eagerly, but have a conservative termination condition: see
   Note [Expanding superclasses] in TcType.

2. Solve the wanteds as usual, but do /no/ expansion of superclasses
   in solveSimpleGivens or solveSimpleWanteds.
   See Note [Danger of adding superclasses during solving]

263 264 265 266 267 268
3. If we have any remaining unsolved wanteds
        (see Note [When superclasses help] in TcRnTypes)
   try harder: take both the Givens and Wanteds, and expand
   superclasses again.  This may succeed in generating (a finite
   number of) extra Givens, and extra Deriveds. Both may help the
   proof.  This is done in TcSimplify.expandSuperClasses.
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300

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

We try to terminate the loop by flagging which class constraints
(given or wanted) are potentially un-expanded.  This is what the
cc_pend_sc flag is for in CDictCan.  So in Step 3 we only expand
superclasses for constraints with cc_pend_sc set to true (i.e.
isPendingScDict holds).

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 [Aggressively expand given superclasses]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In step (1) of Note [The superclass story], why do we aggressively
expand Given superclasses by one layer?  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 [Why adding superclasses can help]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Examples of how adding superclasses can help:
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318

    --- 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 we get [D] beta ~ b, and can solve that.

319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
    -- 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.

337 338
Note [Danger of adding superclasses during solving]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
339
Here's a serious, but now out-dated example, from Trac #4497:
Simon Peyton Jones's avatar
Simon Peyton Jones committed
340

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

Simon Peyton Jones's avatar
Simon Peyton Jones committed
344
Assume the generated wanted constraint is:
345 346 347
   [W] RealOf e ~ e
   [W] Normed e

Simon Peyton Jones's avatar
Simon Peyton Jones committed
348
If we were to be adding the superclasses during simplification we'd get:
349 350 351 352
   [W] RealOf e ~ e
   [W] Normed e
   [D] RealOf e ~ fuv
   [D] Num fuv
Simon Peyton Jones's avatar
Simon Peyton Jones committed
353
==>
354
   e := fuv, Num fuv, Normed fuv, RealOf fuv ~ fuv
Simon Peyton Jones's avatar
Simon Peyton Jones committed
355

356 357 358
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
359
happen.
360 361 362 363

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

365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
mkGivensWithSuperClasses :: CtLoc -> [EvId] -> TcS [Ct]
-- From a given EvId, make its Ct, plus the Ct's of its superclasses
-- See Note [The superclass story]
-- The loop-breaking here follows Note [Expanding superclasses] in TcType
mkGivensWithSuperClasses loc ev_ids = concatMapM go ev_ids
  where
    go ev_id = mk_superclasses emptyNameSet $
               CtGiven { ctev_evar = ev_id
                       , ctev_pred = evVarPred ev_id
                       , ctev_loc  = loc }

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 TcType
makeSuperClasses cts = concatMapM go cts
  where
    go (CDictCan { cc_ev = ev, cc_class = cls, cc_tyargs = tys })
          = mk_strict_superclasses emptyNameSet ev cls tys
    go ct = pprPanic "makeSuperClasses" (ppr ct)

mk_superclasses :: NameSet -> CtEvidence -> TcS [Ct]
-- Return this constraint, plus its superclasses, if any
mk_superclasses rec_clss ev
  | ClassPred cls tys <- classifyPredType (ctEvPred ev)
  = mk_superclasses_of rec_clss ev cls tys

  | otherwise   -- Superclass is not a class predicate
  = return [mkNonCanonical ev]

mk_superclasses_of :: NameSet -> CtEvidence -> Class -> [Type] -> TcS [Ct]
-- Return this class constraint, plus its superclasses
mk_superclasses_of rec_clss ev cls tys
  | loop_found
  = return [this_ct]
  | otherwise
  = do { sc_cts <- mk_strict_superclasses rec_clss' ev cls tys
       ; return (this_ct : sc_cts) }
  where
    cls_nm     = className cls
    loop_found = cls_nm `elemNameSet` rec_clss
    rec_clss'  | isCTupleClass cls = rec_clss  -- Never contribute to recursion
               | otherwise         = rec_clss `extendNameSet` cls_nm
    this_ct    = CDictCan { cc_ev = ev, cc_class = cls, cc_tyargs = tys
                          , cc_pend_sc = loop_found }

mk_strict_superclasses :: NameSet -> CtEvidence -> Class -> [Type] -> TcS [Ct]
mk_strict_superclasses rec_clss ev cls tys
  | CtGiven { ctev_evar = evar, ctev_loc = loc } <- ev
  = do { sc_evs <- newGivenEvVars (mk_given_loc loc)
                                  (mkEvScSelectors (EvId evar) cls tys)
       ; concatMapM (mk_superclasses rec_clss) sc_evs }
dimitris's avatar
dimitris committed
417

418 419 420

  | isEmptyVarSet (tyCoVarsOfTypes tys)
  = return [] -- Wanteds with no variables yield no deriveds.
421
              -- See Note [Improvement from Ground Wanteds]
422

423
  | otherwise -- Wanted/Derived case, just add those SC that can lead to improvement.
424 425 426
  = do { let loc = ctEvLoc ev
       ; sc_evs <- mapM (newDerivedNC loc) (immSuperClasses cls tys)
       ; concatMapM (mk_superclasses rec_clss) sc_evs }
427
  where
428
    size = sizeTypes tys
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
    mk_given_loc loc
       | isCTupleClass cls
       = 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.
               -- Trac #10335

       | GivenOrigin skol_info <- ctLocOrigin loc
         -- See Note [Solving superclass constraints] in TcInstDcls
         -- for explantation of this transformation for givens
       = case skol_info of
            InstSkol -> loc { ctl_origin = GivenOrigin (InstSC size) }
            InstSC n -> loc { ctl_origin = GivenOrigin (InstSC (n `max` size)) }
            _        -> loc

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

447 448


Austin Seipp's avatar
Austin Seipp committed
449 450 451 452 453 454 455
{-
************************************************************************
*                                                                      *
*                      Irreducibles canonicalization
*                                                                      *
************************************************************************
-}
456

457
canIrred :: CtEvidence -> TcS (StopOrContinue Ct)
458
-- Precondition: ty not a tuple and no other evidence form
459
canIrred old_ev
Simon Peyton Jones's avatar
Simon Peyton Jones committed
460 461
  = do { let old_ty = ctEvPred old_ev
       ; traceTcS "can_pred" (text "IrredPred = " <+> ppr old_ty)
462
       ; (xi,co) <- flatten FM_FlattenAll old_ev old_ty -- co :: xi ~ old_ty
463
       ; rewriteEvidence old_ev xi co `andWhenContinue` \ new_ev ->
464 465
    do { -- Re-classify, in case flattening has improved its shape
       ; case classifyPredType (ctEvPred new_ev) of
466 467 468 469
           ClassPred cls tys     -> canClassNC new_ev cls tys
           EqPred eq_rel ty1 ty2 -> canEqNC new_ev eq_rel ty1 ty2
           _                     -> continueWith $
                                    CIrredEvCan { cc_ev = new_ev } } }
470

thomasw's avatar
thomasw committed
471 472
canHole :: CtEvidence -> OccName -> HoleSort -> TcS (StopOrContinue Ct)
canHole ev occ hole_sort
473 474
  = do { let ty = ctEvPred ev
       ; (xi,co) <- flatten FM_SubstOnly ev ty -- co :: xi ~ ty
475 476 477 478 479
       ; rewriteEvidence ev xi co `andWhenContinue` \ new_ev ->
    do { emitInsoluble (CHoleCan { cc_ev = new_ev
                                 , cc_occ = occ
                                 , cc_hole = hole_sort })
       ; stopWith new_ev "Emit insoluble hole" } }
480

Austin Seipp's avatar
Austin Seipp committed
481 482 483 484 485 486
{-
************************************************************************
*                                                                      *
*        Equalities
*                                                                      *
************************************************************************
487 488 489 490 491 492 493 494 495 496 497 498 499

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)
Austin Seipp's avatar
Austin Seipp committed
500
-}
501

502 503
canEqNC :: CtEvidence -> EqRel -> Type -> Type -> TcS (StopOrContinue Ct)
canEqNC ev eq_rel ty1 ty2
504 505 506 507
  = do { result <- zonk_eq_types ty1 ty2
       ; case result of
           Left (Pair ty1' ty2') -> can_eq_nc False ev eq_rel ty1' ty1 ty2' ty2
           Right ty              -> canEqReflexive ev eq_rel ty }
508

509
can_eq_nc
510 511
   :: Bool            -- True => both types are flat
   -> CtEvidence
512
   -> EqRel
Austin Seipp's avatar
Austin Seipp committed
513 514
   -> Type -> Type    -- LHS, after and before type-synonym expansion, resp
   -> Type -> Type    -- RHS, after and before type-synonym expansion, resp
515
   -> TcS (StopOrContinue Ct)
516
can_eq_nc flat ev eq_rel ty1 ps_ty1 ty2 ps_ty2
Austin Seipp's avatar
Austin Seipp committed
517
  = do { traceTcS "can_eq_nc" $
518 519 520
         vcat [ ppr ev, ppr eq_rel, ppr ty1, ppr ps_ty1, ppr ty2, ppr ps_ty2 ]
       ; rdr_env <- getGlobalRdrEnvTcS
       ; fam_insts <- getFamInstEnvs
521
       ; can_eq_nc' flat rdr_env fam_insts ev eq_rel ty1 ps_ty1 ty2 ps_ty2 }
522 523

can_eq_nc'
524 525
   :: Bool           -- True => both input types are flattened
   -> GlobalRdrEnv   -- needed to see which newtypes are in scope
526 527 528 529 530 531
   -> 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)
532 533

-- Expand synonyms first; see Note [Type synonyms and canonicalization]
534
can_eq_nc' flat _rdr_env _envs ev eq_rel ty1 ps_ty1 ty2 ps_ty2
535 536
  | Just ty1' <- coreView ty1 = can_eq_nc flat ev eq_rel ty1' ps_ty1 ty2  ps_ty2
  | Just ty2' <- coreView ty2 = can_eq_nc flat ev eq_rel ty1  ps_ty1 ty2' ps_ty2
537 538

-- need to check for reflexivity in the ReprEq case.
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
539
-- See Note [Eager reflexivity check]
540 541 542
-- Check only when flat because the zonk_eq_types check in canEqNC takes
-- care of the non-flat case.
can_eq_nc' True _rdr_env _envs ev ReprEq ty1 _ ty2 _
543 544 545 546 547
  | ty1 `eqType` ty2
  = canEqReflexive ev ReprEq ty1

-- When working with ReprEq, unwrap newtypes.
can_eq_nc' _flat rdr_env envs ev ReprEq ty1 _ ty2 ps_ty2
548 549
  | Just (co, ty1') <- tcTopNormaliseNewTypeTF_maybe envs rdr_env ty1
  = can_eq_newtype_nc rdr_env ev NotSwapped co ty1 ty1' ty2 ps_ty2
550
can_eq_nc' _flat rdr_env envs ev ReprEq ty1 ps_ty1 ty2 _
551 552
  | Just (co, ty2') <- tcTopNormaliseNewTypeTF_maybe envs rdr_env ty2
  = can_eq_newtype_nc rdr_env ev IsSwapped  co ty2 ty2' ty1 ps_ty1
553

554 555 556 557 558 559
-- Then, get rid of casts
can_eq_nc' flat _rdr_env _envs ev eq_rel (CastTy ty1 co1) _ ty2 ps_ty2
  = canEqCast flat ev eq_rel NotSwapped ty1 co1 ty2 ps_ty2
can_eq_nc' flat _rdr_env _envs ev eq_rel ty1 ps_ty1 (CastTy ty2 co2) _
  = canEqCast flat ev eq_rel IsSwapped ty2 co2 ty1 ps_ty1

560 561 562 563 564
----------------------
-- Otherwise try to decompose
----------------------

-- Literals
565
can_eq_nc' _flat _rdr_env _envs ev eq_rel ty1@(LitTy l1) _ (LitTy l2) _
566
 | l1 == l2
567
  = do { setEqIfWanted ev (mkReflCo (eqRelRole eq_rel) ty1)
568
       ; stopWith ev "Equal LitTy" }
569

Simon Peyton Jones's avatar
Simon Peyton Jones committed
570 571
-- Try to decompose type constructor applications
-- Including FunTy (s -> t)
572
can_eq_nc' _flat _rdr_env _envs ev eq_rel ty1 _ ty2 _
573 574
  | Just (tc1, tys1) <- tcRepSplitTyConApp_maybe ty1
  , Just (tc2, tys2) <- tcRepSplitTyConApp_maybe ty2
575 576
  , not (isTypeFamilyTyCon tc1)
  , not (isTypeFamilyTyCon tc2)
577
  = canTyConApp ev eq_rel tc1 tys1 tc2 tys2
578

579
can_eq_nc' _flat _rdr_env _envs ev eq_rel
580 581 582 583 584 585 586
           s1@(ForAllTy (Named {}) _) _ s2@(ForAllTy (Named {}) _) _
 | CtWanted { ctev_loc = loc, ctev_dest = orig_dest } <- ev
 = do { let (bndrs1,body1) = tcSplitNamedPiTys s1
            (bndrs2,body2) = tcSplitNamedPiTys s2
      ; if not (equalLength bndrs1 bndrs2)
           || not (map binderVisibility bndrs1 == map binderVisibility bndrs2)
        then canEqHardFailure ev s1 s2
587
        else
588
          do { traceTcS "Creating implication for polytype equality" $ ppr ev
589 590 591 592 593
             ; kind_cos <- zipWithM (unifyWanted loc Nominal)
                             (map binderType bndrs1) (map binderType bndrs2)
             ; all_co <- deferTcSForAllEq (eqRelRole eq_rel) loc
                                           kind_cos (bndrs1,body1) (bndrs2,body2)
             ; setWantedEq orig_dest all_co
594
             ; stopWith ev "Deferred polytype equality" } }
595
 | otherwise
596
 = do { traceTcS "Omitting decomposition of given polytype equality" $
597
        pprEq s1 s2    -- See Note [Do not decompose given polytype equalities]
598
      ; stopWith ev "Discard given polytype equality" }
599

600
-- See Note [Canonicalising type applications] about why we require flat types
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
601
can_eq_nc' True _rdr_env _envs ev eq_rel (AppTy t1 s1) _ ty2 _
602
  | Just (t2, s2) <- tcSplitAppTy_maybe ty2
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
603 604
  = can_eq_app ev eq_rel t1 s1 t2 s2
can_eq_nc' True _rdr_env _envs ev eq_rel ty1 _ (AppTy t2 s2) _
605
  | Just (t1, s1) <- tcSplitAppTy_maybe ty1
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
606
  = can_eq_app ev eq_rel t1 s1 t2 s2
607

608
-- No similarity in type structure detected. Flatten and try again.
609 610 611
can_eq_nc' False rdr_env envs ev eq_rel _ ps_ty1 _ ps_ty2
  = do { (xi1, co1) <- flatten FM_FlattenAll ev ps_ty1
       ; (xi2, co2) <- flatten FM_FlattenAll ev ps_ty2
612
       ; rewriteEqEvidence ev NotSwapped xi1 xi2 co1 co2
613
         `andWhenContinue` \ new_ev ->
614 615 616 617 618 619 620 621 622 623 624
         can_eq_nc' True rdr_env envs new_ev eq_rel xi1 xi1 xi2 xi2 }

-- Type variable on LHS or RHS are last. We want only flat types sent
-- to canEqTyVar.
-- See also Note [No top-level newtypes on RHS of representational equalities]
can_eq_nc' True _rdr_env _envs ev eq_rel (TyVarTy tv1) _ _ ps_ty2
  = canEqTyVar ev eq_rel NotSwapped tv1 ps_ty2
can_eq_nc' True _rdr_env _envs ev eq_rel _ ps_ty1 (TyVarTy tv2) _
  = canEqTyVar ev eq_rel IsSwapped  tv2 ps_ty1

-- We've flattened and the types don't match. Give up.
625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729
can_eq_nc' True _rdr_env _envs ev _eq_rel _ ps_ty1 _ ps_ty2
  = do { traceTcS "can_eq_nc' catch-all case" (ppr ps_ty1 $$ ppr ps_ty2)
       ; canEqHardFailure ev ps_ty1 ps_ty2 }

---------------------------------
-- | 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 = go
  where
    go (TyVarTy tv1) (TyVarTy tv2) = tyvar_tyvar tv1 tv2
    go (TyVarTy tv1) ty2           = tyvar NotSwapped tv1 ty2
    go ty1 (TyVarTy tv2)           = tyvar IsSwapped  tv2 ty1

    go ty1 ty2
      | Just (tc1, tys1) <- tcRepSplitTyConApp_maybe ty1
      , Just (tc2, tys2) <- tcRepSplitTyConApp_maybe ty2
      , tc1 == tc2
      = tycon tc1 tys1 tys2

    go ty1 ty2
      | Just (ty1a, ty1b) <- tcRepSplitAppTy_maybe ty1
      , Just (ty2a, ty2b) <- tcRepSplitAppTy_maybe ty2
      = do { res_a <- go ty1a ty2a
           ; res_b <- go ty1b ty2b
           ; return $ combine_rev mkAppTy res_b res_a }

    go ty1@(LitTy lit1) (LitTy lit2)
      | lit1 == lit2
      = return (Right ty1)

    go ty1 ty2 = return $ Left (Pair ty1 ty2)
      -- we don't handle more complex forms here

    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 swapped tv ty
      = case tcTyVarDetails tv of
          MetaTv { mtv_ref = ref }
            -> do { cts <- readTcRef ref
                  ; case cts of
                      Flexi        -> give_up
                      Indirect ty' -> unSwap swapped go ty' ty }
          _ -> give_up
      where
        give_up = return $ Left $ unSwap swapped Pair (mkTyVarTy tv) ty

    tyvar_tyvar tv1 tv2
      | tv1 == tv2 = return (Right (mkTyVarTy tv1))
      | otherwise  = do { (ty1', progress1) <- quick_zonk tv1
                        ; (ty2', progress2) <- quick_zonk tv2
                        ; if progress1 || progress2
                          then go ty1' ty2'
                          else return $ Left (Pair (TyVarTy tv1) (TyVarTy tv2)) }

    quick_zonk tv = case tcTyVarDetails tv of
      MetaTv { mtv_ref = ref }
        -> do { cts <- readTcRef ref
              ; case cts of
                  Flexi        -> return (TyVarTy tv, False)
                  Indirect ty' -> return (ty', True) }
      _ -> return (TyVarTy tv, 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 tc tys1 tys2
      = do { results <- zipWithM go tys1 tys2
           ; return $ case combine_results results of
               Left tys  -> Left (mkTyConApp tc <$> tys)
               Right tys -> Right (mkTyConApp tc tys) }

    combine_results :: [Either (Pair TcType) TcType]
                    -> Either (Pair [TcType]) [TcType]
    combine_results = bimap (fmap reverse) reverse .
                      foldl' (combine_rev (:)) (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 f (Left list) (Left elt) = Left (f <$> elt     <*> list)
    combine_rev f (Left list) (Right ty) = Left (f <$> pure ty <*> list)
    combine_rev f (Right tys) (Left elt) = Left (f <$> elt     <*> pure tys)
    combine_rev f (Right tys) (Right ty) = Right (f ty tys)
730

731
{-
732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749
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.

750 751 752 753 754 755 756 757 758
Note [Eager reflexivity check]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose we have

  newtype X = MkX (Int -> X)

and

  [W] X ~R X
759

760 761 762 763 764
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.

765 766
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.
767

eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
768
Here's another place where this reflexivity check is key:
769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795
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 CIrredEvCan. 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 :: GlobalRdrEnv
                  -> CtEvidence           -- ^ :: ty1 ~ ty2
                  -> SwapFlag
                  -> TcCoercion           -- ^ :: ty1 ~ ty1'
                  -> TcType               -- ^ ty1
                  -> TcType               -- ^ ty1'
                  -> TcType               -- ^ ty2
                  -> TcType               -- ^ ty2, with type synonyms
                  -> TcS (StopOrContinue Ct)
can_eq_newtype_nc rdr_env ev swapped co ty1 ty1' ty2 ps_ty2
  = do { traceTcS "can_eq_newtype_nc" $
         vcat [ ppr ev, ppr swapped, ppr co, ppr ty1', ppr ty2 ]

         -- check for blowing our stack:
796 797
         -- See Note [Newtypes can blow the stack]
       ; checkReductionDepth (ctEvLoc ev) ty1
798
       ; addUsedDataCons rdr_env (tyConAppTyCon ty1)
799 800 801
           -- we have actually used the newtype constructor here, so
           -- make sure we don't warn about importing it!

802
       ; rewriteEqEvidence ev swapped ty1' ps_ty2
803 804
                           (mkTcSymCo co) (mkTcReflCo Representational ps_ty2)
         `andWhenContinue` \ new_ev ->
805
         can_eq_nc False new_ev ReprEq ty1' ty1' ty2 ps_ty2 }
806

807
---------
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
808
-- ^ Decompose a type application.
809
-- All input types must be flat. See Note [Canonicalising type applications]
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
810 811
can_eq_app :: CtEvidence       -- :: s1 t1 ~r s2 t2
           -> EqRel            -- r
812 813 814
           -> Xi -> Xi         -- s1 t1
           -> Xi -> Xi         -- s2 t2
           -> TcS (StopOrContinue Ct)
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
815 816

-- AppTys only decompose for nominal equality, so this case just leads
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
817
-- to an irreducible constraint; see typecheck/should_compile/T10494
Simon Peyton Jones's avatar
Simon Peyton Jones committed
818
-- See Note [Decomposing equality], note {4}
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
819 820 821
can_eq_app ev ReprEq _ _ _ _
  = do { traceTcS "failing to decompose representational AppTy equality" (ppr ev)
       ; continueWith (CIrredEvCan { cc_ev = ev }) }
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
822 823
          -- no need to call canEqFailure, because that flattens, and the
          -- types involved here are already flat
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
824 825

can_eq_app ev NomEq s1 t1 s2 t2
826
  | CtDerived { ctev_loc = loc } <- ev
827 828 829 830
  = do { unifyDeriveds loc [Nominal, Nominal] [s1, t1] [s2, t2]
       ; stopWith ev "Decomposed [D] AppTy" }
  | CtWanted { ctev_dest = dest, ctev_loc = loc } <- ev
  = do { co_s <- unifyWanted loc Nominal s1 s2
831
       ; co_t <- unifyWanted loc Nominal t1 t2
832 833 834
       ; let co = mkAppCo co_s co_t
       ; setWantedEq dest co
       ; stopWith ev "Decomposed [W] AppTy" }
835 836
  | CtGiven { ctev_evar = evar, ctev_loc = loc } <- ev
  = do { let co   = mkTcCoVarCo evar
837 838
             co_s = mkTcLRCo CLeft  co
             co_t = mkTcLRCo CRight co
839 840 841 842
       ; evar_s <- newGivenEvVar loc ( mkTcEqPredLikeEv ev s1 s2
                                     , EvCoercion co_s )
       ; evar_t <- newGivenEvVar loc ( mkTcEqPredLikeEv ev t1 t2
                                     , EvCoercion co_t )
843 844 845 846
       ; emitWorkNC [evar_t]
       ; canEqNC evar_s NomEq s1 s2 }
  | otherwise  -- Can't happen
  = error "can_eq_app"
847

848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869
-----------------------
-- | Break apart an equality over a casted type
canEqCast :: Bool         -- are both types flat?
          -> CtEvidence
          -> EqRel
          -> SwapFlag
          -> TcType -> Coercion   -- LHS (res. RHS), the casted type
          -> TcType -> TcType     -- RHS (res. LHS), both normal and pretty
          -> TcS (StopOrContinue Ct)
canEqCast flat ev eq_rel swapped ty1 co1 ty2 ps_ty2
  = do { traceTcS "Decomposing cast" (vcat [ ppr ev
                                           , ppr ty1 <+> text "|>" <+> ppr co1
                                           , ppr ps_ty2 ])
       ; rewriteEqEvidence ev swapped ty1 ps_ty2
                           (mkTcReflCo role ty1
                              `mkTcCoherenceRightCo` co1)
                           (mkTcReflCo role ps_ty2)
         `andWhenContinue` \ new_ev ->
         can_eq_nc flat new_ev eq_rel ty1 ty1 ty2 ps_ty2 }
  where
    role = eqRelRole eq_rel

870
------------------------
871 872 873 874
canTyConApp :: CtEvidence -> EqRel
            -> TyCon -> [TcType]
            -> TyCon -> [TcType]
            -> TcS (StopOrContinue Ct)
875
-- See Note [Decomposing TyConApps]
876
canTyConApp ev eq_rel tc1 tys1 tc2 tys2
877
  | tc1 == tc2
878
  , length tys1 == length tys2
879
  = do { inerts <- getTcSInerts
880 881
       ; if can_decompose inerts
         then do { traceTcS "canTyConApp"
882 883 884 885
                       (ppr ev $$ ppr eq_rel $$ ppr tc1 $$ ppr tys1 $$ ppr tys2)
                 ; canDecomposableTyConAppOK ev eq_rel tc1 tys1 tys2
                 ; stopWith ev "Decomposed TyConApp" }
         else canEqFailure ev eq_rel ty1 ty2 }
886

887 888
  -- Fail straight away for better error messages
  -- See Note [Use canEqFailure in canDecomposableTyConApp]
889 890
  | eq_rel == ReprEq && not (isGenerativeTyCon tc1 Representational &&
                             isGenerativeTyCon tc2 Representational)
891 892
  = canEqFailure ev eq_rel ty1 ty2
  | otherwise
893
  = canEqHardFailure ev ty1 ty2
894 895 896 897
  where
    ty1 = mkTyConApp tc1 tys1
    ty2 = mkTyConApp tc2 tys2

898 899 900
    loc  = ctEvLoc ev
    pred = ctEvPred ev

901 902 903 904 905
     -- See Note [Decomposing equality]
    can_decompose inerts
      =  isInjectiveTyCon tc1 (eqRelRole eq_rel)
      || (ctEvFlavour ev /= Given && isEmptyBag (matchableGivens loc pred inerts))

906 907 908 909 910
{-
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.
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
911
Here is one case:
912 913 914 915 916

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

eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
917
Suppose we are canonicalising (Int ~R DF (TF a)), where we don't yet
918 919
know `a`. This is *not* a hard failure, because we might soon learn
that `a` is, in fact, Char, and then the equality succeeds.
920

eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
921 922
Here is another case:

eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
923
  [G] Age ~R Int
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
924 925 926 927

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

eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
928 929 930 931 932 933 934 935 936 937
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.

938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976
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.

Simon Peyton Jones's avatar
Simon Peyton Jones committed
977 978 979 980 981 982
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)
983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009

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

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1010
{2}: See Note [Decomposing newtypes at representational role]
1011

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1012 1013 1014
{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
1015
typecheck/should_fail/T10534.
1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026

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

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058
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.

1059
Furthermore, as explained in Note [NthCo and newtypes] in TyCoRep, we can't use
Simon Peyton Jones's avatar
Simon Peyton Jones committed
1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
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 TcInteract.

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

canDecomposableTyConAppOK :: CtEvidence -> EqRel
1090
                          -> TyCon -> [TcType] -> [TcType]
1091 1092
                          -> TcS ()
-- Precondition: tys1 and tys2 are the same length, hence "OK"
1093
canDecomposableTyConAppOK ev eq_rel tc tys1 tys2
1094
  = case ev of
1095
     CtDerived {}
1096
        -> unifyDeriveds loc tc_roles tys1 tys2
1097

1098 1099 1100
     CtWanted { ctev_dest = dest }
        -> do { cos <- zipWith4M unifyWanted new_locs tc_roles tys1 tys2
              ; setWantedEq dest (mkTyConAppCo role tc cos) }
1101

1102 1103
     CtGiven { ctev_evar = evar }
        -> do { let ev_co = mkCoVarCo evar
1104
              ; given_evs <- newGivenEvVars loc $
1105 1106
                             [ ( mkPrimEqPredRole r ty1 ty2
                               , EvCoercion (mkNthCo i ev_co) )
1107
                             | (r, ty1, ty2, i) <- zip4 tc_roles tys1 tys2 [0..]
1108 1109
                             , r /= Phantom
                             , not (isCoercionTy ty1) && not (isCoercionTy ty2) ]
1110 1111
              ; emitWorkNC given_evs }
  where
1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125
    loc        = ctEvLoc ev
    role       = eqRelRole eq_rel
    tc_roles   = tyConRolesX role tc

      -- the following makes a better distinction between "kind" and "type"
      -- in error messages
    (bndrs, _) = splitPiTys (tyConKind tc)
    kind_loc   = toKindLoc loc
    is_kinds   = map isNamedBinder bndrs
    new_locs | Just KindLevel <- ctLocTypeOrKind_maybe loc
             = repeat loc
             | otherwise
             = map (\is_kind -> if is_kind then kind_loc else loc) is_kinds

1126 1127 1128

-- | Call when canonicalizing an equality fails, but if the equality is
-- representational, there is some hope for the future.
1129
-- Examples in Note [Use canEqFailure in canDecomposableTyConApp]
1130 1131
canEqFailure :: CtEvidence -> EqRel
             -> TcType -> TcType -> TcS (StopOrContinue Ct)
1132
canEqFailure ev NomEq ty1 ty2
1133
  = canEqHardFailure ev ty1 ty2
1134
canEqFailure ev ReprEq ty1 ty2
1135
  = do { (xi1, co1) <- flatten FM_FlattenAll ev ty1
1136
       ; (xi2, co2) <- flatten FM_FlattenAll ev ty2
1137 1138 1139
            -- 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
1140 1141
       ; traceTcS "canEqFailure with ReprEq" $
         vcat [ ppr ev, ppr ty1, ppr ty2, ppr xi1, ppr xi2 ]
1142
       ; rewriteEqEvidence ev NotSwapped xi1 xi2 co1 co2
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
1143 1144
         `andWhenContinue` \ new_ev ->
         continueWith (CIrredEvCan { cc_ev = new_ev }) }
1145 1146

-- | Call when canonicalizing an equality fails with utterly no hope.
1147
canEqHardFailure :: CtEvidence
1148
                 -> TcType -> TcType -> TcS (StopOrContinue Ct)
1149
-- See Note [Make sure that insolubles are fully rewritten]
1150
canEqHardFailure ev ty1 ty2
1151 1152
  = do { (s1, co1) <- flatten FM_SubstOnly ev ty1
       ; (s2, co2) <- flatten FM_SubstOnly ev ty2
1153
       ; rewriteEqEvidence ev NotSwapped s1 s2 co1 co2
1154 1155 1156
         `andWhenContinue` \ new_ev ->
    do { emitInsoluble (mkNonCanonical new_ev)
       ; stopWith new_ev "Definitely not equal" }}
1157

Austin Seipp's avatar
Austin Seipp committed
1158
{-
1159 1160 1161 1162 1163 1164
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
Jan Stolarek's avatar
Jan Stolarek committed
1165
then we will just decomopose s1~s2, and it might be better to
1166 1167 1168 1169 1170 1171
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.

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

Austin Seipp's avatar
Austin Seipp committed
1181
However, over-eager decomposition gives bad error messages
1182 1183 1184 1185 1186 1187 1188
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
Austin Seipp's avatar
Austin Seipp committed
1189
we get an error        "Can't match Array ~ Maybe",
1190 1191
but we'd prefer to get "Can't match Array b ~ Maybe c".

1192 1193 1194
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.
1195

1196 1197
Note [Make sure that insolubles are fully rewritten]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Simon Peyton Jones's avatar
Simon Peyton Jones committed
1198 1199
When an equality fails, we still want to rewrite the equality
all the way down, so that it accurately reflects
1200 1201
 (a) the mutable reference substitution in force at start of solving
 (b) any ty-binds in force at this point in solving
1202
See Note [Kick out insolubles] in TcSMonad.
Simon Peyton Jones's avatar
Simon Peyton Jones committed
1203
And if we don't do this there is a bad danger that
1204 1205 1206
TcSimplify.applyTyVarDefaulting will find a variable
that has in fact been substituted.

1207
Note [Do not decompose Given polytype equalities]
1208 1209
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider [G] (forall a. t1 ~ forall a. t2).  Can we decompose this?
1210
No -- what would the evidence look like?  So instead we simply discard
Simon Peyton Jones's avatar
Simon Peyton Jones committed
1211
this given evidence.
1212 1213


1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226
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.
1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237

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

1238 1239 1240 1241
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.
1242

1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259
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 isTyVarUnderDatatype
does. (The other name I considered, isTyVarUnderTyConGenerativeWrtReprEq was
a bit verbose. And the shorter name gets the point across.)

See also #10715, which induced this addition.

1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272
Note [No derived kind equalities]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When we're working with a heterogeneous derived equality

  [D] (t1 :: k1) ~ (t2 :: k2)

we want to homogenise to establish the kind invariant on CTyEqCans.
But we can't emit [D] k1 ~ k2 because we wouldn't then be able to
use the evidence in the homogenised types. So we emit a wanted
constraint, because we do really need the evidence here.

Thus: no derived kind equalities.

Austin Seipp's avatar
Austin Seipp committed
1273
-}
Simon Peyton Jones's avatar
Simon Peyton Jones committed
1274

Austin Seipp's avatar
Austin Seipp committed
1275
canCFunEqCan :: CtEvidence
1276
             -> TyCon -> [TcType]   -- LHS
1277 1278
             -> TcTyVar             -- RHS
             -> TcS (StopOrContinue Ct)
Austin Seipp's avatar
Austin Seipp committed
1279 1280
-- ^ Canonicalise a CFunEqCan.  We know that
--     the arg types are already flat,
1281 1282 1283
-- and the RHS is a fsk, which we must *not* substitute.
-- So just substitute in the LHS
canCFunEqCan ev fn tys fsk
1284
  = do { (tys', cos) <- flattenManyNom ev tys
1285 1286 1287 1288 1289
                        -- cos :: tys' ~ tys
       ; let lhs_co  = mkTcTyConAppCo Nominal fn cos
                        -- :: F tys' ~ F tys
             new_lhs = mkTyConApp fn tys'
             fsk_ty  = mkTyVarTy fsk
1290
       ; rewriteEqEvidence ev NotSwapped new_lhs fsk_ty
1291 1292 1293
                           lhs_co (mkTcNomReflCo fsk_ty)
         `andWhenContinue` \ ev' ->
    do { extendFlatCache fn tys' (ctEvCoercion ev', fsk_ty, ctEvFlavour ev')
1294
       ; continueWith (CFunEqCan { cc_ev = ev', cc_fun = fn
1295
                                 , cc_tyargs = tys', cc_fsk = fsk }) } }
1296 1297

---------------------
1298
canEqTyVar :: CtEvidence -> EqRel -> SwapFlag
1299 1300
           -> TcTyVar             -- already flat
           -> TcType              -- already flat
1301
           -> TcS (StopOrContinue Ct)
1302
-- A TyVar on LHS, but so far un-zonked
1303 1304 1305
canEqTyVar ev eq_rel swapped tv1 ps_ty2              -- ev :: tv ~ s2
  = do { traceTcS "canEqTyVar" (ppr tv1 $$ ppr ps_ty2 $$ ppr swapped)
         -- FM_Avoid commented out: see Note [Lazy flattening] in TcFlatten
1306 1307 1308 1309
         -- let fmode = FE { fe_ev = ev, fe_mode = FM_Avoid tv1' True }
         -- Flatten the RHS less vigorously, to avoid gratuitous flattening
         -- True <=> xi2 should not itself be a type-function application
       ; dflags <- getDynFlags
1310
       ; canEqTyVar2 dflags ev eq_rel swapped tv1 ps_ty2 }
1311 1312

canEqTyVar2 :: DynFlags
1313
            -> CtEvidence   -- lhs ~ rhs (or, if swapped, orhs ~ olhs)
1314
            -> EqRel
1315
            -> SwapFlag
1316 1317
            -> TcTyVar      -- lhs, flat
            -> TcType       -- rhs, flat
1318
            -> TcS (StopOrContinue Ct)
Austin Seipp's avatar
Austin Seipp committed
1319
-- LHS is an inert type variable,
1320
-- and RHS is fully rewritten, but with