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