Another major constraint-solver refactoring
[ghc.git] / compiler / typecheck / TcCanonical.hs
1 {-# LANGUAGE CPP #-}
2
3 module TcCanonical(
4 canonicalize,
5 unifyDerived,
6 makeSuperClasses, maybeSym,
7 StopOrContinue(..), stopWith, continueWith
8 ) where
9
10 #include "HsVersions.h"
11
12 import TcRnTypes
13 import TcUnify( swapOverTyVars, metaTyVarUpdateOK )
14 import TcType
15 import Type
16 import TcFlatten
17 import TcSMonad
18 import TcEvidence
19 import Class
20 import TyCon
21 import TyCoRep -- cleverly decomposes types, good for completeness checking
22 import Coercion
23 import FamInstEnv ( FamInstEnvs )
24 import FamInst ( tcTopNormaliseNewTypeTF_maybe )
25 import Var
26 import Outputable
27 import DynFlags( DynFlags )
28 import VarSet
29 import NameSet
30 import RdrName
31
32 import Pair
33 import Util
34 import Bag
35 import MonadUtils
36 import Control.Monad
37 import Data.List ( zip4, foldl' )
38 import BasicTypes
39
40 import Data.Bifunctor ( bimap )
41
42 {-
43 ************************************************************************
44 * *
45 * The Canonicaliser *
46 * *
47 ************************************************************************
48
49 Note [Canonicalization]
50 ~~~~~~~~~~~~~~~~~~~~~~~
51
52 Canonicalization converts a simple constraint to a canonical form. It is
53 unary (i.e. treats individual constraints one at a time), does not do
54 any zonking, but lives in TcS monad because it needs to create fresh
55 variables (for flattening) and consult the inerts (for efficiency).
56
57 The execution plan for canonicalization is the following:
58
59 1) Decomposition of equalities happens as necessary until we reach a
60 variable or type family in one side. There is no decomposition step
61 for other forms of constraints.
62
63 2) If, when we decompose, we discover a variable on the head then we
64 look at inert_eqs from the current inert for a substitution for this
65 variable and contine decomposing. Hence we lazily apply the inert
66 substitution if it is needed.
67
68 3) If no more decomposition is possible, we deeply apply the substitution
69 from the inert_eqs and continue with flattening.
70
71 4) During flattening, we examine whether we have already flattened some
72 function application by looking at all the CTyFunEqs with the same
73 function in the inert set. The reason for deeply applying the inert
74 substitution at step (3) is to maximise our chances of matching an
75 already flattened family application in the inert.
76
77 The net result is that a constraint coming out of the canonicalization
78 phase cannot be rewritten any further from the inerts (but maybe /it/ can
79 rewrite an inert or still interact with an inert in a further phase in the
80 simplifier.
81
82 Note [Caching for canonicals]
83 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
84 Our plan with pre-canonicalization is to be able to solve a constraint
85 really fast from existing bindings in TcEvBinds. So one may think that
86 the condition (isCNonCanonical) is not necessary. However consider
87 the following setup:
88
89 InertSet = { [W] d1 : Num t }
90 WorkList = { [W] d2 : Num t, [W] c : t ~ Int}
91
92 Now, we prioritize equalities, but in our concrete example
93 (should_run/mc17.hs) the first (d2) constraint is dealt with first,
94 because (t ~ Int) is an equality that only later appears in the
95 worklist since it is pulled out from a nested implication
96 constraint. So, let's examine what happens:
97
98 - We encounter work item (d2 : Num t)
99
100 - Nothing is yet in EvBinds, so we reach the interaction with inerts
101 and set:
102 d2 := d1
103 and we discard d2 from the worklist. The inert set remains unaffected.
104
105 - Now the equation ([W] c : t ~ Int) is encountered and kicks-out
106 (d1 : Num t) from the inerts. Then that equation gets
107 spontaneously solved, perhaps. We end up with:
108 InertSet : { [G] c : t ~ Int }
109 WorkList : { [W] d1 : Num t}
110
111 - Now we examine (d1), we observe that there is a binding for (Num
112 t) in the evidence binds and we set:
113 d1 := d2
114 and end up in a loop!
115
116 Now, the constraints that get kicked out from the inert set are always
117 Canonical, so by restricting the use of the pre-canonicalizer to
118 NonCanonical constraints we eliminate this danger. Moreover, for
119 canonical constraints we already have good caching mechanisms
120 (effectively the interaction solver) and we are interested in reducing
121 things like superclasses of the same non-canonical constraint being
122 generated hence I don't expect us to lose a lot by introducing the
123 (isCNonCanonical) restriction.
124
125 A similar situation can arise in TcSimplify, at the end of the
126 solve_wanteds function, where constraints from the inert set are
127 returned as new work -- our substCt ensures however that if they are
128 not rewritten by subst, they remain canonical and hence we will not
129 attempt to solve them from the EvBinds. If on the other hand they did
130 get rewritten and are now non-canonical they will still not match the
131 EvBinds, so we are again good.
132 -}
133
134 -- Top-level canonicalization
135 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
136
137 canonicalize :: Ct -> TcS (StopOrContinue Ct)
138 canonicalize ct@(CNonCanonical { cc_ev = ev })
139 = do { traceTcS "canonicalize (non-canonical)" (ppr ct)
140 ; {-# SCC "canEvVar" #-}
141 canEvNC ev }
142
143 canonicalize (CDictCan { cc_ev = ev, cc_class = cls
144 , cc_tyargs = xis, cc_pend_sc = pend_sc })
145 = {-# SCC "canClass" #-}
146 canClass ev cls xis pend_sc
147
148 canonicalize (CTyEqCan { cc_ev = ev
149 , cc_tyvar = tv
150 , cc_rhs = xi
151 , cc_eq_rel = eq_rel })
152 = {-# SCC "canEqLeafTyVarEq" #-}
153 canEqNC ev eq_rel (mkTyVarTy tv) xi
154 -- NB: Don't use canEqTyVar because that expects flattened types,
155 -- and tv and xi may not be flat w.r.t. an updated inert set
156
157 canonicalize (CFunEqCan { cc_ev = ev
158 , cc_fun = fn
159 , cc_tyargs = xis1
160 , cc_fsk = fsk })
161 = {-# SCC "canEqLeafFunEq" #-}
162 canCFunEqCan ev fn xis1 fsk
163
164 canonicalize (CIrredEvCan { cc_ev = ev })
165 = canIrred ev
166 canonicalize (CHoleCan { cc_ev = ev, cc_hole = hole })
167 = canHole ev hole
168
169 canEvNC :: CtEvidence -> TcS (StopOrContinue Ct)
170 -- Called only for non-canonical EvVars
171 canEvNC ev
172 = case classifyPredType (ctEvPred ev) of
173 ClassPred cls tys -> do traceTcS "canEvNC:cls" (ppr cls <+> ppr tys)
174 canClassNC ev cls tys
175 EqPred eq_rel ty1 ty2 -> do traceTcS "canEvNC:eq" (ppr ty1 $$ ppr ty2)
176 canEqNC ev eq_rel ty1 ty2
177 IrredPred {} -> do traceTcS "canEvNC:irred" (ppr (ctEvPred ev))
178 canIrred ev
179 {-
180 ************************************************************************
181 * *
182 * Class Canonicalization
183 * *
184 ************************************************************************
185 -}
186
187 canClassNC :: CtEvidence -> Class -> [Type] -> TcS (StopOrContinue Ct)
188 -- "NC" means "non-canonical"; that is, we have got here
189 -- from a NonCanonical constrataint, not from a CDictCan
190 -- Precondition: EvVar is class evidence
191 canClassNC ev cls tys
192 | isGiven ev -- See Note [Eagerly expand given superclasses]
193 = do { sc_cts <- mkStrictSuperClasses ev cls tys
194 ; emitWork sc_cts
195 ; canClass ev cls tys False }
196 | otherwise
197 = canClass ev cls tys (has_scs cls)
198 where
199 has_scs cls = not (null (classSCTheta cls))
200
201 canClass :: CtEvidence
202 -> Class -> [Type]
203 -> Bool -- True <=> un-explored superclasses
204 -> TcS (StopOrContinue Ct)
205 -- Precondition: EvVar is class evidence
206
207 canClass ev cls tys pend_sc
208 = -- all classes do *nominal* matching
209 ASSERT2( ctEvRole ev == Nominal, ppr ev $$ ppr cls $$ ppr tys )
210 do { (xis, cos) <- flattenManyNom ev tys
211 ; let co = mkTcTyConAppCo Nominal (classTyCon cls) cos
212 xi = mkClassPred cls xis
213 mk_ct new_ev = CDictCan { cc_ev = new_ev
214 , cc_tyargs = xis
215 , cc_class = cls
216 , cc_pend_sc = pend_sc }
217 ; mb <- rewriteEvidence ev xi co
218 ; traceTcS "canClass" (vcat [ ppr ev
219 , ppr xi, ppr mb ])
220 ; return (fmap mk_ct mb) }
221
222 {- Note [The superclass story]
223 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
224 We need to add superclass constraints for two reasons:
225
226 * For givens, they give us a route to to proof. E.g.
227 f :: Ord a => a -> Bool
228 f x = x == x
229 We get a Wanted (Eq a), which can only be solved from the superclass
230 of the Given (Ord a).
231
232 * For wanteds, they may give useful functional dependencies. E.g.
233 class C a b | a -> b where ...
234 class C a b => D a b where ...
235 Now a Wanted constraint (D Int beta) has (C Int beta) as a superclass
236 and that might tell us about beta, via C's fundeps. We can get this
237 by generateing a Derived (C Int beta) constraint. It's derived because
238 we don't actually have to cough up any evidence for it; it's only there
239 to generate fundep equalities.
240
241 See Note [Why adding superclasses can help].
242
243 For these reasons we want to generate superclass constraints for both
244 Givens and Wanteds. But:
245
246 * (Minor) they are often not needed, so generating them aggressively
247 is a waste of time.
248
249 * (Major) if we want recursive superclasses, there would be an infinite
250 number of them. Here is a real-life example (Trac #10318);
251
252 class (Frac (Frac a) ~ Frac a,
253 Fractional (Frac a),
254 IntegralDomain (Frac a))
255 => IntegralDomain a where
256 type Frac a :: *
257
258 Notice that IntegralDomain has an associated type Frac, and one
259 of IntegralDomain's superclasses is another IntegralDomain constraint.
260
261 So here's the plan:
262
263 1. Eagerly generate superclasses for given (but not wanted)
264 constraints; see Note [Eagerly expand given superclasses].
265 This is done in canClassNC, when we take a non-canonical constraint
266 and cannonicalise it.
267
268 However stop if you encounter the same class twice. That is,
269 expand eagerly, but have a conservative termination condition: see
270 Note [Expanding superclasses] in TcType.
271
272 2. Solve the wanteds as usual, but do no further expansion of
273 superclasses for canonical CDictCans in solveSimpleGivens or
274 solveSimpleWanteds; Note [Danger of adding superclasses during solving]
275
276 However, /do/ continue to eagerly expand superlasses for /given/
277 non-canonical constraints (canClassNC does this). As Trac #12175
278 showed, a type-family application can expand to a class constraint,
279 and we want to see its superclasses for just the same reason as
280 Note [Eagerly expand given superclasses].
281
282 3. If we have any remaining unsolved wanteds
283 (see Note [When superclasses help] in TcRnTypes)
284 try harder: take both the Givens and Wanteds, and expand
285 superclasses again. This may succeed in generating (a finite
286 number of) extra Givens, and extra Deriveds. Both may help the
287 proof. This is done in TcSimplify.expandSuperClasses.
288
289 4. Go round to (2) again. This loop (2,3,4) is implemented
290 in TcSimplify.simpl_loop.
291
292 We try to terminate the loop by flagging which class constraints
293 (given or wanted) are potentially un-expanded. This is what the
294 cc_pend_sc flag is for in CDictCan. So in Step 3 we only expand
295 superclasses for constraints with cc_pend_sc set to true (i.e.
296 isPendingScDict holds).
297
298 When we take a CNonCanonical or CIrredCan, but end up classifying it
299 as a CDictCan, we set the cc_pend_sc flag to False.
300
301 Note [Eagerly expand given superclasses]
302 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
303 In step (1) of Note [The superclass story], why do we eagerly expand
304 Given superclasses by one layer? Mainly because of some very obscure
305 cases like this:
306
307 instance Bad a => Eq (T a)
308
309 f :: (Ord (T a)) => blah
310 f x = ....needs Eq (T a), Ord (T a)....
311
312 Here if we can't satisfy (Eq (T a)) from the givens we'll use the
313 instance declaration; but then we are stuck with (Bad a). Sigh.
314 This is really a case of non-confluent proofs, but to stop our users
315 complaining we expand one layer in advance.
316
317 Note [Instance and Given overlap] in TcInteract.
318
319 We also want to do this if we have
320
321 f :: F (T a) => blah
322
323 where
324 type instance F (T a) = Ord (T a)
325
326 So we may need to do a little work on the givens to expose the
327 class that has the superclasses. That's why the superclass
328 expansion for Givens happens in canClassNC.
329
330 Note [Why adding superclasses can help]
331 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
332 Examples of how adding superclasses can help:
333
334 --- Example 1
335 class C a b | a -> b
336 Suppose we want to solve
337 [G] C a b
338 [W] C a beta
339 Then adding [D] beta~b will let us solve it.
340
341 -- Example 2 (similar but using a type-equality superclass)
342 class (F a ~ b) => C a b
343 And try to sllve:
344 [G] C a b
345 [W] C a beta
346 Follow the superclass rules to add
347 [G] F a ~ b
348 [D] F a ~ beta
349 Now we we get [D] beta ~ b, and can solve that.
350
351 -- Example (tcfail138)
352 class L a b | a -> b
353 class (G a, L a b) => C a b
354
355 instance C a b' => G (Maybe a)
356 instance C a b => C (Maybe a) a
357 instance L (Maybe a) a
358
359 When solving the superclasses of the (C (Maybe a) a) instance, we get
360 [G] C a b, and hance by superclasses, [G] G a, [G] L a b
361 [W] G (Maybe a)
362 Use the instance decl to get
363 [W] C a beta
364 Generate its derived superclass
365 [D] L a beta. Now using fundeps, combine with [G] L a b to get
366 [D] beta ~ b
367 which is what we want.
368
369 Note [Danger of adding superclasses during solving]
370 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
371 Here's a serious, but now out-dated example, from Trac #4497:
372
373 class Num (RealOf t) => Normed t
374 type family RealOf x
375
376 Assume the generated wanted constraint is:
377 [W] RealOf e ~ e
378 [W] Normed e
379
380 If we were to be adding the superclasses during simplification we'd get:
381 [W] RealOf e ~ e
382 [W] Normed e
383 [D] RealOf e ~ fuv
384 [D] Num fuv
385 ==>
386 e := fuv, Num fuv, Normed fuv, RealOf fuv ~ fuv
387
388 While looks exactly like our original constraint. If we add the
389 superclass of (Normed fuv) again we'd loop. By adding superclasses
390 definitely only once, during canonicalisation, this situation can't
391 happen.
392
393 Mind you, now that Wanteds cannot rewrite Derived, I think this particular
394 situation can't happen.
395 -}
396
397 makeSuperClasses :: [Ct] -> TcS [Ct]
398 -- Returns strict superclasses, transitively, see Note [The superclasses story]
399 -- See Note [The superclass story]
400 -- The loop-breaking here follows Note [Expanding superclasses] in TcType
401 -- Specifically, for an incoming (C t) constraint, we return all of (C t)'s
402 -- superclasses, up to /and including/ the first repetition of C
403 --
404 -- Example: class D a => C a
405 -- class C [a] => D a
406 -- makeSuperClasses (C x) will return (D x, C [x])
407 --
408 -- NB: the incoming constraints have had their cc_pend_sc flag already
409 -- flipped to False, by isPendingScDict, so we are /obliged/ to at
410 -- least produce the immediate superclasses
411 makeSuperClasses cts = concatMapM go cts
412 where
413 go (CDictCan { cc_ev = ev, cc_class = cls, cc_tyargs = tys })
414 = mkStrictSuperClasses ev cls tys
415 go ct = pprPanic "makeSuperClasses" (ppr ct)
416
417 mkStrictSuperClasses :: CtEvidence -> Class -> [Type] -> TcS [Ct]
418 -- Return constraints for the strict superclasses of (c tys)
419 mkStrictSuperClasses ev cls tys
420 = mk_strict_superclasses (unitNameSet (className cls)) ev cls tys
421
422 mk_superclasses :: NameSet -> CtEvidence -> TcS [Ct]
423 -- Return this constraint, plus its superclasses, if any
424 mk_superclasses rec_clss ev
425 | ClassPred cls tys <- classifyPredType (ctEvPred ev)
426 = mk_superclasses_of rec_clss ev cls tys
427
428 | otherwise -- Superclass is not a class predicate
429 = return [mkNonCanonical ev]
430
431 mk_superclasses_of :: NameSet -> CtEvidence -> Class -> [Type] -> TcS [Ct]
432 -- Always return this class constraint,
433 -- and expand its superclasses
434 mk_superclasses_of rec_clss ev cls tys
435 | loop_found = do { traceTcS "mk_superclasses_of: loop" (ppr cls <+> ppr tys)
436 ; return [this_ct] } -- cc_pend_sc of this_ct = True
437 | otherwise = do { traceTcS "mk_superclasses_of" (vcat [ ppr cls <+> ppr tys
438 , ppr (isCTupleClass cls)
439 , ppr rec_clss
440 ])
441 ; sc_cts <- mk_strict_superclasses rec_clss' ev cls tys
442 ; return (this_ct : sc_cts) }
443 -- cc_pend_sc of this_ct = False
444 where
445 cls_nm = className cls
446 loop_found = not (isCTupleClass cls) && cls_nm `elemNameSet` rec_clss
447 -- Tuples neveer contribute to recursion, and can be nested
448 rec_clss' = rec_clss `extendNameSet` cls_nm
449 this_ct = CDictCan { cc_ev = ev, cc_class = cls, cc_tyargs = tys
450 , cc_pend_sc = loop_found }
451 -- NB: If there is a loop, we cut off, so we have not
452 -- added the superclasses, hence cc_pend_sc = True
453
454 mk_strict_superclasses :: NameSet -> CtEvidence -> Class -> [Type] -> TcS [Ct]
455 -- Always return the immediate superclasses of (cls tys);
456 -- and expand their superclasses, provided none of them are in rec_clss
457 -- nor are repeated
458 mk_strict_superclasses rec_clss ev cls tys
459 | CtGiven { ctev_evar = evar, ctev_loc = loc } <- ev
460 = do { sc_evs <- newGivenEvVars (mk_given_loc loc)
461 (mkEvScSelectors (EvId evar) cls tys)
462 ; concatMapM (mk_superclasses rec_clss) sc_evs }
463
464 | isEmptyVarSet (tyCoVarsOfTypes tys)
465 = return [] -- Wanteds with no variables yield no deriveds.
466 -- See Note [Improvement from Ground Wanteds]
467
468 | otherwise -- Wanted/Derived case, just add Derived superclasses
469 -- that can lead to improvement.
470 = do { let loc = ctEvLoc ev
471 ; sc_evs <- mapM (newDerivedNC loc) (immSuperClasses cls tys)
472 ; concatMapM (mk_superclasses rec_clss) sc_evs }
473 where
474 size = sizeTypes tys
475 mk_given_loc loc
476 | isCTupleClass cls
477 = loc -- For tuple predicates, just take them apart, without
478 -- adding their (large) size into the chain. When we
479 -- get down to a base predicate, we'll include its size.
480 -- Trac #10335
481
482 | GivenOrigin skol_info <- ctLocOrigin loc
483 -- See Note [Solving superclass constraints] in TcInstDcls
484 -- for explantation of this transformation for givens
485 = case skol_info of
486 InstSkol -> loc { ctl_origin = GivenOrigin (InstSC size) }
487 InstSC n -> loc { ctl_origin = GivenOrigin (InstSC (n `max` size)) }
488 _ -> loc
489
490 | otherwise -- Probably doesn't happen, since this function
491 = loc -- is only used for Givens, but does no harm
492
493
494 {-
495 ************************************************************************
496 * *
497 * Irreducibles canonicalization
498 * *
499 ************************************************************************
500 -}
501
502 canIrred :: CtEvidence -> TcS (StopOrContinue Ct)
503 -- Precondition: ty not a tuple and no other evidence form
504 canIrred old_ev
505 = do { let old_ty = ctEvPred old_ev
506 ; traceTcS "can_pred" (text "IrredPred = " <+> ppr old_ty)
507 ; (xi,co) <- flatten FM_FlattenAll old_ev old_ty -- co :: xi ~ old_ty
508 ; rewriteEvidence old_ev xi co `andWhenContinue` \ new_ev ->
509 do { -- Re-classify, in case flattening has improved its shape
510 ; case classifyPredType (ctEvPred new_ev) of
511 ClassPred cls tys -> canClassNC new_ev cls tys
512 EqPred eq_rel ty1 ty2 -> canEqNC new_ev eq_rel ty1 ty2
513 _ -> continueWith $
514 CIrredEvCan { cc_ev = new_ev } } }
515
516 canHole :: CtEvidence -> Hole -> TcS (StopOrContinue Ct)
517 canHole ev hole
518 = do { let ty = ctEvPred ev
519 ; (xi,co) <- flatten FM_SubstOnly ev ty -- co :: xi ~ ty
520 ; rewriteEvidence ev xi co `andWhenContinue` \ new_ev ->
521 do { emitInsoluble (CHoleCan { cc_ev = new_ev
522 , cc_hole = hole })
523 ; stopWith new_ev "Emit insoluble hole" } }
524
525 {-
526 ************************************************************************
527 * *
528 * Equalities
529 * *
530 ************************************************************************
531
532 Note [Canonicalising equalities]
533 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
534 In order to canonicalise an equality, we look at the structure of the
535 two types at hand, looking for similarities. A difficulty is that the
536 types may look dissimilar before flattening but similar after flattening.
537 However, we don't just want to jump in and flatten right away, because
538 this might be wasted effort. So, after looking for similarities and failing,
539 we flatten and then try again. Of course, we don't want to loop, so we
540 track whether or not we've already flattened.
541
542 It is conceivable to do a better job at tracking whether or not a type
543 is flattened, but this is left as future work. (Mar '15)
544 -}
545
546 canEqNC :: CtEvidence -> EqRel -> Type -> Type -> TcS (StopOrContinue Ct)
547 canEqNC ev eq_rel ty1 ty2
548 = do { result <- zonk_eq_types ty1 ty2
549 ; case result of
550 Left (Pair ty1' ty2') -> can_eq_nc False ev eq_rel ty1' ty1 ty2' ty2
551 Right ty -> canEqReflexive ev eq_rel ty }
552
553 can_eq_nc
554 :: Bool -- True => both types are flat
555 -> CtEvidence
556 -> EqRel
557 -> Type -> Type -- LHS, after and before type-synonym expansion, resp
558 -> Type -> Type -- RHS, after and before type-synonym expansion, resp
559 -> TcS (StopOrContinue Ct)
560 can_eq_nc flat ev eq_rel ty1 ps_ty1 ty2 ps_ty2
561 = do { traceTcS "can_eq_nc" $
562 vcat [ ppr flat, ppr ev, ppr eq_rel, ppr ty1, ppr ps_ty1, ppr ty2, ppr ps_ty2 ]
563 ; rdr_env <- getGlobalRdrEnvTcS
564 ; fam_insts <- getFamInstEnvs
565 ; can_eq_nc' flat rdr_env fam_insts ev eq_rel ty1 ps_ty1 ty2 ps_ty2 }
566
567 can_eq_nc'
568 :: Bool -- True => both input types are flattened
569 -> GlobalRdrEnv -- needed to see which newtypes are in scope
570 -> FamInstEnvs -- needed to unwrap data instances
571 -> CtEvidence
572 -> EqRel
573 -> Type -> Type -- LHS, after and before type-synonym expansion, resp
574 -> Type -> Type -- RHS, after and before type-synonym expansion, resp
575 -> TcS (StopOrContinue Ct)
576
577 -- Expand synonyms first; see Note [Type synonyms and canonicalization]
578 can_eq_nc' flat _rdr_env _envs ev eq_rel ty1 ps_ty1 ty2 ps_ty2
579 | Just ty1' <- coreView ty1 = can_eq_nc flat ev eq_rel ty1' ps_ty1 ty2 ps_ty2
580 | Just ty2' <- coreView ty2 = can_eq_nc flat ev eq_rel ty1 ps_ty1 ty2' ps_ty2
581
582 -- need to check for reflexivity in the ReprEq case.
583 -- See Note [Eager reflexivity check]
584 -- Check only when flat because the zonk_eq_types check in canEqNC takes
585 -- care of the non-flat case.
586 can_eq_nc' True _rdr_env _envs ev ReprEq ty1 _ ty2 _
587 | ty1 `tcEqType` ty2
588 = canEqReflexive ev ReprEq ty1
589
590 -- When working with ReprEq, unwrap newtypes.
591 can_eq_nc' _flat rdr_env envs ev ReprEq ty1 _ ty2 ps_ty2
592 | Just stuff1 <- tcTopNormaliseNewTypeTF_maybe envs rdr_env ty1
593 = can_eq_newtype_nc ev NotSwapped ty1 stuff1 ty2 ps_ty2
594 can_eq_nc' _flat rdr_env envs ev ReprEq ty1 ps_ty1 ty2 _
595 | Just stuff2 <- tcTopNormaliseNewTypeTF_maybe envs rdr_env ty2
596 = can_eq_newtype_nc ev IsSwapped ty2 stuff2 ty1 ps_ty1
597
598 -- Then, get rid of casts
599 can_eq_nc' flat _rdr_env _envs ev eq_rel (CastTy ty1 co1) _ ty2 ps_ty2
600 = canEqCast flat ev eq_rel NotSwapped ty1 co1 ty2 ps_ty2
601 can_eq_nc' flat _rdr_env _envs ev eq_rel ty1 ps_ty1 (CastTy ty2 co2) _
602 = canEqCast flat ev eq_rel IsSwapped ty2 co2 ty1 ps_ty1
603
604 ----------------------
605 -- Otherwise try to decompose
606 ----------------------
607
608 -- Literals
609 can_eq_nc' _flat _rdr_env _envs ev eq_rel ty1@(LitTy l1) _ (LitTy l2) _
610 | l1 == l2
611 = do { setEqIfWanted ev (mkReflCo (eqRelRole eq_rel) ty1)
612 ; stopWith ev "Equal LitTy" }
613
614 -- Try to decompose type constructor applications
615 -- Including FunTy (s -> t)
616 can_eq_nc' _flat _rdr_env _envs ev eq_rel ty1 _ ty2 _
617 | Just (tc1, tys1) <- tcRepSplitTyConApp_maybe ty1
618 , Just (tc2, tys2) <- tcRepSplitTyConApp_maybe ty2
619 , not (isTypeFamilyTyCon tc1)
620 , not (isTypeFamilyTyCon tc2)
621 = canTyConApp ev eq_rel tc1 tys1 tc2 tys2
622
623 can_eq_nc' _flat _rdr_env _envs ev eq_rel
624 s1@(ForAllTy {}) _ s2@(ForAllTy {}) _
625 | CtWanted { ctev_loc = loc, ctev_dest = orig_dest } <- ev
626 = do { let (bndrs1,body1) = tcSplitForAllTyVarBndrs s1
627 (bndrs2,body2) = tcSplitForAllTyVarBndrs s2
628 ; if not (equalLength bndrs1 bndrs2)
629 then do { traceTcS "Forall failure" $
630 vcat [ ppr s1, ppr s2, ppr bndrs1, ppr bndrs2
631 , ppr (map binderArgFlag bndrs1)
632 , ppr (map binderArgFlag bndrs2) ]
633 ; canEqHardFailure ev s1 s2 }
634 else
635 do { traceTcS "Creating implication for polytype equality" $ ppr ev
636 ; kind_cos <- zipWithM (unifyWanted loc Nominal)
637 (map binderKind bndrs1) (map binderKind bndrs2)
638 ; all_co <- deferTcSForAllEq (eqRelRole eq_rel) loc
639 kind_cos (bndrs1,body1) (bndrs2,body2)
640 ; setWantedEq orig_dest all_co
641 ; stopWith ev "Deferred polytype equality" } }
642 | otherwise
643 = do { traceTcS "Omitting decomposition of given polytype equality" $
644 pprEq s1 s2 -- See Note [Do not decompose given polytype equalities]
645 ; stopWith ev "Discard given polytype equality" }
646
647 -- See Note [Canonicalising type applications] about why we require flat types
648 can_eq_nc' True _rdr_env _envs ev eq_rel (AppTy t1 s1) _ ty2 _
649 | Just (t2, s2) <- tcSplitAppTy_maybe ty2
650 = can_eq_app ev eq_rel t1 s1 t2 s2
651 can_eq_nc' True _rdr_env _envs ev eq_rel ty1 _ (AppTy t2 s2) _
652 | Just (t1, s1) <- tcSplitAppTy_maybe ty1
653 = can_eq_app ev eq_rel t1 s1 t2 s2
654
655 -- No similarity in type structure detected. Flatten and try again.
656 can_eq_nc' False rdr_env envs ev eq_rel _ ps_ty1 _ ps_ty2
657 = do { (xi1, co1) <- flatten FM_FlattenAll ev ps_ty1
658 ; (xi2, co2) <- flatten FM_FlattenAll ev ps_ty2
659 ; rewriteEqEvidence ev NotSwapped xi1 xi2 co1 co2
660 `andWhenContinue` \ new_ev ->
661 can_eq_nc' True rdr_env envs new_ev eq_rel xi1 xi1 xi2 xi2 }
662
663 -- Type variable on LHS or RHS are last.
664 -- NB: pattern match on True: we want only flat types sent to canEqTyVar.
665 -- See also Note [No top-level newtypes on RHS of representational equalities]
666 can_eq_nc' True _rdr_env _envs ev eq_rel (TyVarTy tv1) ps_ty1 ty2 ps_ty2
667 = canEqTyVar ev eq_rel NotSwapped tv1 ps_ty1 ty2 ps_ty2
668 can_eq_nc' True _rdr_env _envs ev eq_rel ty1 ps_ty1 (TyVarTy tv2) ps_ty2
669 = canEqTyVar ev eq_rel IsSwapped tv2 ps_ty2 ty1 ps_ty1
670
671 -- We've flattened and the types don't match. Give up.
672 can_eq_nc' True _rdr_env _envs ev _eq_rel _ ps_ty1 _ ps_ty2
673 = do { traceTcS "can_eq_nc' catch-all case" (ppr ps_ty1 $$ ppr ps_ty2)
674 ; canEqHardFailure ev ps_ty1 ps_ty2 }
675
676 ---------------------------------
677 -- | Compare types for equality, while zonking as necessary. Gives up
678 -- as soon as it finds that two types are not equal.
679 -- This is quite handy when some unification has made two
680 -- types in an inert wanted to be equal. We can discover the equality without
681 -- flattening, which is sometimes very expensive (in the case of type functions).
682 -- In particular, this function makes a ~20% improvement in test case
683 -- perf/compiler/T5030.
684 --
685 -- Returns either the (partially zonked) types in the case of
686 -- inequality, or the one type in the case of equality. canEqReflexive is
687 -- a good next step in the 'Right' case. Returning 'Left' is always safe.
688 --
689 -- NB: This does *not* look through type synonyms. In fact, it treats type
690 -- synonyms as rigid constructors. In the future, it might be convenient
691 -- to look at only those arguments of type synonyms that actually appear
692 -- in the synonym RHS. But we're not there yet.
693 zonk_eq_types :: TcType -> TcType -> TcS (Either (Pair TcType) TcType)
694 zonk_eq_types = go
695 where
696 go (TyVarTy tv1) (TyVarTy tv2) = tyvar_tyvar tv1 tv2
697 go (TyVarTy tv1) ty2 = tyvar NotSwapped tv1 ty2
698 go ty1 (TyVarTy tv2) = tyvar IsSwapped tv2 ty1
699
700 go ty1 ty2
701 | Just (tc1, tys1) <- tcRepSplitTyConApp_maybe ty1
702 , Just (tc2, tys2) <- tcRepSplitTyConApp_maybe ty2
703 , tc1 == tc2
704 = tycon tc1 tys1 tys2
705
706 go ty1 ty2
707 | Just (ty1a, ty1b) <- tcRepSplitAppTy_maybe ty1
708 , Just (ty2a, ty2b) <- tcRepSplitAppTy_maybe ty2
709 = do { res_a <- go ty1a ty2a
710 ; res_b <- go ty1b ty2b
711 ; return $ combine_rev mkAppTy res_b res_a }
712
713 go ty1@(LitTy lit1) (LitTy lit2)
714 | lit1 == lit2
715 = return (Right ty1)
716
717 go ty1 ty2 = return $ Left (Pair ty1 ty2)
718 -- we don't handle more complex forms here
719
720 tyvar :: SwapFlag -> TcTyVar -> TcType
721 -> TcS (Either (Pair TcType) TcType)
722 -- try to do as little as possible, as anything we do here is redundant
723 -- with flattening. In particular, no need to zonk kinds. That's why
724 -- we don't use the already-defined zonking functions
725 tyvar swapped tv ty
726 = case tcTyVarDetails tv of
727 MetaTv { mtv_ref = ref }
728 -> do { cts <- readTcRef ref
729 ; case cts of
730 Flexi -> give_up
731 Indirect ty' -> unSwap swapped go ty' ty }
732 _ -> give_up
733 where
734 give_up = return $ Left $ unSwap swapped Pair (mkTyVarTy tv) ty
735
736 tyvar_tyvar tv1 tv2
737 | tv1 == tv2 = return (Right (mkTyVarTy tv1))
738 | otherwise = do { (ty1', progress1) <- quick_zonk tv1
739 ; (ty2', progress2) <- quick_zonk tv2
740 ; if progress1 || progress2
741 then go ty1' ty2'
742 else return $ Left (Pair (TyVarTy tv1) (TyVarTy tv2)) }
743
744 quick_zonk tv = case tcTyVarDetails tv of
745 MetaTv { mtv_ref = ref }
746 -> do { cts <- readTcRef ref
747 ; case cts of
748 Flexi -> return (TyVarTy tv, False)
749 Indirect ty' -> return (ty', True) }
750 _ -> return (TyVarTy tv, False)
751
752 -- This happens for type families, too. But recall that failure
753 -- here just means to try harder, so it's OK if the type function
754 -- isn't injective.
755 tycon :: TyCon -> [TcType] -> [TcType]
756 -> TcS (Either (Pair TcType) TcType)
757 tycon tc tys1 tys2
758 = do { results <- zipWithM go tys1 tys2
759 ; return $ case combine_results results of
760 Left tys -> Left (mkTyConApp tc <$> tys)
761 Right tys -> Right (mkTyConApp tc tys) }
762
763 combine_results :: [Either (Pair TcType) TcType]
764 -> Either (Pair [TcType]) [TcType]
765 combine_results = bimap (fmap reverse) reverse .
766 foldl' (combine_rev (:)) (Right [])
767
768 -- combine (in reverse) a new result onto an already-combined result
769 combine_rev :: (a -> b -> c)
770 -> Either (Pair b) b
771 -> Either (Pair a) a
772 -> Either (Pair c) c
773 combine_rev f (Left list) (Left elt) = Left (f <$> elt <*> list)
774 combine_rev f (Left list) (Right ty) = Left (f <$> pure ty <*> list)
775 combine_rev f (Right tys) (Left elt) = Left (f <$> elt <*> pure tys)
776 combine_rev f (Right tys) (Right ty) = Right (f ty tys)
777
778 {-
779 Note [Newtypes can blow the stack]
780 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
781 Suppose we have
782
783 newtype X = MkX (Int -> X)
784 newtype Y = MkY (Int -> Y)
785
786 and now wish to prove
787
788 [W] X ~R Y
789
790 This Wanted will loop, expanding out the newtypes ever deeper looking
791 for a solid match or a solid discrepancy. Indeed, there is something
792 appropriate to this looping, because X and Y *do* have the same representation,
793 in the limit -- they're both (Fix ((->) Int)). However, no finitely-sized
794 coercion will ever witness it. This loop won't actually cause GHC to hang,
795 though, because we check our depth when unwrapping newtypes.
796
797 Note [Eager reflexivity check]
798 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
799 Suppose we have
800
801 newtype X = MkX (Int -> X)
802
803 and
804
805 [W] X ~R X
806
807 Naively, we would start unwrapping X and end up in a loop. Instead,
808 we do this eager reflexivity check. This is necessary only for representational
809 equality because the flattener technology deals with the similar case
810 (recursive type families) for nominal equality.
811
812 Note that this check does not catch all cases, but it will catch the cases
813 we're most worried about, types like X above that are actually inhabited.
814
815 Here's another place where this reflexivity check is key:
816 Consider trying to prove (f a) ~R (f a). The AppTys in there can't
817 be decomposed, because representational equality isn't congruent with respect
818 to AppTy. So, when canonicalising the equality above, we get stuck and
819 would normally produce a CIrredEvCan. However, we really do want to
820 be able to solve (f a) ~R (f a). So, in the representational case only,
821 we do a reflexivity check.
822
823 (This would be sound in the nominal case, but unnecessary, and I [Richard
824 E.] am worried that it would slow down the common case.)
825 -}
826
827 ------------------------
828 -- | We're able to unwrap a newtype. Update the bits accordingly.
829 can_eq_newtype_nc :: CtEvidence -- ^ :: ty1 ~ ty2
830 -> SwapFlag
831 -> TcType -- ^ ty1
832 -> ((Bag GlobalRdrElt, TcCoercion), TcType) -- ^ :: ty1 ~ ty1'
833 -> TcType -- ^ ty2
834 -> TcType -- ^ ty2, with type synonyms
835 -> TcS (StopOrContinue Ct)
836 can_eq_newtype_nc ev swapped ty1 ((gres, co), ty1') ty2 ps_ty2
837 = do { traceTcS "can_eq_newtype_nc" $
838 vcat [ ppr ev, ppr swapped, ppr co, ppr gres, ppr ty1', ppr ty2 ]
839
840 -- check for blowing our stack:
841 -- See Note [Newtypes can blow the stack]
842 ; checkReductionDepth (ctEvLoc ev) ty1
843 ; addUsedGREs (bagToList gres)
844 -- we have actually used the newtype constructor here, so
845 -- make sure we don't warn about importing it!
846
847 ; rewriteEqEvidence ev swapped ty1' ps_ty2
848 (mkTcSymCo co) (mkTcReflCo Representational ps_ty2)
849 `andWhenContinue` \ new_ev ->
850 can_eq_nc False new_ev ReprEq ty1' ty1' ty2 ps_ty2 }
851
852 ---------
853 -- ^ Decompose a type application.
854 -- All input types must be flat. See Note [Canonicalising type applications]
855 can_eq_app :: CtEvidence -- :: s1 t1 ~r s2 t2
856 -> EqRel -- r
857 -> Xi -> Xi -- s1 t1
858 -> Xi -> Xi -- s2 t2
859 -> TcS (StopOrContinue Ct)
860
861 -- AppTys only decompose for nominal equality, so this case just leads
862 -- to an irreducible constraint; see typecheck/should_compile/T10494
863 -- See Note [Decomposing equality], note {4}
864 can_eq_app ev ReprEq _ _ _ _
865 = do { traceTcS "failing to decompose representational AppTy equality" (ppr ev)
866 ; continueWith (CIrredEvCan { cc_ev = ev }) }
867 -- no need to call canEqFailure, because that flattens, and the
868 -- types involved here are already flat
869
870 can_eq_app ev NomEq s1 t1 s2 t2
871 | CtDerived { ctev_loc = loc } <- ev
872 = do { unifyDeriveds loc [Nominal, Nominal] [s1, t1] [s2, t2]
873 ; stopWith ev "Decomposed [D] AppTy" }
874 | CtWanted { ctev_dest = dest, ctev_loc = loc } <- ev
875 = do { co_s <- unifyWanted loc Nominal s1 s2
876 ; co_t <- unifyWanted loc Nominal t1 t2
877 ; let co = mkAppCo co_s co_t
878 ; setWantedEq dest co
879 ; stopWith ev "Decomposed [W] AppTy" }
880 | CtGiven { ctev_evar = evar, ctev_loc = loc } <- ev
881 = do { let co = mkTcCoVarCo evar
882 co_s = mkTcLRCo CLeft co
883 co_t = mkTcLRCo CRight co
884 ; evar_s <- newGivenEvVar loc ( mkTcEqPredLikeEv ev s1 s2
885 , EvCoercion co_s )
886 ; evar_t <- newGivenEvVar loc ( mkTcEqPredLikeEv ev t1 t2
887 , EvCoercion co_t )
888 ; emitWorkNC [evar_t]
889 ; canEqNC evar_s NomEq s1 s2 }
890 | otherwise -- Can't happen
891 = error "can_eq_app"
892
893 -----------------------
894 -- | Break apart an equality over a casted type
895 -- looking like (ty1 |> co1) ~ ty2 (modulo a swap-flag)
896 canEqCast :: Bool -- are both types flat?
897 -> CtEvidence
898 -> EqRel
899 -> SwapFlag
900 -> TcType -> Coercion -- LHS (res. RHS), ty1 |> co1
901 -> TcType -> TcType -- RHS (res. LHS), ty2 both normal and pretty
902 -> TcS (StopOrContinue Ct)
903 canEqCast flat ev eq_rel swapped ty1 co1 ty2 ps_ty2
904 = do { traceTcS "Decomposing cast" (vcat [ ppr ev
905 , ppr ty1 <+> text "|>" <+> ppr co1
906 , ppr ps_ty2 ])
907 ; rewriteEqEvidence ev swapped ty1 ps_ty2
908 (mkTcReflCo role ty1
909 `mkTcCoherenceRightCo` co1)
910 (mkTcReflCo role ps_ty2)
911 `andWhenContinue` \ new_ev ->
912 can_eq_nc flat new_ev eq_rel ty1 ty1 ty2 ps_ty2 }
913 where
914 role = eqRelRole eq_rel
915
916 ------------------------
917 canTyConApp :: CtEvidence -> EqRel
918 -> TyCon -> [TcType]
919 -> TyCon -> [TcType]
920 -> TcS (StopOrContinue Ct)
921 -- See Note [Decomposing TyConApps]
922 canTyConApp ev eq_rel tc1 tys1 tc2 tys2
923 | tc1 == tc2
924 , length tys1 == length tys2
925 = do { inerts <- getTcSInerts
926 ; if can_decompose inerts
927 then do { traceTcS "canTyConApp"
928 (ppr ev $$ ppr eq_rel $$ ppr tc1 $$ ppr tys1 $$ ppr tys2)
929 ; canDecomposableTyConAppOK ev eq_rel tc1 tys1 tys2
930 ; stopWith ev "Decomposed TyConApp" }
931 else canEqFailure ev eq_rel ty1 ty2 }
932
933 -- See Note [Skolem abstract data] (at SkolemAbstract)
934 | isSkolemAbstractTyCon tc1 || isSkolemAbstractTyCon tc2
935 = do { traceTcS "canTyConApp: skolem abstract" (ppr tc1 $$ ppr tc2)
936 ; continueWith (CIrredEvCan { cc_ev = ev }) }
937
938 -- Fail straight away for better error messages
939 -- See Note [Use canEqFailure in canDecomposableTyConApp]
940 | eq_rel == ReprEq && not (isGenerativeTyCon tc1 Representational &&
941 isGenerativeTyCon tc2 Representational)
942 = canEqFailure ev eq_rel ty1 ty2
943 | otherwise
944 = canEqHardFailure ev ty1 ty2
945 where
946 ty1 = mkTyConApp tc1 tys1
947 ty2 = mkTyConApp tc2 tys2
948
949 loc = ctEvLoc ev
950 pred = ctEvPred ev
951
952 -- See Note [Decomposing equality]
953 can_decompose inerts
954 = isInjectiveTyCon tc1 (eqRelRole eq_rel)
955 || (ctEvFlavour ev /= Given && isEmptyBag (matchableGivens loc pred inerts))
956
957 {-
958 Note [Use canEqFailure in canDecomposableTyConApp]
959 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
960 We must use canEqFailure, not canEqHardFailure here, because there is
961 the possibility of success if working with a representational equality.
962 Here is one case:
963
964 type family TF a where TF Char = Bool
965 data family DF a
966 newtype instance DF Bool = MkDF Int
967
968 Suppose we are canonicalising (Int ~R DF (TF a)), where we don't yet
969 know `a`. This is *not* a hard failure, because we might soon learn
970 that `a` is, in fact, Char, and then the equality succeeds.
971
972 Here is another case:
973
974 [G] Age ~R Int
975
976 where Age's constructor is not in scope. We don't want to report
977 an "inaccessible code" error in the context of this Given!
978
979 For example, see typecheck/should_compile/T10493, repeated here:
980
981 import Data.Ord (Down) -- no constructor
982
983 foo :: Coercible (Down Int) Int => Down Int -> Int
984 foo = coerce
985
986 That should compile, but only because we use canEqFailure and not
987 canEqHardFailure.
988
989 Note [Decomposing equality]
990 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
991 If we have a constraint (of any flavour and role) that looks like
992 T tys1 ~ T tys2, what can we conclude about tys1 and tys2? The answer,
993 of course, is "it depends". This Note spells it all out.
994
995 In this Note, "decomposition" refers to taking the constraint
996 [fl] (T tys1 ~X T tys2)
997 (for some flavour fl and some role X) and replacing it with
998 [fls'] (tys1 ~Xs' tys2)
999 where that notation indicates a list of new constraints, where the
1000 new constraints may have different flavours and different roles.
1001
1002 The key property to consider is injectivity. When decomposing a Given the
1003 decomposition is sound if and only if T is injective in all of its type
1004 arguments. When decomposing a Wanted, the decomposition is sound (assuming the
1005 correct roles in the produced equality constraints), but it may be a guess --
1006 that is, an unforced decision by the constraint solver. Decomposing Wanteds
1007 over injective TyCons does not entail guessing. But sometimes we want to
1008 decompose a Wanted even when the TyCon involved is not injective! (See below.)
1009
1010 So, in broad strokes, we want this rule:
1011
1012 (*) Decompose a constraint (T tys1 ~X T tys2) if and only if T is injective
1013 at role X.
1014
1015 Pursuing the details requires exploring three axes:
1016 * Flavour: Given vs. Derived vs. Wanted
1017 * Role: Nominal vs. Representational
1018 * TyCon species: datatype vs. newtype vs. data family vs. type family vs. type variable
1019
1020 (So a type variable isn't a TyCon, but it's convenient to put the AppTy case
1021 in the same table.)
1022
1023 Right away, we can say that Derived behaves just as Wanted for the purposes
1024 of decomposition. The difference between Derived and Wanted is the handling of
1025 evidence. Since decomposition in these cases isn't a matter of soundness but of
1026 guessing, we want the same behavior regardless of evidence.
1027
1028 Here is a table (discussion following) detailing where decomposition of
1029 (T s1 ... sn) ~r (T t1 .. tn)
1030 is allowed. The first four lines (Data types ... type family) refer
1031 to TyConApps with various TyCons T; the last line is for AppTy, where
1032 there is presumably a type variable at the head, so it's actually
1033 (s s1 ... sn) ~r (t t1 .. tn)
1034
1035 NOMINAL GIVEN WANTED
1036
1037 Datatype YES YES
1038 Newtype YES YES
1039 Data family YES YES
1040 Type family YES, in injective args{1} YES, in injective args{1}
1041 Type variable YES YES
1042
1043 REPRESENTATIONAL GIVEN WANTED
1044
1045 Datatype YES YES
1046 Newtype NO{2} MAYBE{2}
1047 Data family NO{3} MAYBE{3}
1048 Type family NO NO
1049 Type variable NO{4} NO{4}
1050
1051 {1}: Type families can be injective in some, but not all, of their arguments,
1052 so we want to do partial decomposition. This is quite different than the way
1053 other decomposition is done, where the decomposed equalities replace the original
1054 one. We thus proceed much like we do with superclasses: emitting new Givens
1055 when "decomposing" a partially-injective type family Given and new Deriveds
1056 when "decomposing" a partially-injective type family Wanted. (As of the time of
1057 writing, 13 June 2015, the implementation of injective type families has not
1058 been merged, but it should be soon. Please delete this parenthetical if the
1059 implementation is indeed merged.)
1060
1061 {2}: See Note [Decomposing newtypes at representational role]
1062
1063 {3}: Because of the possibility of newtype instances, we must treat
1064 data families like newtypes. See also Note [Decomposing newtypes at
1065 representational role]. See #10534 and test case
1066 typecheck/should_fail/T10534.
1067
1068 {4}: Because type variables can stand in for newtypes, we conservatively do not
1069 decompose AppTys over representational equality.
1070
1071 In the implementation of can_eq_nc and friends, we don't directly pattern
1072 match using lines like in the tables above, as those tables don't cover
1073 all cases (what about PrimTyCon? tuples?). Instead we just ask about injectivity,
1074 boiling the tables above down to rule (*). The exceptions to rule (*) are for
1075 injective type families, which are handled separately from other decompositions,
1076 and the MAYBE entries above.
1077
1078 Note [Decomposing newtypes at representational role]
1079 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1080 This note discusses the 'newtype' line in the REPRESENTATIONAL table
1081 in Note [Decomposing equality]. (At nominal role, newtypes are fully
1082 decomposable.)
1083
1084 Here is a representative example of why representational equality over
1085 newtypes is tricky:
1086
1087 newtype Nt a = Mk Bool -- NB: a is not used in the RHS,
1088 type role Nt representational -- but the user gives it an R role anyway
1089
1090 If we have [W] Nt alpha ~R Nt beta, we *don't* want to decompose to
1091 [W] alpha ~R beta, because it's possible that alpha and beta aren't
1092 representationally equal. Here's another example.
1093
1094 newtype Nt a = MkNt (Id a)
1095 type family Id a where Id a = a
1096
1097 [W] Nt Int ~R Nt Age
1098
1099 Because of its use of a type family, Nt's parameter will get inferred to have
1100 a nominal role. Thus, decomposing the wanted will yield [W] Int ~N Age, which
1101 is unsatisfiable. Unwrapping, though, leads to a solution.
1102
1103 Conclusion:
1104 * Unwrap newtypes before attempting to decompose them.
1105 This is done in can_eq_nc'.
1106
1107 It all comes from the fact that newtypes aren't necessarily injective
1108 w.r.t. representational equality.
1109
1110 Furthermore, as explained in Note [NthCo and newtypes] in TyCoRep, we can't use
1111 NthCo on representational coercions over newtypes. NthCo comes into play
1112 only when decomposing givens.
1113
1114 Conclusion:
1115 * Do not decompose [G] N s ~R N t
1116
1117 Is it sensible to decompose *Wanted* constraints over newtypes? Yes!
1118 It's the only way we could ever prove (IO Int ~R IO Age), recalling
1119 that IO is a newtype.
1120
1121 However we must be careful. Consider
1122
1123 type role Nt representational
1124
1125 [G] Nt a ~R Nt b (1)
1126 [W] NT alpha ~R Nt b (2)
1127 [W] alpha ~ a (3)
1128
1129 If we focus on (3) first, we'll substitute in (2), and now it's
1130 identical to the given (1), so we succeed. But if we focus on (2)
1131 first, and decompose it, we'll get (alpha ~R b), which is not soluble.
1132 This is exactly like the question of overlapping Givens for class
1133 constraints: see Note [Instance and Given overlap] in TcInteract.
1134
1135 Conclusion:
1136 * Decompose [W] N s ~R N t iff there no given constraint that could
1137 later solve it.
1138 -}
1139
1140 canDecomposableTyConAppOK :: CtEvidence -> EqRel
1141 -> TyCon -> [TcType] -> [TcType]
1142 -> TcS ()
1143 -- Precondition: tys1 and tys2 are the same length, hence "OK"
1144 canDecomposableTyConAppOK ev eq_rel tc tys1 tys2
1145 = case ev of
1146 CtDerived {}
1147 -> unifyDeriveds loc tc_roles tys1 tys2
1148
1149 CtWanted { ctev_dest = dest }
1150 -> do { cos <- zipWith4M unifyWanted new_locs tc_roles tys1 tys2
1151 ; setWantedEq dest (mkTyConAppCo role tc cos) }
1152
1153 CtGiven { ctev_evar = evar }
1154 -> do { let ev_co = mkCoVarCo evar
1155 ; given_evs <- newGivenEvVars loc $
1156 [ ( mkPrimEqPredRole r ty1 ty2
1157 , EvCoercion (mkNthCo i ev_co) )
1158 | (r, ty1, ty2, i) <- zip4 tc_roles tys1 tys2 [0..]
1159 , r /= Phantom
1160 , not (isCoercionTy ty1) && not (isCoercionTy ty2) ]
1161 ; emitWorkNC given_evs }
1162 where
1163 loc = ctEvLoc ev
1164 role = eqRelRole eq_rel
1165 tc_roles = tyConRolesX role tc
1166
1167 -- the following makes a better distinction between "kind" and "type"
1168 -- in error messages
1169 bndrs = tyConBinders tc
1170 kind_loc = toKindLoc loc
1171 is_kinds = map isNamedTyConBinder bndrs
1172 new_locs | Just KindLevel <- ctLocTypeOrKind_maybe loc
1173 = repeat loc
1174 | otherwise
1175 = map (\is_kind -> if is_kind then kind_loc else loc) is_kinds
1176
1177
1178 -- | Call when canonicalizing an equality fails, but if the equality is
1179 -- representational, there is some hope for the future.
1180 -- Examples in Note [Use canEqFailure in canDecomposableTyConApp]
1181 canEqFailure :: CtEvidence -> EqRel
1182 -> TcType -> TcType -> TcS (StopOrContinue Ct)
1183 canEqFailure ev NomEq ty1 ty2
1184 = canEqHardFailure ev ty1 ty2
1185 canEqFailure ev ReprEq ty1 ty2
1186 = do { (xi1, co1) <- flatten FM_FlattenAll ev ty1
1187 ; (xi2, co2) <- flatten FM_FlattenAll ev ty2
1188 -- We must flatten the types before putting them in the
1189 -- inert set, so that we are sure to kick them out when
1190 -- new equalities become available
1191 ; traceTcS "canEqFailure with ReprEq" $
1192 vcat [ ppr ev, ppr ty1, ppr ty2, ppr xi1, ppr xi2 ]
1193 ; rewriteEqEvidence ev NotSwapped xi1 xi2 co1 co2
1194 `andWhenContinue` \ new_ev ->
1195 continueWith (CIrredEvCan { cc_ev = new_ev }) }
1196
1197 -- | Call when canonicalizing an equality fails with utterly no hope.
1198 canEqHardFailure :: CtEvidence
1199 -> TcType -> TcType -> TcS (StopOrContinue Ct)
1200 -- See Note [Make sure that insolubles are fully rewritten]
1201 canEqHardFailure ev ty1 ty2
1202 = do { (s1, co1) <- flatten FM_SubstOnly ev ty1
1203 ; (s2, co2) <- flatten FM_SubstOnly ev ty2
1204 ; rewriteEqEvidence ev NotSwapped s1 s2 co1 co2
1205 `andWhenContinue` \ new_ev ->
1206 do { emitInsoluble (mkNonCanonical new_ev)
1207 ; stopWith new_ev "Definitely not equal" }}
1208
1209 {-
1210 Note [Decomposing TyConApps]
1211 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1212 If we see (T s1 t1 ~ T s2 t2), then we can just decompose to
1213 (s1 ~ s2, t1 ~ t2)
1214 and push those back into the work list. But if
1215 s1 = K k1 s2 = K k2
1216 then we will just decomopose s1~s2, and it might be better to
1217 do so on the spot. An important special case is where s1=s2,
1218 and we get just Refl.
1219
1220 So canDecomposableTyCon is a fast-path decomposition that uses
1221 unifyWanted etc to short-cut that work.
1222
1223 Note [Canonicalising type applications]
1224 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1225 Given (s1 t1) ~ ty2, how should we proceed?
1226 The simple things is to see if ty2 is of form (s2 t2), and
1227 decompose. By this time s1 and s2 can't be saturated type
1228 function applications, because those have been dealt with
1229 by an earlier equation in can_eq_nc, so it is always sound to
1230 decompose.
1231
1232 However, over-eager decomposition gives bad error messages
1233 for things like
1234 a b ~ Maybe c
1235 e f ~ p -> q
1236 Suppose (in the first example) we already know a~Array. Then if we
1237 decompose the application eagerly, yielding
1238 a ~ Maybe
1239 b ~ c
1240 we get an error "Can't match Array ~ Maybe",
1241 but we'd prefer to get "Can't match Array b ~ Maybe c".
1242
1243 So instead can_eq_wanted_app flattens the LHS and RHS, in the hope of
1244 replacing (a b) by (Array b), before using try_decompose_app to
1245 decompose it.
1246
1247 Note [Make sure that insolubles are fully rewritten]
1248 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1249 When an equality fails, we still want to rewrite the equality
1250 all the way down, so that it accurately reflects
1251 (a) the mutable reference substitution in force at start of solving
1252 (b) any ty-binds in force at this point in solving
1253 See Note [Kick out insolubles] in TcSMonad.
1254 And if we don't do this there is a bad danger that
1255 TcSimplify.applyTyVarDefaulting will find a variable
1256 that has in fact been substituted.
1257
1258 Note [Do not decompose Given polytype equalities]
1259 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1260 Consider [G] (forall a. t1 ~ forall a. t2). Can we decompose this?
1261 No -- what would the evidence look like? So instead we simply discard
1262 this given evidence.
1263
1264
1265 Note [Combining insoluble constraints]
1266 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1267 As this point we have an insoluble constraint, like Int~Bool.
1268
1269 * If it is Wanted, delete it from the cache, so that subsequent
1270 Int~Bool constraints give rise to separate error messages
1271
1272 * But if it is Derived, DO NOT delete from cache. A class constraint
1273 may get kicked out of the inert set, and then have its functional
1274 dependency Derived constraints generated a second time. In that
1275 case we don't want to get two (or more) error messages by
1276 generating two (or more) insoluble fundep constraints from the same
1277 class constraint.
1278
1279 Note [No top-level newtypes on RHS of representational equalities]
1280 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1281 Suppose we're in this situation:
1282
1283 work item: [W] c1 : a ~R b
1284 inert: [G] c2 : b ~R Id a
1285
1286 where
1287 newtype Id a = Id a
1288
1289 We want to make sure canEqTyVar sees [W] a ~R a, after b is flattened
1290 and the Id newtype is unwrapped. This is assured by requiring only flat
1291 types in canEqTyVar *and* having the newtype-unwrapping check above
1292 the tyvar check in can_eq_nc.
1293
1294 Note [Occurs check error]
1295 ~~~~~~~~~~~~~~~~~~~~~~~~~
1296 If we have an occurs check error, are we necessarily hosed? Say our
1297 tyvar is tv1 and the type it appears in is xi2. Because xi2 is function
1298 free, then if we're computing w.r.t. nominal equality, then, yes, we're
1299 hosed. Nothing good can come from (a ~ [a]). If we're computing w.r.t.
1300 representational equality, this is a little subtler. Once again, (a ~R [a])
1301 is a bad thing, but (a ~R N a) for a newtype N might be just fine. This
1302 means also that (a ~ b a) might be fine, because `b` might become a newtype.
1303
1304 So, we must check: does tv1 appear in xi2 under any type constructor that
1305 is generative w.r.t. representational equality? That's what isTyVarUnderDatatype
1306 does. (The other name I considered, isTyVarUnderTyConGenerativeWrtReprEq was
1307 a bit verbose. And the shorter name gets the point across.)
1308
1309 See also #10715, which induced this addition.
1310
1311 Note [No derived kind equalities]
1312 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1313 When we're working with a heterogeneous derived equality
1314
1315 [D] (t1 :: k1) ~ (t2 :: k2)
1316
1317 we want to homogenise to establish the kind invariant on CTyEqCans.
1318 But we can't emit [D] k1 ~ k2 because we wouldn't then be able to
1319 use the evidence in the homogenised types. So we emit a wanted
1320 constraint, because we do really need the evidence here.
1321
1322 Thus: no derived kind equalities.
1323
1324 -}
1325
1326 canCFunEqCan :: CtEvidence
1327 -> TyCon -> [TcType] -- LHS
1328 -> TcTyVar -- RHS
1329 -> TcS (StopOrContinue Ct)
1330 -- ^ Canonicalise a CFunEqCan. We know that
1331 -- the arg types are already flat,
1332 -- and the RHS is a fsk, which we must *not* substitute.
1333 -- So just substitute in the LHS
1334 canCFunEqCan ev fn tys fsk
1335 = do { (tys', cos) <- flattenManyNom ev tys
1336 -- cos :: tys' ~ tys
1337 ; let lhs_co = mkTcTyConAppCo Nominal fn cos
1338 -- :: F tys' ~ F tys
1339 new_lhs = mkTyConApp fn tys'
1340 fsk_ty = mkTyVarTy fsk
1341 ; rewriteEqEvidence ev NotSwapped new_lhs fsk_ty
1342 lhs_co (mkTcNomReflCo fsk_ty)
1343 `andWhenContinue` \ ev' ->
1344 do { extendFlatCache fn tys' (ctEvCoercion ev', fsk_ty, ctEvFlavour ev')
1345 ; continueWith (CFunEqCan { cc_ev = ev', cc_fun = fn
1346 , cc_tyargs = tys', cc_fsk = fsk }) } }
1347
1348 ---------------------
1349 canEqTyVar :: CtEvidence -- ev :: lhs ~ rhs
1350 -> EqRel -> SwapFlag
1351 -> TcTyVar -> TcType -- lhs: already flat, not a cast
1352 -> TcType -> TcType -- rhs: already flat, not a cast
1353 -> TcS (StopOrContinue Ct)
1354 canEqTyVar ev eq_rel swapped tv1 ps_ty1 (TyVarTy tv2) _
1355 | tv1 == tv2
1356 = canEqReflexive ev eq_rel ps_ty1
1357
1358 | swapOverTyVars tv1 tv2
1359 = do { traceTcS "canEqTyVar" (ppr tv1 $$ ppr tv2 $$ ppr swapped)
1360 -- FM_Avoid commented out: see Note [Lazy flattening] in TcFlatten
1361 -- let fmode = FE { fe_ev = ev, fe_mode = FM_Avoid tv1' True }
1362 -- Flatten the RHS less vigorously, to avoid gratuitous flattening
1363 -- True <=> xi2 should not itself be a type-function application
1364 ; dflags <- getDynFlags
1365 ; canEqTyVar2 dflags ev eq_rel (flipSwap swapped) tv2 ps_ty1 }
1366
1367 canEqTyVar ev eq_rel swapped tv1 _ _ ps_ty2
1368 = do { dflags <- getDynFlags
1369 ; canEqTyVar2 dflags ev eq_rel swapped tv1 ps_ty2 }
1370
1371 canEqTyVar2 :: DynFlags
1372 -> CtEvidence -- lhs ~ rhs (or, if swapped, orhs ~ olhs)
1373 -> EqRel
1374 -> SwapFlag
1375 -> TcTyVar -- lhs, flat
1376 -> TcType -- rhs, flat
1377 -> TcS (StopOrContinue Ct)
1378 -- LHS is an inert type variable,
1379 -- and RHS is fully rewritten, but with type synonyms
1380 -- preserved as much as possible
1381
1382 canEqTyVar2 dflags ev eq_rel swapped tv1 xi2
1383 | Just xi2' <- metaTyVarUpdateOK dflags tv1 xi2 -- No occurs check
1384 -- Must do the occurs check even on tyvar/tyvar
1385 -- equalities, in case have x ~ (y :: ..x...)
1386 -- Trac #12593
1387 = rewriteEqEvidence ev swapped xi1 xi2' co1 co2
1388 `andWhenContinue` \ new_ev ->
1389 homogeniseRhsKind new_ev eq_rel xi1 xi2' $ \new_new_ev xi2'' ->
1390 CTyEqCan { cc_ev = new_new_ev, cc_tyvar = tv1
1391 , cc_rhs = xi2'', cc_eq_rel = eq_rel }
1392
1393 | otherwise -- Occurs check error (or a forall)
1394 = do { traceTcS "canEqTyVar2 occurs check error" (ppr tv1 $$ ppr xi2)
1395 ; rewriteEqEvidence ev swapped xi1 xi2 co1 co2
1396 `andWhenContinue` \ new_ev ->
1397 if eq_rel == NomEq || isTyVarUnderDatatype tv1 xi2
1398 then do { emitInsoluble (mkNonCanonical new_ev)
1399 -- If we have a ~ [a], it is not canonical, and in particular
1400 -- we don't want to rewrite existing inerts with it, otherwise
1401 -- we'd risk divergence in the constraint solver
1402 ; stopWith new_ev "Occurs check" }
1403
1404 -- A representational equality with an occurs-check problem isn't
1405 -- insoluble! For example:
1406 -- a ~R b a
1407 -- We might learn that b is the newtype Id.
1408 -- But, the occurs-check certainly prevents the equality from being
1409 -- canonical, and we might loop if we were to use it in rewriting.
1410 else do { traceTcS "Occurs-check in representational equality"
1411 (ppr xi1 $$ ppr xi2)
1412 ; continueWith (CIrredEvCan { cc_ev = new_ev }) } }
1413 where
1414 role = eqRelRole eq_rel
1415 xi1 = mkTyVarTy tv1
1416 co1 = mkTcReflCo role xi1
1417 co2 = mkTcReflCo role xi2
1418
1419 -- | Solve a reflexive equality constraint
1420 canEqReflexive :: CtEvidence -- ty ~ ty
1421 -> EqRel
1422 -> TcType -- ty
1423 -> TcS (StopOrContinue Ct) -- always Stop
1424 canEqReflexive ev eq_rel ty
1425 = do { setEvBindIfWanted ev (EvCoercion $
1426 mkTcReflCo (eqRelRole eq_rel) ty)
1427 ; stopWith ev "Solved by reflexivity" }
1428
1429 -- See Note [Equalities with incompatible kinds]
1430 homogeniseRhsKind :: CtEvidence -- ^ the evidence to homogenise
1431 -> EqRel
1432 -> TcType -- ^ original LHS
1433 -> Xi -- ^ original RHS
1434 -> (CtEvidence -> Xi -> Ct)
1435 -- ^ how to build the homogenised constraint;
1436 -- the 'Xi' is the new RHS
1437 -> TcS (StopOrContinue Ct)
1438 homogeniseRhsKind ev eq_rel lhs rhs build_ct
1439 | k1 `tcEqType` k2
1440 = continueWith (build_ct ev rhs)
1441
1442 | CtGiven { ctev_evar = evar } <- ev
1443 -- tm :: (lhs :: k1) ~ (rhs :: k2)
1444 = do { kind_ev_id <- newBoundEvVarId kind_pty
1445 (EvCoercion $
1446 mkTcKindCo $ mkTcCoVarCo evar)
1447 -- kind_ev_id :: (k1 :: *) ~# (k2 :: *)
1448 ; let kind_ev = CtGiven { ctev_pred = kind_pty
1449 , ctev_evar = kind_ev_id
1450 , ctev_loc = kind_loc }
1451 homo_co = mkSymCo $ mkCoVarCo kind_ev_id
1452 rhs' = mkCastTy rhs homo_co
1453 ; traceTcS "Hetero equality gives rise to given kind equality"
1454 (ppr kind_ev_id <+> dcolon <+> ppr kind_pty)
1455 ; emitWorkNC [kind_ev]
1456 ; type_ev <- newGivenEvVar loc
1457 ( mkTcEqPredLikeEv ev lhs rhs'
1458 , EvCoercion $
1459 mkTcCoherenceRightCo (mkTcCoVarCo evar) homo_co )
1460 -- type_ev :: (lhs :: k1) ~ ((rhs |> sym kind_ev_id) :: k1)
1461 ; continueWith (build_ct type_ev rhs') }
1462
1463 | otherwise -- Wanted and Derived. See Note [No derived kind equalities]
1464 -- evar :: (lhs :: k1) ~ (rhs :: k2)
1465 = do { kind_co <- emitNewWantedEq kind_loc Nominal k1 k2
1466 -- kind_ev :: (k1 :: *) ~ (k2 :: *)
1467 ; traceTcS "Hetero equality gives rise to wanted kind equality" $
1468 ppr (kind_co)
1469 ; let homo_co = mkSymCo kind_co
1470 -- homo_co :: k2 ~ k1
1471 rhs' = mkCastTy rhs homo_co
1472 ; case ev of
1473 CtGiven {} -> panic "homogeniseRhsKind"
1474 CtDerived {} -> continueWith (build_ct (ev { ctev_pred = homo_pred })
1475 rhs')
1476 where homo_pred = mkTcEqPredLikeEv ev lhs rhs'
1477 CtWanted { ctev_dest = dest } -> do
1478 { (type_ev, hole_co) <- newWantedEq loc role lhs rhs'
1479 -- type_ev :: (lhs :: k1) ~ (rhs |> sym kind_co :: k1)
1480 ; setWantedEq dest
1481 (hole_co `mkTransCo`
1482 (mkReflCo role rhs
1483 `mkCoherenceLeftCo` homo_co))
1484
1485 -- dest := hole ; <rhs> |> homo_co :: (lhs :: k1) ~ (rhs :: k2)
1486 ; continueWith (build_ct type_ev rhs') }}
1487
1488 where
1489 k1 = typeKind lhs
1490 k2 = typeKind rhs
1491
1492 kind_pty = mkHeteroPrimEqPred liftedTypeKind liftedTypeKind k1 k2
1493 kind_loc = mkKindLoc lhs rhs loc
1494
1495 loc = ctev_loc ev
1496 role = eqRelRole eq_rel
1497
1498 {-
1499 Note [Canonical orientation for tyvar/tyvar equality constraints]
1500 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1501 When we have a ~ b where both 'a' and 'b' are TcTyVars, which way
1502 round should be oriented in the CTyEqCan? The rules, implemented by
1503 canEqTyVarTyVar, are these
1504
1505 * If either is a flatten-meta-variables, it goes on the left.
1506
1507 * Put a meta-tyvar on the left if possible
1508 alpha[3] ~ r
1509
1510 * If both are meta-tyvars, put the more touchable one (deepest level
1511 number) on the left, so there is the best chance of unifying it
1512 alpha[3] ~ beta[2]
1513
1514 * If both are meta-tyvars and both at the same level, put a SigTv
1515 on the right if possible
1516 alpha[2] ~ beta[2](sig-tv)
1517 That way, when we unify alpha := beta, we don't lose the SigTv flag.
1518
1519 * Put a meta-tv with a System Name on the left if possible so it
1520 gets eliminated (improves error messages)
1521
1522 * If one is a flatten-skolem, put it on the left so that it is
1523 substituted out Note [Elminate flat-skols]
1524 fsk ~ a
1525
1526 Note [Avoid unnecessary swaps]
1527 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1528 If we swap without actually improving matters, we can get an infnite loop.
1529 Consider
1530 work item: a ~ b
1531 inert item: b ~ c
1532 We canonicalise the work-time to (a ~ c). If we then swap it before
1533 aeding to the inert set, we'll add (c ~ a), and therefore kick out the
1534 inert guy, so we get
1535 new work item: b ~ c
1536 inert item: c ~ a
1537 And now the cycle just repeats
1538
1539 Note [Eliminate flat-skols]
1540 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
1541 Suppose we have [G] Num (F [a])
1542 then we flatten to
1543 [G] Num fsk
1544 [G] F [a] ~ fsk
1545 where fsk is a flatten-skolem (FlatSkol). Suppose we have
1546 type instance F [a] = a
1547 then we'll reduce the second constraint to
1548 [G] a ~ fsk
1549 and then replace all uses of 'a' with fsk. That's bad because
1550 in error messages intead of saying 'a' we'll say (F [a]). In all
1551 places, including those where the programmer wrote 'a' in the first
1552 place. Very confusing! See Trac #7862.
1553
1554 Solution: re-orient a~fsk to fsk~a, so that we preferentially eliminate
1555 the fsk.
1556
1557 Note [Equalities with incompatible kinds]
1558 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1559 canEqLeaf is about to make a CTyEqCan or CFunEqCan; but both have the
1560 invariant that LHS and RHS satisfy the kind invariants for CTyEqCan,
1561 CFunEqCan. What if we try to unify two things with incompatible
1562 kinds?
1563
1564 eg a ~ b where a::*, b::*->*
1565 or a ~ b where a::*, b::k, k is a kind variable
1566
1567 The CTyEqCan compatKind invariant is important. If we make a CTyEqCan
1568 for a~b, then we might well *substitute* 'b' for 'a', and that might make
1569 a well-kinded type ill-kinded; and that is bad (eg typeKind can crash, see
1570 Trac #7696).
1571
1572 So instead for these ill-kinded equalities we homogenise the RHS of the
1573 equality, emitting new constraints as necessary.
1574
1575 Note [Type synonyms and canonicalization]
1576 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1577 We treat type synonym applications as xi types, that is, they do not
1578 count as type function applications. However, we do need to be a bit
1579 careful with type synonyms: like type functions they may not be
1580 generative or injective. However, unlike type functions, they are
1581 parametric, so there is no problem in expanding them whenever we see
1582 them, since we do not need to know anything about their arguments in
1583 order to expand them; this is what justifies not having to treat them
1584 as specially as type function applications. The thing that causes
1585 some subtleties is that we prefer to leave type synonym applications
1586 *unexpanded* whenever possible, in order to generate better error
1587 messages.
1588
1589 If we encounter an equality constraint with type synonym applications
1590 on both sides, or a type synonym application on one side and some sort
1591 of type application on the other, we simply must expand out the type
1592 synonyms in order to continue decomposing the equality constraint into
1593 primitive equality constraints. For example, suppose we have
1594
1595 type F a = [Int]
1596
1597 and we encounter the equality
1598
1599 F a ~ [b]
1600
1601 In order to continue we must expand F a into [Int], giving us the
1602 equality
1603
1604 [Int] ~ [b]
1605
1606 which we can then decompose into the more primitive equality
1607 constraint
1608
1609 Int ~ b.
1610
1611 However, if we encounter an equality constraint with a type synonym
1612 application on one side and a variable on the other side, we should
1613 NOT (necessarily) expand the type synonym, since for the purpose of
1614 good error messages we want to leave type synonyms unexpanded as much
1615 as possible. Hence the ps_ty1, ps_ty2 argument passed to canEqTyVar.
1616
1617 -}
1618
1619 {-
1620 ************************************************************************
1621 * *
1622 Evidence transformation
1623 * *
1624 ************************************************************************
1625 -}
1626
1627 data StopOrContinue a
1628 = ContinueWith a -- The constraint was not solved, although it may have
1629 -- been rewritten
1630
1631 | Stop CtEvidence -- The (rewritten) constraint was solved
1632 SDoc -- Tells how it was solved
1633 -- Any new sub-goals have been put on the work list
1634
1635 instance Functor StopOrContinue where
1636 fmap f (ContinueWith x) = ContinueWith (f x)
1637 fmap _ (Stop ev s) = Stop ev s
1638
1639 instance Outputable a => Outputable (StopOrContinue a) where
1640 ppr (Stop ev s) = text "Stop" <> parens s <+> ppr ev
1641 ppr (ContinueWith w) = text "ContinueWith" <+> ppr w
1642
1643 continueWith :: a -> TcS (StopOrContinue a)
1644 continueWith = return . ContinueWith
1645
1646 stopWith :: CtEvidence -> String -> TcS (StopOrContinue a)
1647 stopWith ev s = return (Stop ev (text s))
1648
1649 andWhenContinue :: TcS (StopOrContinue a)
1650 -> (a -> TcS (StopOrContinue b))
1651 -> TcS (StopOrContinue b)
1652 andWhenContinue tcs1 tcs2
1653 = do { r <- tcs1
1654 ; case r of
1655 Stop ev s -> return (Stop ev s)
1656 ContinueWith ct -> tcs2 ct }
1657 infixr 0 `andWhenContinue` -- allow chaining with ($)
1658
1659 rewriteEvidence :: CtEvidence -- old evidence
1660 -> TcPredType -- new predicate
1661 -> TcCoercion -- Of type :: new predicate ~ <type of old evidence>
1662 -> TcS (StopOrContinue CtEvidence)
1663 -- Returns Just new_ev iff either (i) 'co' is reflexivity
1664 -- or (ii) 'co' is not reflexivity, and 'new_pred' not cached
1665 -- In either case, there is nothing new to do with new_ev
1666 {-
1667 rewriteEvidence old_ev new_pred co
1668 Main purpose: create new evidence for new_pred;
1669 unless new_pred is cached already
1670 * Returns a new_ev : new_pred, with same wanted/given/derived flag as old_ev
1671 * If old_ev was wanted, create a binding for old_ev, in terms of new_ev
1672 * If old_ev was given, AND not cached, create a binding for new_ev, in terms of old_ev
1673 * Returns Nothing if new_ev is already cached
1674
1675 Old evidence New predicate is Return new evidence
1676 flavour of same flavor
1677 -------------------------------------------------------------------
1678 Wanted Already solved or in inert Nothing
1679 or Derived Not Just new_evidence
1680
1681 Given Already in inert Nothing
1682 Not Just new_evidence
1683
1684 Note [Rewriting with Refl]
1685 ~~~~~~~~~~~~~~~~~~~~~~~~~~
1686 If the coercion is just reflexivity then you may re-use the same
1687 variable. But be careful! Although the coercion is Refl, new_pred
1688 may reflect the result of unification alpha := ty, so new_pred might
1689 not _look_ the same as old_pred, and it's vital to proceed from now on
1690 using new_pred.
1691
1692 The flattener preserves type synonyms, so they should appear in new_pred
1693 as well as in old_pred; that is important for good error messages.
1694 -}
1695
1696
1697 rewriteEvidence old_ev@(CtDerived {}) new_pred _co
1698 = -- If derived, don't even look at the coercion.
1699 -- This is very important, DO NOT re-order the equations for
1700 -- rewriteEvidence to put the isTcReflCo test first!
1701 -- Why? Because for *Derived* constraints, c, the coercion, which
1702 -- was produced by flattening, may contain suspended calls to
1703 -- (ctEvTerm c), which fails for Derived constraints.
1704 -- (Getting this wrong caused Trac #7384.)
1705 continueWith (old_ev { ctev_pred = new_pred })
1706
1707 rewriteEvidence old_ev new_pred co
1708 | isTcReflCo co -- See Note [Rewriting with Refl]
1709 = continueWith (old_ev { ctev_pred = new_pred })
1710
1711 rewriteEvidence ev@(CtGiven { ctev_evar = old_evar , ctev_loc = loc }) new_pred co
1712 = do { new_ev <- newGivenEvVar loc (new_pred, new_tm)
1713 ; continueWith new_ev }
1714 where
1715 -- mkEvCast optimises ReflCo
1716 new_tm = mkEvCast (EvId old_evar) (tcDowngradeRole Representational
1717 (ctEvRole ev)
1718 (mkTcSymCo co))
1719
1720 rewriteEvidence ev@(CtWanted { ctev_dest = dest
1721 , ctev_loc = loc }) new_pred co
1722 = do { mb_new_ev <- newWanted loc new_pred
1723 ; MASSERT( tcCoercionRole co == ctEvRole ev )
1724 ; setWantedEvTerm dest
1725 (mkEvCast (getEvTerm mb_new_ev)
1726 (tcDowngradeRole Representational (ctEvRole ev) co))
1727 ; case mb_new_ev of
1728 Fresh new_ev -> continueWith new_ev
1729 Cached _ -> stopWith ev "Cached wanted" }
1730
1731
1732 rewriteEqEvidence :: CtEvidence -- Old evidence :: olhs ~ orhs (not swapped)
1733 -- or orhs ~ olhs (swapped)
1734 -> SwapFlag
1735 -> TcType -> TcType -- New predicate nlhs ~ nrhs
1736 -- Should be zonked, because we use typeKind on nlhs/nrhs
1737 -> TcCoercion -- lhs_co, of type :: nlhs ~ olhs
1738 -> TcCoercion -- rhs_co, of type :: nrhs ~ orhs
1739 -> TcS (StopOrContinue CtEvidence) -- Of type nlhs ~ nrhs
1740 -- For (rewriteEqEvidence (Given g olhs orhs) False nlhs nrhs lhs_co rhs_co)
1741 -- we generate
1742 -- If not swapped
1743 -- g1 : nlhs ~ nrhs = lhs_co ; g ; sym rhs_co
1744 -- If 'swapped'
1745 -- g1 : nlhs ~ nrhs = lhs_co ; Sym g ; sym rhs_co
1746 --
1747 -- For (Wanted w) we do the dual thing.
1748 -- New w1 : nlhs ~ nrhs
1749 -- If not swapped
1750 -- w : olhs ~ orhs = sym lhs_co ; w1 ; rhs_co
1751 -- If swapped
1752 -- w : orhs ~ olhs = sym rhs_co ; sym w1 ; lhs_co
1753 --
1754 -- It's all a form of rewwriteEvidence, specialised for equalities
1755 rewriteEqEvidence old_ev swapped nlhs nrhs lhs_co rhs_co
1756 | CtDerived {} <- old_ev -- Don't force the evidence for a Derived
1757 = continueWith (old_ev { ctev_pred = new_pred })
1758
1759 | NotSwapped <- swapped
1760 , isTcReflCo lhs_co -- See Note [Rewriting with Refl]
1761 , isTcReflCo rhs_co
1762 = continueWith (old_ev { ctev_pred = new_pred })
1763
1764 | CtGiven { ctev_evar = old_evar } <- old_ev
1765 = do { let new_tm = EvCoercion (lhs_co
1766 `mkTcTransCo` maybeSym swapped (mkTcCoVarCo old_evar)
1767 `mkTcTransCo` mkTcSymCo rhs_co)
1768 ; new_ev <- newGivenEvVar loc' (new_pred, new_tm)
1769 ; continueWith new_ev }
1770
1771 | CtWanted { ctev_dest = dest } <- old_ev
1772 = do { (new_ev, hole_co) <- newWantedEq loc' (ctEvRole old_ev) nlhs nrhs
1773 ; let co = maybeSym swapped $
1774 mkSymCo lhs_co
1775 `mkTransCo` hole_co
1776 `mkTransCo` rhs_co
1777 ; setWantedEq dest co
1778 ; traceTcS "rewriteEqEvidence" (vcat [ppr old_ev, ppr nlhs, ppr nrhs, ppr co])
1779 ; continueWith new_ev }
1780
1781 | otherwise
1782 = panic "rewriteEvidence"
1783 where
1784 new_pred = mkTcEqPredLikeEv old_ev nlhs nrhs
1785
1786 -- equality is like a type class. Bumping the depth is necessary because
1787 -- of recursive newtypes, where "reducing" a newtype can actually make
1788 -- it bigger. See Note [Newtypes can blow the stack].
1789 loc = ctEvLoc old_ev
1790 loc' = bumpCtLocDepth loc
1791
1792 {- Note [unifyWanted and unifyDerived]
1793 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1794 When decomposing equalities we often create new wanted constraints for
1795 (s ~ t). But what if s=t? Then it'd be faster to return Refl right away.
1796 Similar remarks apply for Derived.
1797
1798 Rather than making an equality test (which traverses the structure of the
1799 type, perhaps fruitlessly, unifyWanted traverses the common structure, and
1800 bales out when it finds a difference by creating a new Wanted constraint.
1801 But where it succeeds in finding common structure, it just builds a coercion
1802 to reflect it.
1803 -}
1804
1805 unifyWanted :: CtLoc -> Role
1806 -> TcType -> TcType -> TcS Coercion
1807 -- Return coercion witnessing the equality of the two types,
1808 -- emitting new work equalities where necessary to achieve that
1809 -- Very good short-cut when the two types are equal, or nearly so
1810 -- See Note [unifyWanted and unifyDerived]
1811 -- The returned coercion's role matches the input parameter
1812 unifyWanted loc Phantom ty1 ty2
1813 = do { kind_co <- unifyWanted loc Nominal (typeKind ty1) (typeKind ty2)
1814 ; return (mkPhantomCo kind_co ty1 ty2) }
1815
1816 unifyWanted loc role orig_ty1 orig_ty2
1817 = go orig_ty1 orig_ty2
1818 where
1819 go ty1 ty2 | Just ty1' <- coreView ty1 = go ty1' ty2
1820 go ty1 ty2 | Just ty2' <- coreView ty2 = go ty1 ty2'
1821
1822 go (FunTy s1 t1) (FunTy s2 t2)
1823 = do { co_s <- unifyWanted loc role s1 s2
1824 ; co_t <- unifyWanted loc role t1 t2
1825 ; return (mkTyConAppCo role funTyCon [co_s,co_t]) }
1826 go (TyConApp tc1 tys1) (TyConApp tc2 tys2)
1827 | tc1 == tc2, tys1 `equalLength` tys2
1828 , isInjectiveTyCon tc1 role -- don't look under newtypes at Rep equality
1829 = do { cos <- zipWith3M (unifyWanted loc)
1830 (tyConRolesX role tc1) tys1 tys2
1831 ; return (mkTyConAppCo role tc1 cos) }
1832
1833 go ty1@(TyVarTy tv) ty2
1834 = do { mb_ty <- isFilledMetaTyVar_maybe tv
1835 ; case mb_ty of
1836 Just ty1' -> go ty1' ty2
1837 Nothing -> bale_out ty1 ty2}
1838 go ty1 ty2@(TyVarTy tv)
1839 = do { mb_ty <- isFilledMetaTyVar_maybe tv
1840 ; case mb_ty of
1841 Just ty2' -> go ty1 ty2'
1842 Nothing -> bale_out ty1 ty2 }
1843
1844 go ty1@(CoercionTy {}) (CoercionTy {})
1845 = return (mkReflCo role ty1) -- we just don't care about coercions!
1846
1847 go ty1 ty2 = bale_out ty1 ty2
1848
1849 bale_out ty1 ty2
1850 | ty1 `tcEqType` ty2 = return (mkTcReflCo role ty1)
1851 -- Check for equality; e.g. a ~ a, or (m a) ~ (m a)
1852 | otherwise = emitNewWantedEq loc role orig_ty1 orig_ty2
1853
1854 unifyDeriveds :: CtLoc -> [Role] -> [TcType] -> [TcType] -> TcS ()
1855 -- See Note [unifyWanted and unifyDerived]
1856 unifyDeriveds loc roles tys1 tys2 = zipWith3M_ (unify_derived loc) roles tys1 tys2
1857
1858 unifyDerived :: CtLoc -> Role -> Pair TcType -> TcS ()
1859 -- See Note [unifyWanted and unifyDerived]
1860 unifyDerived loc role (Pair ty1 ty2) = unify_derived loc role ty1 ty2
1861
1862 unify_derived :: CtLoc -> Role -> TcType -> TcType -> TcS ()
1863 -- Create new Derived and put it in the work list
1864 -- Should do nothing if the two types are equal
1865 -- See Note [unifyWanted and unifyDerived]
1866 unify_derived _ Phantom _ _ = return ()
1867 unify_derived loc role orig_ty1 orig_ty2
1868 = go orig_ty1 orig_ty2
1869 where
1870 go ty1 ty2 | Just ty1' <- coreView ty1 = go ty1' ty2
1871 go ty1 ty2 | Just ty2' <- coreView ty2 = go ty1 ty2'
1872
1873 go (FunTy s1 t1) (FunTy s2 t2)
1874 = do { unify_derived loc role s1 s2
1875 ; unify_derived loc role t1 t2 }
1876 go (TyConApp tc1 tys1) (TyConApp tc2 tys2)
1877 | tc1 == tc2, tys1 `equalLength` tys2
1878 , isInjectiveTyCon tc1 role
1879 = unifyDeriveds loc (tyConRolesX role tc1) tys1 tys2
1880 go ty1@(TyVarTy tv) ty2
1881 = do { mb_ty <- isFilledMetaTyVar_maybe tv
1882 ; case mb_ty of
1883 Just ty1' -> go ty1' ty2
1884 Nothing -> bale_out ty1 ty2 }
1885 go ty1 ty2@(TyVarTy tv)
1886 = do { mb_ty <- isFilledMetaTyVar_maybe tv
1887 ; case mb_ty of
1888 Just ty2' -> go ty1 ty2'
1889 Nothing -> bale_out ty1 ty2 }
1890 go ty1 ty2 = bale_out ty1 ty2
1891
1892 bale_out ty1 ty2
1893 | ty1 `tcEqType` ty2 = return ()
1894 -- Check for equality; e.g. a ~ a, or (m a) ~ (m a)
1895 | otherwise = emitNewDerivedEq loc role orig_ty1 orig_ty2
1896
1897 maybeSym :: SwapFlag -> TcCoercion -> TcCoercion
1898 maybeSym IsSwapped co = mkTcSymCo co
1899 maybeSym NotSwapped co = co