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

3
module TcCanonical( canonicalize ) where
4 5 6 7 8

#include "HsVersions.h"

import TcRnTypes
import TcType
9
import Type
dreixel's avatar
dreixel committed
10
import Kind
11 12
import TcFlatten
import TcSMonad
13
import TcEvidence
14 15 16 17
import Class
import TyCon
import TypeRep
import Var
18
import Name( isSystemName )
19
import OccName( OccName )
20
import Outputable
21
import Control.Monad    ( when )
22
import DynFlags( DynFlags )
23 24
import VarSet

25
import Util
26
import BasicTypes
27

Austin Seipp's avatar
Austin Seipp committed
28 29 30 31 32 33
{-
************************************************************************
*                                                                      *
*                      The Canonicaliser                               *
*                                                                      *
************************************************************************
34

35 36
Note [Canonicalization]
~~~~~~~~~~~~~~~~~~~~~~~
37

38 39 40 41
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).
42

43
The execution plan for canonicalization is the following:
Simon Peyton Jones's avatar
Simon Peyton Jones committed
44 45

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

Simon Peyton Jones's avatar
Simon Peyton Jones committed
49 50 51 52
  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.
53

54 55
  3) If no more decomposition is possible, we deeply apply the substitution
     from the inert_eqs and continue with flattening.
56

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

Simon Peyton Jones's avatar
Simon Peyton Jones committed
63 64
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
65 66
rewrite an inert or still interact with an inert in a further phase in the
simplifier.
dimitris's avatar
dimitris committed
67

68
Note [Caching for canonicals]
Simon Peyton Jones's avatar
Simon Peyton Jones committed
69
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Simon Peyton Jones's avatar
Simon Peyton Jones committed
70 71 72 73
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:
74

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

Simon Peyton Jones's avatar
Simon Peyton Jones committed
78 79 80 81 82
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
83

84 85
   - We encounter work item (d2 : Num t)

Simon Peyton Jones's avatar
Simon Peyton Jones committed
86
   - Nothing is yet in EvBinds, so we reach the interaction with inerts
87
     and set:
Simon Peyton Jones's avatar
Simon Peyton Jones committed
88
              d2 := d1
89 90
    and we discard d2 from the worklist. The inert set remains unaffected.

Simon Peyton Jones's avatar
Simon Peyton Jones committed
91 92 93
   - 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:
94
        InertSet : { [G] c : t ~ Int }
Simon Peyton Jones's avatar
Simon Peyton Jones committed
95
        WorkList : { [W] d1 : Num t}
96

Simon Peyton Jones's avatar
Simon Peyton Jones committed
97 98
   - 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
99
             d1 := d2
100 101
     and end up in a loop!

Simon Peyton Jones's avatar
Simon Peyton Jones committed
102 103 104 105 106 107 108 109
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.
110

Simon Peyton Jones's avatar
Simon Peyton Jones committed
111 112 113 114 115 116 117
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
118
-}
119

120 121 122
-- Top-level canonicalization
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

123
canonicalize :: Ct -> TcS (StopOrContinue Ct)
124
canonicalize ct@(CNonCanonical { cc_ev = ev })
125
  = do { traceTcS "canonicalize (non-canonical)" (ppr ct)
126
       ; {-# SCC "canEvVar" #-}
127
         canEvNC ev }
128

129
canonicalize (CDictCan { cc_ev = ev
130 131
                       , cc_class  = cls
                       , cc_tyargs = xis })
132
  = {-# SCC "canClass" #-}
133 134
    canClass ev cls xis -- Do not add any superclasses
canonicalize (CTyEqCan { cc_ev = ev
135 136
                       , cc_tyvar  = tv
                       , cc_rhs    = xi })
137
  = {-# SCC "canEqLeafTyVarEq" #-}
138
    canEqTyVar ev NotSwapped tv xi xi
139

140
canonicalize (CFunEqCan { cc_ev = ev
141 142
                        , cc_fun    = fn
                        , cc_tyargs = xis1
143
                        , cc_fsk    = fsk })
Simon Peyton Jones's avatar
Simon Peyton Jones committed
144
  = {-# SCC "canEqLeafFunEq" #-}
145
    canCFunEqCan ev fn xis1 fsk
146

147 148
canonicalize (CIrredEvCan { cc_ev = ev })
  = canIrred ev
thomasw's avatar
thomasw committed
149 150
canonicalize (CHoleCan { cc_ev = ev, cc_occ = occ, cc_hole = hole })
  = canHole ev occ hole
151

152
canEvNC :: CtEvidence -> TcS (StopOrContinue Ct)
Simon Peyton Jones's avatar
Simon Peyton Jones committed
153
-- Called only for non-canonical EvVars
154
canEvNC ev
155
  = case classifyPredType (ctEvPred ev) of
156 157 158 159
      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
Simon Peyton Jones's avatar
Simon Peyton Jones committed
160

Austin Seipp's avatar
Austin Seipp committed
161 162 163 164 165 166 167
{-
************************************************************************
*                                                                      *
*                      Tuple Canonicalization
*                                                                      *
************************************************************************
-}
Simon Peyton Jones's avatar
Simon Peyton Jones committed
168

169
canTuple :: CtEvidence -> [PredType] -> TcS (StopOrContinue Ct)
170
canTuple ev tys
dimitris's avatar
dimitris committed
171 172
  = do { traceTcS "can_pred" (text "TuplePred!")
       ; let xcomp = EvTupleMk
Simon Peyton Jones's avatar
Simon Peyton Jones committed
173
             xdecomp x = zipWith (\_ i -> EvTupleSel x i) tys [0..]
174 175
       ; xCtEvidence ev (XEvTerm tys xcomp xdecomp)
       ; stopWith ev "Decomposed tuple constraint" }
Simon Peyton Jones's avatar
Simon Peyton Jones committed
176

Austin Seipp's avatar
Austin Seipp committed
177 178 179 180 181 182 183
{-
************************************************************************
*                                                                      *
*                      Class Canonicalization
*                                                                      *
************************************************************************
-}
184

Simon Peyton Jones's avatar
Simon Peyton Jones committed
185
canClass, canClassNC
186
   :: CtEvidence
187
   -> Class -> [Type] -> TcS (StopOrContinue Ct)
Simon Peyton Jones's avatar
Simon Peyton Jones committed
188
-- Precondition: EvVar is class evidence
Simon Peyton Jones's avatar
Simon Peyton Jones committed
189 190 191 192 193 194

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

195 196
canClassNC ev cls tys
  = canClass ev cls tys
Simon Peyton Jones's avatar
Simon Peyton Jones committed
197 198
    `andWhenContinue` emitSuperclasses

199
canClass ev cls tys
200 201
  = do { let fmode = FE { fe_ev = ev, fe_mode = FM_FlattenAll }
       ; (xis, cos) <- flattenMany fmode tys
Joachim Breitner's avatar
Joachim Breitner committed
202
       ; let co = mkTcTyConAppCo Nominal (classTyCon cls) cos
203
             xi = mkClassPred cls xis
204 205
             mk_ct new_ev = CDictCan { cc_ev = new_ev
                                     , cc_tyargs = xis, cc_class = cls }
206
       ; mb <- rewriteEvidence ev xi co
Simon Peyton Jones's avatar
Simon Peyton Jones committed
207
       ; traceTcS "canClass" (vcat [ ppr ev <+> ppr cls <+> ppr tys
Simon Peyton Jones's avatar
Simon Peyton Jones committed
208
                                   , ppr xi, ppr mb ])
209
       ; return (fmap mk_ct mb) }
dimitris's avatar
dimitris committed
210

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

Austin Seipp's avatar
Austin Seipp committed
222
{-
223
Note [Adding superclasses]
Simon Peyton Jones's avatar
Simon Peyton Jones committed
224
~~~~~~~~~~~~~~~~~~~~~~~~~~
225 226 227 228 229 230
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
231 232
For Givens:
       We add all their superclasses as Givens.
233

Simon Peyton Jones's avatar
Simon Peyton Jones committed
234 235
For Wanteds:
       Generally speaking we want to be able to add superclasses of
236
       wanteds for two reasons:
237

Simon Peyton Jones's avatar
Simon Peyton Jones committed
238 239 240 241 242 243 244 245 246
       (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.
247

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

Simon Peyton Jones's avatar
Simon Peyton Jones committed
252 253
       We deal with (2) completely independently in TcSimplify. See
       Note [Minimize by SuperClasses] in TcSimplify.
254 255


Simon Peyton Jones's avatar
Simon Peyton Jones committed
256 257 258 259
       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.
260

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

263

Simon Peyton Jones's avatar
Simon Peyton Jones committed
264
For Deriveds:
265
       We do nothing.
266 267 268

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
269

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

Simon Peyton Jones's avatar
Simon Peyton Jones committed
273 274 275 276 277 278 279 280 281 282 283
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
284
happen.
Austin Seipp's avatar
Austin Seipp committed
285
-}
286

287
newSCWorkFromFlavored :: CtEvidence -> Class -> [Xi] -> TcS ()
288
-- Returns superclasses, see Note [Adding superclasses]
289
newSCWorkFromFlavored flavor cls xis
Simon Peyton Jones's avatar
Simon Peyton Jones committed
290
  | isDerived flavor
291
  = return ()  -- Deriveds don't yield more superclasses because we will
Simon Peyton Jones's avatar
Simon Peyton Jones committed
292 293 294 295 296
               -- 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..]
297 298
             xev = XEvTerm { ev_preds  =  sc_theta
                           , ev_comp   = panic "Can't compose for given!"
299
                           , ev_decomp = xev_decomp }
300
       ; xCtEvidence flavor xev }
dimitris's avatar
dimitris committed
301 302

  | isEmptyVarSet (tyVarsOfTypes xis)
303
  = return () -- Wanteds with no variables yield no deriveds.
304
              -- See Note [Improvement from Ground Wanteds]
305

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

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

Austin Seipp's avatar
Austin Seipp committed
323 324 325 326 327 328 329
{-
************************************************************************
*                                                                      *
*                      Irreducibles canonicalization
*                                                                      *
************************************************************************
-}
Simon Peyton Jones's avatar
Simon Peyton Jones committed
330

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

    do { -- Re-classify, in case flattening has improved its shape
       ; case classifyPredType (ctEvPred new_ev) of
346 347
           ClassPred cls tys -> canClassNC new_ev cls tys
           TuplePred tys     -> canTuple   new_ev tys
348 349 350
           EqPred ty1 ty2    -> canEqNC new_ev ty1 ty2
           _                 -> continueWith $
                                CIrredEvCan { cc_ev = new_ev } } } }
351

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

Austin Seipp's avatar
Austin Seipp committed
365 366 367 368 369 370 371
{-
************************************************************************
*                                                                      *
*        Equalities
*                                                                      *
************************************************************************
-}
Simon Peyton Jones's avatar
Simon Peyton Jones committed
372

373
canEqNC :: CtEvidence -> Type -> Type -> TcS (StopOrContinue Ct)
374 375
canEqNC ev ty1 ty2 = can_eq_nc ev ty1 ty1 ty2 ty2

Austin Seipp's avatar
Austin Seipp committed
376 377 378 379
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
380
   -> TcS (StopOrContinue Ct)
381 382

can_eq_nc ev ty1 ps_ty1 ty2 ps_ty2
Austin Seipp's avatar
Austin Seipp committed
383
  = do { traceTcS "can_eq_nc" $
384 385 386 387 388 389 390 391
         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

392 393 394 395
-- 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
396
  | isTypeFamilyTyCon fn1 = can_eq_fam_nc ev NotSwapped fn1 tys1 ty2 ps_ty2
397
can_eq_nc' ev ty1 ps_ty1 (TyConApp fn2 tys2) _
398
  | isTypeFamilyTyCon fn2 = can_eq_fam_nc ev IsSwapped fn2 tys2 ty1 ps_ty1
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414

-- 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))
415
       ; stopWith ev "Equal LitTy" }
Simon Peyton Jones's avatar
Simon Peyton Jones committed
416

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

425
can_eq_nc' ev (TyConApp tc1 _) ps_ty1 (FunTy {}) ps_ty2
Austin Seipp's avatar
Austin Seipp committed
426
  | isDecomposableTyCon tc1
427 428 429 430 431 432 433 434 435
      -- 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) _
  = canDecomposableTyConAppOK ev funTyCon [s1,t1] [s2,t2]

can_eq_nc' ev (FunTy {}) ps_ty1 (TyConApp tc2 _) ps_ty2
Austin Seipp's avatar
Austin Seipp committed
436
  | isDecomposableTyCon tc2
437 438 439 440
  = canEqFailure ev ps_ty1 ps_ty2

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

455 456 457 458 459 460
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
461 462 463 464 465

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

466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
------------
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
  = do { let fmode = FE { fe_ev = ev, fe_mode = FM_FlattenAll }
       ; (xi_lhs, co_lhs) <- flattenFamApp fmode fn tys
       ; 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 }

482 483
-----------------------------------
-- Dealing with AppTy
484
-- See Note [Canonicalising type applications]
Simon Peyton Jones's avatar
Simon Peyton Jones committed
485

486 487 488 489 490 491 492 493 494 495 496 497 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 529 530 531 532 533 534 535 536 537 538 539 540 541 542
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
  = do { let fmode = FE { fe_ev = ev, fe_mode = FM_FlattenAll }
       ; (xi1, co1) <- flatten fmode ty1
       ; (xi2, co2) <- flatten fmode ty2
        ; 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
       = do { (ev_s,fr_s) <- newWantedEvVar loc (mkTcEqPred s1 s2)
            ; (ev_t,fr_t) <- newWantedEvVar loc (mkTcEqPred t1 t2)
            ; let co = mkTcAppCo (ctEvCoercion ev_s) (ctEvCoercion ev_t)
            ; setEvBind evar (EvCoercion co)
            ; when (isFresh fr_t) $ emitWorkNC [ev_t]
            ; case fr_s of
                Fresh  -> try_decompose_app ev_s s1 s2
                Cached -> return (Stop ev (text "Decomposed app")) }
       | 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"
543

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

canDecomposableTyConAppOK :: CtEvidence
                          -> TyCon -> [TcType] -> [TcType]
559
                          -> TcS (StopOrContinue Ct)
560 561

canDecomposableTyConAppOK ev tc1 tys1 tys2
Joachim Breitner's avatar
Joachim Breitner committed
562
  = do { let xcomp xs  = EvCoercion (mkTcTyConAppCo Nominal tc1 (map evTermCoercion xs))
Simon Peyton Jones's avatar
Simon Peyton Jones committed
563
             xdecomp x = zipWith (\_ i -> EvCoercion $ mkTcNthCo i (evTermCoercion x)) tys1 [0..]
564
             xev = XEvTerm (zipWith mkTcEqPred tys1 tys2) xcomp xdecomp
565 566
       ; xCtEvidence ev xev
       ; stopWith ev "Decomposed TyConApp" }
567

568
canEqFailure :: CtEvidence -> TcType -> TcType -> TcS (StopOrContinue Ct)
569
-- See Note [Make sure that insolubles are fully rewritten]
570
canEqFailure ev ty1 ty2
571 572 573
  = do { let fmode = FE { fe_ev = ev, fe_mode = FM_SubstOnly }
       ; (s1, co1) <- flatten fmode ty1
       ; (s2, co2) <- flatten fmode ty2
574
       ; mb_ct <- rewriteEqEvidence ev NotSwapped s1 s2 co1 co2
575
       ; case mb_ct of
576 577 578
           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) }
579

Austin Seipp's avatar
Austin Seipp committed
580
{-
581 582 583
Note [Canonicalising type applications]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Given (s1 t1) ~ ty2, how should we proceed?
Austin Seipp's avatar
Austin Seipp committed
584
The simple things is to see if ty2 is of form (s2 t2), and
585
decompose.  By this time s1 and s2 can't be saturated type
Austin Seipp's avatar
Austin Seipp committed
586 587
function applications, because those have been dealt with
by an earlier equation in can_eq_nc, so it is always sound to
588 589
decompose.

Austin Seipp's avatar
Austin Seipp committed
590
However, over-eager decomposition gives bad error messages
591 592 593 594 595 596 597
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
598
we get an error        "Can't match Array ~ Maybe",
599 600
but we'd prefer to get "Can't match Array b ~ Maybe c".

601 602
So instead can_eq_wanted_app flattens the LHS and RHS before using
try_decompose_app to decompose it.
603

604 605
Note [Make sure that insolubles are fully rewritten]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Simon Peyton Jones's avatar
Simon Peyton Jones committed
606 607
When an equality fails, we still want to rewrite the equality
all the way down, so that it accurately reflects
608 609 610
 (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
611
And if we don't do this there is a bad danger that
612 613 614
TcSimplify.applyTyVarDefaulting will find a variable
that has in fact been substituted.

615
Note [Do not decompose Given polytype equalities]
616 617
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider [G] (forall a. t1 ~ forall a. t2).  Can we decompose this?
618
No -- what would the evidence look like?  So instead we simply discard
Simon Peyton Jones's avatar
Simon Peyton Jones committed
619
this given evidence.
620 621


622 623 624 625 626 627 628 629 630 631 632 633 634
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
635
-}
Simon Peyton Jones's avatar
Simon Peyton Jones committed
636

Austin Seipp's avatar
Austin Seipp committed
637
canCFunEqCan :: CtEvidence
638
             -> TyCon -> [TcType]   -- LHS
639 640
             -> TcTyVar             -- RHS
             -> TcS (StopOrContinue Ct)
Austin Seipp's avatar
Austin Seipp committed
641 642
-- ^ Canonicalise a CFunEqCan.  We know that
--     the arg types are already flat,
643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661
-- and the RHS is a fsk, which we must *not* substitute.
-- So just substitute in the LHS
canCFunEqCan ev fn tys fsk
  = do { let fmode = FE { fe_ev = ev, fe_mode = FM_FlattenAll }
       ; (tys', cos) <- flattenMany fmode tys
                        -- 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' ->

    do { extendFlatCache fn tys' (ctEvCoercion ev', fsk)
       ; continueWith (CFunEqCan { cc_ev = ev', cc_fun = fn
                                 , cc_tyargs = tys', cc_fsk = fsk }) } } }
662 663 664

---------------------
canEqTyVar :: CtEvidence -> SwapFlag
665
           -> TcTyVar
666
           -> TcType -> TcType
667
           -> TcS (StopOrContinue Ct)
668 669 670
-- 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)
671
       ; mb_yes <- flattenTyVarOuter ev tv1
672
       ; case mb_yes of
673
           Right (ty1, co1)  -- co1 :: ty1 ~ tv1
674 675 676 677 678 679 680 681
                     -> 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 }

682 683
           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 }
684 685
                                 -- Flatten the RHS less vigorously, to avoid gratuitous flattening
                                 -- True <=> xi2 should not itself be a type-function application
686
                             let fmode = FE { fe_ev = ev, fe_mode = FM_FlattenAll }
687
                           ; (xi2, co2) <- flatten fmode ps_ty2 -- co2 :: xi2 ~ ps_ty2
688 689 690 691 692 693 694 695 696 697
                                           -- 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
698
            -> TcS (StopOrContinue Ct)
Austin Seipp's avatar
Austin Seipp committed
699
-- LHS is an inert type variable,
700
-- and RHS is fully rewritten, but with type synonyms
701
-- preserved as much as possible
702 703 704 705 706

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

707
  | OC_OK xi2' <- occurCheckExpand dflags tv1 xi2  -- No occurs check
708
  = do { mb <- rewriteEqEvidence ev swapped xi1 xi2' co1 co2
Simon Peyton Jones's avatar
Simon Peyton Jones committed
709
                -- Ensure that the new goal has enough type synonyms
710
                -- expanded by the occurCheckExpand; hence using xi2' here
711
                -- See Note [occurCheckExpand]
712

713 714
       ; let k1 = tyVarKind tv1
             k2 = typeKind xi2'
Simon Peyton Jones's avatar
Simon Peyton Jones committed
715
       ; case mb of
716
            Stop ev s -> return (Stop ev s)
Austin Seipp's avatar
Austin Seipp committed
717
            ContinueWith new_ev
718 719 720 721 722 723 724 725
                | 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 }
726 727

  | otherwise  -- Occurs check error
728 729
  = do { mb <- rewriteEqEvidence ev swapped xi1 xi2 co1 co2
       ; case mb of
730 731 732 733 734 735
           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" } }
736 737 738 739 740
  where
    xi1 = mkTyVarTy tv1
    co1 = mkTcNomReflCo xi1


741 742

canEqTyVarTyVar :: CtEvidence           -- tv1 ~ orhs (or orhs ~ tv1, if swapped)
743
                -> SwapFlag
744 745 746
                -> TcTyVar -> TcTyVar   -- tv2, tv2
                -> TcCoercion           -- tv2 ~ orhs
                -> TcS (StopOrContinue Ct)
747
-- Both LHS and RHS rewrote to a type variable,
748 749 750 751
-- 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]
752 753 754 755 756
canEqTyVarTyVar ev swapped tv1 tv2 co2
  | tv1 == tv2
  = do { when (isWanted ev) $
         ASSERT( tcCoercionRole co2 == Nominal )
         setEvBind (ctev_evar ev) (EvCoercion (maybeSym swapped co2))
757 758 759 760 761 762 763 764
       ; 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
765 766
  where
    xi1 = mkTyVarTy tv1
767 768 769
    xi2 = mkTyVarTy tv2
    k1  = tyVarKind tv1
    k2  = tyVarKind tv2
770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808
    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]
809 810
      | Just lvl1 <- metaTyVarTcLevel_maybe tv1
      = case metaTyVarTcLevel_maybe tv2 of
811 812 813 814 815 816 817
          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
818
      -- This is not because it'll be solved; but because
819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837
      -- 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
838
-- LHS and RHS have incompatible kinds, so emit an "irreducible" constraint
839 840
--       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
841
-- When the latter is solved, it'll kick out the irreducible equality for
842
-- a second attempt at solving
843 844
--
-- See Note [Equalities with incompatible kinds]
845

846
incompatibleKind new_ev s1 k1 s2 k2   -- See Note [Equalities with incompatible kinds]
847
  = ASSERT( isKind k1 && isKind k2 )
848 849 850
    do { traceTcS "canEqLeaf: incompatible kinds" (vcat [ppr k1, ppr k2])

         -- Create a derived kind-equality, and solve it
851
       ; emitNewDerived kind_co_loc (mkTcEqPred k1 k2)
852 853 854

         -- Put the not-currently-soluble thing into the inert set
       ; continueWith (CIrredEvCan { cc_ev = new_ev }) }
855
  where
856
    loc = ctEvLoc new_ev
857
    kind_co_loc = setCtLocOrigin loc (KindEqOrigin s1 s2 (ctLocOrigin loc))
858

Austin Seipp's avatar
Austin Seipp committed
859
{-
860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905
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

906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923
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.

924 925 926
Note [Equalities with incompatible kinds]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
canEqLeaf is about to make a CTyEqCan or CFunEqCan; but both have the
927 928 929 930
invariant that LHS and RHS satisfy the kind invariants for CTyEqCan,
CFunEqCan.  What if we try to unify two things with incompatible
kinds?

931 932 933 934 935 936 937 938
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
939
So instead for these ill-kinded equalities we generate a CIrredCan,
940 941
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.
942

943 944 945 946 947 948
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
949

950 951
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
952
to an infinite loop when we encountered it again, and put it back in
953 954
the work list again.

955 956 957
See also Note [Kind orientation for CTyEqCan] and
         Note [Kind orientation for CFunEqCan] in TcRnTypes

958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997
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
998
as possible.  Hence the ps_ty1, ps_ty2 argument passed to canEqTyVar.
999

1000 1001 1002 1003 1004 1005

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
1006 1007 1008 1009 1010