TcCanonical.hs 55.4 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 22
import Class
import TyCon
import TypeRep
import Var
23
import Name( isSystemName )
24
import OccName( OccName )
25
import Outputable
26
import Control.Monad
27
import DynFlags( DynFlags )
28 29
import VarSet

30
import Pair
31
import Util
32
import BasicTypes
33
import FastString
34

Austin Seipp's avatar
Austin Seipp committed
35 36 37 38 39 40
{-
************************************************************************
*                                                                      *
*                      The Canonicaliser                               *
*                                                                      *
************************************************************************
41

42 43
Note [Canonicalization]
~~~~~~~~~~~~~~~~~~~~~~~
44

45 46 47 48
Canonicalization converts a flat constraint to a canonical form. It is
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).
49

50
The execution plan for canonicalization is the following:
Simon Peyton Jones's avatar
Simon Peyton Jones committed
51 52

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

Simon Peyton Jones's avatar
Simon Peyton Jones committed
56 57 58 59
  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.
60

61 62
  3) If no more decomposition is possible, we deeply apply the substitution
     from the inert_eqs and continue with flattening.
63

Simon Peyton Jones's avatar
Simon Peyton Jones committed
64 65 66 67 68
  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.
69

Simon Peyton Jones's avatar
Simon Peyton Jones committed
70 71
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
72 73
rewrite an inert or still interact with an inert in a further phase in the
simplifier.
dimitris's avatar
dimitris committed
74

75
Note [Caching for canonicals]
Simon Peyton Jones's avatar
Simon Peyton Jones committed
76
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
77 78 79 80
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:
81

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

85 86 87 88 89
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
90

91 92
   - We encounter work item (d2 : Num t)

Simon Peyton Jones's avatar
Simon Peyton Jones committed
93
   - Nothing is yet in EvBinds, so we reach the interaction with inerts
94
     and set:
Simon Peyton Jones's avatar
Simon Peyton Jones committed
95
              d2 := d1
96 97
    and we discard d2 from the worklist. The inert set remains unaffected.

98 99 100
   - 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:
101
        InertSet : { [G] c : t ~ Int }
Simon Peyton Jones's avatar
Simon Peyton Jones committed
102
        WorkList : { [W] d1 : Num t}
103

104 105
   - 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
106
             d1 := d2
107 108
     and end up in a loop!

109 110 111 112 113 114 115 116
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.
117

118 119 120 121 122 123 124
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
125
-}
126

127 128 129
-- Top-level canonicalization
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

130
canonicalize :: Ct -> TcS (StopOrContinue Ct)
131
canonicalize ct@(CNonCanonical { cc_ev = ev })
132
  = do { traceTcS "canonicalize (non-canonical)" (ppr ct)
133
       ; {-# SCC "canEvVar" #-}
134
         canEvNC ev }
135

136
canonicalize (CDictCan { cc_ev = ev
137 138
                       , cc_class  = cls
                       , cc_tyargs = xis })
139
  = {-# SCC "canClass" #-}
140 141
    canClass ev cls xis -- Do not add any superclasses
canonicalize (CTyEqCan { cc_ev = ev
142 143
                       , cc_tyvar  = tv
                       , cc_rhs    = xi })
144
  = {-# SCC "canEqLeafTyVarEq" #-}
145
    canEqTyVar ev NotSwapped tv xi xi
146

147
canonicalize (CFunEqCan { cc_ev = ev
148 149
                        , cc_fun    = fn
                        , cc_tyargs = xis1
150
                        , cc_fsk    = fsk })
Simon Peyton Jones's avatar
Simon Peyton Jones committed
151
  = {-# SCC "canEqLeafFunEq" #-}
152
    canCFunEqCan ev fn xis1 fsk
153

154 155
canonicalize (CIrredEvCan { cc_ev = ev })
  = canIrred ev
thomasw's avatar
thomasw committed
156 157
canonicalize (CHoleCan { cc_ev = ev, cc_occ = occ, cc_hole = hole })
  = canHole ev occ hole
158

159
canEvNC :: CtEvidence -> TcS (StopOrContinue Ct)
Simon Peyton Jones's avatar
Simon Peyton Jones committed
160
-- Called only for non-canonical EvVars
161
canEvNC ev
162
  = case classifyPredType (ctEvPred ev) of
163 164 165 166
      ClassPred cls tys -> traceTcS "canEvNC:cls" (ppr cls <+> ppr tys) >> canClassNC ev cls tys
      EqPred ty1 ty2    -> traceTcS "canEvNC:eq" (ppr ty1 $$ ppr ty2)   >> canEqNC    ev ty1 ty2
      TuplePred tys     -> traceTcS "canEvNC:tup" (ppr tys)             >> canTuple   ev tys
      IrredPred {}      -> traceTcS "canEvNC:irred" (ppr (ctEvPred ev)) >> canIrred   ev
167

Austin Seipp's avatar
Austin Seipp committed
168 169 170 171 172 173 174
{-
************************************************************************
*                                                                      *
*                      Tuple Canonicalization
*                                                                      *
************************************************************************
-}
175

176
canTuple :: CtEvidence -> [PredType] -> TcS (StopOrContinue Ct)
177
canTuple ev tys
dimitris's avatar
dimitris committed
178 179
  = do { traceTcS "can_pred" (text "TuplePred!")
       ; let xcomp = EvTupleMk
Simon Peyton Jones's avatar
Simon Peyton Jones committed
180
             xdecomp x = zipWith (\_ i -> EvTupleSel x i) tys [0..]
181 182
       ; xCtEvidence ev (XEvTerm tys xcomp xdecomp)
       ; stopWith ev "Decomposed tuple constraint" }
183

Austin Seipp's avatar
Austin Seipp committed
184 185 186 187 188 189 190
{-
************************************************************************
*                                                                      *
*                      Class Canonicalization
*                                                                      *
************************************************************************
-}
191

Simon Peyton Jones's avatar
Simon Peyton Jones committed
192
canClass, canClassNC
193
   :: CtEvidence
194
   -> Class -> [Type] -> TcS (StopOrContinue Ct)
Simon Peyton Jones's avatar
Simon Peyton Jones committed
195
-- Precondition: EvVar is class evidence
196 197 198 199 200 201

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

202 203
canClassNC ev cls tys
  = canClass ev cls tys
204 205
    `andWhenContinue` emitSuperclasses

206
canClass ev cls tys
207
  = do { (xis, cos) <- flattenMany FM_FlattenAll ev tys
Joachim Breitner's avatar
Joachim Breitner committed
208
       ; let co = mkTcTyConAppCo Nominal (classTyCon cls) cos
209
             xi = mkClassPred cls xis
210 211
             mk_ct new_ev = CDictCan { cc_ev = new_ev
                                     , cc_tyargs = xis, cc_class = cls }
212
       ; mb <- rewriteEvidence ev xi co
Simon Peyton Jones's avatar
Simon Peyton Jones committed
213
       ; traceTcS "canClass" (vcat [ ppr ev <+> ppr cls <+> ppr tys
Simon Peyton Jones's avatar
Simon Peyton Jones committed
214
                                   , ppr xi, ppr mb ])
215
       ; return (fmap mk_ct mb) }
dimitris's avatar
dimitris committed
216

217
emitSuperclasses :: Ct -> TcS (StopOrContinue Ct)
218
emitSuperclasses ct@(CDictCan { cc_ev = ev , cc_tyargs = xis_new, cc_class = cls })
Simon Peyton Jones's avatar
Simon Peyton Jones committed
219 220
            -- Add superclasses of this one here, See Note [Adding superclasses].
            -- But only if we are not simplifying the LHS of a rule.
221
 = do { newSCWorkFromFlavored ev cls xis_new
Simon Peyton Jones's avatar
Simon Peyton Jones committed
222
      -- Arguably we should "seq" the coercions if they are derived,
223
      -- as we do below for emit_kind_constraint, to allow errors in
Simon Peyton Jones's avatar
Simon Peyton Jones committed
224
      -- superclasses to be executed if deferred to runtime!
225 226
      ; continueWith ct }
emitSuperclasses _ = panic "emit_superclasses of non-class!"
227

Austin Seipp's avatar
Austin Seipp committed
228
{-
229
Note [Adding superclasses]
Simon Peyton Jones's avatar
Simon Peyton Jones committed
230
~~~~~~~~~~~~~~~~~~~~~~~~~~
231 232 233 234 235 236
Since dictionaries are canonicalized only once in their lifetime, the
place to add their superclasses is canonicalisation (The alternative
would be to do it during constraint solving, but we'd have to be
extremely careful to not repeatedly introduced the same superclass in
our worklist). Here is what we do:

Simon Peyton Jones's avatar
Simon Peyton Jones committed
237 238
For Givens:
       We add all their superclasses as Givens.
239

Simon Peyton Jones's avatar
Simon Peyton Jones committed
240 241
For Wanteds:
       Generally speaking we want to be able to add superclasses of
242
       wanteds for two reasons:
243

Simon Peyton Jones's avatar
Simon Peyton Jones committed
244 245 246 247 248 249 250 251 252
       (1) Oportunities for improvement. Example:
                  class (a ~ b) => C a b
           Wanted constraint is: C alpha beta
           We'd like to simply have C alpha alpha. Similar
           situations arise in relation to functional dependencies.

       (2) To have 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.
253

254
       To deal with (1) above we only add the superclasses of wanteds
Simon Peyton Jones's avatar
Simon Peyton Jones committed
255 256
       which may lead to improvement, that is: equality superclasses or
       superclasses with functional dependencies.
257

Simon Peyton Jones's avatar
Simon Peyton Jones committed
258 259
       We deal with (2) completely independently in TcSimplify. See
       Note [Minimize by SuperClasses] in TcSimplify.
260 261


Simon Peyton Jones's avatar
Simon Peyton Jones committed
262 263 264 265
       Moreover, in all cases the extra improvement constraints are
       Derived. Derived constraints have an identity (for now), but
       we don't do anything with their evidence. For instance they
       are never used to rewrite other constraints.
266

Simon Peyton Jones's avatar
Simon Peyton Jones committed
267
       See also [New Wanted Superclass Work] in TcInteract.
268

269

Simon Peyton Jones's avatar
Simon Peyton Jones committed
270
For Deriveds:
271
       We do nothing.
272 273 274

Here's an example that demonstrates why we chose to NOT add
superclasses during simplification: [Comes from ticket #4497]
Simon Peyton Jones's avatar
Simon Peyton Jones committed
275

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

Simon Peyton Jones's avatar
Simon Peyton Jones committed
279 280 281 282 283 284 285 286 287 288 289
Assume the generated wanted constraint is:
   RealOf e ~ e, Normed e
If we were to be adding the superclasses during simplification we'd get:
   Num uf, Normed e, RealOf e ~ e, RealOf e ~ uf
==>
   e ~ uf, Num uf, Normed e, RealOf e ~ e
==> [Spontaneous solve]
   Num uf, Normed uf, RealOf uf ~ uf

While looks exactly like our original constraint. If we add the superclass again we'd loop.
By adding superclasses definitely only once, during canonicalisation, this situation can't
290
happen.
Austin Seipp's avatar
Austin Seipp committed
291
-}
292

293
newSCWorkFromFlavored :: CtEvidence -> Class -> [Xi] -> TcS ()
294
-- Returns superclasses, see Note [Adding superclasses]
295
newSCWorkFromFlavored flavor cls xis
Simon Peyton Jones's avatar
Simon Peyton Jones committed
296
  | isDerived flavor
297
  = return ()  -- Deriveds don't yield more superclasses because we will
Simon Peyton Jones's avatar
Simon Peyton Jones committed
298 299 300 301 302
               -- add them transitively in the case of wanteds.

  | isGiven flavor
  = do { let sc_theta = immSuperClasses cls xis
             xev_decomp x = zipWith (\_ i -> EvSuperClass x i) sc_theta [0..]
303 304
             xev = XEvTerm { ev_preds  =  sc_theta
                           , ev_comp   = panic "Can't compose for given!"
305
                           , ev_decomp = xev_decomp }
306
       ; xCtEvidence flavor xev }
dimitris's avatar
dimitris committed
307 308

  | isEmptyVarSet (tyVarsOfTypes xis)
309
  = return () -- Wanteds with no variables yield no deriveds.
310
              -- See Note [Improvement from Ground Wanteds]
311

Simon Peyton Jones's avatar
Simon Peyton Jones committed
312 313
  | otherwise -- Wanted case, just add those SC that can lead to improvement.
  = do { let sc_rec_theta = transSuperClasses cls xis
314
             impr_theta   = filter is_improvement_pty sc_rec_theta
315
             loc          = ctEvLoc flavor
316
       ; traceTcS "newSCWork/Derived" $ text "impr_theta =" <+> ppr impr_theta
317
       ; mapM_ (emitNewDerived loc) impr_theta }
318

Simon Peyton Jones's avatar
Simon Peyton Jones committed
319
is_improvement_pty :: PredType -> Bool
320
-- Either it's an equality, or has some functional dependency
321
is_improvement_pty ty = go (classifyPredType ty)
batterseapower's avatar
batterseapower committed
322
  where
323
    go (EqPred t1 t2)       = not (t1 `tcEqType` t2)
324
    go (ClassPred cls _tys) = not $ null fundeps
325 326 327
                            where (_,fundeps) = classTvsFds cls
    go (TuplePred ts)       = any is_improvement_pty ts
    go (IrredPred {})       = True -- Might have equalities after reduction?
328

Austin Seipp's avatar
Austin Seipp committed
329 330 331 332 333 334 335
{-
************************************************************************
*                                                                      *
*                      Irreducibles canonicalization
*                                                                      *
************************************************************************
-}
336

337
canIrred :: CtEvidence -> TcS (StopOrContinue Ct)
338
-- Precondition: ty not a tuple and no other evidence form
339
canIrred old_ev
Simon Peyton Jones's avatar
Simon Peyton Jones committed
340 341
  = do { let old_ty = ctEvPred old_ev
       ; traceTcS "can_pred" (text "IrredPred = " <+> ppr old_ty)
342 343
       ; (xi,co) <- flatten FM_FlattenAll old_ev old_ty -- co :: xi ~ old_ty
                      -- Flatten (F [a]), say, so that it can reduce to Eq a
344
       ; mb <- rewriteEvidence old_ev xi co
345
       ; case mb of {
346 347
             Stop ev s           -> return (Stop ev s) ;
             ContinueWith new_ev ->
348 349 350

    do { -- Re-classify, in case flattening has improved its shape
       ; case classifyPredType (ctEvPred new_ev) of
351 352
           ClassPred cls tys -> canClassNC new_ev cls tys
           TuplePred tys     -> canTuple   new_ev tys
353 354 355
           EqPred ty1 ty2    -> canEqNC new_ev ty1 ty2
           _                 -> continueWith $
                                CIrredEvCan { cc_ev = new_ev } } } }
356

thomasw's avatar
thomasw committed
357 358
canHole :: CtEvidence -> OccName -> HoleSort -> TcS (StopOrContinue Ct)
canHole ev occ hole_sort
359 360
  = do { let ty = ctEvPred ev
       ; (xi,co) <- flatten FM_SubstOnly ev ty -- co :: xi ~ ty
361
       ; mb <- rewriteEvidence ev xi co
dimitris's avatar
dimitris committed
362
       ; case mb of
thomasw's avatar
thomasw committed
363 364 365
           ContinueWith new_ev -> do { emitInsoluble (CHoleCan { cc_ev = new_ev
                                                               , cc_occ = occ
                                                               , cc_hole = hole_sort })
366 367
                                     ; stopWith new_ev "Emit insoluble hole" }
           Stop ev s -> return (Stop ev s) } -- Found a cached copy; won't happen
368

Austin Seipp's avatar
Austin Seipp committed
369 370 371 372 373 374 375
{-
************************************************************************
*                                                                      *
*        Equalities
*                                                                      *
************************************************************************
-}
376

377
canEqNC :: CtEvidence -> Type -> Type -> TcS (StopOrContinue Ct)
378 379
canEqNC ev ty1 ty2 = can_eq_nc ev ty1 ty1 ty2 ty2

Austin Seipp's avatar
Austin Seipp committed
380 381 382 383
can_eq_nc, can_eq_nc'
   :: CtEvidence
   -> Type -> Type    -- LHS, after and before type-synonym expansion, resp
   -> Type -> Type    -- RHS, after and before type-synonym expansion, resp
384
   -> TcS (StopOrContinue Ct)
385 386

can_eq_nc ev ty1 ps_ty1 ty2 ps_ty2
Austin Seipp's avatar
Austin Seipp committed
387
  = do { traceTcS "can_eq_nc" $
388 389 390 391 392 393 394 395
         vcat [ ppr ev, ppr ty1, ppr ps_ty1, ppr ty2, ppr ps_ty2 ]
       ; can_eq_nc' ev ty1 ps_ty1 ty2 ps_ty2 }

-- Expand synonyms first; see Note [Type synonyms and canonicalization]
can_eq_nc' ev ty1 ps_ty1 ty2 ps_ty2
  | Just ty1' <- tcView ty1 = can_eq_nc ev ty1' ps_ty1 ty2  ps_ty2
  | Just ty2' <- tcView ty2 = can_eq_nc ev ty1  ps_ty1 ty2' ps_ty2

396 397 398 399
-- Type family on LHS or RHS take priority over tyvars,
-- so that  tv ~ F ty gets flattened
-- Otherwise  F a ~ F a  might not get solved!
can_eq_nc' ev (TyConApp fn1 tys1) _ ty2 ps_ty2
400
  | isTypeFamilyTyCon fn1 = can_eq_fam_nc ev NotSwapped fn1 tys1 ty2 ps_ty2
401
can_eq_nc' ev ty1 ps_ty1 (TyConApp fn2 tys2) _
402
  | isTypeFamilyTyCon fn2 = can_eq_fam_nc ev IsSwapped fn2 tys2 ty1 ps_ty1
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418

-- Type variable on LHS or RHS are next
can_eq_nc' ev (TyVarTy tv1) _ ty2 ps_ty2
  = canEqTyVar ev NotSwapped tv1 ty2 ps_ty2
can_eq_nc' ev ty1 ps_ty1 (TyVarTy tv2) _
  = canEqTyVar ev IsSwapped tv2 ty1 ps_ty1

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

-- Literals
can_eq_nc' ev ty1@(LitTy l1) _ (LitTy l2) _
 | l1 == l2
  = do { when (isWanted ev) $
         setEvBind (ctev_evar ev) (EvCoercion (mkTcNomReflCo ty1))
419
       ; stopWith ev "Equal LitTy" }
420

Austin Seipp's avatar
Austin Seipp committed
421
-- Decomposable type constructor applications
422
-- Synonyms and type functions (which are not decomposable)
Austin Seipp's avatar
Austin Seipp committed
423
-- have already been dealt with
424 425 426
can_eq_nc' ev (TyConApp tc1 tys1) _ (TyConApp tc2 tys2) _
  | isDecomposableTyCon tc1
  , isDecomposableTyCon tc2
427
  = canDecomposableTyConApp ev tc1 tys1 tc2 tys2
428

429
can_eq_nc' ev (TyConApp tc1 _) ps_ty1 (FunTy {}) ps_ty2
Austin Seipp's avatar
Austin Seipp committed
430
  | isDecomposableTyCon tc1
431 432 433 434 435 436
      -- 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
  = canEqFailure ev ps_ty1 ps_ty2

can_eq_nc' ev (FunTy s1 t1) _ (FunTy s2 t2) _
437 438 439
  = do { canDecomposableTyConAppOK ev funTyCon [s1,t1] [s2,t2]
       ; stopWith ev "Decomposed FunTyCon" }

440 441

can_eq_nc' ev (FunTy {}) ps_ty1 (TyConApp tc2 _) ps_ty2
Austin Seipp's avatar
Austin Seipp committed
442
  | isDecomposableTyCon tc2
443 444 445 446
  = canEqFailure ev ps_ty1 ps_ty2

can_eq_nc' ev s1@(ForAllTy {}) _ s2@(ForAllTy {}) _
 | CtWanted { ctev_loc = loc, ctev_evar = orig_ev } <- ev
447 448
 = do { let (tvs1,body1) = tcSplitForAllTys s1
            (tvs2,body2) = tcSplitForAllTys s2
Simon Peyton Jones's avatar
Simon Peyton Jones committed
449
      ; if not (equalLength tvs1 tvs2) then
450
          canEqFailure ev s1 s2
451
        else
452
          do { traceTcS "Creating implication for polytype equality" $ ppr ev
453 454
             ; ev_term <- deferTcSForAllEq Nominal loc (tvs1,body1) (tvs2,body2)
             ; setEvBind orig_ev ev_term
455
             ; stopWith ev "Deferred polytype equality" } }
456
 | otherwise
Simon Peyton Jones's avatar
Simon Peyton Jones committed
457
 = do { traceTcS "Ommitting decomposition of given polytype equality" $
458
        pprEq s1 s2    -- See Note [Do not decompose given polytype equalities]
459
      ; stopWith ev "Discard given polytype equality" }
460

461 462 463 464 465 466
can_eq_nc' ev (AppTy {}) ps_ty1 _ ps_ty2
  | isGiven ev = try_decompose_app ev ps_ty1 ps_ty2
  | otherwise  = can_eq_wanted_app ev ps_ty1 ps_ty2
can_eq_nc' ev _ ps_ty1 (AppTy {}) ps_ty2
  | isGiven ev = try_decompose_app ev ps_ty1 ps_ty2
  | otherwise  = can_eq_wanted_app ev ps_ty1 ps_ty2
467 468 469 470 471

-- Everything else is a definite type error, eg LitTy ~ TyConApp
can_eq_nc' ev _ ps_ty1 _ ps_ty2
  = canEqFailure ev ps_ty1 ps_ty2

472 473 474 475 476 477 478 479 480
------------
can_eq_fam_nc :: CtEvidence -> SwapFlag
              -> TyCon -> [TcType]
              -> TcType -> TcType
              -> TcS (StopOrContinue Ct)
-- Canonicalise a non-canonical equality of form (F tys ~ ty)
--   or the swapped version thereof
-- Flatten both sides and go round again
can_eq_fam_nc ev swapped fn tys rhs ps_rhs
481
  = do { (xi_lhs, co_lhs) <- flattenFamApp FM_FlattenAll ev fn tys
482 483 484 485 486
       ; mb_ct <- rewriteEqEvidence ev swapped xi_lhs rhs co_lhs (mkTcNomReflCo rhs)
       ; case mb_ct of
           Stop ev s           -> return (Stop ev s)
           ContinueWith new_ev -> can_eq_nc new_ev xi_lhs xi_lhs rhs ps_rhs }

487 488
-----------------------------------
-- Dealing with AppTy
489
-- See Note [Canonicalising type applications]
490

491 492 493 494 495
can_eq_wanted_app :: CtEvidence -> TcType -> TcType
                  -> TcS (StopOrContinue Ct)
-- One or the other is an App; neither is a type variable
-- See Note [Canonicalising type applications]
can_eq_wanted_app ev ty1 ty2
496 497
  = do { (xi1, co1) <- flatten FM_FlattenAll ev ty1
       ; (xi2, co2) <- flatten FM_FlattenAll ev ty2
498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528
        ; mb_ct <- rewriteEqEvidence ev NotSwapped xi1 xi2 co1 co2
        ; case mb_ct of {
            Stop ev s           -> return (Stop ev s) ;
            ContinueWith new_ev -> try_decompose_app new_ev xi1 xi2 } }

try_decompose_app :: CtEvidence -> TcType -> TcType -> TcS (StopOrContinue Ct)
-- Preconditions: neither is a type variable
--                so can't turn it into an application if it
--                   doesn't look like one already
-- See Note [Canonicalising type applications]
try_decompose_app ev ty1 ty2
   | AppTy s1 t1  <- ty1
   = case tcSplitAppTy_maybe ty2 of
       Nothing      -> canEqFailure ev ty1 ty2
       Just (s2,t2) -> do_decompose s1 t1 s2 t2

   | AppTy s2 t2 <- ty2
   = case tcSplitAppTy_maybe ty1 of
       Nothing      -> canEqFailure ev ty1 ty2
       Just (s1,t1) -> do_decompose s1 t1 s2 t2

   | otherwise  -- Neither is an AppTy
   = canEqNC ev ty1 ty2
   where
     -- do_decompose is like xCtEvidence, but recurses
     -- to try_decompose_app to decompose a chain of AppTys
     do_decompose s1 t1 s2 t2
       | CtDerived { ctev_loc = loc } <- ev
       = do { emitNewDerived loc (mkTcEqPred t1 t2)
            ; try_decompose_app ev s1 s2 }
       | CtWanted { ctev_evar = evar, ctev_loc = loc } <- ev
529 530 531
       = do { ev_s <- newWantedEvVarNC loc (mkTcEqPred s1 s2)
            ; co_t <- unifyWanted loc t1 t2
            ; let co = mkTcAppCo (ctEvCoercion ev_s) co_t
532
            ; setEvBind evar (EvCoercion co)
533
            ; try_decompose_app ev_s s1 s2 }
534 535 536 537 538 539 540 541 542 543
       | 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]
            ; try_decompose_app evar_s s1 s2 }
       | otherwise  -- Can't happen
       = error "try_decompose_app"
544

545
------------------------
546
canDecomposableTyConApp :: CtEvidence
Simon Peyton Jones's avatar
Simon Peyton Jones committed
547 548
                        -> TyCon -> [TcType]
                        -> TyCon -> [TcType]
549
                        -> TcS (StopOrContinue Ct)
550
-- See Note [Decomposing TyConApps]
551
canDecomposableTyConApp ev tc1 tys1 tc2 tys2
552 553
  | tc1 /= tc2 || length tys1 /= length tys2
    -- Fail straight away for better error messages
554
  = canEqFailure ev (mkTyConApp tc1 tys1) (mkTyConApp tc2 tys2)
555
  | otherwise
556
  = do { traceTcS "canDecomposableTyConApp" (ppr ev $$ ppr tc1 $$ ppr tys1 $$ ppr tys2)
557 558
       ; canDecomposableTyConAppOK ev tc1 tys1 tys2
       ; stopWith ev "Decomposed TyConApp" }
559 560 561

canDecomposableTyConAppOK :: CtEvidence
                          -> TyCon -> [TcType] -> [TcType]
562 563
                          -> TcS ()
-- Precondition: tys1 and tys2 are the same length, hence "OK"
564
canDecomposableTyConAppOK ev tc1 tys1 tys2
565 566 567 568 569 570 571 572 573 574 575 576 577 578 579
  = case ev of
     CtDerived { ctev_loc = loc }
        -> mapM_ (unifyDerived loc) (zipWith Pair tys1 tys2)

     CtWanted { ctev_evar = evar, ctev_loc = loc }
        -> do { cos <- zipWithM (unifyWanted loc) tys1 tys2
              ; setEvBind evar (EvCoercion (mkTcTyConAppCo Nominal tc1 cos)) }

     CtGiven { ctev_evtm = ev_tm, ctev_loc = loc }
        -> do { given_evs <- newGivenEvVars loc $
                             zipWith3 (mk_given ev_tm) tys1 tys2 [0..]
              ; emitWorkNC given_evs }
  where
    mk_given ev_tm ty1 ty2 i
       = (mkTcEqPred ty1 ty2, EvCoercion (mkTcNthCo i (evTermCoercion ev_tm)))
580

581
--------------------
582
canEqFailure :: CtEvidence -> TcType -> TcType -> TcS (StopOrContinue Ct)
583
-- See Note [Make sure that insolubles are fully rewritten]
584
canEqFailure ev ty1 ty2
585 586
  = do { (s1, co1) <- flatten FM_SubstOnly ev ty1
       ; (s2, co2) <- flatten FM_SubstOnly ev ty2
587
       ; mb_ct <- rewriteEqEvidence ev NotSwapped s1 s2 co1 co2
588
       ; case mb_ct of
589 590 591
           ContinueWith new_ev -> do { emitInsoluble (mkNonCanonical new_ev)
                                     ; stopWith new_ev "Definitely not equal" }
           Stop ev s -> pprPanic "canEqFailure" (s $$ ppr ev $$ ppr ty1 $$ ppr ty2) }
592

Austin Seipp's avatar
Austin Seipp committed
593
{-
594 595 596 597 598 599 600 601 602 603 604 605 606 607
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.


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

Austin Seipp's avatar
Austin Seipp committed
617
However, over-eager decomposition gives bad error messages
618 619 620 621 622 623 624
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
625
we get an error        "Can't match Array ~ Maybe",
626 627
but we'd prefer to get "Can't match Array b ~ Maybe c".

628 629
So instead can_eq_wanted_app flattens the LHS and RHS before using
try_decompose_app to decompose it.
630

631 632
Note [Make sure that insolubles are fully rewritten]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Simon Peyton Jones's avatar
Simon Peyton Jones committed
633 634
When an equality fails, we still want to rewrite the equality
all the way down, so that it accurately reflects
635 636 637
 (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
638
And if we don't do this there is a bad danger that
639 640 641
TcSimplify.applyTyVarDefaulting will find a variable
that has in fact been substituted.

642
Note [Do not decompose Given polytype equalities]
643 644
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider [G] (forall a. t1 ~ forall a. t2).  Can we decompose this?
645
No -- what would the evidence look like?  So instead we simply discard
Simon Peyton Jones's avatar
Simon Peyton Jones committed
646
this given evidence.
647 648


649 650 651 652 653 654 655 656 657 658 659 660 661
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.
Austin Seipp's avatar
Austin Seipp committed
662
-}
Simon Peyton Jones's avatar
Simon Peyton Jones committed
663

Austin Seipp's avatar
Austin Seipp committed
664
canCFunEqCan :: CtEvidence
665
             -> TyCon -> [TcType]   -- LHS
666 667
             -> TcTyVar             -- RHS
             -> TcS (StopOrContinue Ct)
Austin Seipp's avatar
Austin Seipp committed
668 669
-- ^ Canonicalise a CFunEqCan.  We know that
--     the arg types are already flat,
670 671 672
-- and the RHS is a fsk, which we must *not* substitute.
-- So just substitute in the LHS
canCFunEqCan ev fn tys fsk
673
  = do { (tys', cos) <- flattenMany FM_FlattenAll ev tys
674 675 676 677 678 679 680 681 682 683 684
                        -- cos :: tys' ~ tys
       ; let lhs_co  = mkTcTyConAppCo Nominal fn cos
                        -- :: F tys' ~ F tys
             new_lhs = mkTyConApp fn tys'
             fsk_ty  = mkTyVarTy fsk
       ; mb_ev <- rewriteEqEvidence ev NotSwapped new_lhs fsk_ty
                                    lhs_co (mkTcNomReflCo fsk_ty)
       ; case mb_ev of {
           Stop ev s        -> return (Stop ev s) ;
           ContinueWith ev' ->

685
    do { extendFlatCache fn tys' (ctEvCoercion ev', fsk_ty, ev')
686 687
       ; continueWith (CFunEqCan { cc_ev = ev', cc_fun = fn
                                 , cc_tyargs = tys', cc_fsk = fsk }) } } }
688 689 690

---------------------
canEqTyVar :: CtEvidence -> SwapFlag
691
           -> TcTyVar
692
           -> TcType -> TcType
693
           -> TcS (StopOrContinue Ct)
694 695 696
-- A TyVar on LHS, but so far un-zonked
canEqTyVar ev swapped tv1 ty2 ps_ty2              -- ev :: tv ~ s2
  = do { traceTcS "canEqTyVar" (ppr tv1 $$ ppr ty2 $$ ppr swapped)
697
       ; mb_yes <- flattenTyVarOuter ev tv1
698
       ; case mb_yes of
699
           Right (ty1, co1)  -- co1 :: ty1 ~ tv1
700 701 702 703 704 705 706 707
                     -> do { mb <- rewriteEqEvidence ev swapped  ty1 ps_ty2
                                                     co1 (mkTcNomReflCo ps_ty2)
                           ; traceTcS "canEqTyVar2" (vcat [ppr tv1, ppr ty2, ppr swapped, ppr ty1,
                                                           ppUnless (isDerived ev) (ppr co1)])
                           ; case mb of
                               Stop ev s           -> return (Stop ev s)
                               ContinueWith new_ev -> can_eq_nc new_ev ty1 ty1 ty2 ps_ty2 }

708 709
           Left tv1' -> do { -- FM_Avoid commented out: see Note [Lazy flattening] in TcFlatten
                             -- let fmode = FE { fe_ev = ev, fe_mode = FM_Avoid tv1' True }
710 711
                                 -- Flatten the RHS less vigorously, to avoid gratuitous flattening
                                 -- True <=> xi2 should not itself be a type-function application
712
                           ; (xi2, co2) <- flatten FM_FlattenAll ev ps_ty2 -- co2 :: xi2 ~ ps_ty2
713 714 715 716 717 718 719 720 721 722
                                           -- Use ps_ty2 to preserve type synonyms if poss
                           ; dflags <- getDynFlags
                           ; canEqTyVar2 dflags ev swapped tv1' xi2 co2 } }

canEqTyVar2 :: DynFlags
            -> CtEvidence   -- olhs ~ orhs (or, if swapped, orhs ~ olhs)
            -> SwapFlag
            -> TcTyVar      -- olhs
            -> TcType       -- nrhs
            -> TcCoercion   -- nrhs ~ orhs
723
            -> TcS (StopOrContinue Ct)
Austin Seipp's avatar
Austin Seipp committed
724
-- LHS is an inert type variable,
725
-- and RHS is fully rewritten, but with type synonyms
726
-- preserved as much as possible
727 728 729 730 731

canEqTyVar2 dflags ev swapped tv1 xi2 co2
  | Just tv2 <- getTyVar_maybe xi2
  = canEqTyVarTyVar ev swapped tv1 tv2 co2

732
  | OC_OK xi2' <- occurCheckExpand dflags tv1 xi2  -- No occurs check
733
  = do { mb <- rewriteEqEvidence ev swapped xi1 xi2' co1 co2
Simon Peyton Jones's avatar
Simon Peyton Jones committed
734
                -- Ensure that the new goal has enough type synonyms
735
                -- expanded by the occurCheckExpand; hence using xi2' here
736
                -- See Note [occurCheckExpand]
737

738 739
       ; let k1 = tyVarKind tv1
             k2 = typeKind xi2'
Simon Peyton Jones's avatar
Simon Peyton Jones committed
740
       ; case mb of
741
            Stop ev s -> return (Stop ev s)
Austin Seipp's avatar
Austin Seipp committed
742
            ContinueWith new_ev
743 744 745 746 747 748 749 750
                | k2 `isSubKind` k1
                -- Establish CTyEqCan kind invariant
                -- Reorientation has done its best, but the kinds might
                -- simply be incompatible
                -> continueWith (CTyEqCan { cc_ev = new_ev
                                          , cc_tyvar  = tv1, cc_rhs = xi2' })
                | otherwise
                -> incompatibleKind new_ev xi1 k1 xi2' k2 }
751 752

  | otherwise  -- Occurs check error
753 754
  = do { mb <- rewriteEqEvidence ev swapped xi1 xi2 co1 co2
       ; case mb of
755 756 757 758 759 760
           Stop ev s           -> return (Stop ev s)
           ContinueWith new_ev -> do { emitInsoluble (mkNonCanonical new_ev)
              -- 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
                                     ; stopWith new_ev "Occurs check" } }
761 762 763 764 765
  where
    xi1 = mkTyVarTy tv1
    co1 = mkTcNomReflCo xi1


766 767

canEqTyVarTyVar :: CtEvidence           -- tv1 ~ orhs (or orhs ~ tv1, if swapped)
768
                -> SwapFlag
769 770 771
                -> TcTyVar -> TcTyVar   -- tv2, tv2
                -> TcCoercion           -- tv2 ~ orhs
                -> TcS (StopOrContinue Ct)
772
-- Both LHS and RHS rewrote to a type variable,
773 774 775 776
-- If swapped = NotSwapped, then
--     rw_orhs = tv1, rw_olhs = orhs
--     rw_nlhs = tv2, rw_nrhs = xi1
-- See Note [Canonical orientation for tyvar/tyvar equality constraints]
777 778 779 780 781
canEqTyVarTyVar ev swapped tv1 tv2 co2
  | tv1 == tv2
  = do { when (isWanted ev) $
         ASSERT( tcCoercionRole co2 == Nominal )
         setEvBind (ctev_evar ev) (EvCoercion (maybeSym swapped co2))
782 783 784 785 786 787 788 789
       ; 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
790 791
  where
    xi1 = mkTyVarTy tv1
792 793 794
    xi2 = mkTyVarTy tv2
    k1  = tyVarKind tv1
    k2  = tyVarKind tv2
795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833
    co1 = mkTcNomReflCo xi1
    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
        -- ev  : tv1 ~ orhs  (not swapped) or   orhs ~ tv1   (swapped)
        -- co1 : xi1 ~ tv1
        -- co2 : xi2 ~ tv2
      = do { mb <- rewriteEqEvidence ev swapped xi1 xi2 co1 co2
           ; let mk_ct ev' = CTyEqCan { cc_ev = ev', cc_tyvar = tv1, cc_rhs = xi2 }
           ; return (fmap mk_ct mb) }

    -- 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
      = ASSERT2( k1_sub_k2, ppr tv1 $$ ppr tv2 )
        ASSERT2( isWanted ev, ppr ev )  -- Only wanteds have flatten meta-vars
        do { tv_ty <- newFlexiTcSTy (tyVarKind tv1)
           ; new_ev <- newWantedEvVarNC (ctEvLoc ev) (mkTcEqPred tv_ty xi2)
           ; emitWorkNC [new_ev]
           ; canon_eq swapped tv1 xi1 tv_ty co1 (ctEvCoercion new_ev `mkTcTransCo` co2) }

    incompat
      = do { mb <- rewriteEqEvidence ev swapped xi1 xi2 (mkTcNomReflCo xi1) co2
           ; case mb of
               Stop ev s        -> return (Stop ev s)
               ContinueWith ev' -> incompatibleKind ev' xi1 k1 xi2 k2 }

    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]
834 835
      | Just lvl1 <- metaTyVarTcLevel_maybe tv1
      = case metaTyVarTcLevel_maybe tv2 of
836 837 838 839 840 841 842
          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
843
      -- This is not because it'll be solved; but because
844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862
      -- 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)))

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
863
-- LHS and RHS have incompatible kinds, so emit an "irreducible" constraint
864 865
--       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
866
-- When the latter is solved, it'll kick out the irreducible equality for
867
-- a second attempt at solving
868 869
--
-- See Note [Equalities with incompatible kinds]
870

871
incompatibleKind new_ev s1 k1 s2 k2   -- See Note [Equalities with incompatible kinds]
872
  = ASSERT( isKind k1 && isKind k2 )
873 874 875
    do { traceTcS "canEqLeaf: incompatible kinds" (vcat [ppr k1, ppr k2])

         -- Create a derived kind-equality, and solve it
876
       ; emitNewDerived kind_co_loc (mkTcEqPred k1 k2)
877 878 879

         -- Put the not-currently-soluble thing into the inert set
       ; continueWith (CIrredEvCan { cc_ev = new_ev }) }
880
  where
881
    loc = ctEvLoc new_ev
882
    kind_co_loc = setCtLocOrigin loc (KindEqOrigin s1 s2 (ctLocOrigin loc))
883

Austin Seipp's avatar
Austin Seipp committed
884
{-
885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930
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

931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948
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.

949 950 951
Note [Equalities with incompatible kinds]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
canEqLeaf is about to make a CTyEqCan or CFunEqCan; but both have the
952 953 954 955
invariant that LHS and RHS satisfy the kind invariants for CTyEqCan,
CFunEqCan.  What if we try to unify two things with incompatible
kinds?

956 957 958 959 960 961 962 963
eg    a ~ b  where a::*, b::*->*
or    a ~ b  where a::*, b::k, k is a kind variable

The CTyEqCan compatKind invariant is important.  If we make a CTyEqCan
for a~b, then we might well *substitute* 'b' for 'a', and that might make
a well-kinded type ill-kinded; and that is bad (eg typeKind can crash, see
Trac #7696).

Simon Peyton Jones's avatar
Simon Peyton Jones committed
964
So instead for these ill-kinded equalities we generate a CIrredCan,
965 966
and put it in the inert set, which keeps it out of the way until a
subsequent substitution (on kind variables, say) re-activates it.
967

968 969 970 971 972 973
NB: it is important that the types s1,s2 are flattened and zonked
    so that their kinds k1, k2 are inert wrt the substitution.  That
    means that they can only become the same if we change the inert
    set, which in turn will kick out the irreducible equality
    E.g. it is WRONG to make an irred (a:k1)~(b:k2)
         if we already have a substitution k1:=k2
974

975 976
NB: it's important that the new CIrredCan goes in the inert set rather
than back into the work list. We used to do the latter, but that led
Gabor Greif's avatar
Gabor Greif committed
977
to an infinite loop when we encountered it again, and put it back in
978 979
the work list again.

980 981 982
See also Note [Kind orientation for CTyEqCan] and
         Note [Kind orientation for CFunEqCan] in TcRnTypes

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 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
Note [Type synonyms and canonicalization]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We treat type synonym applications as xi types, that is, they do not
count as type function applications.  However, we do need to be a bit
careful with type synonyms: like type functions they may not be
generative or injective.  However, unlike type functions, they are
parametric, so there is no problem in expanding them whenever we see
them, since we do not need to know anything about their arguments in
order to expand them; this is what justifies not having to treat them
as specially as type function applications.  The thing that causes
some subtleties is that we prefer to leave type synonym applications
*unexpanded* whenever possible, in order to generate better error
messages.

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

  type F a = [Int]

and we encounter the equality

  F a ~ [b]

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

  [Int] ~ [b]

which we can then decompose into the more primitive equality
constraint

  Int ~ b.

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

1025 1026 1027 1028 1029 1030

Note [occurCheckExpand]
~~~~~~~~~~~~~~~~~~~~~~~
There is a subtle point with type synonyms and the occurs check that
takes place for equality constraints of the form tv ~ xi.  As an
example, suppose we have
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 1059 1060

  type F a = Int

and we come across the equality constraint

  a ~ F a

This should not actually fail the occurs check, since expanding out
the type synonym results in the legitimate equality constraint a ~
Int.  We must actually do this expansion, because unifying a with F a
will lead the type checker into infinite loops later.  Put another
way, canonical equality constraints should never *syntactically*
contain the LHS variable in the RHS type.  However, we don't always
need to expand type synonyms when doing an occurs check; for example,
the constraint

  a ~ F b

is obviously fine no matter what F expands to. And in this case we
would rather unify a with F b (rather than F b's expansion) in order
to get better error messages later.

So, when doing an occurs check with a type synonym application on the
RHS, we use some heuristics to find an expansion of the RHS which does
not contain the variable from the LHS.  In particular, given

  a ~ F t1 ... tn

we first try expanding each of the ti to types which no longer contain
a.  If this turns out to be impossible, we next try expanding F
1061
itself, and so on.  See Note [Occurs check expansion] in TcType
Austin Seipp's avatar
Austin Seipp committed
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 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 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380

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

{-
Note [xCtEvidence]
~~~~~~~~~~~~~~~~~~
A call might look like this:

    xCtEvidence ev evidence-transformer

  ev is Given   => use ev_decomp to create new Givens for ev_preds,
                   and return them

  ev is Wanted  => create new wanteds for ev_preds,
                   use ev_comp to bind ev,
                   return fresh wanteds (ie ones not cached in inert_cans or solved)

  ev is Derived => create new deriveds for ev_preds
                      (unless cached in inert_cans or solved)

Note: The [CtEvidence] returned is a subset of the subgoal-preds passed in
      Ones that are already cached are not returned

Example
    ev : Tree a b ~ Tree c d
    xCtEvidence ev [a~c, b~d] (XEvTerm { ev_comp = \[c1 c2]. <Tree> c1 c2
                                       , ev_decomp = \c. [nth 1 c, nth 2 c] })
              (\fresh-goals.  stuff)

Note [Bind new Givens immediately]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For Givens we make new EvVars and bind them immediately. We don't worry
about caching, but we don't expect complicated calculations among Givens.
It is important to bind each given:
      class (a~b) => C a b where ....
      f :: C a b => ....
Then in f's Givens we have g:(C a b) and the superclass sc(g,0):a~b.
But that superclass selector can't (yet) appear in a coercion
(see evTermCoercion), so the easy thing is to bind it to an Id.

See Note [Coercion evidence terms] in TcEvidence.
-}

xCtEvidence :: CtEvidence            -- Original evidence
            -> XEvTerm               -- Instructions about how to manipulate evidence
            -> TcS ()

xCtEvidence (CtWanted { ctev_evar = evar, ctev_loc = loc })
            (XEvTerm { ev_preds = ptys, ev_comp = comp_fn })
  = do { new_evars <- mapM (newWantedEvVar loc) ptys
       ; setEvBind evar (comp_fn (map (ctEvTerm . fst) new_evars))
       ; emitWorkNC (freshGoals new_evars) }
         -- Note the "NC": these are fresh goals, not necessarily canonical

xCtEvidence (CtGiven { ctev_evtm = tm, ctev_loc = loc })
            (XEvTerm { ev_preds = ptys, ev_decomp = decomp_fn })
  = ASSERT( equalLength ptys (decomp_fn tm) )
    do { given_evs <- newGivenEvVars loc (ptys `zip` decomp_fn tm)
       ; emitWorkNC given_evs }

xCtEvidence (CtDerived { ctev_loc = loc })
            (XEvTerm { ev_preds = ptys })
  = mapM_ (emitNewDerived loc) ptys

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

  | Stop CtEvidence   -- The (rewritten) constraint was solved
         SDoc         -- Tells how it was solved
                      -- Any new sub-goals have been put on the work list

instance Functor StopOrContinue where
  fmap f (ContinueWith x) = ContinueWith (f x)
  fmap _ (Stop ev s)      = Stop ev s

instance Outputable a => Outputable (StopOrContinue a) where
  ppr (Stop ev s)      = ptext (sLit "Stop") <> parens s <+> ppr ev
  ppr (ContinueWith w) = ptext (sLit "ContinueWith") <+> ppr w

continueWith :: a -> TcS (StopOrContinue a)
continueWith = return . ContinueWith

stopWith :: CtEvidence -> String -> TcS (StopOrContinue a)
stopWith ev s = return (Stop ev (text s))

andWhenContinue :: TcS (StopOrContinue a)
                -> (a -> TcS (StopOrContinue b))
                -> TcS (StopOrContinue b)
andWhenContinue tcs1 tcs2
  = do { r <- tcs1
       ; case r of
           Stop ev s       -> return (Stop ev s)
           ContinueWith ct -> tcs2 ct }

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

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

        Given           Already in inert               Nothing
                        Not                            Just new_evidence

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

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


rewriteEvidence old_ev@(CtDerived { ctev_loc = loc }) new_pred _co
  = -- If derived, don't even look at the coercion.
    -- This is very important, DO NOT re-order the equations for
    -- rewriteEvidence to put the isTcReflCo test first!
    -- Why?  Because for *Derived* constraints, c, the coercion, which
    -- was produced by flattening, may contain suspended calls to
    -- (ctEvTerm c), which fails for Derived constraints.
    -- (Getting this wrong caused Trac #7384.)
    do { mb_ev <- newDerived loc new_pred
       ; case mb_ev of
           Just new_ev -> continueWith new_ev
           Nothing     -> stopWith old_ev "Cached derived" }

rewriteEvidence old_ev new_pred co
  | isTcReflCo co -- See Note [Rewriting with Refl]
  = return (ContinueWith (old_ev { ctev_pred = new_pred }))

rewriteEvidence (CtGiven { ctev_evtm = old_tm , ctev_loc = loc }) new_pred co
  = do { new_ev <- newGivenEvVar loc (new_pred, new_tm)  -- See Note [Bind new Givens immediately]
       ; return (ContinueWith new_ev) }
  where
    new_tm = mkEvCast old_tm (mkTcSubCo (mkTcSymCo co))  -- mkEvCast optimises ReflCo

rewriteEvidence ev@(CtWanted { ctev_evar = evar, ctev_loc = loc }) new_pred co
  = do { (new_ev<