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

3 4 5 6 7 8
module TcCanonical( 
     canonicalize,
     unifyDerived,

     StopOrContinue(..), stopWith, continueWith
  ) where
9 10 11 12 13

#include "HsVersions.h"

import TcRnTypes
import TcType
14
import Type
dreixel's avatar
dreixel committed
15
import Kind
16 17
import TcFlatten
import TcSMonad
18
import TcEvidence
19 20 21
import Class
import TyCon
import TypeRep
22 23 24
import Coercion
import FamInstEnv ( FamInstEnvs )
import FamInst ( tcTopNormaliseNewTypeTF_maybe )
25
import Var
26
import Name( isSystemName, nameOccName )
27
import OccName( OccName )
28
import Outputable
29
import DynFlags( DynFlags )
30
import VarSet
31
import RdrName
32
import DataCon ( dataConName )
33

34
import Pair
35
import Util
36 37
import MonadUtils ( zipWith3M, zipWith3M_ )
import Data.List  ( zip4 )
38
import BasicTypes
39
import FastString
40

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

48 49
Note [Canonicalization]
~~~~~~~~~~~~~~~~~~~~~~~
50

51
Canonicalization converts a simple constraint to a canonical form. It is
52 53 54
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).
55

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

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

Simon Peyton Jones's avatar
Simon Peyton Jones committed
62 63 64 65
  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.
66

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

Simon Peyton Jones's avatar
Simon Peyton Jones committed
70 71 72 73 74
  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.
75

Simon Peyton Jones's avatar
Simon Peyton Jones committed
76 77
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
78 79
rewrite an inert or still interact with an inert in a further phase in the
simplifier.
dimitris's avatar
dimitris committed
80

81
Note [Caching for canonicals]
Simon Peyton Jones's avatar
Simon Peyton Jones committed
82
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
83 84 85 86
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:
87

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

91 92 93 94 95
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
96

97 98
   - We encounter work item (d2 : Num t)

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

104 105 106
   - 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:
107
        InertSet : { [G] c : t ~ Int }
Simon Peyton Jones's avatar
Simon Peyton Jones committed
108
        WorkList : { [W] d1 : Num t}
109

110 111
   - 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
112
             d1 := d2
113 114
     and end up in a loop!

115 116 117 118 119 120 121 122
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.
123

124 125 126 127 128 129 130
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
131
-}
132

133 134 135
-- Top-level canonicalization
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

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

142
canonicalize (CDictCan { cc_ev = ev
143 144
                       , cc_class  = cls
                       , cc_tyargs = xis })
145
  = {-# SCC "canClass" #-}
146 147
    canClass ev cls xis -- Do not add any superclasses
canonicalize (CTyEqCan { cc_ev = ev
148
                       , cc_tyvar  = tv
149 150
                       , cc_rhs    = xi
                       , cc_eq_rel = eq_rel })
151
  = {-# SCC "canEqLeafTyVarEq" #-}
152 153 154
    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
155

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

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

168
canEvNC :: CtEvidence -> TcS (StopOrContinue Ct)
Simon Peyton Jones's avatar
Simon Peyton Jones committed
169
-- Called only for non-canonical EvVars
170
canEvNC ev
171
  = case classifyPredType (ctEvPred ev) of
172 173 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
      TuplePred tys         -> do traceTcS "canEvNC:tup" (ppr tys)
                                  canTuple   ev tys
      IrredPred {}          -> do traceTcS "canEvNC:irred" (ppr (ctEvPred ev))
                                  canIrred   ev
Austin Seipp's avatar
Austin Seipp committed
180 181 182 183 184 185 186
{-
************************************************************************
*                                                                      *
*                      Tuple Canonicalization
*                                                                      *
************************************************************************
-}
187

188
canTuple :: CtEvidence -> [PredType] -> TcS (StopOrContinue Ct)
189 190 191
canTuple ev preds
  | CtWanted { ctev_evar = evar, ctev_loc = loc } <- ev
  = do { new_evars <- mapM (newWantedEvVar loc) preds
192
       ; setWantedEvBind evar (EvTupleMk (map (ctEvTerm . fst) new_evars))
193 194 195 196 197 198 199 200 201 202 203 204
       ; emitWorkNC (freshGoals new_evars)
         -- Note the "NC": these are fresh goals, not necessarily canonical
       ; stopWith ev "Decomposed tuple constraint" }

  | CtGiven { ctev_evtm = tm, ctev_loc = loc } <- ev
  = do { let mk_pr pred i = (pred, EvTupleSel tm i)
       ; given_evs <- newGivenEvVars loc (zipWith mk_pr preds [0..])
       ; emitWorkNC given_evs
       ; stopWith ev "Decomposed tuple constraint" }

  | CtDerived { ctev_loc = loc } <- ev
  = do { mapM_ (emitNewDerived loc) preds
205
       ; stopWith ev "Decomposed tuple constraint" }
206

207 208 209
  | otherwise = panic "canTuple"


Austin Seipp's avatar
Austin Seipp committed
210 211 212 213 214 215 216
{-
************************************************************************
*                                                                      *
*                      Class Canonicalization
*                                                                      *
************************************************************************
-}
217

Simon Peyton Jones's avatar
Simon Peyton Jones committed
218
canClass, canClassNC
219
   :: CtEvidence
220
   -> Class -> [Type] -> TcS (StopOrContinue Ct)
Simon Peyton Jones's avatar
Simon Peyton Jones committed
221
-- Precondition: EvVar is class evidence
222 223 224 225 226 227

-- The canClassNC version is used on non-canonical constraints
-- and adds superclasses.  The plain canClass version is used
-- for already-canonical class constraints (but which might have
-- been subsituted or somthing), and hence do not need superclasses

228 229
canClassNC ev cls tys
  = canClass ev cls tys
230 231
    `andWhenContinue` emitSuperclasses

232
canClass ev cls tys
233 234
  =   -- all classes do *nominal* matching
    ASSERT2( ctEvRole ev == Nominal, ppr ev $$ ppr cls $$ ppr tys )
235
    do { (xis, cos) <- flattenManyNom ev tys
Joachim Breitner's avatar
Joachim Breitner committed
236
       ; let co = mkTcTyConAppCo Nominal (classTyCon cls) cos
237
             xi = mkClassPred cls xis
238 239
             mk_ct new_ev = CDictCan { cc_ev = new_ev
                                     , cc_tyargs = xis, cc_class = cls }
240
       ; mb <- rewriteEvidence ev xi co
Simon Peyton Jones's avatar
Simon Peyton Jones committed
241
       ; traceTcS "canClass" (vcat [ ppr ev <+> ppr cls <+> ppr tys
Simon Peyton Jones's avatar
Simon Peyton Jones committed
242
                                   , ppr xi, ppr mb ])
243
       ; return (fmap mk_ct mb) }
dimitris's avatar
dimitris committed
244

245
emitSuperclasses :: Ct -> TcS (StopOrContinue Ct)
246
emitSuperclasses ct@(CDictCan { cc_ev = ev , cc_tyargs = xis_new, cc_class = cls })
Simon Peyton Jones's avatar
Simon Peyton Jones committed
247 248
            -- Add superclasses of this one here, See Note [Adding superclasses].
            -- But only if we are not simplifying the LHS of a rule.
249
 = do { newSCWorkFromFlavored ev cls xis_new
Simon Peyton Jones's avatar
Simon Peyton Jones committed
250
      -- Arguably we should "seq" the coercions if they are derived,
251
      -- as we do below for emit_kind_constraint, to allow errors in
Simon Peyton Jones's avatar
Simon Peyton Jones committed
252
      -- superclasses to be executed if deferred to runtime!
253 254
      ; continueWith ct }
emitSuperclasses _ = panic "emit_superclasses of non-class!"
255

Austin Seipp's avatar
Austin Seipp committed
256
{-
257
Note [Adding superclasses]
Simon Peyton Jones's avatar
Simon Peyton Jones committed
258
~~~~~~~~~~~~~~~~~~~~~~~~~~
259

260 261 262 263 264 265 266 267 268 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 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
Since dictionaries are canonicalized only once in their lifetime, the
place to add their superclasses is canonicalisation.  See Note [Add
superclasses only during canonicalisation].  Here is what we do:

  Deriveds: Do nothing.

  Givens:   Add all their superclasses as Givens.

  Wanteds:  Add all their superclasses as Derived.
            Not as Wanted: we don't need a proof.
            Nor as Given: that leads to superclass loops.

We also want to ensure minimal constraints to quantify over.  For
instance, if our wanted constraint is (Eq a, Ord a) we'd only like to
quantify over Ord a.  But we deal with that completely independently
in TcSimplify. See Note [Minimize by SuperClasses] in TcSimplify.

Examples of how adding superclasses as Derived is useful

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

Example of why adding superclass of a Wanted as a Given would
be terrible, see Note [Do not add superclasses of solved dictionaries]
in TcSMonad, which has this example:
        class Ord a => C a where
        instance Ord [a] => C [a] where ...
Suppose we are trying to solve
  [G] d1 : Ord a
  [W] d2 : C [a]
If we (bogusly) added the superclass of d2 as Gievn we'd have
  [G] d1 : Ord a
  [W] d2 : C [a]
  [G] d3 : Ord [a]   -- Superclass of d2, bogus

Then we'll use the instance decl to give
  [G] d1 : Ord a     Solved: d2 : C [a] = $dfCList d4
  [G] d3 : Ord [a]   -- Superclass of d2, bogus
  [W] d4: Ord [a]

ANd now we could bogusly solve d4 from d3.


Note [Add superclasses only during canonicalisation]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We add superclasses only during canonicalisation, on the passage
from CNonCanonical to CDictCan.  A class constraint can be repeatedly
rewritten, and there's no point in repeatedly adding its superclasses.

Here's a serious, but now out-dated example, from Trac #4497:
Simon Peyton Jones's avatar
Simon Peyton Jones committed
324

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

Simon Peyton Jones's avatar
Simon Peyton Jones committed
328
Assume the generated wanted constraint is:
329 330 331
   [W] RealOf e ~ e
   [W] Normed e

Simon Peyton Jones's avatar
Simon Peyton Jones committed
332
If we were to be adding the superclasses during simplification we'd get:
333 334 335 336
   [W] RealOf e ~ e
   [W] Normed e
   [D] RealOf e ~ fuv
   [D] Num fuv
Simon Peyton Jones's avatar
Simon Peyton Jones committed
337
==>
338
   e := fuv, Num fuv, Normed fuv, RealOf fuv ~ fuv
Simon Peyton Jones's avatar
Simon Peyton Jones committed
339

340 341 342
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
343
happen.
344 345 346 347

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

349
newSCWorkFromFlavored :: CtEvidence -> Class -> [Xi] -> TcS ()
350
-- Returns superclasses, see Note [Adding superclasses]
351
newSCWorkFromFlavored flavor cls xis
Simon Peyton Jones's avatar
Simon Peyton Jones committed
352
  | isDerived flavor
353
  = return ()  -- Deriveds don't yield more superclasses because we will
Simon Peyton Jones's avatar
Simon Peyton Jones committed
354 355
               -- add them transitively in the case of wanteds.

356
  | CtGiven { ctev_evtm = ev_tm, ctev_loc = loc } <- flavor
Simon Peyton Jones's avatar
Simon Peyton Jones committed
357
  = do { let sc_theta = immSuperClasses cls xis
358 359 360
             mk_pr sc_pred i = (sc_pred, EvSuperClass ev_tm i)
       ; given_evs <- newGivenEvVars loc (zipWith mk_pr sc_theta [0..])
       ; emitWorkNC given_evs }
dimitris's avatar
dimitris committed
361 362

  | isEmptyVarSet (tyVarsOfTypes xis)
363
  = return () -- Wanteds with no variables yield no deriveds.
364
              -- See Note [Improvement from Ground Wanteds]
365

Simon Peyton Jones's avatar
Simon Peyton Jones committed
366 367
  | otherwise -- Wanted case, just add those SC that can lead to improvement.
  = do { let sc_rec_theta = transSuperClasses cls xis
368
             impr_theta   = filter isImprovementPred sc_rec_theta
369
             loc          = ctEvLoc flavor
370
       ; traceTcS "newSCWork/Derived" $ text "impr_theta =" <+> ppr impr_theta
371
       ; mapM_ (emitNewDerived loc) impr_theta }
372 373


Austin Seipp's avatar
Austin Seipp committed
374 375 376 377 378 379 380
{-
************************************************************************
*                                                                      *
*                      Irreducibles canonicalization
*                                                                      *
************************************************************************
-}
381

382
canIrred :: CtEvidence -> TcS (StopOrContinue Ct)
383
-- Precondition: ty not a tuple and no other evidence form
384
canIrred old_ev
Simon Peyton Jones's avatar
Simon Peyton Jones committed
385 386
  = do { let old_ty = ctEvPred old_ev
       ; traceTcS "can_pred" (text "IrredPred = " <+> ppr old_ty)
387
       ; (xi,co) <- flatten FM_FlattenAll old_ev old_ty -- co :: xi ~ old_ty
388
       ; rewriteEvidence old_ev xi co `andWhenContinue` \ new_ev ->
389 390
    do { -- Re-classify, in case flattening has improved its shape
       ; case classifyPredType (ctEvPred new_ev) of
391 392 393 394 395
           ClassPred cls tys     -> canClassNC new_ev cls tys
           TuplePred tys         -> canTuple   new_ev tys
           EqPred eq_rel ty1 ty2 -> canEqNC new_ev eq_rel ty1 ty2
           _                     -> continueWith $
                                    CIrredEvCan { cc_ev = new_ev } } }
396

thomasw's avatar
thomasw committed
397 398
canHole :: CtEvidence -> OccName -> HoleSort -> TcS (StopOrContinue Ct)
canHole ev occ hole_sort
399 400
  = do { let ty = ctEvPred ev
       ; (xi,co) <- flatten FM_SubstOnly ev ty -- co :: xi ~ ty
401 402 403 404 405
       ; 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" } }
406

Austin Seipp's avatar
Austin Seipp committed
407 408 409 410 411 412
{-
************************************************************************
*                                                                      *
*        Equalities
*                                                                      *
************************************************************************
413 414 415 416 417 418 419 420 421 422 423 424 425

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
426
-}
427

428 429
canEqNC :: CtEvidence -> EqRel -> Type -> Type -> TcS (StopOrContinue Ct)
canEqNC ev eq_rel ty1 ty2
430
  = can_eq_nc False ev eq_rel ty1 ty1 ty2 ty2
431

432
can_eq_nc
433 434
   :: Bool            -- True => both types are flat
   -> CtEvidence
435
   -> EqRel
Austin Seipp's avatar
Austin Seipp committed
436 437
   -> Type -> Type    -- LHS, after and before type-synonym expansion, resp
   -> Type -> Type    -- RHS, after and before type-synonym expansion, resp
438
   -> TcS (StopOrContinue Ct)
439
can_eq_nc flat ev eq_rel ty1 ps_ty1 ty2 ps_ty2
Austin Seipp's avatar
Austin Seipp committed
440
  = do { traceTcS "can_eq_nc" $
441 442 443
         vcat [ ppr ev, ppr eq_rel, ppr ty1, ppr ps_ty1, ppr ty2, ppr ps_ty2 ]
       ; rdr_env <- getGlobalRdrEnvTcS
       ; fam_insts <- getFamInstEnvs
444
       ; can_eq_nc' flat rdr_env fam_insts ev eq_rel ty1 ps_ty1 ty2 ps_ty2 }
445 446

can_eq_nc'
447 448
   :: Bool           -- True => both input types are flattened
   -> GlobalRdrEnv   -- needed to see which newtypes are in scope
449 450 451 452 453 454
   -> 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)
455 456

-- Expand synonyms first; see Note [Type synonyms and canonicalization]
457 458 459 460 461 462 463 464 465 466 467 468
can_eq_nc' flat _rdr_env _envs ev eq_rel ty1 ps_ty1 ty2 ps_ty2
  | Just ty1' <- tcView ty1 = can_eq_nc flat ev eq_rel ty1' ps_ty1 ty2  ps_ty2
  | Just ty2' <- tcView ty2 = can_eq_nc flat ev eq_rel ty1  ps_ty1 ty2' ps_ty2

-- need to check for reflexivity in the ReprEq case.
-- See Note [AppTy reflexivity check] and Note [Eager reflexivity check]
can_eq_nc' _flat _rdr_env _envs ev ReprEq ty1 _ ty2 _
  | 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
469 470
  | Just (co, ty1') <- tcTopNormaliseNewTypeTF_maybe envs rdr_env ty1
  = can_eq_newtype_nc rdr_env ev NotSwapped co ty1 ty1' ty2 ps_ty2
471
can_eq_nc' _flat rdr_env envs ev ReprEq ty1 ps_ty1 ty2 _
472 473
  | Just (co, ty2') <- tcTopNormaliseNewTypeTF_maybe envs rdr_env ty2
  = can_eq_newtype_nc rdr_env ev IsSwapped  co ty2 ty2' ty1 ps_ty1
474 475 476 477 478 479

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

-- Literals
480
can_eq_nc' _flat _rdr_env _envs ev eq_rel ty1@(LitTy l1) _ (LitTy l2) _
481
 | l1 == l2
482 483
  = do { setEvBindIfWanted ev (EvCoercion $
                               mkTcReflCo (eqRelRole eq_rel) ty1)
484
       ; stopWith ev "Equal LitTy" }
485

Austin Seipp's avatar
Austin Seipp committed
486
-- Decomposable type constructor applications
487
-- Synonyms and type functions (which are not decomposable)
Austin Seipp's avatar
Austin Seipp committed
488
-- have already been dealt with
489 490
can_eq_nc' _flat _rdr_env _envs ev eq_rel
          (TyConApp tc1 tys1) _ (TyConApp tc2 tys2) _
491 492
  | isDecomposableTyCon tc1
  , isDecomposableTyCon tc2
493
  = canDecomposableTyConApp ev eq_rel tc1 tys1 tc2 tys2
494

495 496
can_eq_nc' _flat _rdr_env _envs ev eq_rel
           (TyConApp tc1 _) ps_ty1 (FunTy {}) ps_ty2
Austin Seipp's avatar
Austin Seipp committed
497
  | isDecomposableTyCon tc1
498 499 500
      -- The guard is important
      -- e.g.  (x -> y) ~ (F x y) where F has arity 1
      --       should not fail, but get the app/app case
501
  = canEqHardFailure ev eq_rel ps_ty1 ps_ty2
502

503
can_eq_nc' _flat _rdr_env _envs ev eq_rel (FunTy s1 t1) _ (FunTy s2 t2) _
504
  = do { canDecomposableTyConAppOK ev eq_rel funTyCon [s1,t1] [s2,t2]
505 506
       ; stopWith ev "Decomposed FunTyCon" }

507 508
can_eq_nc' _flat _rdr_env _envs ev eq_rel
          (FunTy {}) ps_ty1 (TyConApp tc2 _) ps_ty2
Austin Seipp's avatar
Austin Seipp committed
509
  | isDecomposableTyCon tc2
510
  = canEqHardFailure ev eq_rel ps_ty1 ps_ty2
511

512 513
can_eq_nc' _flat _rdr_env _envs ev eq_rel
           s1@(ForAllTy {}) _ s2@(ForAllTy {}) _
514
 | CtWanted { ctev_loc = loc, ctev_evar = orig_ev } <- ev
515 516
 = do { let (tvs1,body1) = tcSplitForAllTys s1
            (tvs2,body2) = tcSplitForAllTys s2
Simon Peyton Jones's avatar
Simon Peyton Jones committed
517
      ; if not (equalLength tvs1 tvs2) then
518
          canEqHardFailure ev eq_rel s1 s2
519
        else
520
          do { traceTcS "Creating implication for polytype equality" $ ppr ev
521 522
             ; ev_term <- deferTcSForAllEq (eqRelRole eq_rel)
                                           loc (tvs1,body1) (tvs2,body2)
523
             ; setWantedEvBind orig_ev ev_term
524
             ; stopWith ev "Deferred polytype equality" } }
525
 | otherwise
Simon Peyton Jones's avatar
Simon Peyton Jones committed
526
 = do { traceTcS "Ommitting decomposition of given polytype equality" $
527
        pprEq s1 s2    -- See Note [Do not decompose given polytype equalities]
528
      ; stopWith ev "Discard given polytype equality" }
529

530 531 532 533 534 535 536 537 538 539 540 541 542
-- AppTys only decompose for nominal equality
-- See Note [Canonicalising type applications] about why we require flat types
can_eq_nc' True _rdr_env _envs ev NomEq (AppTy t1 s1) _ ty2 _
  | Just (t2, s2) <- tcSplitAppTy_maybe ty2
  = can_eq_app ev t1 s1 t2 s2
can_eq_nc' True _rdr_env _envs ev NomEq ty1 _ (AppTy t2 s2) _
  | Just (t1, s1) <- tcSplitAppTy_maybe ty1
  = can_eq_app ev t1 s1 t2 s2

-- See Note [AppTy reflexivity check]
can_eq_nc' _flat _rdr_env _envs ev ReprEq ty1@(AppTy {}) _ ty2@(AppTy {}) _
  | ty1 `eqType` ty2
  = canEqReflexive ev ReprEq ty1
543

544 545 546 547 548
-- No similarity in type structure detected. Flatten and try again!
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
       ; rewriteEqEvidence ev eq_rel NotSwapped xi1 xi2 co1 co2
549
         `andWhenContinue` \ new_ev ->
550 551 552 553 554 555 556 557 558 559 560 561 562
         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.
can_eq_nc' True _rdr_env _envs ev eq_rel _ ps_ty1 _ ps_ty2
  = canEqHardFailure ev eq_rel ps_ty1 ps_ty2
563

564
{-
565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582
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.

583 584 585 586 587 588 589 590 591
Note [Eager reflexivity check]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose we have

  newtype X = MkX (Int -> X)

and

  [W] X ~R X
592

593 594 595 596 597
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.

598 599
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.
600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629

Note [AppTy reflexivity check]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
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:
630 631 632
         -- See Note [Newtypes can blow the stack]
       ; checkReductionDepth (ctEvLoc ev) ty1
       ; markDataConsAsUsed rdr_env (tyConAppTyCon ty1)
633 634 635 636 637 638
           -- we have actually used the newtype constructor here, so
           -- make sure we don't warn about importing it!

       ; rewriteEqEvidence ev ReprEq swapped ty1' ps_ty2
                           (mkTcSymCo co) (mkTcReflCo Representational ps_ty2)
         `andWhenContinue` \ new_ev ->
639
         can_eq_nc False new_ev ReprEq ty1' ty1' ty2 ps_ty2 }
640 641 642 643 644 645 646 647 648 649 650 651

-- | Mark all the datacons of the given 'TyCon' as used in this module,
-- avoiding "redundant import" warnings.
markDataConsAsUsed :: GlobalRdrEnv -> TyCon -> TcS ()
markDataConsAsUsed rdr_env tc = addUsedRdrNamesTcS
  [ mkRdrQual (is_as (is_decl imp_spec)) occ
  | dc <- tyConDataCons tc
  , let dc_name = dataConName dc
        occ  = nameOccName dc_name
  , gre : _               <- return $ lookupGRE_Name rdr_env dc_name
  , Imported (imp_spec:_) <- return $ gre_prov gre ]

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
-- ^ Decompose a type application. Nominal equality only!
-- All input types must be flat. See Note [Canonicalising type applications]
can_eq_app :: CtEvidence       -- :: s1 t1 ~N s2 t2
           -> Xi -> Xi         -- s1 t1
           -> Xi -> Xi         -- s2 t2
           -> TcS (StopOrContinue Ct)
can_eq_app ev s1 t1 s2 t2
  | CtDerived { ctev_loc = loc } <- ev
  = do { emitNewDerived loc (mkTcEqPred t1 t2)
       ; canEqNC ev NomEq s1 s2 }
  | CtWanted { ctev_evar = evar, ctev_loc = loc } <- ev
  = do { ev_s <- newWantedEvVarNC loc (mkTcEqPred s1 s2)
       ; co_t <- unifyWanted loc Nominal t1 t2
       ; let co = mkTcAppCo (ctEvCoercion ev_s) co_t
       ; setWantedEvBind evar (EvCoercion co)
       ; canEqNC ev_s NomEq s1 s2 }
  | CtGiven { ctev_evtm = ev_tm, ctev_loc = loc } <- ev
  = do { let co   = evTermCoercion ev_tm
             co_s = mkTcLRCo CLeft  co
             co_t = mkTcLRCo CRight co
       ; evar_s <- newGivenEvVar loc (mkTcEqPred s1 s2, EvCoercion co_s)
       ; evar_t <- newGivenEvVar loc (mkTcEqPred t1 t2, EvCoercion co_t)
       ; emitWorkNC [evar_t]
       ; canEqNC evar_s NomEq s1 s2 }
  | otherwise  -- Can't happen
  = error "can_eq_app"
679

680
------------------------
681
canDecomposableTyConApp :: CtEvidence -> EqRel
Simon Peyton Jones's avatar
Simon Peyton Jones committed
682 683
                        -> TyCon -> [TcType]
                        -> TyCon -> [TcType]
684
                        -> TcS (StopOrContinue Ct)
685
-- See Note [Decomposing TyConApps]
686
canDecomposableTyConApp ev eq_rel tc1 tys1 tc2 tys2
687 688
  | tc1 == tc2
  , length tys1 == length tys2  -- Success: decompose!
689 690 691
  = do { traceTcS "canDecomposableTyConApp"
                  (ppr ev $$ ppr eq_rel $$ ppr tc1 $$ ppr tys1 $$ ppr tys2)
       ; canDecomposableTyConAppOK ev eq_rel tc1 tys1 tys2
692
       ; stopWith ev "Decomposed TyConApp" }
693

694 695 696 697 698 699 700 701 702 703
  -- Fail straight away for better error messages
  -- See Note [Use canEqFailure in canDecomposableTyConApp]
  | isDataFamilyTyCon tc1 || isDataFamilyTyCon tc2
  = canEqFailure ev eq_rel ty1 ty2
  | otherwise
  = canEqHardFailure ev eq_rel ty1 ty2
  where
    ty1 = mkTyConApp tc1 tys1
    ty2 = mkTyConApp tc2 tys2

704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720
{-
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 the 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 (T 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.
-}

canDecomposableTyConAppOK :: CtEvidence -> EqRel
721
                          -> TyCon -> [TcType] -> [TcType]
722 723
                          -> TcS ()
-- Precondition: tys1 and tys2 are the same length, hence "OK"
724
canDecomposableTyConAppOK ev eq_rel tc tys1 tys2
725 726
  = case ev of
     CtDerived { ctev_loc = loc }
727
        -> unifyDeriveds loc tc_roles tys1 tys2
728 729

     CtWanted { ctev_evar = evar, ctev_loc = loc }
730
        -> do { cos <- zipWith3M (unifyWanted loc) tc_roles tys1 tys2
731
              ; setWantedEvBind evar (EvCoercion (mkTcTyConAppCo role tc cos)) }
732 733

     CtGiven { ctev_evtm = ev_tm, ctev_loc = loc }
734 735 736 737 738 739
        -> do { let ev_co = evTermCoercion ev_tm
              ; given_evs <- newGivenEvVars loc $
                             [ ( mkTcEqPredRole r ty1 ty2
                               , EvCoercion (mkTcNthCo i ev_co) )
                             | (r, ty1, ty2, i) <- zip4 tc_roles tys1 tys2 [0..]
                             , r /= Phantom ]
740 741
              ; emitWorkNC given_evs }
  where
742 743 744 745 746
    role     = eqRelRole eq_rel
    tc_roles = tyConRolesX role tc

-- | Call when canonicalizing an equality fails, but if the equality is
-- representational, there is some hope for the future.
747
-- Examples in Note [Use canEqFailure in canDecomposableTyConApp]
748 749 750
canEqFailure :: CtEvidence -> EqRel
             -> TcType -> TcType -> TcS (StopOrContinue Ct)
canEqFailure ev ReprEq ty1 ty2
751
  = do { (xi1, co1) <- flatten FM_FlattenAll ev ty1
752 753 754
       ; (xi2, co2) <- flatten FM_FlattenAll ev ty2
       ; traceTcS "canEqFailure with ReprEq" $
         vcat [ ppr ev, ppr ty1, ppr ty2, ppr xi1, ppr xi2 ]
755 756
       ; if isTcReflCo co1 && isTcReflCo co2
         then continueWith (CIrredEvCan { cc_ev = ev })
757 758
         else rewriteEqEvidence ev ReprEq NotSwapped xi1 xi2 co1 co2
              `andWhenContinue` \ new_ev ->
759
              can_eq_nc True new_ev ReprEq xi1 xi1 xi2 xi2 }
760 761 762 763 764
canEqFailure ev NomEq ty1 ty2 = canEqHardFailure ev NomEq ty1 ty2

-- | Call when canonicalizing an equality fails with utterly no hope.
canEqHardFailure :: CtEvidence -> EqRel
                 -> TcType -> TcType -> TcS (StopOrContinue Ct)
765
-- See Note [Make sure that insolubles are fully rewritten]
766
canEqHardFailure ev eq_rel ty1 ty2
767 768
  = do { (s1, co1) <- flatten FM_SubstOnly ev ty1
       ; (s2, co2) <- flatten FM_SubstOnly ev ty2
769 770 771 772
       ; rewriteEqEvidence ev eq_rel NotSwapped s1 s2 co1 co2
         `andWhenContinue` \ new_ev ->
    do { emitInsoluble (mkNonCanonical new_ev)
       ; stopWith new_ev "Definitely not equal" }}
773

Austin Seipp's avatar
Austin Seipp committed
774
{-
775 776 777 778 779 780 781 782 783 784 785 786 787
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 jus 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.

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

Austin Seipp's avatar
Austin Seipp committed
797
However, over-eager decomposition gives bad error messages
798 799 800 801 802 803 804
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
805
we get an error        "Can't match Array ~ Maybe",
806 807
but we'd prefer to get "Can't match Array b ~ Maybe c".

808 809 810
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.
811

812 813
Note [Make sure that insolubles are fully rewritten]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Simon Peyton Jones's avatar
Simon Peyton Jones committed
814 815
When an equality fails, we still want to rewrite the equality
all the way down, so that it accurately reflects
816 817 818
 (a) the mutable reference substitution in force at start of solving
 (b) any ty-binds in force at this point in solving
See Note [Kick out insolubles] in TcInteract.
Simon Peyton Jones's avatar
Simon Peyton Jones committed
819
And if we don't do this there is a bad danger that
820 821 822
TcSimplify.applyTyVarDefaulting will find a variable
that has in fact been substituted.

823
Note [Do not decompose Given polytype equalities]
824 825
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider [G] (forall a. t1 ~ forall a. t2).  Can we decompose this?
826
No -- what would the evidence look like?  So instead we simply discard
Simon Peyton Jones's avatar
Simon Peyton Jones committed
827
this given evidence.
828 829


830 831 832 833 834 835 836 837 838 839 840 841 842
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.
843 844 845 846 847 848 849 850 851 852 853

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

854 855 856 857
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.
858

Austin Seipp's avatar
Austin Seipp committed
859
-}
Simon Peyton Jones's avatar
Simon Peyton Jones committed
860

Austin Seipp's avatar
Austin Seipp committed
861
canCFunEqCan :: CtEvidence
862
             -> TyCon -> [TcType]   -- LHS
863 864
             -> TcTyVar             -- RHS
             -> TcS (StopOrContinue Ct)
Austin Seipp's avatar
Austin Seipp committed
865 866
-- ^ Canonicalise a CFunEqCan.  We know that
--     the arg types are already flat,
867 868 869
-- and the RHS is a fsk, which we must *not* substitute.
-- So just substitute in the LHS
canCFunEqCan ev fn tys fsk
870
  = do { (tys', cos) <- flattenManyNom ev tys
871 872 873 874 875
                        -- cos :: tys' ~ tys
       ; let lhs_co  = mkTcTyConAppCo Nominal fn cos
                        -- :: F tys' ~ F tys
             new_lhs = mkTyConApp fn tys'
             fsk_ty  = mkTyVarTy fsk
876 877 878 879
       ; rewriteEqEvidence ev NomEq NotSwapped new_lhs fsk_ty
                           lhs_co (mkTcNomReflCo fsk_ty)
         `andWhenContinue` \ ev' ->
    do { extendFlatCache fn tys' (ctEvCoercion ev', fsk_ty, ctEvFlavour ev')
880
       ; continueWith (CFunEqCan { cc_ev = ev', cc_fun = fn
881
                                 , cc_tyargs = tys', cc_fsk = fsk }) } }
882 883

---------------------
884
canEqTyVar :: CtEvidence -> EqRel -> SwapFlag
885 886
           -> TcTyVar             -- already flat
           -> TcType              -- already flat
887
           -> TcS (StopOrContinue Ct)
888
-- A TyVar on LHS, but so far un-zonked
889 890 891
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
892 893 894 895
         -- 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
896
       ; canEqTyVar2 dflags ev eq_rel swapped tv1 ps_ty2 }
897 898

canEqTyVar2 :: DynFlags
899
            -> CtEvidence   -- lhs ~ rhs (or, if swapped, orhs ~ olhs)
900
            -> EqRel
901
            -> SwapFlag
902 903
            -> TcTyVar      -- lhs, flat
            -> TcType       -- rhs, flat
904
            -> TcS (StopOrContinue Ct)
Austin Seipp's avatar
Austin Seipp committed
905
-- LHS is an inert type variable,
906
-- and RHS is fully rewritten, but with type synonyms
907
-- preserved as much as possible
908

909
canEqTyVar2 dflags ev eq_rel swapped tv1 xi2
910
  | Just tv2 <- getTyVar_maybe xi2
911
  = canEqTyVarTyVar ev eq_rel swapped tv1 tv2
912

913
  | OC_OK xi2' <- occurCheckExpand dflags tv1 xi2  -- No occurs check
914 915 916 917
     -- We use xi2' on the RHS of the new CTyEqCan, a ~ xi2'
     -- to establish the invariant that a does not appear in the
     -- rhs of the CTyEqCan. This is guaranteed by occurCheckExpand;
     -- see Note [Occurs check expansion] in TcType
918 919
  = do { let k1 = tyVarKind tv1
             k2 = typeKind xi2'
920
       ; rewriteEqEvidence ev eq_rel swapped xi1 xi2' co1 (mkTcReflCo role xi2')
921 922 923
         `andWhenContinue` \ new_ev ->
         if k2 `isSubKind` k1
         then   -- Establish CTyEqCan kind invariant
924 925
                -- Reorientation has done its best, but the kinds might
                -- simply be incompatible
926 927 928 929
               continueWith (CTyEqCan { cc_ev = new_ev
                                      , cc_tyvar  = tv1, cc_rhs = xi2'
                                      , cc_eq_rel = eq_rel })
         else incompatibleKind new_ev xi1 k1 xi2' k2 }
930 931

  | otherwise  -- Occurs check error
932 933 934
  = rewriteEqEvidence ev eq_rel swapped xi1 xi2 co1 co2
    `andWhenContinue` \ new_ev ->
    case eq_rel of
935
      NomEq  -> do { emitInsoluble (mkNonCanonical ev)
936 937 938
              -- 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
939 940 941 942 943 944 945 946 947 948 949
                   ; stopWith new_ev "Occurs check" }

        -- 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.
      ReprEq -> do { traceTcS "Occurs-check in representational equality"
                              (ppr xi1 $$ ppr xi2)
                   ; continueWith (CIrredEvCan { cc_ev = new_ev }) }
950
  where
951 952 953 954
    role = eqRelRole eq_rel
    xi1  = mkTyVarTy tv1
    co1  = mkTcReflCo role xi1
    co2  = mkTcReflCo role xi2
955

956
canEqTyVarTyVar :: CtEvidence           -- tv1 ~ rhs (or rhs ~ tv1, if swapped)
957
                -> EqRel
958
                -> SwapFlag
959
                -> TcTyVar -> TcTyVar   -- tv1, tv2
960
                -> TcS (StopOrContinue Ct)
961
-- Both LHS and RHS rewrote to a type variable
962
-- See Note [Canonical orientation for tyvar/tyvar equality constraints]
963
canEqTyVarTyVar ev eq_rel swapped tv1 tv2
964
  | tv1 == tv2
965
  = do { setEvBindIfWanted ev (EvCoercion $ mkTcReflCo role xi1)
966 967 968 969 970 971 972 973
       ; stopWith ev "Equal tyvars" }

  | incompat_kind   = incompat
  | isFmvTyVar tv1  = do_fmv swapped            tv1 xi1 xi2 co1 co2
  | isFmvTyVar tv2  = do_fmv (flipSwap swapped) tv2 xi2 xi1 co2 co1
  | same_kind       = if swap_over then do_swap else no_swap
  | k1_sub_k2       = do_swap   -- Note [Kind orientation for CTyEqCan]
  | otherwise       = no_swap   -- k2_sub_k1
974
  where
975
    role = eqRelRole eq_rel
976
    xi1 = mkTyVarTy tv1
977
    co1 = mkTcReflCo role xi1
978
    xi2 = mkTyVarTy tv2
979
    co2 = mkTcReflCo role xi2
980 981
    k1  = tyVarKind tv1
    k2  = tyVarKind tv2
982 983 984 985 986 987 988 989 990
    k1_sub_k2     = k1 `isSubKind` k2
    k2_sub_k1     = k2 `isSubKind` k1
    same_kind     = k1_sub_k2 && k2_sub_k1
    incompat_kind = not (k1_sub_k2 || k2_sub_k1)

    no_swap = canon_eq swapped            tv1 xi1 xi2 co1 co2
    do_swap = canon_eq (flipSwap swapped) tv2 xi2 xi1 co2 co1

    canon_eq swapped tv1 xi1 xi2 co1 co2
991 992 993 994 995
        -- ev  : tv1 ~ rhs  (not swapped) or   rhs ~ tv1   (swapped)
      = rewriteEqEvidence ev eq_rel swapped xi1 xi2 co1 co2
        `andWhenContinue` \ new_ev ->
        continueWith (CTyEqCan { cc_ev = new_ev, cc_tyvar = tv1
                               , cc_rhs = xi2, cc_eq_rel = eq_rel })
996 997 998 999 1000 1001

    -- See Note [Orient equalities with flatten-meta-vars on the left] in TcFlatten
    do_fmv swapped tv1 xi1 xi2 co1 co2
      | same_kind
      = canon_eq swapped tv1 xi1 xi2 co1 co2
      | otherwise  -- Presumably tv1 `subKind` tv2, which is the wrong way round
1002 1003 1004
      = ASSERT2( tyVarKind tv1 `isSubKind` typeKind xi2,
                 ppr tv1 <+> dcolon <+> ppr (tyVarKind tv1) $$
                 ppr xi2 <+> dcolon <+> ppr (typeKind xi2) )
1005 1006
        ASSERT2( isWanted ev, ppr ev )  -- Only wanteds have flatten meta-vars
        do { tv_ty <- newFlexiTcSTy (tyVarKind tv1)
1007 1008 1009
           ; new_ev <- newWantedEvVarNC (ctEvLoc ev)
                                        (mkTcEqPredRole (eqRelRole eq_rel)
                                                        tv_ty xi2)
1010
           ; emitWorkNC [new_ev]
1011
           ; canon_eq swapped tv1 xi1 tv_ty co1 (ctEvCoercion new_ev) }
1012

1013
    incompat = incompatibleKind ev xi1 k1 xi2 k2
1014 1015 1016 1017 1018

    swap_over
      -- If tv1 is touchable, swap only if tv2 is also
      -- touchable and it's strictly better to update the latter
      -- But see Note [Avoid unnecessary swaps]
1019 1020
      | Just lvl1 <- metaTyVarTcLevel_maybe tv1
      = case metaTyVarTcLevel_maybe tv2 of
1021 1022 1023 1024 1025 1026 1027
          Nothing   -> False
          Just lvl2 | lvl2 `strictlyDeeperThan` lvl1 -> True
                    | lvl1 `strictlyDeeperThan` lvl2 -> False
                    | otherwise                      -> nicer_to_update_tv2

      -- So tv1 is not a meta tyvar
      -- If only one is a meta tyvar, put it on the left
Gabor Greif's avatar
Gabor Greif committed
1028
      -- This is not because it'll be solved; but because
1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
      -- the floating step looks for meta tyvars on the left
      | isMetaTyVar tv2 = True

      -- So neither is a meta tyvar

      -- If only one is a flatten tyvar, put it on the left
      -- See Note [Eliminate flat-skols]
      | not (isFlattenTyVar tv1), isFlattenTyVar tv2 = True

      | otherwise = False

    nicer_to_update_tv2
      =  (isSigTyVar tv1                 && not (isSigTyVar tv2))
      || (isSystemName (Var.varName tv2) && not (isSystemName (Var.varName tv1)))

1044 1045 1046 1047 1048 1049
-- | Solve a reflexive equality constraint
canEqReflexive :: CtEvidence    -- ty ~ ty
               -> EqRel
               -> TcType        -- ty
               -> TcS (StopOrContinue Ct)   -- always Stop
canEqReflexive ev eq_rel ty
1050 1051
  = do { setEvBindIfWanted ev (EvCoercion $
                               mkTcReflCo (eqRelRole eq_rel) ty)
1052 1053
       ; stopWith ev "Solved by reflexivity" }

1054 1055 1056 1057
incompatibleKind :: CtEvidence         -- t1~t2
                 -> TcType -> TcKind
                 -> TcType -> TcKind   -- s1~s2, flattened and zonked
                 -> TcS (StopOrContinue Ct)
Simon Peyton Jones's avatar
Simon Peyton Jones committed
1058
-- LHS and RHS have incompatible kinds, so emit an "irreducible" constraint
1059 1060
--       CIrredEvCan (NOT CTyEqCan or CFunEqCan)
-- for the type equality; and continue with the kind equality constraint.
Simon Peyton Jones's avatar
Simon Peyton Jones committed
1061
-- When the latter is solved, it'll kick out the irreducible equality for
1062
-- a second attempt at solving
1063 1064
--
-- See Note [Equalities with incompatible kinds]
1065

1066
incompatibleKind new_ev s1 k1 s2 k2   -- See Note [Equalities with incompatible kinds]
1067
  = ASSERT( isKind k1 && isKind k2 )
1068 1069 1070
    do { traceTcS "canEqLeaf: incompatible kinds" (vcat [ppr k1, ppr k2])

         -- Create a derived kind-equality, and solve it
1071
       ; emitNewDerived kind_co_loc (mkTcEqPred k1 k2)
1072 1073 1074

         -- Put the not-currently-soluble thing into the inert set
       ; continueWith (CIrredEvCan { cc_ev = new_ev }) }
1075
  where
1076
    loc = ctEvLoc new_ev
1077
    kind_co_loc = setCtLocOrigin loc (KindEqOrigin s1 s2 (ctLocOrigin loc))
1078

Austin Seipp's avatar
Austin Seipp committed
1079
{-
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125
Note [Canonical orientation for tyvar/tyvar equality constraints]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When we have a ~ b where both 'a' and 'b' are TcTyVars, which way
round should be oriented in the CTyEqCan?  The rules, implemented by
canEqTyVarTyVar, are these

 * If either is a flatten-meta-variables, it goes on the left.

 * If one is a strict sub-kind of the other e.g.
       (alpha::?) ~ (beta::*)
   orient them so RHS is a subkind of LHS.  That way we will replace
   'a' with 'b', correctly narrowing the kind.
   This establishes the subkind invariant of CTyEqCan.

 * Put a meta-tyvar on the left if possible
       alpha[3] ~ r

 * If both are meta-tyvars, put the more touchable one (deepest level
   number) on the left, so there is the best chance of unifying it
        alpha[3] ~ beta[2]

 * If both are meta-tyvars and both at the same level, put a SigTv
   on the right if possible
        alpha[2] ~ beta[2](sig-tv)
   That way, when we unify alpha := beta, we don't lose the SigTv flag.

 * Put a meta-tv with a System Name on the left if possible so it
   gets eliminated (improves error messages)

 * If one is a flatten-skolem, put it on the left so that it is
   substituted out  Note [Elminate flat-skols]
        fsk ~ a

Note [Avoid unnecessary swaps]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If we swap without actually improving matters, we can get an infnite loop.
Consider
    work item:  a ~ b
   inert item:  b ~ c
We canonicalise the work-time to (a ~ c).  If we then swap it before
aeding to the inert set, we'll add (c ~ a), and therefore kick out the
inert guy, so we get
   new work item:  b ~ c
   inert item:     c ~ a
And now the cycle just repeats

1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143
Note [Eliminate flat-skols]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose we have  [G] Num (F [a])
then we flatten to
     [G] Num fsk
     [G] F [a] ~ fsk
where fsk is a flatten-skolem (FlatSkol). Suppose we have
      type instance F [a] = a
then we'll reduce the second constraint to
     [G] a ~ fsk
and then replace all uses of 'a' with fsk.  That's bad because
in error messages intead of saying 'a' we'll say (F [a]).  In all
places, including those where the programmer wrote 'a' in the first
place.  Very confusing!  See Trac #7862.

Solution: re-orient a~fsk to fsk~a, so that we preferentially eliminate
the fsk.

1144 1145 1146
Note [Equalities with incompatible kinds]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
canEqLeaf is about to make a CTyEqCan or CFunEqCan; but both have the