Deal correctly with unused imports for 'coerce'
[ghc.git] / compiler / typecheck / TcCanonical.hs
1 {-# LANGUAGE CPP #-}
2
3 module TcCanonical(
4 canonicalize,
5 unifyDerived,
6 makeSuperClasses,
7 StopOrContinue(..), stopWith, continueWith
8 ) where
9
10 #include "HsVersions.h"
11
12 import TcRnTypes
13 import TcType
14 import Type
15 import TcFlatten
16 import TcSMonad
17 import TcEvidence
18 import Class
19 import TyCon
20 import TyCoRep -- cleverly decomposes types, good for completeness checking
21 import Coercion
22 import FamInstEnv ( FamInstEnvs )
23 import FamInst ( tcTopNormaliseNewTypeTF_maybe )
24 import Var
25 import Name( isSystemName )
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 = return [this_ct] -- cc_pend_sc of this_ct = True
436 | otherwise = do { sc_cts <- mk_strict_superclasses rec_clss' ev cls tys
437 ; return (this_ct : sc_cts) }
438 -- cc_pend_sc of this_ct = False
439 where
440 cls_nm = className cls
441 loop_found = cls_nm `elemNameSet` rec_clss
442 rec_clss' | isCTupleClass cls = rec_clss -- Never contribute to recursion
443 | otherwise = rec_clss `extendNameSet` cls_nm
444 this_ct = CDictCan { cc_ev = ev, cc_class = cls, cc_tyargs = tys
445 , cc_pend_sc = loop_found }
446 -- NB: If there is a loop, we cut off, so we have not
447 -- added the superclasses, hence cc_pend_sc = True
448
449 mk_strict_superclasses :: NameSet -> CtEvidence -> Class -> [Type] -> TcS [Ct]
450 -- Always return the immediate superclasses of (cls tys);
451 -- and expand their superclasses, provided none of them are in rec_clss
452 -- nor are repeated
453 mk_strict_superclasses rec_clss ev cls tys
454 | CtGiven { ctev_evar = evar, ctev_loc = loc } <- ev
455 = do { sc_evs <- newGivenEvVars (mk_given_loc loc)
456 (mkEvScSelectors (EvId evar) cls tys)
457 ; concatMapM (mk_superclasses rec_clss) sc_evs }
458
459 | isEmptyVarSet (tyCoVarsOfTypes tys)
460 = return [] -- Wanteds with no variables yield no deriveds.
461 -- See Note [Improvement from Ground Wanteds]
462
463 | otherwise -- Wanted/Derived case, just add those SC that can lead to improvement.
464 = do { let loc = ctEvLoc ev
465 ; sc_evs <- mapM (newDerivedNC loc) (immSuperClasses cls tys)
466 ; concatMapM (mk_superclasses rec_clss) sc_evs }
467 where
468 size = sizeTypes tys
469 mk_given_loc loc
470 | isCTupleClass cls
471 = loc -- For tuple predicates, just take them apart, without
472 -- adding their (large) size into the chain. When we
473 -- get down to a base predicate, we'll include its size.
474 -- Trac #10335
475
476 | GivenOrigin skol_info <- ctLocOrigin loc
477 -- See Note [Solving superclass constraints] in TcInstDcls
478 -- for explantation of this transformation for givens
479 = case skol_info of
480 InstSkol -> loc { ctl_origin = GivenOrigin (InstSC size) }
481 InstSC n -> loc { ctl_origin = GivenOrigin (InstSC (n `max` size)) }
482 _ -> loc
483
484 | otherwise -- Probably doesn't happen, since this function
485 = loc -- is only used for Givens, but does no harm
486
487
488 {-
489 ************************************************************************
490 * *
491 * Irreducibles canonicalization
492 * *
493 ************************************************************************
494 -}
495
496 canIrred :: CtEvidence -> TcS (StopOrContinue Ct)
497 -- Precondition: ty not a tuple and no other evidence form
498 canIrred old_ev
499 = do { let old_ty = ctEvPred old_ev
500 ; traceTcS "can_pred" (text "IrredPred = " <+> ppr old_ty)
501 ; (xi,co) <- flatten FM_FlattenAll old_ev old_ty -- co :: xi ~ old_ty
502 ; rewriteEvidence old_ev xi co `andWhenContinue` \ new_ev ->
503 do { -- Re-classify, in case flattening has improved its shape
504 ; case classifyPredType (ctEvPred new_ev) of
505 ClassPred cls tys -> canClassNC new_ev cls tys
506 EqPred eq_rel ty1 ty2 -> canEqNC new_ev eq_rel ty1 ty2
507 _ -> continueWith $
508 CIrredEvCan { cc_ev = new_ev } } }
509
510 canHole :: CtEvidence -> Hole -> TcS (StopOrContinue Ct)
511 canHole ev hole
512 = do { let ty = ctEvPred ev
513 ; (xi,co) <- flatten FM_SubstOnly ev ty -- co :: xi ~ ty
514 ; rewriteEvidence ev xi co `andWhenContinue` \ new_ev ->
515 do { emitInsoluble (CHoleCan { cc_ev = new_ev
516 , cc_hole = hole })
517 ; stopWith new_ev "Emit insoluble hole" } }
518
519 {-
520 ************************************************************************
521 * *
522 * Equalities
523 * *
524 ************************************************************************
525
526 Note [Canonicalising equalities]
527 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
528 In order to canonicalise an equality, we look at the structure of the
529 two types at hand, looking for similarities. A difficulty is that the
530 types may look dissimilar before flattening but similar after flattening.
531 However, we don't just want to jump in and flatten right away, because
532 this might be wasted effort. So, after looking for similarities and failing,
533 we flatten and then try again. Of course, we don't want to loop, so we
534 track whether or not we've already flattened.
535
536 It is conceivable to do a better job at tracking whether or not a type
537 is flattened, but this is left as future work. (Mar '15)
538 -}
539
540 canEqNC :: CtEvidence -> EqRel -> Type -> Type -> TcS (StopOrContinue Ct)
541 canEqNC ev eq_rel ty1 ty2
542 = do { result <- zonk_eq_types ty1 ty2
543 ; case result of
544 Left (Pair ty1' ty2') -> can_eq_nc False ev eq_rel ty1' ty1 ty2' ty2
545 Right ty -> canEqReflexive ev eq_rel ty }
546
547 can_eq_nc
548 :: Bool -- True => both types are flat
549 -> CtEvidence
550 -> EqRel
551 -> Type -> Type -- LHS, after and before type-synonym expansion, resp
552 -> Type -> Type -- RHS, after and before type-synonym expansion, resp
553 -> TcS (StopOrContinue Ct)
554 can_eq_nc flat ev eq_rel ty1 ps_ty1 ty2 ps_ty2
555 = do { traceTcS "can_eq_nc" $
556 vcat [ ppr flat, ppr ev, ppr eq_rel, ppr ty1, ppr ps_ty1, ppr ty2, ppr ps_ty2 ]
557 ; rdr_env <- getGlobalRdrEnvTcS
558 ; fam_insts <- getFamInstEnvs
559 ; can_eq_nc' flat rdr_env fam_insts ev eq_rel ty1 ps_ty1 ty2 ps_ty2 }
560
561 can_eq_nc'
562 :: Bool -- True => both input types are flattened
563 -> GlobalRdrEnv -- needed to see which newtypes are in scope
564 -> FamInstEnvs -- needed to unwrap data instances
565 -> CtEvidence
566 -> EqRel
567 -> Type -> Type -- LHS, after and before type-synonym expansion, resp
568 -> Type -> Type -- RHS, after and before type-synonym expansion, resp
569 -> TcS (StopOrContinue Ct)
570
571 -- Expand synonyms first; see Note [Type synonyms and canonicalization]
572 can_eq_nc' flat _rdr_env _envs ev eq_rel ty1 ps_ty1 ty2 ps_ty2
573 | Just ty1' <- coreView ty1 = can_eq_nc flat ev eq_rel ty1' ps_ty1 ty2 ps_ty2
574 | Just ty2' <- coreView ty2 = can_eq_nc flat ev eq_rel ty1 ps_ty1 ty2' ps_ty2
575
576 -- need to check for reflexivity in the ReprEq case.
577 -- See Note [Eager reflexivity check]
578 -- Check only when flat because the zonk_eq_types check in canEqNC takes
579 -- care of the non-flat case.
580 can_eq_nc' True _rdr_env _envs ev ReprEq ty1 _ ty2 _
581 | ty1 `tcEqType` ty2
582 = canEqReflexive ev ReprEq ty1
583
584 -- When working with ReprEq, unwrap newtypes.
585 can_eq_nc' _flat rdr_env envs ev ReprEq ty1 _ ty2 ps_ty2
586 | Just stuff1 <- tcTopNormaliseNewTypeTF_maybe envs rdr_env ty1
587 = can_eq_newtype_nc ev NotSwapped ty1 stuff1 ty2 ps_ty2
588 can_eq_nc' _flat rdr_env envs ev ReprEq ty1 ps_ty1 ty2 _
589 | Just stuff2 <- tcTopNormaliseNewTypeTF_maybe envs rdr_env ty2
590 = can_eq_newtype_nc ev IsSwapped ty2 stuff2 ty1 ps_ty1
591
592 -- Then, get rid of casts
593 can_eq_nc' flat _rdr_env _envs ev eq_rel (CastTy ty1 co1) _ ty2 ps_ty2
594 = canEqCast flat ev eq_rel NotSwapped ty1 co1 ty2 ps_ty2
595 can_eq_nc' flat _rdr_env _envs ev eq_rel ty1 ps_ty1 (CastTy ty2 co2) _
596 = canEqCast flat ev eq_rel IsSwapped ty2 co2 ty1 ps_ty1
597
598 ----------------------
599 -- Otherwise try to decompose
600 ----------------------
601
602 -- Literals
603 can_eq_nc' _flat _rdr_env _envs ev eq_rel ty1@(LitTy l1) _ (LitTy l2) _
604 | l1 == l2
605 = do { setEqIfWanted ev (mkReflCo (eqRelRole eq_rel) ty1)
606 ; stopWith ev "Equal LitTy" }
607
608 -- Try to decompose type constructor applications
609 -- Including FunTy (s -> t)
610 can_eq_nc' _flat _rdr_env _envs ev eq_rel ty1 _ ty2 _
611 | Just (tc1, tys1) <- tcRepSplitTyConApp_maybe ty1
612 , Just (tc2, tys2) <- tcRepSplitTyConApp_maybe ty2
613 , not (isTypeFamilyTyCon tc1)
614 , not (isTypeFamilyTyCon tc2)
615 = canTyConApp ev eq_rel tc1 tys1 tc2 tys2
616
617 can_eq_nc' _flat _rdr_env _envs ev eq_rel
618 s1@(ForAllTy {}) _ s2@(ForAllTy {}) _
619 | CtWanted { ctev_loc = loc, ctev_dest = orig_dest } <- ev
620 = do { let (bndrs1,body1) = tcSplitForAllTyVarBndrs s1
621 (bndrs2,body2) = tcSplitForAllTyVarBndrs s2
622 ; if not (equalLength bndrs1 bndrs2)
623 then do { traceTcS "Forall failure" $
624 vcat [ ppr s1, ppr s2, ppr bndrs1, ppr bndrs2
625 , ppr (map binderArgFlag bndrs1)
626 , ppr (map binderArgFlag bndrs2) ]
627 ; canEqHardFailure ev s1 s2 }
628 else
629 do { traceTcS "Creating implication for polytype equality" $ ppr ev
630 ; kind_cos <- zipWithM (unifyWanted loc Nominal)
631 (map binderKind bndrs1) (map binderKind bndrs2)
632 ; all_co <- deferTcSForAllEq (eqRelRole eq_rel) loc
633 kind_cos (bndrs1,body1) (bndrs2,body2)
634 ; setWantedEq orig_dest all_co
635 ; stopWith ev "Deferred polytype equality" } }
636 | otherwise
637 = do { traceTcS "Omitting decomposition of given polytype equality" $
638 pprEq s1 s2 -- See Note [Do not decompose given polytype equalities]
639 ; stopWith ev "Discard given polytype equality" }
640
641 -- See Note [Canonicalising type applications] about why we require flat types
642 can_eq_nc' True _rdr_env _envs ev eq_rel (AppTy t1 s1) _ ty2 _
643 | Just (t2, s2) <- tcSplitAppTy_maybe ty2
644 = can_eq_app ev eq_rel t1 s1 t2 s2
645 can_eq_nc' True _rdr_env _envs ev eq_rel ty1 _ (AppTy t2 s2) _
646 | Just (t1, s1) <- tcSplitAppTy_maybe ty1
647 = can_eq_app ev eq_rel t1 s1 t2 s2
648
649 -- No similarity in type structure detected. Flatten and try again.
650 can_eq_nc' False rdr_env envs ev eq_rel _ ps_ty1 _ ps_ty2
651 = do { (xi1, co1) <- flatten FM_FlattenAll ev ps_ty1
652 ; (xi2, co2) <- flatten FM_FlattenAll ev ps_ty2
653 ; rewriteEqEvidence ev NotSwapped xi1 xi2 co1 co2
654 `andWhenContinue` \ new_ev ->
655 can_eq_nc' True rdr_env envs new_ev eq_rel xi1 xi1 xi2 xi2 }
656
657 -- Type variable on LHS or RHS are last. We want only flat types sent
658 -- to canEqTyVar.
659 -- See also Note [No top-level newtypes on RHS of representational equalities]
660 can_eq_nc' True _rdr_env _envs ev eq_rel (TyVarTy tv1) _ _ ps_ty2
661 = canEqTyVar ev eq_rel NotSwapped tv1 ps_ty2
662 can_eq_nc' True _rdr_env _envs ev eq_rel _ ps_ty1 (TyVarTy tv2) _
663 = canEqTyVar ev eq_rel IsSwapped tv2 ps_ty1
664
665 -- We've flattened and the types don't match. Give up.
666 can_eq_nc' True _rdr_env _envs ev _eq_rel _ ps_ty1 _ ps_ty2
667 = do { traceTcS "can_eq_nc' catch-all case" (ppr ps_ty1 $$ ppr ps_ty2)
668 ; canEqHardFailure ev ps_ty1 ps_ty2 }
669
670 ---------------------------------
671 -- | Compare types for equality, while zonking as necessary. Gives up
672 -- as soon as it finds that two types are not equal.
673 -- This is quite handy when some unification has made two
674 -- types in an inert wanted to be equal. We can discover the equality without
675 -- flattening, which is sometimes very expensive (in the case of type functions).
676 -- In particular, this function makes a ~20% improvement in test case
677 -- perf/compiler/T5030.
678 --
679 -- Returns either the (partially zonked) types in the case of
680 -- inequality, or the one type in the case of equality. canEqReflexive is
681 -- a good next step in the 'Right' case. Returning 'Left' is always safe.
682 --
683 -- NB: This does *not* look through type synonyms. In fact, it treats type
684 -- synonyms as rigid constructors. In the future, it might be convenient
685 -- to look at only those arguments of type synonyms that actually appear
686 -- in the synonym RHS. But we're not there yet.
687 zonk_eq_types :: TcType -> TcType -> TcS (Either (Pair TcType) TcType)
688 zonk_eq_types = go
689 where
690 go (TyVarTy tv1) (TyVarTy tv2) = tyvar_tyvar tv1 tv2
691 go (TyVarTy tv1) ty2 = tyvar NotSwapped tv1 ty2
692 go ty1 (TyVarTy tv2) = tyvar IsSwapped tv2 ty1
693
694 go ty1 ty2
695 | Just (tc1, tys1) <- tcRepSplitTyConApp_maybe ty1
696 , Just (tc2, tys2) <- tcRepSplitTyConApp_maybe ty2
697 , tc1 == tc2
698 = tycon tc1 tys1 tys2
699
700 go ty1 ty2
701 | Just (ty1a, ty1b) <- tcRepSplitAppTy_maybe ty1
702 , Just (ty2a, ty2b) <- tcRepSplitAppTy_maybe ty2
703 = do { res_a <- go ty1a ty2a
704 ; res_b <- go ty1b ty2b
705 ; return $ combine_rev mkAppTy res_b res_a }
706
707 go ty1@(LitTy lit1) (LitTy lit2)
708 | lit1 == lit2
709 = return (Right ty1)
710
711 go ty1 ty2 = return $ Left (Pair ty1 ty2)
712 -- we don't handle more complex forms here
713
714 tyvar :: SwapFlag -> TcTyVar -> TcType
715 -> TcS (Either (Pair TcType) TcType)
716 -- try to do as little as possible, as anything we do here is redundant
717 -- with flattening. In particular, no need to zonk kinds. That's why
718 -- we don't use the already-defined zonking functions
719 tyvar swapped tv ty
720 = case tcTyVarDetails tv of
721 MetaTv { mtv_ref = ref }
722 -> do { cts <- readTcRef ref
723 ; case cts of
724 Flexi -> give_up
725 Indirect ty' -> unSwap swapped go ty' ty }
726 _ -> give_up
727 where
728 give_up = return $ Left $ unSwap swapped Pair (mkTyVarTy tv) ty
729
730 tyvar_tyvar tv1 tv2
731 | tv1 == tv2 = return (Right (mkTyVarTy tv1))
732 | otherwise = do { (ty1', progress1) <- quick_zonk tv1
733 ; (ty2', progress2) <- quick_zonk tv2
734 ; if progress1 || progress2
735 then go ty1' ty2'
736 else return $ Left (Pair (TyVarTy tv1) (TyVarTy tv2)) }
737
738 quick_zonk tv = case tcTyVarDetails tv of
739 MetaTv { mtv_ref = ref }
740 -> do { cts <- readTcRef ref
741 ; case cts of
742 Flexi -> return (TyVarTy tv, False)
743 Indirect ty' -> return (ty', True) }
744 _ -> return (TyVarTy tv, False)
745
746 -- This happens for type families, too. But recall that failure
747 -- here just means to try harder, so it's OK if the type function
748 -- isn't injective.
749 tycon :: TyCon -> [TcType] -> [TcType]
750 -> TcS (Either (Pair TcType) TcType)
751 tycon tc tys1 tys2
752 = do { results <- zipWithM go tys1 tys2
753 ; return $ case combine_results results of
754 Left tys -> Left (mkTyConApp tc <$> tys)
755 Right tys -> Right (mkTyConApp tc tys) }
756
757 combine_results :: [Either (Pair TcType) TcType]
758 -> Either (Pair [TcType]) [TcType]
759 combine_results = bimap (fmap reverse) reverse .
760 foldl' (combine_rev (:)) (Right [])
761
762 -- combine (in reverse) a new result onto an already-combined result
763 combine_rev :: (a -> b -> c)
764 -> Either (Pair b) b
765 -> Either (Pair a) a
766 -> Either (Pair c) c
767 combine_rev f (Left list) (Left elt) = Left (f <$> elt <*> list)
768 combine_rev f (Left list) (Right ty) = Left (f <$> pure ty <*> list)
769 combine_rev f (Right tys) (Left elt) = Left (f <$> elt <*> pure tys)
770 combine_rev f (Right tys) (Right ty) = Right (f ty tys)
771
772 {-
773 Note [Newtypes can blow the stack]
774 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
775 Suppose we have
776
777 newtype X = MkX (Int -> X)
778 newtype Y = MkY (Int -> Y)
779
780 and now wish to prove
781
782 [W] X ~R Y
783
784 This Wanted will loop, expanding out the newtypes ever deeper looking
785 for a solid match or a solid discrepancy. Indeed, there is something
786 appropriate to this looping, because X and Y *do* have the same representation,
787 in the limit -- they're both (Fix ((->) Int)). However, no finitely-sized
788 coercion will ever witness it. This loop won't actually cause GHC to hang,
789 though, because we check our depth when unwrapping newtypes.
790
791 Note [Eager reflexivity check]
792 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
793 Suppose we have
794
795 newtype X = MkX (Int -> X)
796
797 and
798
799 [W] X ~R X
800
801 Naively, we would start unwrapping X and end up in a loop. Instead,
802 we do this eager reflexivity check. This is necessary only for representational
803 equality because the flattener technology deals with the similar case
804 (recursive type families) for nominal equality.
805
806 Note that this check does not catch all cases, but it will catch the cases
807 we're most worried about, types like X above that are actually inhabited.
808
809 Here's another place where this reflexivity check is key:
810 Consider trying to prove (f a) ~R (f a). The AppTys in there can't
811 be decomposed, because representational equality isn't congruent with respect
812 to AppTy. So, when canonicalising the equality above, we get stuck and
813 would normally produce a CIrredEvCan. However, we really do want to
814 be able to solve (f a) ~R (f a). So, in the representational case only,
815 we do a reflexivity check.
816
817 (This would be sound in the nominal case, but unnecessary, and I [Richard
818 E.] am worried that it would slow down the common case.)
819 -}
820
821 ------------------------
822 -- | We're able to unwrap a newtype. Update the bits accordingly.
823 can_eq_newtype_nc :: CtEvidence -- ^ :: ty1 ~ ty2
824 -> SwapFlag
825 -> TcType -- ^ ty1
826 -> ((Bag GlobalRdrElt, TcCoercion), TcType) -- ^ :: ty1 ~ ty1'
827 -> TcType -- ^ ty2
828 -> TcType -- ^ ty2, with type synonyms
829 -> TcS (StopOrContinue Ct)
830 can_eq_newtype_nc ev swapped ty1 ((gres, co), ty1') ty2 ps_ty2
831 = do { traceTcS "can_eq_newtype_nc" $
832 vcat [ ppr ev, ppr swapped, ppr co, ppr gres, ppr ty1', ppr ty2 ]
833
834 -- check for blowing our stack:
835 -- See Note [Newtypes can blow the stack]
836 ; checkReductionDepth (ctEvLoc ev) ty1
837 ; addUsedGREs (bagToList gres)
838 -- we have actually used the newtype constructor here, so
839 -- make sure we don't warn about importing it!
840
841 ; rewriteEqEvidence ev swapped ty1' ps_ty2
842 (mkTcSymCo co) (mkTcReflCo Representational ps_ty2)
843 `andWhenContinue` \ new_ev ->
844 can_eq_nc False new_ev ReprEq ty1' ty1' ty2 ps_ty2 }
845
846 ---------
847 -- ^ Decompose a type application.
848 -- All input types must be flat. See Note [Canonicalising type applications]
849 can_eq_app :: CtEvidence -- :: s1 t1 ~r s2 t2
850 -> EqRel -- r
851 -> Xi -> Xi -- s1 t1
852 -> Xi -> Xi -- s2 t2
853 -> TcS (StopOrContinue Ct)
854
855 -- AppTys only decompose for nominal equality, so this case just leads
856 -- to an irreducible constraint; see typecheck/should_compile/T10494
857 -- See Note [Decomposing equality], note {4}
858 can_eq_app ev ReprEq _ _ _ _
859 = do { traceTcS "failing to decompose representational AppTy equality" (ppr ev)
860 ; continueWith (CIrredEvCan { cc_ev = ev }) }
861 -- no need to call canEqFailure, because that flattens, and the
862 -- types involved here are already flat
863
864 can_eq_app ev NomEq s1 t1 s2 t2
865 | CtDerived { ctev_loc = loc } <- ev
866 = do { unifyDeriveds loc [Nominal, Nominal] [s1, t1] [s2, t2]
867 ; stopWith ev "Decomposed [D] AppTy" }
868 | CtWanted { ctev_dest = dest, ctev_loc = loc } <- ev
869 = do { co_s <- unifyWanted loc Nominal s1 s2
870 ; co_t <- unifyWanted loc Nominal t1 t2
871 ; let co = mkAppCo co_s co_t
872 ; setWantedEq dest co
873 ; stopWith ev "Decomposed [W] AppTy" }
874 | CtGiven { ctev_evar = evar, ctev_loc = loc } <- ev
875 = do { let co = mkTcCoVarCo evar
876 co_s = mkTcLRCo CLeft co
877 co_t = mkTcLRCo CRight co
878 ; evar_s <- newGivenEvVar loc ( mkTcEqPredLikeEv ev s1 s2
879 , EvCoercion co_s )
880 ; evar_t <- newGivenEvVar loc ( mkTcEqPredLikeEv ev t1 t2
881 , EvCoercion co_t )
882 ; emitWorkNC [evar_t]
883 ; canEqNC evar_s NomEq s1 s2 }
884 | otherwise -- Can't happen
885 = error "can_eq_app"
886
887 -----------------------
888 -- | Break apart an equality over a casted type
889 -- looking like (ty1 |> co1) ~ ty2 (modulo a swap-flag)
890 canEqCast :: Bool -- are both types flat?
891 -> CtEvidence
892 -> EqRel
893 -> SwapFlag
894 -> TcType -> Coercion -- LHS (res. RHS), ty1 |> co1
895 -> TcType -> TcType -- RHS (res. LHS), ty2 both normal and pretty
896 -> TcS (StopOrContinue Ct)
897 canEqCast flat ev eq_rel swapped ty1 co1 ty2 ps_ty2
898 = do { traceTcS "Decomposing cast" (vcat [ ppr ev
899 , ppr ty1 <+> text "|>" <+> ppr co1
900 , ppr ps_ty2 ])
901 ; rewriteEqEvidence ev swapped ty1 ps_ty2
902 (mkTcReflCo role ty1
903 `mkTcCoherenceRightCo` co1)
904 (mkTcReflCo role ps_ty2)
905 `andWhenContinue` \ new_ev ->
906 can_eq_nc flat new_ev eq_rel ty1 ty1 ty2 ps_ty2 }
907 where
908 role = eqRelRole eq_rel
909
910 ------------------------
911 canTyConApp :: CtEvidence -> EqRel
912 -> TyCon -> [TcType]
913 -> TyCon -> [TcType]
914 -> TcS (StopOrContinue Ct)
915 -- See Note [Decomposing TyConApps]
916 canTyConApp ev eq_rel tc1 tys1 tc2 tys2
917 | tc1 == tc2
918 , length tys1 == length tys2
919 = do { inerts <- getTcSInerts
920 ; if can_decompose inerts
921 then do { traceTcS "canTyConApp"
922 (ppr ev $$ ppr eq_rel $$ ppr tc1 $$ ppr tys1 $$ ppr tys2)
923 ; canDecomposableTyConAppOK ev eq_rel tc1 tys1 tys2
924 ; stopWith ev "Decomposed TyConApp" }
925 else canEqFailure ev eq_rel ty1 ty2 }
926
927 -- Fail straight away for better error messages
928 -- See Note [Use canEqFailure in canDecomposableTyConApp]
929 | eq_rel == ReprEq && not (isGenerativeTyCon tc1 Representational &&
930 isGenerativeTyCon tc2 Representational)
931 = canEqFailure ev eq_rel ty1 ty2
932 | otherwise
933 = canEqHardFailure ev ty1 ty2
934 where
935 ty1 = mkTyConApp tc1 tys1
936 ty2 = mkTyConApp tc2 tys2
937
938 loc = ctEvLoc ev
939 pred = ctEvPred ev
940
941 -- See Note [Decomposing equality]
942 can_decompose inerts
943 = isInjectiveTyCon tc1 (eqRelRole eq_rel)
944 || (ctEvFlavour ev /= Given && isEmptyBag (matchableGivens loc pred inerts))
945
946 {-
947 Note [Use canEqFailure in canDecomposableTyConApp]
948 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
949 We must use canEqFailure, not canEqHardFailure here, because there is
950 the possibility of success if working with a representational equality.
951 Here is one case:
952
953 type family TF a where TF Char = Bool
954 data family DF a
955 newtype instance DF Bool = MkDF Int
956
957 Suppose we are canonicalising (Int ~R DF (TF a)), where we don't yet
958 know `a`. This is *not* a hard failure, because we might soon learn
959 that `a` is, in fact, Char, and then the equality succeeds.
960
961 Here is another case:
962
963 [G] Age ~R Int
964
965 where Age's constructor is not in scope. We don't want to report
966 an "inaccessible code" error in the context of this Given!
967
968 For example, see typecheck/should_compile/T10493, repeated here:
969
970 import Data.Ord (Down) -- no constructor
971
972 foo :: Coercible (Down Int) Int => Down Int -> Int
973 foo = coerce
974
975 That should compile, but only because we use canEqFailure and not
976 canEqHardFailure.
977
978 Note [Decomposing equality]
979 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
980 If we have a constraint (of any flavour and role) that looks like
981 T tys1 ~ T tys2, what can we conclude about tys1 and tys2? The answer,
982 of course, is "it depends". This Note spells it all out.
983
984 In this Note, "decomposition" refers to taking the constraint
985 [fl] (T tys1 ~X T tys2)
986 (for some flavour fl and some role X) and replacing it with
987 [fls'] (tys1 ~Xs' tys2)
988 where that notation indicates a list of new constraints, where the
989 new constraints may have different flavours and different roles.
990
991 The key property to consider is injectivity. When decomposing a Given the
992 decomposition is sound if and only if T is injective in all of its type
993 arguments. When decomposing a Wanted, the decomposition is sound (assuming the
994 correct roles in the produced equality constraints), but it may be a guess --
995 that is, an unforced decision by the constraint solver. Decomposing Wanteds
996 over injective TyCons does not entail guessing. But sometimes we want to
997 decompose a Wanted even when the TyCon involved is not injective! (See below.)
998
999 So, in broad strokes, we want this rule:
1000
1001 (*) Decompose a constraint (T tys1 ~X T tys2) if and only if T is injective
1002 at role X.
1003
1004 Pursuing the details requires exploring three axes:
1005 * Flavour: Given vs. Derived vs. Wanted
1006 * Role: Nominal vs. Representational
1007 * TyCon species: datatype vs. newtype vs. data family vs. type family vs. type variable
1008
1009 (So a type variable isn't a TyCon, but it's convenient to put the AppTy case
1010 in the same table.)
1011
1012 Right away, we can say that Derived behaves just as Wanted for the purposes
1013 of decomposition. The difference between Derived and Wanted is the handling of
1014 evidence. Since decomposition in these cases isn't a matter of soundness but of
1015 guessing, we want the same behavior regardless of evidence.
1016
1017 Here is a table (discussion following) detailing where decomposition of
1018 (T s1 ... sn) ~r (T t1 .. tn)
1019 is allowed. The first four lines (Data types ... type family) refer
1020 to TyConApps with various TyCons T; the last line is for AppTy, where
1021 there is presumably a type variable at the head, so it's actually
1022 (s s1 ... sn) ~r (t t1 .. tn)
1023
1024 NOMINAL GIVEN WANTED
1025
1026 Datatype YES YES
1027 Newtype YES YES
1028 Data family YES YES
1029 Type family YES, in injective args{1} YES, in injective args{1}
1030 Type variable YES YES
1031
1032 REPRESENTATIONAL GIVEN WANTED
1033
1034 Datatype YES YES
1035 Newtype NO{2} MAYBE{2}
1036 Data family NO{3} MAYBE{3}
1037 Type family NO NO
1038 Type variable NO{4} NO{4}
1039
1040 {1}: Type families can be injective in some, but not all, of their arguments,
1041 so we want to do partial decomposition. This is quite different than the way
1042 other decomposition is done, where the decomposed equalities replace the original
1043 one. We thus proceed much like we do with superclasses: emitting new Givens
1044 when "decomposing" a partially-injective type family Given and new Deriveds
1045 when "decomposing" a partially-injective type family Wanted. (As of the time of
1046 writing, 13 June 2015, the implementation of injective type families has not
1047 been merged, but it should be soon. Please delete this parenthetical if the
1048 implementation is indeed merged.)
1049
1050 {2}: See Note [Decomposing newtypes at representational role]
1051
1052 {3}: Because of the possibility of newtype instances, we must treat
1053 data families like newtypes. See also Note [Decomposing newtypes at
1054 representational role]. See #10534 and test case
1055 typecheck/should_fail/T10534.
1056
1057 {4}: Because type variables can stand in for newtypes, we conservatively do not
1058 decompose AppTys over representational equality.
1059
1060 In the implementation of can_eq_nc and friends, we don't directly pattern
1061 match using lines like in the tables above, as those tables don't cover
1062 all cases (what about PrimTyCon? tuples?). Instead we just ask about injectivity,
1063 boiling the tables above down to rule (*). The exceptions to rule (*) are for
1064 injective type families, which are handled separately from other decompositions,
1065 and the MAYBE entries above.
1066
1067 Note [Decomposing newtypes at representational role]
1068 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1069 This note discusses the 'newtype' line in the REPRESENTATIONAL table
1070 in Note [Decomposing equality]. (At nominal role, newtypes are fully
1071 decomposable.)
1072
1073 Here is a representative example of why representational equality over
1074 newtypes is tricky:
1075
1076 newtype Nt a = Mk Bool -- NB: a is not used in the RHS,
1077 type role Nt representational -- but the user gives it an R role anyway
1078
1079 If we have [W] Nt alpha ~R Nt beta, we *don't* want to decompose to
1080 [W] alpha ~R beta, because it's possible that alpha and beta aren't
1081 representationally equal. Here's another example.
1082
1083 newtype Nt a = MkNt (Id a)
1084 type family Id a where Id a = a
1085
1086 [W] Nt Int ~R Nt Age
1087
1088 Because of its use of a type family, Nt's parameter will get inferred to have
1089 a nominal role. Thus, decomposing the wanted will yield [W] Int ~N Age, which
1090 is unsatisfiable. Unwrapping, though, leads to a solution.
1091
1092 Conclusion:
1093 * Unwrap newtypes before attempting to decompose them.
1094 This is done in can_eq_nc'.
1095
1096 It all comes from the fact that newtypes aren't necessarily injective
1097 w.r.t. representational equality.
1098
1099 Furthermore, as explained in Note [NthCo and newtypes] in TyCoRep, we can't use
1100 NthCo on representational coercions over newtypes. NthCo comes into play
1101 only when decomposing givens.
1102
1103 Conclusion:
1104 * Do not decompose [G] N s ~R N t
1105
1106 Is it sensible to decompose *Wanted* constraints over newtypes? Yes!
1107 It's the only way we could ever prove (IO Int ~R IO Age), recalling
1108 that IO is a newtype.
1109
1110 However we must be careful. Consider
1111
1112 type role Nt representational
1113
1114 [G] Nt a ~R Nt b (1)
1115 [W] NT alpha ~R Nt b (2)
1116 [W] alpha ~ a (3)
1117
1118 If we focus on (3) first, we'll substitute in (2), and now it's
1119 identical to the given (1), so we succeed. But if we focus on (2)
1120 first, and decompose it, we'll get (alpha ~R b), which is not soluble.
1121 This is exactly like the question of overlapping Givens for class
1122 constraints: see Note [Instance and Given overlap] in TcInteract.
1123
1124 Conclusion:
1125 * Decompose [W] N s ~R N t iff there no given constraint that could
1126 later solve it.
1127 -}
1128
1129 canDecomposableTyConAppOK :: CtEvidence -> EqRel
1130 -> TyCon -> [TcType] -> [TcType]
1131 -> TcS ()
1132 -- Precondition: tys1 and tys2 are the same length, hence "OK"
1133 canDecomposableTyConAppOK ev eq_rel tc tys1 tys2
1134 = case ev of
1135 CtDerived {}
1136 -> unifyDeriveds loc tc_roles tys1 tys2
1137
1138 CtWanted { ctev_dest = dest }
1139 -> do { cos <- zipWith4M unifyWanted new_locs tc_roles tys1 tys2
1140 ; setWantedEq dest (mkTyConAppCo role tc cos) }
1141
1142 CtGiven { ctev_evar = evar }
1143 -> do { let ev_co = mkCoVarCo evar
1144 ; given_evs <- newGivenEvVars loc $
1145 [ ( mkPrimEqPredRole r ty1 ty2
1146 , EvCoercion (mkNthCo i ev_co) )
1147 | (r, ty1, ty2, i) <- zip4 tc_roles tys1 tys2 [0..]
1148 , r /= Phantom
1149 , not (isCoercionTy ty1) && not (isCoercionTy ty2) ]
1150 ; emitWorkNC given_evs }
1151 where
1152 loc = ctEvLoc ev
1153 role = eqRelRole eq_rel
1154 tc_roles = tyConRolesX role tc
1155
1156 -- the following makes a better distinction between "kind" and "type"
1157 -- in error messages
1158 bndrs = tyConBinders tc
1159 kind_loc = toKindLoc loc
1160 is_kinds = map isNamedTyConBinder bndrs
1161 new_locs | Just KindLevel <- ctLocTypeOrKind_maybe loc
1162 = repeat loc
1163 | otherwise
1164 = map (\is_kind -> if is_kind then kind_loc else loc) is_kinds
1165
1166
1167 -- | Call when canonicalizing an equality fails, but if the equality is
1168 -- representational, there is some hope for the future.
1169 -- Examples in Note [Use canEqFailure in canDecomposableTyConApp]
1170 canEqFailure :: CtEvidence -> EqRel
1171 -> TcType -> TcType -> TcS (StopOrContinue Ct)
1172 canEqFailure ev NomEq ty1 ty2
1173 = canEqHardFailure ev ty1 ty2
1174 canEqFailure ev ReprEq ty1 ty2
1175 = do { (xi1, co1) <- flatten FM_FlattenAll ev ty1
1176 ; (xi2, co2) <- flatten FM_FlattenAll ev ty2
1177 -- We must flatten the types before putting them in the
1178 -- inert set, so that we are sure to kick them out when
1179 -- new equalities become available
1180 ; traceTcS "canEqFailure with ReprEq" $
1181 vcat [ ppr ev, ppr ty1, ppr ty2, ppr xi1, ppr xi2 ]
1182 ; rewriteEqEvidence ev NotSwapped xi1 xi2 co1 co2
1183 `andWhenContinue` \ new_ev ->
1184 continueWith (CIrredEvCan { cc_ev = new_ev }) }
1185
1186 -- | Call when canonicalizing an equality fails with utterly no hope.
1187 canEqHardFailure :: CtEvidence
1188 -> TcType -> TcType -> TcS (StopOrContinue Ct)
1189 -- See Note [Make sure that insolubles are fully rewritten]
1190 canEqHardFailure ev ty1 ty2
1191 = do { (s1, co1) <- flatten FM_SubstOnly ev ty1
1192 ; (s2, co2) <- flatten FM_SubstOnly ev ty2
1193 ; rewriteEqEvidence ev NotSwapped s1 s2 co1 co2
1194 `andWhenContinue` \ new_ev ->
1195 do { emitInsoluble (mkNonCanonical new_ev)
1196 ; stopWith new_ev "Definitely not equal" }}
1197
1198 {-
1199 Note [Decomposing TyConApps]
1200 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1201 If we see (T s1 t1 ~ T s2 t2), then we can just decompose to
1202 (s1 ~ s2, t1 ~ t2)
1203 and push those back into the work list. But if
1204 s1 = K k1 s2 = K k2
1205 then we will just decomopose s1~s2, and it might be better to
1206 do so on the spot. An important special case is where s1=s2,
1207 and we get just Refl.
1208
1209 So canDecomposableTyCon is a fast-path decomposition that uses
1210 unifyWanted etc to short-cut that work.
1211
1212 Note [Canonicalising type applications]
1213 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1214 Given (s1 t1) ~ ty2, how should we proceed?
1215 The simple things is to see if ty2 is of form (s2 t2), and
1216 decompose. By this time s1 and s2 can't be saturated type
1217 function applications, because those have been dealt with
1218 by an earlier equation in can_eq_nc, so it is always sound to
1219 decompose.
1220
1221 However, over-eager decomposition gives bad error messages
1222 for things like
1223 a b ~ Maybe c
1224 e f ~ p -> q
1225 Suppose (in the first example) we already know a~Array. Then if we
1226 decompose the application eagerly, yielding
1227 a ~ Maybe
1228 b ~ c
1229 we get an error "Can't match Array ~ Maybe",
1230 but we'd prefer to get "Can't match Array b ~ Maybe c".
1231
1232 So instead can_eq_wanted_app flattens the LHS and RHS, in the hope of
1233 replacing (a b) by (Array b), before using try_decompose_app to
1234 decompose it.
1235
1236 Note [Make sure that insolubles are fully rewritten]
1237 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1238 When an equality fails, we still want to rewrite the equality
1239 all the way down, so that it accurately reflects
1240 (a) the mutable reference substitution in force at start of solving
1241 (b) any ty-binds in force at this point in solving
1242 See Note [Kick out insolubles] in TcSMonad.
1243 And if we don't do this there is a bad danger that
1244 TcSimplify.applyTyVarDefaulting will find a variable
1245 that has in fact been substituted.
1246
1247 Note [Do not decompose Given polytype equalities]
1248 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1249 Consider [G] (forall a. t1 ~ forall a. t2). Can we decompose this?
1250 No -- what would the evidence look like? So instead we simply discard
1251 this given evidence.
1252
1253
1254 Note [Combining insoluble constraints]
1255 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1256 As this point we have an insoluble constraint, like Int~Bool.
1257
1258 * If it is Wanted, delete it from the cache, so that subsequent
1259 Int~Bool constraints give rise to separate error messages
1260
1261 * But if it is Derived, DO NOT delete from cache. A class constraint
1262 may get kicked out of the inert set, and then have its functional
1263 dependency Derived constraints generated a second time. In that
1264 case we don't want to get two (or more) error messages by
1265 generating two (or more) insoluble fundep constraints from the same
1266 class constraint.
1267
1268 Note [No top-level newtypes on RHS of representational equalities]
1269 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1270 Suppose we're in this situation:
1271
1272 work item: [W] c1 : a ~R b
1273 inert: [G] c2 : b ~R Id a
1274
1275 where
1276 newtype Id a = Id a
1277
1278 We want to make sure canEqTyVar sees [W] a ~R a, after b is flattened
1279 and the Id newtype is unwrapped. This is assured by requiring only flat
1280 types in canEqTyVar *and* having the newtype-unwrapping check above
1281 the tyvar check in can_eq_nc.
1282
1283 Note [Occurs check error]
1284 ~~~~~~~~~~~~~~~~~~~~~~~~~
1285 If we have an occurs check error, are we necessarily hosed? Say our
1286 tyvar is tv1 and the type it appears in is xi2. Because xi2 is function
1287 free, then if we're computing w.r.t. nominal equality, then, yes, we're
1288 hosed. Nothing good can come from (a ~ [a]). If we're computing w.r.t.
1289 representational equality, this is a little subtler. Once again, (a ~R [a])
1290 is a bad thing, but (a ~R N a) for a newtype N might be just fine. This
1291 means also that (a ~ b a) might be fine, because `b` might become a newtype.
1292
1293 So, we must check: does tv1 appear in xi2 under any type constructor that
1294 is generative w.r.t. representational equality? That's what isTyVarUnderDatatype
1295 does. (The other name I considered, isTyVarUnderTyConGenerativeWrtReprEq was
1296 a bit verbose. And the shorter name gets the point across.)
1297
1298 See also #10715, which induced this addition.
1299
1300 Note [No derived kind equalities]
1301 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1302 When we're working with a heterogeneous derived equality
1303
1304 [D] (t1 :: k1) ~ (t2 :: k2)
1305
1306 we want to homogenise to establish the kind invariant on CTyEqCans.
1307 But we can't emit [D] k1 ~ k2 because we wouldn't then be able to
1308 use the evidence in the homogenised types. So we emit a wanted
1309 constraint, because we do really need the evidence here.
1310
1311 Thus: no derived kind equalities.
1312
1313 -}
1314
1315 canCFunEqCan :: CtEvidence
1316 -> TyCon -> [TcType] -- LHS
1317 -> TcTyVar -- RHS
1318 -> TcS (StopOrContinue Ct)
1319 -- ^ Canonicalise a CFunEqCan. We know that
1320 -- the arg types are already flat,
1321 -- and the RHS is a fsk, which we must *not* substitute.
1322 -- So just substitute in the LHS
1323 canCFunEqCan ev fn tys fsk
1324 = do { (tys', cos) <- flattenManyNom ev tys
1325 -- cos :: tys' ~ tys
1326 ; let lhs_co = mkTcTyConAppCo Nominal fn cos
1327 -- :: F tys' ~ F tys
1328 new_lhs = mkTyConApp fn tys'
1329 fsk_ty = mkTyVarTy fsk
1330 ; rewriteEqEvidence ev NotSwapped new_lhs fsk_ty
1331 lhs_co (mkTcNomReflCo fsk_ty)
1332 `andWhenContinue` \ ev' ->
1333 do { extendFlatCache fn tys' (ctEvCoercion ev', fsk_ty, ctEvFlavour ev')
1334 ; continueWith (CFunEqCan { cc_ev = ev', cc_fun = fn
1335 , cc_tyargs = tys', cc_fsk = fsk }) } }
1336
1337 ---------------------
1338 canEqTyVar :: CtEvidence -> EqRel -> SwapFlag
1339 -> TcTyVar -- already flat
1340 -> TcType -- already flat
1341 -> TcS (StopOrContinue Ct)
1342 -- A TyVar on LHS, but so far un-zonked
1343 canEqTyVar ev eq_rel swapped tv1 ps_ty2 -- ev :: tv ~ s2
1344 = do { traceTcS "canEqTyVar" (ppr tv1 $$ ppr ps_ty2 $$ ppr swapped)
1345 -- FM_Avoid commented out: see Note [Lazy flattening] in TcFlatten
1346 -- let fmode = FE { fe_ev = ev, fe_mode = FM_Avoid tv1' True }
1347 -- Flatten the RHS less vigorously, to avoid gratuitous flattening
1348 -- True <=> xi2 should not itself be a type-function application
1349 ; dflags <- getDynFlags
1350 ; canEqTyVar2 dflags ev eq_rel swapped tv1 ps_ty2 }
1351
1352 canEqTyVar2 :: DynFlags
1353 -> CtEvidence -- lhs ~ rhs (or, if swapped, orhs ~ olhs)
1354 -> EqRel
1355 -> SwapFlag
1356 -> TcTyVar -- lhs, flat
1357 -> TcType -- rhs, flat
1358 -> TcS (StopOrContinue Ct)
1359 -- LHS is an inert type variable,
1360 -- and RHS is fully rewritten, but with type synonyms
1361 -- preserved as much as possible
1362
1363 canEqTyVar2 dflags ev eq_rel swapped tv1 xi2
1364 | Just (tv2, kco2) <- getCastedTyVar_maybe xi2
1365 = canEqTyVarTyVar ev eq_rel swapped tv1 tv2 kco2
1366
1367 | OC_OK xi2' <- occurCheckExpand dflags tv1 xi2 -- No occurs check
1368 -- We use xi2' on the RHS of the new CTyEqCan, a ~ xi2'
1369 -- to establish the invariant that a does not appear in the
1370 -- rhs of the CTyEqCan. This is guaranteed by occurCheckExpand;
1371 -- see Note [Occurs check expansion] in TcType
1372 = rewriteEqEvidence ev swapped xi1 xi2' co1 (mkTcReflCo role xi2')
1373 `andWhenContinue` \ new_ev ->
1374 homogeniseRhsKind new_ev eq_rel xi1 xi2' $ \new_new_ev xi2'' ->
1375 CTyEqCan { cc_ev = new_new_ev, cc_tyvar = tv1
1376 , cc_rhs = xi2'', cc_eq_rel = eq_rel }
1377
1378 | otherwise -- Occurs check error
1379 = do { traceTcS "canEqTyVar2 occurs check error" (ppr tv1 $$ ppr xi2)
1380 ; rewriteEqEvidence ev swapped xi1 xi2 co1 co2
1381 `andWhenContinue` \ new_ev ->
1382 if eq_rel == NomEq || isTyVarUnderDatatype tv1 xi2
1383 then do { emitInsoluble (mkNonCanonical new_ev)
1384 -- If we have a ~ [a], it is not canonical, and in particular
1385 -- we don't want to rewrite existing inerts with it, otherwise
1386 -- we'd risk divergence in the constraint solver
1387 ; stopWith new_ev "Occurs check" }
1388
1389 -- A representational equality with an occurs-check problem isn't
1390 -- insoluble! For example:
1391 -- a ~R b a
1392 -- We might learn that b is the newtype Id.
1393 -- But, the occurs-check certainly prevents the equality from being
1394 -- canonical, and we might loop if we were to use it in rewriting.
1395 else do { traceTcS "Occurs-check in representational equality"
1396 (ppr xi1 $$ ppr xi2)
1397 ; continueWith (CIrredEvCan { cc_ev = new_ev }) } }
1398 where
1399 role = eqRelRole eq_rel
1400 xi1 = mkTyVarTy tv1
1401 co1 = mkTcReflCo role xi1
1402 co2 = mkTcReflCo role xi2
1403
1404 canEqTyVarTyVar :: CtEvidence -- tv1 ~ rhs (or rhs ~ tv1, if swapped)
1405 -> EqRel
1406 -> SwapFlag
1407 -> TcTyVar -> TcTyVar -- tv1, tv2
1408 -> Coercion -- the co in (rhs = tv2 |> co)
1409 -> TcS (StopOrContinue Ct)
1410 -- Both LHS and RHS rewrote to a type variable
1411 -- See Note [Canonical orientation for tyvar/tyvar equality constraints]
1412 canEqTyVarTyVar ev eq_rel swapped tv1 tv2 kco2
1413 | tv1 == tv2
1414 = do { let mk_coh = case swapped of IsSwapped -> mkTcCoherenceLeftCo
1415 NotSwapped -> mkTcCoherenceRightCo
1416 ; setEvBindIfWanted ev (EvCoercion $ mkTcReflCo role xi1 `mk_coh` kco2)
1417 ; stopWith ev "Equal tyvars" }
1418
1419 -- We don't do this any more
1420 -- See Note [Orientation of equalities with fmvs] in TcFlatten
1421 -- | isFmvTyVar tv1 = do_fmv swapped tv1 xi1 xi2 co1 co2
1422 -- | isFmvTyVar tv2 = do_fmv (flipSwap swapped) tv2 xi2 xi1 co2 co1
1423
1424 | swap_over = do_swap
1425 | otherwise = no_swap
1426 where
1427 role = eqRelRole eq_rel
1428 xi1 = mkTyVarTy tv1
1429 co1 = mkTcReflCo role xi1
1430 xi2 = mkTyVarTy tv2
1431 co2 = mkTcReflCo role xi2 `mkTcCoherenceRightCo` kco2
1432
1433 no_swap = canon_eq swapped tv1 xi1 xi2 co1 co2
1434 do_swap = canon_eq (flipSwap swapped) tv2 xi2 xi1 co2 co1
1435
1436 canon_eq swapped tv1 ty1 ty2 co1 co2
1437 -- ev : tv1 ~ orhs (not swapped) or orhs ~ tv1 (swapped)
1438 -- co1 : xi1 ~ tv1
1439 -- co2 : xi2 ~ tv2
1440 = do { traceTcS "canEqTyVarTyVar"
1441 (vcat [ ppr swapped
1442 , ppr tv1 <+> dcolon <+> ppr (tyVarKind tv1)
1443 , ppr ty1 <+> dcolon <+> ppr (typeKind ty1)
1444 , ppr ty2 <+> dcolon <+> ppr (typeKind ty2)
1445 , ppr co1 <+> dcolon <+> ppr (tcCoercionKind co1)
1446 , ppr co2 <+> dcolon <+> ppr (tcCoercionKind co2) ])
1447 ; rewriteEqEvidence ev swapped ty1 ty2 co1 co2
1448 `andWhenContinue` \ new_ev ->
1449 homogeniseRhsKind new_ev eq_rel ty1 ty2 $ \new_new_ev ty2' ->
1450 CTyEqCan { cc_ev = new_new_ev, cc_tyvar = tv1
1451 , cc_rhs = ty2', cc_eq_rel = eq_rel } }
1452
1453 {- We don't do this any more
1454 See Note [Orientation of equalities with fmvs] in TcFlatten
1455 -- tv1 is the flatten meta-var
1456 do_fmv swapped tv1 xi1 xi2 co1 co2
1457 | same_kind
1458 = canon_eq swapped tv1 xi1 xi2 co1 co2
1459 | otherwise -- Presumably tv1 :: *, since it is a flatten meta-var,
1460 -- at a kind that has some interesting sub-kind structure.
1461 -- Since the two kinds are not the same, we must have
1462 -- tv1 `subKind` tv2, which is the wrong way round
1463 -- e.g. (fmv::*) ~ (a::OpenKind)
1464 -- So make a new meta-var and use that:
1465 -- fmv ~ (beta::*)
1466 -- (a::OpenKind) ~ (beta::*)
1467 = ASSERT2( k1_sub_k2,
1468 ppr tv1 <+> dcolon <+> ppr (tyVarKind tv1) $$
1469 ppr xi2 <+> dcolon <+> ppr (typeKind xi2) )
1470 ASSERT2( isWanted ev, ppr ev ) -- Only wanteds have flatten meta-vars
1471 do { tv_ty <- newFlexiTcSTy (tyVarKind tv1)
1472 ; new_ev <- newWantedEvVarNC (ctEvLoc ev)
1473 (mkPrimEqPredRole (eqRelRole eq_rel)
1474 g tv_ty xi2)
1475 ; emitWorkNC [new_ev]
1476 ; canon_eq swapped tv1 xi1 tv_ty co1 (ctEvCoercion new_ev) }
1477 -}
1478
1479 swap_over
1480 -- If tv1 is touchable, swap only if tv2 is also
1481 -- touchable and it's strictly better to update the latter
1482 -- But see Note [Avoid unnecessary swaps]
1483 | Just lvl1 <- metaTyVarTcLevel_maybe tv1
1484 = case metaTyVarTcLevel_maybe tv2 of
1485 Nothing -> False
1486 Just lvl2 | lvl2 `strictlyDeeperThan` lvl1 -> True
1487 | lvl1 `strictlyDeeperThan` lvl2 -> False
1488 | otherwise -> nicer_to_update_tv2
1489
1490 -- So tv1 is not a meta tyvar
1491 -- If only one is a meta tyvar, put it on the left
1492 -- This is not because it'll be solved; but because
1493 -- the floating step looks for meta tyvars on the left
1494 | isMetaTyVar tv2 = True
1495
1496 -- So neither is a meta tyvar (including FlatMetaTv)
1497
1498 -- If only one is a flatten skolem, put it on the left
1499 -- See Note [Eliminate flat-skols]
1500 | not (isFlattenTyVar tv1), isFlattenTyVar tv2 = True
1501
1502 | otherwise = False
1503
1504 nicer_to_update_tv2
1505 = (isSigTyVar tv1 && not (isSigTyVar tv2))
1506 || (isSystemName (Var.varName tv2) && not (isSystemName (Var.varName tv1)))
1507
1508 -- | Solve a reflexive equality constraint
1509 canEqReflexive :: CtEvidence -- ty ~ ty
1510 -> EqRel
1511 -> TcType -- ty
1512 -> TcS (StopOrContinue Ct) -- always Stop
1513 canEqReflexive ev eq_rel ty
1514 = do { setEvBindIfWanted ev (EvCoercion $
1515 mkTcReflCo (eqRelRole eq_rel) ty)
1516 ; stopWith ev "Solved by reflexivity" }
1517
1518 -- See Note [Equalities with incompatible kinds]
1519 homogeniseRhsKind :: CtEvidence -- ^ the evidence to homogenise
1520 -> EqRel
1521 -> TcType -- ^ original LHS
1522 -> Xi -- ^ original RHS
1523 -> (CtEvidence -> Xi -> Ct)
1524 -- ^ how to build the homogenised constraint;
1525 -- the 'Xi' is the new RHS
1526 -> TcS (StopOrContinue Ct)
1527 homogeniseRhsKind ev eq_rel lhs rhs build_ct
1528 | k1 `tcEqType` k2
1529 = continueWith (build_ct ev rhs)
1530
1531 | CtGiven { ctev_evar = evar } <- ev
1532 -- tm :: (lhs :: k1) ~ (rhs :: k2)
1533 = do { kind_ev_id <- newBoundEvVarId kind_pty
1534 (EvCoercion $
1535 mkTcKindCo $ mkTcCoVarCo evar)
1536 -- kind_ev_id :: (k1 :: *) ~# (k2 :: *)
1537 ; let kind_ev = CtGiven { ctev_pred = kind_pty
1538 , ctev_evar = kind_ev_id
1539 , ctev_loc = kind_loc }
1540 homo_co = mkSymCo $ mkCoVarCo kind_ev_id
1541 rhs' = mkCastTy rhs homo_co
1542 ; traceTcS "Hetero equality gives rise to given kind equality"
1543 (ppr kind_ev_id <+> dcolon <+> ppr kind_pty)
1544 ; emitWorkNC [kind_ev]
1545 ; type_ev <- newGivenEvVar loc
1546 ( mkTcEqPredLikeEv ev lhs rhs'
1547 , EvCoercion $
1548 mkTcCoherenceRightCo (mkTcCoVarCo evar) homo_co )
1549 -- type_ev :: (lhs :: k1) ~ ((rhs |> sym kind_ev_id) :: k1)
1550 ; continueWith (build_ct type_ev rhs') }
1551
1552 | otherwise -- Wanted and Derived. See Note [No derived kind equalities]
1553 -- evar :: (lhs :: k1) ~ (rhs :: k2)
1554 = do { (kind_ev, kind_co) <- newWantedEq kind_loc Nominal k1 k2
1555 -- kind_ev :: (k1 :: *) ~ (k2 :: *)
1556 ; traceTcS "Hetero equality gives rise to wanted kind equality" $
1557 ppr (kind_ev)
1558 ; emitWorkNC [kind_ev]
1559 ; let homo_co = mkSymCo kind_co
1560 -- homo_co :: k2 ~ k1
1561 rhs' = mkCastTy rhs homo_co
1562 ; case ev of
1563 CtGiven {} -> panic "homogeniseRhsKind"
1564 CtDerived {} -> continueWith (build_ct (ev { ctev_pred = homo_pred })
1565 rhs')
1566 where homo_pred = mkTcEqPredLikeEv ev lhs rhs'
1567 CtWanted { ctev_dest = dest } -> do
1568 { (type_ev, hole_co) <- newWantedEq loc role lhs rhs'
1569 -- type_ev :: (lhs :: k1) ~ (rhs |> sym kind_ev :: k1)
1570 ; setWantedEq dest
1571 (hole_co `mkTransCo`
1572 (mkReflCo role rhs
1573 `mkCoherenceLeftCo` homo_co))
1574
1575 -- dest := hole ; <rhs> |> homo_co :: (lhs :: k1) ~ (rhs :: k2)
1576 ; continueWith (build_ct type_ev rhs') }}
1577
1578 where
1579 k1 = typeKind lhs
1580 k2 = typeKind rhs
1581
1582 kind_pty = mkHeteroPrimEqPred liftedTypeKind liftedTypeKind k1 k2
1583 kind_loc = mkKindLoc lhs rhs loc
1584
1585 loc = ctev_loc ev
1586 role = eqRelRole eq_rel
1587
1588 {-
1589 Note [Canonical orientation for tyvar/tyvar equality constraints]
1590 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1591 When we have a ~ b where both 'a' and 'b' are TcTyVars, which way
1592 round should be oriented in the CTyEqCan? The rules, implemented by
1593 canEqTyVarTyVar, are these
1594
1595 * If either is a flatten-meta-variables, it goes on the left.
1596
1597 * If one is a strict sub-kind of the other e.g.
1598 (alpha::?) ~ (beta::*)
1599 orient them so RHS is a subkind of LHS. That way we will replace
1600 'a' with 'b', correctly narrowing the kind.
1601 This establishes the subkind invariant of CTyEqCan.
1602
1603 * Put a meta-tyvar on the left if possible
1604 alpha[3] ~ r
1605
1606 * If both are meta-tyvars, put the more touchable one (deepest level
1607 number) on the left, so there is the best chance of unifying it
1608 alpha[3] ~ beta[2]
1609
1610 * If both are meta-tyvars and both at the same level, put a SigTv
1611 on the right if possible
1612 alpha[2] ~ beta[2](sig-tv)
1613 That way, when we unify alpha := beta, we don't lose the SigTv flag.
1614
1615 * Put a meta-tv with a System Name on the left if possible so it
1616 gets eliminated (improves error messages)
1617
1618 * If one is a flatten-skolem, put it on the left so that it is
1619 substituted out Note [Elminate flat-skols]
1620 fsk ~ a
1621
1622 Note [Avoid unnecessary swaps]
1623 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1624 If we swap without actually improving matters, we can get an infnite loop.
1625 Consider
1626 work item: a ~ b
1627 inert item: b ~ c
1628 We canonicalise the work-time to (a ~ c). If we then swap it before
1629 aeding to the inert set, we'll add (c ~ a), and therefore kick out the
1630 inert guy, so we get
1631 new work item: b ~ c
1632 inert item: c ~ a
1633 And now the cycle just repeats
1634
1635 Note [Eliminate flat-skols]
1636 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
1637 Suppose we have [G] Num (F [a])
1638 then we flatten to
1639 [G] Num fsk
1640 [G] F [a] ~ fsk
1641 where fsk is a flatten-skolem (FlatSkol). Suppose we have
1642 type instance F [a] = a
1643 then we'll reduce the second constraint to
1644 [G] a ~ fsk
1645 and then replace all uses of 'a' with fsk. That's bad because
1646 in error messages intead of saying 'a' we'll say (F [a]). In all
1647 places, including those where the programmer wrote 'a' in the first
1648 place. Very confusing! See Trac #7862.
1649
1650 Solution: re-orient a~fsk to fsk~a, so that we preferentially eliminate
1651 the fsk.
1652
1653 Note [Equalities with incompatible kinds]
1654 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1655 canEqLeaf is about to make a CTyEqCan or CFunEqCan; but both have the
1656 invariant that LHS and RHS satisfy the kind invariants for CTyEqCan,
1657 CFunEqCan. What if we try to unify two things with incompatible
1658 kinds?
1659
1660 eg a ~ b where a::*, b::*->*
1661 or a ~ b where a::*, b::k, k is a kind variable
1662
1663 The CTyEqCan compatKind invariant is important. If we make a CTyEqCan
1664 for a~b, then we might well *substitute* 'b' for 'a', and that might make
1665 a well-kinded type ill-kinded; and that is bad (eg typeKind can crash, see
1666 Trac #7696).
1667
1668 So instead for these ill-kinded equalities we homogenise the RHS of the
1669 equality, emitting new constraints as necessary.
1670
1671 Note [Type synonyms and canonicalization]
1672 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1673 We treat type synonym applications as xi types, that is, they do not
1674 count as type function applications. However, we do need to be a bit
1675 careful with type synonyms: like type functions they may not be
1676 generative or injective. However, unlike type functions, they are
1677 parametric, so there is no problem in expanding them whenever we see
1678 them, since we do not need to know anything about their arguments in
1679 order to expand them; this is what justifies not having to treat them
1680 as specially as type function applications. The thing that causes
1681 some subtleties is that we prefer to leave type synonym applications
1682 *unexpanded* whenever possible, in order to generate better error
1683 messages.
1684
1685 If we encounter an equality constraint with type synonym applications
1686 on both sides, or a type synonym application on one side and some sort
1687 of type application on the other, we simply must expand out the type
1688 synonyms in order to continue decomposing the equality constraint into
1689 primitive equality constraints. For example, suppose we have
1690
1691 type F a = [Int]
1692
1693 and we encounter the equality
1694
1695 F a ~ [b]
1696
1697 In order to continue we must expand F a into [Int], giving us the
1698 equality
1699
1700 [Int] ~ [b]
1701
1702 which we can then decompose into the more primitive equality
1703 constraint
1704
1705 Int ~ b.
1706
1707 However, if we encounter an equality constraint with a type synonym
1708 application on one side and a variable on the other side, we should
1709 NOT (necessarily) expand the type synonym, since for the purpose of
1710 good error messages we want to leave type synonyms unexpanded as much
1711 as possible. Hence the ps_ty1, ps_ty2 argument passed to canEqTyVar.
1712
1713 -}
1714
1715 {-
1716 ************************************************************************
1717 * *
1718 Evidence transformation
1719 * *
1720 ************************************************************************
1721 -}
1722
1723 data StopOrContinue a
1724 = ContinueWith a -- The constraint was not solved, although it may have
1725 -- been rewritten
1726
1727 | Stop CtEvidence -- The (rewritten) constraint was solved
1728 SDoc -- Tells how it was solved
1729 -- Any new sub-goals have been put on the work list
1730
1731 instance Functor StopOrContinue where
1732 fmap f (ContinueWith x) = ContinueWith (f x)
1733 fmap _ (Stop ev s) = Stop ev s
1734
1735 instance Outputable a => Outputable (StopOrContinue a) where
1736 ppr (Stop ev s) = text "Stop" <> parens s <+> ppr ev
1737 ppr (ContinueWith w) = text "ContinueWith" <+> ppr w
1738
1739 continueWith :: a -> TcS (StopOrContinue a)
1740 continueWith = return . ContinueWith
1741
1742 stopWith :: CtEvidence -> String -> TcS (StopOrContinue a)
1743 stopWith ev s = return (Stop ev (text s))
1744
1745 andWhenContinue :: TcS (StopOrContinue a)
1746 -> (a -> TcS (StopOrContinue b))
1747 -> TcS (StopOrContinue b)
1748 andWhenContinue tcs1 tcs2
1749 = do { r <- tcs1
1750 ; case r of
1751 Stop ev s -> return (Stop ev s)
1752 ContinueWith ct -> tcs2 ct }
1753 infixr 0 `andWhenContinue` -- allow chaining with ($)
1754
1755 rewriteEvidence :: CtEvidence -- old evidence
1756 -> TcPredType -- new predicate
1757 -> TcCoercion -- Of type :: new predicate ~ <type of old evidence>
1758 -> TcS (StopOrContinue CtEvidence)
1759 -- Returns Just new_ev iff either (i) 'co' is reflexivity
1760 -- or (ii) 'co' is not reflexivity, and 'new_pred' not cached
1761 -- In either case, there is nothing new to do with new_ev
1762 {-
1763 rewriteEvidence old_ev new_pred co
1764 Main purpose: create new evidence for new_pred;
1765 unless new_pred is cached already
1766 * Returns a new_ev : new_pred, with same wanted/given/derived flag as old_ev
1767 * If old_ev was wanted, create a binding for old_ev, in terms of new_ev
1768 * If old_ev was given, AND not cached, create a binding for new_ev, in terms of old_ev
1769 * Returns Nothing if new_ev is already cached
1770
1771 Old evidence New predicate is Return new evidence
1772 flavour of same flavor
1773 -------------------------------------------------------------------
1774 Wanted Already solved or in inert Nothing
1775 or Derived Not Just new_evidence
1776
1777 Given Already in inert Nothing
1778 Not Just new_evidence
1779
1780 Note [Rewriting with Refl]
1781 ~~~~~~~~~~~~~~~~~~~~~~~~~~
1782 If the coercion is just reflexivity then you may re-use the same
1783 variable. But be careful! Although the coercion is Refl, new_pred
1784 may reflect the result of unification alpha := ty, so new_pred might
1785 not _look_ the same as old_pred, and it's vital to proceed from now on
1786 using new_pred.
1787
1788 The flattener preserves type synonyms, so they should appear in new_pred
1789 as well as in old_pred; that is important for good error messages.
1790 -}
1791
1792
1793 rewriteEvidence old_ev@(CtDerived {}) new_pred _co
1794 = -- If derived, don't even look at the coercion.
1795 -- This is very important, DO NOT re-order the equations for
1796 -- rewriteEvidence to put the isTcReflCo test first!
1797 -- Why? Because for *Derived* constraints, c, the coercion, which
1798 -- was produced by flattening, may contain suspended calls to
1799 -- (ctEvTerm c), which fails for Derived constraints.
1800 -- (Getting this wrong caused Trac #7384.)
1801 continueWith (old_ev { ctev_pred = new_pred })
1802
1803 rewriteEvidence old_ev new_pred co
1804 | isTcReflCo co -- See Note [Rewriting with Refl]
1805 = continueWith (old_ev { ctev_pred = new_pred })
1806
1807 rewriteEvidence ev@(CtGiven { ctev_evar = old_evar , ctev_loc = loc }) new_pred co
1808 = do { new_ev <- newGivenEvVar loc (new_pred, new_tm)
1809 ; continueWith new_ev }
1810 where
1811 -- mkEvCast optimises ReflCo
1812 new_tm = mkEvCast (EvId old_evar) (tcDowngradeRole Representational
1813 (ctEvRole ev)
1814 (mkTcSymCo co))
1815
1816 rewriteEvidence ev@(CtWanted { ctev_dest = dest
1817 , ctev_loc = loc }) new_pred co
1818 = do { mb_new_ev <- newWanted loc new_pred
1819 ; MASSERT( tcCoercionRole co == ctEvRole ev )
1820 ; setWantedEvTerm dest
1821 (mkEvCast (getEvTerm mb_new_ev)
1822 (tcDowngradeRole Representational (ctEvRole ev) co))
1823 ; case mb_new_ev of
1824 Fresh new_ev -> continueWith new_ev
1825 Cached _ -> stopWith ev "Cached wanted" }
1826
1827
1828 rewriteEqEvidence :: CtEvidence -- Old evidence :: olhs ~ orhs (not swapped)
1829 -- or orhs ~ olhs (swapped)
1830 -> SwapFlag
1831 -> TcType -> TcType -- New predicate nlhs ~ nrhs
1832 -- Should be zonked, because we use typeKind on nlhs/nrhs
1833 -> TcCoercion -- lhs_co, of type :: nlhs ~ olhs
1834 -> TcCoercion -- rhs_co, of type :: nrhs ~ orhs
1835 -> TcS (StopOrContinue CtEvidence) -- Of type nlhs ~ nrhs
1836 -- For (rewriteEqEvidence (Given g olhs orhs) False nlhs nrhs lhs_co rhs_co)
1837 -- we generate
1838 -- If not swapped
1839 -- g1 : nlhs ~ nrhs = lhs_co ; g ; sym rhs_co
1840 -- If 'swapped'
1841 -- g1 : nlhs ~ nrhs = lhs_co ; Sym g ; sym rhs_co
1842 --
1843 -- For (Wanted w) we do the dual thing.
1844 -- New w1 : nlhs ~ nrhs
1845 -- If not swapped
1846 -- w : olhs ~ orhs = sym lhs_co ; w1 ; rhs_co
1847 -- If swapped
1848 -- w : orhs ~ olhs = sym rhs_co ; sym w1 ; lhs_co
1849 --
1850 -- It's all a form of rewwriteEvidence, specialised for equalities
1851 rewriteEqEvidence old_ev swapped nlhs nrhs lhs_co rhs_co
1852 | CtDerived {} <- old_ev -- Don't force the evidence for a Derived
1853 = continueWith (old_ev { ctev_pred = new_pred })
1854
1855 | NotSwapped <- swapped
1856 , isTcReflCo lhs_co -- See Note [Rewriting with Refl]
1857 , isTcReflCo rhs_co
1858 = continueWith (old_ev { ctev_pred = new_pred })
1859
1860 | CtGiven { ctev_evar = old_evar } <- old_ev
1861 = do { let new_tm = EvCoercion (lhs_co
1862 `mkTcTransCo` maybeSym swapped (mkTcCoVarCo old_evar)
1863 `mkTcTransCo` mkTcSymCo rhs_co)
1864 ; new_ev <- newGivenEvVar loc' (new_pred, new_tm)
1865 ; continueWith new_ev }
1866
1867 | CtWanted { ctev_dest = dest } <- old_ev
1868 = do { (new_ev, hole_co) <- newWantedEq loc' (ctEvRole old_ev) nlhs nrhs
1869 ; let co = maybeSym swapped $
1870 mkSymCo lhs_co
1871 `mkTransCo` hole_co
1872 `mkTransCo` rhs_co
1873 ; setWantedEq dest co
1874 ; traceTcS "rewriteEqEvidence" (vcat [ppr old_ev, ppr nlhs, ppr nrhs, ppr co])
1875 ; continueWith new_ev }
1876
1877 | otherwise
1878 = panic "rewriteEvidence"
1879 where
1880 new_pred = mkTcEqPredLikeEv old_ev nlhs nrhs
1881
1882 -- equality is like a type class. Bumping the depth is necessary because
1883 -- of recursive newtypes, where "reducing" a newtype can actually make
1884 -- it bigger. See Note [Newtypes can blow the stack].
1885 loc = ctEvLoc old_ev
1886 loc' = bumpCtLocDepth loc
1887
1888 {- Note [unifyWanted and unifyDerived]
1889 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1890 When decomposing equalities we often create new wanted constraints for
1891 (s ~ t). But what if s=t? Then it'd be faster to return Refl right away.
1892 Similar remarks apply for Derived.
1893
1894 Rather than making an equality test (which traverses the structure of the
1895 type, perhaps fruitlessly, unifyWanted traverses the common structure, and
1896 bales out when it finds a difference by creating a new Wanted constraint.
1897 But where it succeeds in finding common structure, it just builds a coercion
1898 to reflect it.
1899 -}
1900
1901 unifyWanted :: CtLoc -> Role
1902 -> TcType -> TcType -> TcS Coercion
1903 -- Return coercion witnessing the equality of the two types,
1904 -- emitting new work equalities where necessary to achieve that
1905 -- Very good short-cut when the two types are equal, or nearly so
1906 -- See Note [unifyWanted and unifyDerived]
1907 -- The returned coercion's role matches the input parameter
1908 unifyWanted loc Phantom ty1 ty2
1909 = do { kind_co <- unifyWanted loc Nominal (typeKind ty1) (typeKind ty2)
1910 ; return (mkPhantomCo kind_co ty1 ty2) }
1911
1912 unifyWanted loc role orig_ty1 orig_ty2
1913 = go orig_ty1 orig_ty2
1914 where
1915 go ty1 ty2 | Just ty1' <- coreView ty1 = go ty1' ty2
1916 go ty1 ty2 | Just ty2' <- coreView ty2 = go ty1 ty2'
1917
1918 go (FunTy s1 t1) (FunTy s2 t2)
1919 = do { co_s <- unifyWanted loc role s1 s2
1920 ; co_t <- unifyWanted loc role t1 t2
1921 ; return (mkTyConAppCo role funTyCon [co_s,co_t]) }
1922 go (TyConApp tc1 tys1) (TyConApp tc2 tys2)
1923 | tc1 == tc2, tys1 `equalLength` tys2
1924 , isInjectiveTyCon tc1 role -- don't look under newtypes at Rep equality
1925 = do { cos <- zipWith3M (unifyWanted loc)
1926 (tyConRolesX role tc1) tys1 tys2
1927 ; return (mkTyConAppCo role tc1 cos) }
1928 go (TyVarTy tv) ty2
1929 = do { mb_ty <- isFilledMetaTyVar_maybe tv
1930 ; case mb_ty of
1931 Just ty1' -> go ty1' ty2
1932 Nothing -> bale_out }
1933 go ty1 (TyVarTy tv)
1934 = do { mb_ty <- isFilledMetaTyVar_maybe tv
1935 ; case mb_ty of
1936 Just ty2' -> go ty1 ty2'
1937 Nothing -> bale_out }
1938
1939 go ty1@(CoercionTy {}) (CoercionTy {})
1940 = return (mkReflCo role ty1) -- we just don't care about coercions!
1941
1942 go _ _ = bale_out
1943
1944 bale_out = do { (new_ev, co) <- newWantedEq loc role orig_ty1 orig_ty2
1945 ; emitWorkNC [new_ev]
1946 ; return co }
1947
1948 unifyDeriveds :: CtLoc -> [Role] -> [TcType] -> [TcType] -> TcS ()
1949 -- See Note [unifyWanted and unifyDerived]
1950 unifyDeriveds loc roles tys1 tys2 = zipWith3M_ (unify_derived loc) roles tys1 tys2
1951
1952 unifyDerived :: CtLoc -> Role -> Pair TcType -> TcS ()
1953 -- See Note [unifyWanted and unifyDerived]
1954 unifyDerived loc role (Pair ty1 ty2) = unify_derived loc role ty1 ty2
1955
1956 unify_derived :: CtLoc -> Role -> TcType -> TcType -> TcS ()
1957 -- Create new Derived and put it in the work list
1958 -- Should do nothing if the two types are equal
1959 -- See Note [unifyWanted and unifyDerived]
1960 unify_derived _ Phantom _ _ = return ()
1961 unify_derived loc role orig_ty1 orig_ty2
1962 = go orig_ty1 orig_ty2
1963 where
1964 go ty1 ty2 | Just ty1' <- coreView ty1 = go ty1' ty2
1965 go ty1 ty2 | Just ty2' <- coreView ty2 = go ty1 ty2'
1966
1967 go (FunTy s1 t1) (FunTy s2 t2)
1968 = do { unify_derived loc role s1 s2
1969 ; unify_derived loc role t1 t2 }
1970 go (TyConApp tc1 tys1) (TyConApp tc2 tys2)
1971 | tc1 == tc2, tys1 `equalLength` tys2
1972 , isInjectiveTyCon tc1 role
1973 = unifyDeriveds loc (tyConRolesX role tc1) tys1 tys2
1974 go (TyVarTy tv) ty2
1975 = do { mb_ty <- isFilledMetaTyVar_maybe tv
1976 ; case mb_ty of
1977 Just ty1' -> go ty1' ty2
1978 Nothing -> bale_out }
1979 go ty1 (TyVarTy tv)
1980 = do { mb_ty <- isFilledMetaTyVar_maybe tv
1981 ; case mb_ty of
1982 Just ty2' -> go ty1 ty2'
1983 Nothing -> bale_out }
1984 go _ _ = bale_out
1985
1986 bale_out = emitNewDerivedEq loc role orig_ty1 orig_ty2
1987
1988 maybeSym :: SwapFlag -> TcCoercion -> TcCoercion
1989 maybeSym IsSwapped co = mkTcSymCo co
1990 maybeSym NotSwapped co = co