TcCanonical.hs 41.7 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
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
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

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.

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

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!

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

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
160

Austin Seipp's avatar
Austin Seipp committed
161 162 163 164 165 166 167
{-
************************************************************************
*                                                                      *
*                      Tuple Canonicalization
*                                                                      *
************************************************************************
-}
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" }
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
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
197 198
    `andWhenContinue` emitSuperclasses

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

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

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

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

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

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

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


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

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

262

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

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
268

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

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

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

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

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

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

Austin Seipp's avatar
Austin Seipp committed
322 323 324 325 326 327 328
{-
************************************************************************
*                                                                      *
*                      Irreducibles canonicalization
*                                                                      *
************************************************************************
-}
329

330
canIrred :: CtEvidence -> TcS (StopOrContinue Ct)
331
-- Precondition: ty not a tuple and no other evidence form
332
canIrred old_ev
Simon Peyton Jones's avatar
Simon Peyton Jones committed
333 334
  = do { let old_ty = ctEvPred old_ev
       ; traceTcS "can_pred" (text "IrredPred = " <+> ppr old_ty)
335 336
       ; (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
337
       ; mb <- rewriteEvidence old_ev xi co
338
       ; case mb of {
339 340
             Stop ev s           -> return (Stop ev s) ;
             ContinueWith new_ev ->
341 342 343

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

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

Austin Seipp's avatar
Austin Seipp committed
362 363 364 365 366 367 368
{-
************************************************************************
*                                                                      *
*        Equalities
*                                                                      *
************************************************************************
-}
369

370
canEqNC :: CtEvidence -> Type -> Type -> TcS (StopOrContinue Ct)
371 372
canEqNC ev ty1 ty2 = can_eq_nc ev ty1 ty1 ty2 ty2

Austin Seipp's avatar
Austin Seipp committed
373 374 375 376
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
377
   -> TcS (StopOrContinue Ct)
378 379

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

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

-- 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))
412
       ; stopWith ev "Equal LitTy" }
413

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

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

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

452 453 454 455 456 457
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
458 459 460 461 462

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

463 464 465 466 467 468 469 470 471
------------
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
472
  = do { (xi_lhs, co_lhs) <- flattenFamApp FM_FlattenAll ev fn tys
473 474 475 476 477
       ; 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 }

478 479
-----------------------------------
-- Dealing with AppTy
480
-- See Note [Canonicalising type applications]
481

482 483 484 485 486
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
487 488
  = do { (xi1, co1) <- flatten FM_FlattenAll ev ty1
       ; (xi2, co2) <- flatten FM_FlattenAll ev ty2
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
        ; 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"
538

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

canDecomposableTyConAppOK :: CtEvidence
                          -> TyCon -> [TcType] -> [TcType]
554
                          -> TcS (StopOrContinue Ct)
555 556

canDecomposableTyConAppOK ev tc1 tys1 tys2
Joachim Breitner's avatar
Joachim Breitner committed
557
  = do { let xcomp xs  = EvCoercion (mkTcTyConAppCo Nominal tc1 (map evTermCoercion xs))
558
             xdecomp x = zipWith (\_ i -> EvCoercion $ mkTcNthCo i (evTermCoercion x)) tys1 [0..]
559
             xev = XEvTerm (zipWith mkTcEqPred tys1 tys2) xcomp xdecomp
560 561
       ; xCtEvidence ev xev
       ; stopWith ev "Decomposed TyConApp" }
562

563
canEqFailure :: CtEvidence -> TcType -> TcType -> TcS (StopOrContinue Ct)
564
-- See Note [Make sure that insolubles are fully rewritten]
565
canEqFailure ev ty1 ty2
566 567
  = do { (s1, co1) <- flatten FM_SubstOnly ev ty1
       ; (s2, co2) <- flatten FM_SubstOnly ev ty2
568
       ; mb_ct <- rewriteEqEvidence ev NotSwapped s1 s2 co1 co2
569
       ; case mb_ct of
570 571 572
           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) }
573

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

Austin Seipp's avatar
Austin Seipp committed
584
However, over-eager decomposition gives bad error messages
585 586 587 588 589 590 591
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
592
we get an error        "Can't match Array ~ Maybe",
593 594
but we'd prefer to get "Can't match Array b ~ Maybe c".

595 596
So instead can_eq_wanted_app flattens the LHS and RHS before using
try_decompose_app to decompose it.
597

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

609
Note [Do not decompose Given polytype equalities]
610 611
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider [G] (forall a. t1 ~ forall a. t2).  Can we decompose this?
612
No -- what would the evidence look like?  So instead we simply discard
Simon Peyton Jones's avatar
Simon Peyton Jones committed
613
this given evidence.
614 615


616 617 618 619 620 621 622 623 624 625 626 627 628
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
629
-}
Simon Peyton Jones's avatar
Simon Peyton Jones committed
630

Austin Seipp's avatar
Austin Seipp committed
631
canCFunEqCan :: CtEvidence
632
             -> TyCon -> [TcType]   -- LHS
633 634
             -> TcTyVar             -- RHS
             -> TcS (StopOrContinue Ct)
Austin Seipp's avatar
Austin Seipp committed
635 636
-- ^ Canonicalise a CFunEqCan.  We know that
--     the arg types are already flat,
637 638 639
-- and the RHS is a fsk, which we must *not* substitute.
-- So just substitute in the LHS
canCFunEqCan ev fn tys fsk
640
  = do { (tys', cos) <- flattenMany FM_FlattenAll ev tys
641 642 643 644 645 646 647 648 649 650 651
                        -- 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' ->

652
    do { extendFlatCache fn tys' (ctEvCoercion ev', fsk_ty, ev')
653 654
       ; continueWith (CFunEqCan { cc_ev = ev', cc_fun = fn
                                 , cc_tyargs = tys', cc_fsk = fsk }) } } }
655 656 657

---------------------
canEqTyVar :: CtEvidence -> SwapFlag
658
           -> TcTyVar
659
           -> TcType -> TcType
660
           -> TcS (StopOrContinue Ct)
661 662 663
-- 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)
664
       ; mb_yes <- flattenTyVarOuter ev tv1
665
       ; case mb_yes of
666
           Right (ty1, co1)  -- co1 :: ty1 ~ tv1
667 668 669 670 671 672 673 674
                     -> 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 }

675 676
           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 }
677 678
                                 -- Flatten the RHS less vigorously, to avoid gratuitous flattening
                                 -- True <=> xi2 should not itself be a type-function application
679
                           ; (xi2, co2) <- flatten FM_FlattenAll ev ps_ty2 -- co2 :: xi2 ~ ps_ty2
680 681 682 683 684 685 686 687 688 689
                                           -- 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
690
            -> TcS (StopOrContinue Ct)
Austin Seipp's avatar
Austin Seipp committed
691
-- LHS is an inert type variable,
692
-- and RHS is fully rewritten, but with type synonyms
693
-- preserved as much as possible
694 695 696 697 698

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

699
  | OC_OK xi2' <- occurCheckExpand dflags tv1 xi2  -- No occurs check
700
  = do { mb <- rewriteEqEvidence ev swapped xi1 xi2' co1 co2
Simon Peyton Jones's avatar
Simon Peyton Jones committed
701
                -- Ensure that the new goal has enough type synonyms
702
                -- expanded by the occurCheckExpand; hence using xi2' here
703
                -- See Note [occurCheckExpand]
704

705 706
       ; let k1 = tyVarKind tv1
             k2 = typeKind xi2'
Simon Peyton Jones's avatar
Simon Peyton Jones committed
707
       ; case mb of
708
            Stop ev s -> return (Stop ev s)
Austin Seipp's avatar
Austin Seipp committed
709
            ContinueWith new_ev
710 711 712 713 714 715 716 717
                | 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 }
718 719

  | otherwise  -- Occurs check error
720 721
  = do { mb <- rewriteEqEvidence ev swapped xi1 xi2 co1 co2
       ; case mb of
722 723 724 725 726 727
           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" } }
728 729 730 731 732
  where
    xi1 = mkTyVarTy tv1
    co1 = mkTcNomReflCo xi1


733 734

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

838
incompatibleKind new_ev s1 k1 s2 k2   -- See Note [Equalities with incompatible kinds]
839
  = ASSERT( isKind k1 && isKind k2 )
840 841 842
    do { traceTcS "canEqLeaf: incompatible kinds" (vcat [ppr k1, ppr k2])

         -- Create a derived kind-equality, and solve it
843
       ; emitNewDerived kind_co_loc (mkTcEqPred k1 k2)
844 845 846

         -- Put the not-currently-soluble thing into the inert set
       ; continueWith (CIrredEvCan { cc_ev = new_ev }) }
847
  where
848
    loc = ctEvLoc new_ev
849
    kind_co_loc = setCtLocOrigin loc (KindEqOrigin s1 s2 (ctLocOrigin loc))
850

Austin Seipp's avatar
Austin Seipp committed
851
{-
852 853 854 855 856 857 858 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
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

898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915
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.

916 917 918
Note [Equalities with incompatible kinds]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
canEqLeaf is about to make a CTyEqCan or CFunEqCan; but both have the
919 920 921 922
invariant that LHS and RHS satisfy the kind invariants for CTyEqCan,
CFunEqCan.  What if we try to unify two things with incompatible
kinds?

923 924 925 926 927 928 929 930
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
931
So instead for these ill-kinded equalities we generate a CIrredCan,
932 933
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.
934

935 936 937 938 939 940
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
941

942 943
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
944
to an infinite loop when we encountered it again, and put it back in
945 946
the work list again.

947 948 949
See also Note [Kind orientation for CTyEqCan] and
         Note [Kind orientation for CFunEqCan] in TcRnTypes

950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989
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
990
as possible.  Hence the ps_ty1, ps_ty2 argument passed to canEqTyVar.
991

992 993 994 995 996 997

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
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 1023 1024 1025 1026 1027

  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
1028
itself, and so on.  See Note [Occurs check expansion] in TcType
Austin Seipp's avatar
Austin Seipp committed
1029
-}