Comments only
[ghc.git] / compiler / typecheck / TcCanonical.hs
1 {-# LANGUAGE CPP #-}
2
3 module TcCanonical(
4 canonicalize,
5 unifyDerived,
6
7 StopOrContinue(..), stopWith, continueWith
8 ) where
9
10 #include "HsVersions.h"
11
12 import TcRnTypes
13 import TcType
14 import Type
15 import Kind
16 import TcFlatten
17 import TcSMonad
18 import TcEvidence
19 import Class
20 import TyCon
21 import TypeRep
22 import Coercion
23 import FamInstEnv ( FamInstEnvs )
24 import FamInst ( tcTopNormaliseNewTypeTF_maybe )
25 import Var
26 import Name( isSystemName )
27 import OccName( OccName )
28 import Outputable
29 import DynFlags( DynFlags )
30 import VarSet
31 import RdrName
32 import DataCon ( dataConName )
33
34 import Pair
35 import Util
36 import Bag
37 import MonadUtils ( zipWith3M, zipWith3M_ )
38 import Data.List ( zip4 )
39 import BasicTypes
40 import FastString
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
144 , cc_class = cls
145 , cc_tyargs = xis })
146 = {-# SCC "canClass" #-}
147 canClass ev cls xis -- Do not add any superclasses
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_occ = occ, cc_hole = hole })
167 = canHole ev occ 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 canClass, canClassNC
188 :: CtEvidence
189 -> Class -> [Type] -> TcS (StopOrContinue Ct)
190 -- Precondition: EvVar is class evidence
191
192 -- The canClassNC version is used on non-canonical constraints
193 -- and adds superclasses. The plain canClass version is used
194 -- for already-canonical class constraints (but which might have
195 -- been subsituted or somthing), and hence do not need superclasses
196
197 canClassNC ev cls tys
198 = canClass ev cls tys
199 `andWhenContinue` emitSuperclasses
200
201 canClass ev cls tys
202 = -- all classes do *nominal* matching
203 ASSERT2( ctEvRole ev == Nominal, ppr ev $$ ppr cls $$ ppr tys )
204 do { (xis, cos) <- flattenManyNom ev tys
205 ; let co = mkTcTyConAppCo Nominal (classTyCon cls) cos
206 xi = mkClassPred cls xis
207 mk_ct new_ev = CDictCan { cc_ev = new_ev
208 , cc_tyargs = xis, cc_class = cls }
209 ; mb <- rewriteEvidence ev xi co
210 ; traceTcS "canClass" (vcat [ ppr ev <+> ppr cls <+> ppr tys
211 , ppr xi, ppr mb ])
212 ; return (fmap mk_ct mb) }
213
214 emitSuperclasses :: Ct -> TcS (StopOrContinue Ct)
215 emitSuperclasses ct@(CDictCan { cc_ev = ev , cc_tyargs = xis_new, cc_class = cls })
216 -- Add superclasses of this one here, See Note [Adding superclasses].
217 -- But only if we are not simplifying the LHS of a rule.
218 = do { newSCWorkFromFlavored ev cls xis_new
219 -- Arguably we should "seq" the coercions if they are derived,
220 -- as we do below for emit_kind_constraint, to allow errors in
221 -- superclasses to be executed if deferred to runtime!
222 ; continueWith ct }
223 emitSuperclasses _ = panic "emit_superclasses of non-class!"
224
225 {- Note [Adding superclasses]
226 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
227 Since dictionaries are canonicalized only once in their lifetime, the
228 place to add their superclasses is canonicalisation. See Note [Add
229 superclasses only during canonicalisation]. Here is what we do:
230
231 Givens: Add all their superclasses as Givens.
232 They may be needed to prove Wanteds.
233
234 Wanteds/Derived:
235 Add all their superclasses as Derived.
236 The sole reason is to expose functional dependencies
237 in superclasses or equality superclasses.
238
239 Examples of how adding superclasses as Derived is useful
240
241 --- Example 1
242 class C a b | a -> b
243 Suppose we want to solve
244 [G] C a b
245 [W] C a beta
246 Then adding [D] beta~b will let us solve it.
247
248 -- Example 2 (similar but using a type-equality superclass)
249 class (F a ~ b) => C a b
250 And try to sllve:
251 [G] C a b
252 [W] C a beta
253 Follow the superclass rules to add
254 [G] F a ~ b
255 [D] F a ~ beta
256 Now we we get [D] beta ~ b, and can solve that.
257
258 -- Example (tcfail138)
259 class L a b | a -> b
260 class (G a, L a b) => C a b
261
262 instance C a b' => G (Maybe a)
263 instance C a b => C (Maybe a) a
264 instance L (Maybe a) a
265
266 When solving the superclasses of the (C (Maybe a) a) instance, we get
267 [G] C a b, and hance by superclasses, [G] G a, [G] L a b
268 [W] G (Maybe a)
269 Use the instance decl to get
270 [W] C a beta
271 Generate its derived superclass
272 [D] L a beta. Now using fundeps, combine with [G] L a b to get
273 [D] beta ~ b
274 which is what we want.
275
276 ---------- Historical note -----------
277 Example of why adding superclass of a Wanted as a Given would
278 be terrible, see Note [Do not add superclasses of solved dictionaries]
279 in TcSMonad, which has this example:
280 class Ord a => C a where
281 instance Ord [a] => C [a] where ...
282 Suppose we are trying to solve
283 [G] d1 : Ord a
284 [W] d2 : C [a]
285 If we (bogusly) added the superclass of d2 as Gievn we'd have
286 [G] d1 : Ord a
287 [W] d2 : C [a]
288 [G] d3 : Ord [a] -- Superclass of d2, bogus
289
290 Then we'll use the instance decl to give
291 [G] d1 : Ord a Solved: d2 : C [a] = $dfCList d4
292 [G] d3 : Ord [a] -- Superclass of d2, bogus
293 [W] d4: Ord [a]
294
295 ANd now we could bogusly solve d4 from d3.
296 ---------- End of historical note -----------
297
298 Note [Add superclasses only during canonicalisation]
299 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
300 We add superclasses only during canonicalisation, on the passage
301 from CNonCanonical to CDictCan. A class constraint can be repeatedly
302 rewritten, and there's no point in repeatedly adding its superclasses.
303
304 Here's a serious, but now out-dated example, from Trac #4497:
305
306 class Num (RealOf t) => Normed t
307 type family RealOf x
308
309 Assume the generated wanted constraint is:
310 [W] RealOf e ~ e
311 [W] Normed e
312
313 If we were to be adding the superclasses during simplification we'd get:
314 [W] RealOf e ~ e
315 [W] Normed e
316 [D] RealOf e ~ fuv
317 [D] Num fuv
318 ==>
319 e := fuv, Num fuv, Normed fuv, RealOf fuv ~ fuv
320
321 While looks exactly like our original constraint. If we add the
322 superclass of (Normed fuv) again we'd loop. By adding superclasses
323 definitely only once, during canonicalisation, this situation can't
324 happen.
325
326 Mind you, now that Wanteds cannot rewrite Derived, I think this particular
327 situation can't happen.
328 -}
329
330 newSCWorkFromFlavored :: CtEvidence -> Class -> [Xi] -> TcS ()
331 -- Returns superclasses, see Note [Adding superclasses]
332 newSCWorkFromFlavored flavor cls xis
333 | CtGiven { ctev_evar = evar, ctev_loc = loc } <- flavor
334 = do { given_evs <- newGivenEvVars (mk_given_loc loc)
335 (mkEvScSelectors (EvId evar) cls xis)
336 ; emitWorkNC given_evs }
337
338 | isEmptyVarSet (tyVarsOfTypes xis)
339 = return () -- Wanteds with no variables yield no deriveds.
340 -- See Note [Improvement from Ground Wanteds]
341
342 | otherwise -- Wanted/Derived case, just add those SC that can lead to improvement.
343 = do { let sc_rec_theta = transSuperClasses cls xis
344 impr_theta = filter isImprovementPred sc_rec_theta
345 loc = ctEvLoc flavor
346 ; traceTcS "newSCWork/Derived" $ text "impr_theta =" <+> ppr impr_theta
347 ; emitNewDeriveds loc impr_theta }
348
349 where
350 size = sizeTypes xis
351 mk_given_loc loc
352 | isCTupleClass cls
353 = loc -- For tuple predicates, just take them apart, without
354 -- adding their (large) size into the chain. When we
355 -- get down to a base predicate, we'll include its size.
356 -- Trac #10335
357
358 | GivenOrigin skol_info <- ctLocOrigin loc
359 -- See Note [Solving superclass constraints] in TcInstDcls
360 -- for explantation of this transformation for givens
361 = case skol_info of
362 InstSkol -> loc { ctl_origin = GivenOrigin (InstSC size) }
363 InstSC n -> loc { ctl_origin = GivenOrigin (InstSC (n `max` size)) }
364 _ -> loc
365
366 | otherwise -- Probably doesn't happen, since this function
367 = loc -- is only used for Givens, but does no harm
368
369 {-
370 ************************************************************************
371 * *
372 * Irreducibles canonicalization
373 * *
374 ************************************************************************
375 -}
376
377 canIrred :: CtEvidence -> TcS (StopOrContinue Ct)
378 -- Precondition: ty not a tuple and no other evidence form
379 canIrred old_ev
380 = do { let old_ty = ctEvPred old_ev
381 ; traceTcS "can_pred" (text "IrredPred = " <+> ppr old_ty)
382 ; (xi,co) <- flatten FM_FlattenAll old_ev old_ty -- co :: xi ~ old_ty
383 ; rewriteEvidence old_ev xi co `andWhenContinue` \ new_ev ->
384 do { -- Re-classify, in case flattening has improved its shape
385 ; case classifyPredType (ctEvPred new_ev) of
386 ClassPred cls tys -> canClassNC new_ev cls tys
387 EqPred eq_rel ty1 ty2 -> canEqNC new_ev eq_rel ty1 ty2
388 _ -> continueWith $
389 CIrredEvCan { cc_ev = new_ev } } }
390
391 canHole :: CtEvidence -> OccName -> HoleSort -> TcS (StopOrContinue Ct)
392 canHole ev occ hole_sort
393 = do { let ty = ctEvPred ev
394 ; (xi,co) <- flatten FM_SubstOnly ev ty -- co :: xi ~ ty
395 ; rewriteEvidence ev xi co `andWhenContinue` \ new_ev ->
396 do { emitInsoluble (CHoleCan { cc_ev = new_ev
397 , cc_occ = occ
398 , cc_hole = hole_sort })
399 ; stopWith new_ev "Emit insoluble hole" } }
400
401 {-
402 ************************************************************************
403 * *
404 * Equalities
405 * *
406 ************************************************************************
407
408 Note [Canonicalising equalities]
409 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
410 In order to canonicalise an equality, we look at the structure of the
411 two types at hand, looking for similarities. A difficulty is that the
412 types may look dissimilar before flattening but similar after flattening.
413 However, we don't just want to jump in and flatten right away, because
414 this might be wasted effort. So, after looking for similarities and failing,
415 we flatten and then try again. Of course, we don't want to loop, so we
416 track whether or not we've already flattened.
417
418 It is conceivable to do a better job at tracking whether or not a type
419 is flattened, but this is left as future work. (Mar '15)
420 -}
421
422 canEqNC :: CtEvidence -> EqRel -> Type -> Type -> TcS (StopOrContinue Ct)
423 canEqNC ev eq_rel ty1 ty2
424 = can_eq_nc False ev eq_rel ty1 ty1 ty2 ty2
425
426 can_eq_nc
427 :: Bool -- True => both types are flat
428 -> CtEvidence
429 -> EqRel
430 -> Type -> Type -- LHS, after and before type-synonym expansion, resp
431 -> Type -> Type -- RHS, after and before type-synonym expansion, resp
432 -> TcS (StopOrContinue Ct)
433 can_eq_nc flat ev eq_rel ty1 ps_ty1 ty2 ps_ty2
434 = do { traceTcS "can_eq_nc" $
435 vcat [ ppr ev, ppr eq_rel, ppr ty1, ppr ps_ty1, ppr ty2, ppr ps_ty2 ]
436 ; rdr_env <- getGlobalRdrEnvTcS
437 ; fam_insts <- getFamInstEnvs
438 ; can_eq_nc' flat rdr_env fam_insts ev eq_rel ty1 ps_ty1 ty2 ps_ty2 }
439
440 can_eq_nc'
441 :: Bool -- True => both input types are flattened
442 -> GlobalRdrEnv -- needed to see which newtypes are in scope
443 -> FamInstEnvs -- needed to unwrap data instances
444 -> CtEvidence
445 -> EqRel
446 -> Type -> Type -- LHS, after and before type-synonym expansion, resp
447 -> Type -> Type -- RHS, after and before type-synonym expansion, resp
448 -> TcS (StopOrContinue Ct)
449
450 -- Expand synonyms first; see Note [Type synonyms and canonicalization]
451 can_eq_nc' flat _rdr_env _envs ev eq_rel ty1 ps_ty1 ty2 ps_ty2
452 | Just ty1' <- tcView ty1 = can_eq_nc flat ev eq_rel ty1' ps_ty1 ty2 ps_ty2
453 | Just ty2' <- tcView ty2 = can_eq_nc flat ev eq_rel ty1 ps_ty1 ty2' ps_ty2
454
455 -- need to check for reflexivity in the ReprEq case.
456 -- See Note [Eager reflexivity check]
457 can_eq_nc' _flat _rdr_env _envs ev ReprEq ty1 _ ty2 _
458 | ty1 `eqType` ty2
459 = canEqReflexive ev ReprEq ty1
460
461 -- When working with ReprEq, unwrap newtypes.
462 can_eq_nc' _flat rdr_env envs ev ReprEq ty1 _ ty2 ps_ty2
463 | Just (co, ty1') <- tcTopNormaliseNewTypeTF_maybe envs rdr_env ty1
464 = can_eq_newtype_nc rdr_env ev NotSwapped co ty1 ty1' ty2 ps_ty2
465 can_eq_nc' _flat rdr_env envs ev ReprEq ty1 ps_ty1 ty2 _
466 | Just (co, ty2') <- tcTopNormaliseNewTypeTF_maybe envs rdr_env ty2
467 = can_eq_newtype_nc rdr_env ev IsSwapped co ty2 ty2' ty1 ps_ty1
468
469 ----------------------
470 -- Otherwise try to decompose
471 ----------------------
472
473 -- Literals
474 can_eq_nc' _flat _rdr_env _envs ev eq_rel ty1@(LitTy l1) _ (LitTy l2) _
475 | l1 == l2
476 = do { setEvBindIfWanted ev (EvCoercion $
477 mkTcReflCo (eqRelRole eq_rel) ty1)
478 ; stopWith ev "Equal LitTy" }
479
480 -- Try to decompose type constructor applications
481 -- Including FunTy (s -> t)
482 can_eq_nc' _flat _rdr_env _envs ev eq_rel ty1 _ ty2 _
483 | Just (tc1, tys1) <- tcSplitTyConApp_maybe ty1
484 , Just (tc2, tys2) <- tcSplitTyConApp_maybe ty2
485 , not (isTypeFamilyTyCon tc1)
486 , not (isTypeFamilyTyCon tc2)
487 = canTyConApp ev eq_rel tc1 tys1 tc2 tys2
488
489 can_eq_nc' _flat _rdr_env _envs ev eq_rel
490 s1@(ForAllTy {}) _ s2@(ForAllTy {}) _
491 | CtWanted { ctev_loc = loc, ctev_evar = orig_ev } <- ev
492 = do { let (tvs1,body1) = tcSplitForAllTys s1
493 (tvs2,body2) = tcSplitForAllTys s2
494 ; if not (equalLength tvs1 tvs2) then
495 canEqHardFailure ev eq_rel s1 s2
496 else
497 do { traceTcS "Creating implication for polytype equality" $ ppr ev
498 ; ev_term <- deferTcSForAllEq (eqRelRole eq_rel)
499 loc (tvs1,body1) (tvs2,body2)
500 ; setWantedEvBind orig_ev ev_term
501 ; stopWith ev "Deferred polytype equality" } }
502 | otherwise
503 = do { traceTcS "Ommitting decomposition of given polytype equality" $
504 pprEq s1 s2 -- See Note [Do not decompose given polytype equalities]
505 ; stopWith ev "Discard given polytype equality" }
506
507 -- See Note [Canonicalising type applications] about why we require flat types
508 can_eq_nc' True _rdr_env _envs ev eq_rel (AppTy t1 s1) _ ty2 _
509 | Just (t2, s2) <- tcSplitAppTy_maybe ty2
510 = can_eq_app ev eq_rel t1 s1 t2 s2
511 can_eq_nc' True _rdr_env _envs ev eq_rel ty1 _ (AppTy t2 s2) _
512 | Just (t1, s1) <- tcSplitAppTy_maybe ty1
513 = can_eq_app ev eq_rel t1 s1 t2 s2
514
515 -- No similarity in type structure detected. Flatten and try again!
516 can_eq_nc' False rdr_env envs ev eq_rel _ ps_ty1 _ ps_ty2
517 = do { (xi1, co1) <- flatten FM_FlattenAll ev ps_ty1
518 ; (xi2, co2) <- flatten FM_FlattenAll ev ps_ty2
519 ; rewriteEqEvidence ev eq_rel NotSwapped xi1 xi2 co1 co2
520 `andWhenContinue` \ new_ev ->
521 can_eq_nc' True rdr_env envs new_ev eq_rel xi1 xi1 xi2 xi2 }
522
523 -- Type variable on LHS or RHS are last. We want only flat types sent
524 -- to canEqTyVar.
525 -- See also Note [No top-level newtypes on RHS of representational equalities]
526 can_eq_nc' True _rdr_env _envs ev eq_rel (TyVarTy tv1) _ _ ps_ty2
527 = canEqTyVar ev eq_rel NotSwapped tv1 ps_ty2
528 can_eq_nc' True _rdr_env _envs ev eq_rel _ ps_ty1 (TyVarTy tv2) _
529 = canEqTyVar ev eq_rel IsSwapped tv2 ps_ty1
530
531 -- We've flattened and the types don't match. Give up.
532 can_eq_nc' True _rdr_env _envs ev eq_rel _ ps_ty1 _ ps_ty2
533 = canEqHardFailure ev eq_rel ps_ty1 ps_ty2
534
535 {-
536 Note [Newtypes can blow the stack]
537 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
538 Suppose we have
539
540 newtype X = MkX (Int -> X)
541 newtype Y = MkY (Int -> Y)
542
543 and now wish to prove
544
545 [W] X ~R Y
546
547 This Wanted will loop, expanding out the newtypes ever deeper looking
548 for a solid match or a solid discrepancy. Indeed, there is something
549 appropriate to this looping, because X and Y *do* have the same representation,
550 in the limit -- they're both (Fix ((->) Int)). However, no finitely-sized
551 coercion will ever witness it. This loop won't actually cause GHC to hang,
552 though, because we check our depth when unwrapping newtypes.
553
554 Note [Eager reflexivity check]
555 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
556 Suppose we have
557
558 newtype X = MkX (Int -> X)
559
560 and
561
562 [W] X ~R X
563
564 Naively, we would start unwrapping X and end up in a loop. Instead,
565 we do this eager reflexivity check. This is necessary only for representational
566 equality because the flattener technology deals with the similar case
567 (recursive type families) for nominal equality.
568
569 Note that this check does not catch all cases, but it will catch the cases
570 we're most worried about, types like X above that are actually inhabited.
571
572 Here's another place where this reflexivity check is key:
573 Consider trying to prove (f a) ~R (f a). The AppTys in there can't
574 be decomposed, because representational equality isn't congruent with respect
575 to AppTy. So, when canonicalising the equality above, we get stuck and
576 would normally produce a CIrredEvCan. However, we really do want to
577 be able to solve (f a) ~R (f a). So, in the representational case only,
578 we do a reflexivity check.
579
580 (This would be sound in the nominal case, but unnecessary, and I [Richard
581 E.] am worried that it would slow down the common case.)
582 -}
583
584 ------------------------
585 -- | We're able to unwrap a newtype. Update the bits accordingly.
586 can_eq_newtype_nc :: GlobalRdrEnv
587 -> CtEvidence -- ^ :: ty1 ~ ty2
588 -> SwapFlag
589 -> TcCoercion -- ^ :: ty1 ~ ty1'
590 -> TcType -- ^ ty1
591 -> TcType -- ^ ty1'
592 -> TcType -- ^ ty2
593 -> TcType -- ^ ty2, with type synonyms
594 -> TcS (StopOrContinue Ct)
595 can_eq_newtype_nc rdr_env ev swapped co ty1 ty1' ty2 ps_ty2
596 = do { traceTcS "can_eq_newtype_nc" $
597 vcat [ ppr ev, ppr swapped, ppr co, ppr ty1', ppr ty2 ]
598
599 -- check for blowing our stack:
600 -- See Note [Newtypes can blow the stack]
601 ; checkReductionDepth (ctEvLoc ev) ty1
602 ; markDataConsAsUsed rdr_env (tyConAppTyCon ty1)
603 -- we have actually used the newtype constructor here, so
604 -- make sure we don't warn about importing it!
605
606 ; rewriteEqEvidence ev ReprEq swapped ty1' ps_ty2
607 (mkTcSymCo co) (mkTcReflCo Representational ps_ty2)
608 `andWhenContinue` \ new_ev ->
609 can_eq_nc False new_ev ReprEq ty1' ty1' ty2 ps_ty2 }
610
611 -- | Mark all the datacons of the given 'TyCon' as used in this module,
612 -- avoiding "redundant import" warnings.
613 markDataConsAsUsed :: GlobalRdrEnv -> TyCon -> TcS ()
614 markDataConsAsUsed rdr_env tc = addUsedRdrNamesTcS
615 [ greUsedRdrName gre
616 | dc <- tyConDataCons tc
617 , gre : _ <- return $ lookupGRE_Name rdr_env (dataConName dc)
618 , not (isLocalGRE gre) ]
619
620 ---------
621 -- ^ Decompose a type application.
622 -- All input types must be flat. See Note [Canonicalising type applications]
623 can_eq_app :: CtEvidence -- :: s1 t1 ~r s2 t2
624 -> EqRel -- r
625 -> Xi -> Xi -- s1 t1
626 -> Xi -> Xi -- s2 t2
627 -> TcS (StopOrContinue Ct)
628
629 -- AppTys only decompose for nominal equality, so this case just leads
630 -- to an irreducible constraint; see typecheck/should_compile/T10494
631 -- See Note [Decomposing equality], note {4}
632 can_eq_app ev ReprEq _ _ _ _
633 = do { traceTcS "failing to decompose representational AppTy equality" (ppr ev)
634 ; continueWith (CIrredEvCan { cc_ev = ev }) }
635 -- no need to call canEqFailure, because that flattens, and the
636 -- types involved here are already flat
637
638 can_eq_app ev NomEq s1 t1 s2 t2
639 | CtDerived { ctev_loc = loc } <- ev
640 = do { emitNewDerivedEq loc (mkTcEqPred t1 t2)
641 ; canEqNC ev NomEq s1 s2 }
642 | CtWanted { ctev_evar = evar, ctev_loc = loc } <- ev
643 = do { ev_s <- newWantedEvVarNC loc (mkTcEqPred s1 s2)
644 ; co_t <- unifyWanted loc Nominal t1 t2
645 ; let co = mkTcAppCo (ctEvCoercion ev_s) co_t
646 ; setWantedEvBind evar (EvCoercion co)
647 ; canEqNC ev_s NomEq s1 s2 }
648 | CtGiven { ctev_evar = evar, ctev_loc = loc } <- ev
649 = do { let co = mkTcCoVarCo evar
650 co_s = mkTcLRCo CLeft co
651 co_t = mkTcLRCo CRight co
652 ; evar_s <- newGivenEvVar loc (mkTcEqPred s1 s2, EvCoercion co_s)
653 ; evar_t <- newGivenEvVar loc (mkTcEqPred t1 t2, EvCoercion co_t)
654 ; emitWorkNC [evar_t]
655 ; canEqNC evar_s NomEq s1 s2 }
656 | otherwise -- Can't happen
657 = error "can_eq_app"
658
659 ------------------------
660 canTyConApp :: CtEvidence -> EqRel
661 -> TyCon -> [TcType]
662 -> TyCon -> [TcType]
663 -> TcS (StopOrContinue Ct)
664 -- See Note [Decomposing TyConApps]
665 canTyConApp ev eq_rel tc1 tys1 tc2 tys2
666 | tc1 == tc2
667 , length tys1 == length tys2
668 = do { inerts <- getTcSInerts
669 ; if can_decompose inerts
670 then do { traceTcS "canTyConApp"
671 (ppr ev $$ ppr eq_rel $$ ppr tc1 $$ ppr tys1 $$ ppr tys2)
672 ; canDecomposableTyConAppOK ev eq_rel tc1 tys1 tys2
673 ; stopWith ev "Decomposed TyConApp" }
674 else canEqFailure ev eq_rel ty1 ty2 }
675
676 -- Fail straight away for better error messages
677 -- See Note [Use canEqFailure in canDecomposableTyConApp]
678 | eq_rel == ReprEq && not (isGenerativeTyCon tc1 Representational &&
679 isGenerativeTyCon tc2 Representational)
680 = canEqFailure ev eq_rel ty1 ty2
681 | otherwise
682 = canEqHardFailure ev eq_rel ty1 ty2
683 where
684 ty1 = mkTyConApp tc1 tys1
685 ty2 = mkTyConApp tc2 tys2
686
687 loc = ctEvLoc ev
688 pred = ctEvPred ev
689
690 -- See Note [Decomposing equality]
691 can_decompose inerts
692 = isInjectiveTyCon tc1 (eqRelRole eq_rel)
693 || (ctEvFlavour ev /= Given && isEmptyBag (matchableGivens loc pred inerts))
694
695 {-
696 Note [Use canEqFailure in canDecomposableTyConApp]
697 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
698 We must use canEqFailure, not canEqHardFailure here, because there is
699 the possibility of success if working with a representational equality.
700 Here is one case:
701
702 type family TF a where TF Char = Bool
703 data family DF a
704 newtype instance DF Bool = MkDF Int
705
706 Suppose we are canonicalising (Int ~R DF (TF a)), where we don't yet
707 know `a`. This is *not* a hard failure, because we might soon learn
708 that `a` is, in fact, Char, and then the equality succeeds.
709
710 Here is another case:
711
712 [G] Age ~R Int
713
714 where Age's constructor is not in scope. We don't want to report
715 an "inaccessible code" error in the context of this Given!
716
717 For example, see typecheck/should_compile/T10493, repeated here:
718
719 import Data.Ord (Down) -- no constructor
720
721 foo :: Coercible (Down Int) Int => Down Int -> Int
722 foo = coerce
723
724 That should compile, but only because we use canEqFailure and not
725 canEqHardFailure.
726
727 Note [Decomposing equality]
728 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
729 If we have a constraint (of any flavour and role) that looks like
730 T tys1 ~ T tys2, what can we conclude about tys1 and tys2? The answer,
731 of course, is "it depends". This Note spells it all out.
732
733 In this Note, "decomposition" refers to taking the constraint
734 [fl] (T tys1 ~X T tys2)
735 (for some flavour fl and some role X) and replacing it with
736 [fls'] (tys1 ~Xs' tys2)
737 where that notation indicates a list of new constraints, where the
738 new constraints may have different flavours and different roles.
739
740 The key property to consider is injectivity. When decomposing a Given the
741 decomposition is sound if and only if T is injective in all of its type
742 arguments. When decomposing a Wanted, the decomposition is sound (assuming the
743 correct roles in the produced equality constraints), but it may be a guess --
744 that is, an unforced decision by the constraint solver. Decomposing Wanteds
745 over injective TyCons does not entail guessing. But sometimes we want to
746 decompose a Wanted even when the TyCon involved is not injective! (See below.)
747
748 So, in broad strokes, we want this rule:
749
750 (*) Decompose a constraint (T tys1 ~X T tys2) if and only if T is injective
751 at role X.
752
753 Pursuing the details requires exploring three axes:
754 * Flavour: Given vs. Derived vs. Wanted
755 * Role: Nominal vs. Representational
756 * TyCon species: datatype vs. newtype vs. data family vs. type family vs. type variable
757
758 (So a type variable isn't a TyCon, but it's convenient to put the AppTy case
759 in the same table.)
760
761 Right away, we can say that Derived behaves just as Wanted for the purposes
762 of decomposition. The difference between Derived and Wanted is the handling of
763 evidence. Since decomposition in these cases isn't a matter of soundness but of
764 guessing, we want the same behavior regardless of evidence.
765
766 Here is a table (discussion following) detailing where decomposition of
767 (T s1 ... sn) ~r (T t1 .. tn)
768 is allowed. The first four lines (Data types ... type family) refer
769 to TyConApps with various TyCons T; the last line is for AppTy, where
770 there is presumably a type variable at the head, so it's actually
771 (s s1 ... sn) ~r (t t1 .. tn)
772
773 NOMINAL GIVEN WANTED
774
775 Datatype YES YES
776 Newtype YES YES
777 Data family YES YES
778 Type family YES, in injective args{1} YES, in injective args{1}
779 Type variable YES YES
780
781 REPRESENTATIONAL GIVEN WANTED
782
783 Datatype YES YES
784 Newtype NO{2} MAYBE{2}
785 Data family NO{3} MAYBE{3}
786 Type family NO NO
787 Type variable NO{4} NO{4}
788
789 {1}: Type families can be injective in some, but not all, of their arguments,
790 so we want to do partial decomposition. This is quite different than the way
791 other decomposition is done, where the decomposed equalities replace the original
792 one. We thus proceed much like we do with superclasses: emitting new Givens
793 when "decomposing" a partially-injective type family Given and new Deriveds
794 when "decomposing" a partially-injective type family Wanted. (As of the time of
795 writing, 13 June 2015, the implementation of injective type families has not
796 been merged, but it should be soon. Please delete this parenthetical if the
797 implementation is indeed merged.)
798
799 {2}: See Note [Decomposing newtypes at representational role]
800
801 {3}: Because of the possibility of newtype instances, we must treat
802 data families like newtypes. See also Note [Decomposing newtypes at
803 representational role]. See #10534 and test case
804 typecheck/should_fail/T10534.
805
806 {4}: Because type variables can stand in for newtypes, we conservatively do not
807 decompose AppTys over representational equality.
808
809 In the implementation of can_eq_nc and friends, we don't directly pattern
810 match using lines like in the tables above, as those tables don't cover
811 all cases (what about PrimTyCon? tuples?). Instead we just ask about injectivity,
812 boiling the tables above down to rule (*). The exceptions to rule (*) are for
813 injective type families, which are handled separately from other decompositions,
814 and the MAYBE entries above.
815
816 Note [Decomposing newtypes at representational role]
817 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
818 This note discusses the 'newtype' line in the REPRESENTATIONAL table
819 in Note [Decomposing equality]. (At nominal role, newtypes are fully
820 decomposable.)
821
822 Here is a representative example of why representational equality over
823 newtypes is tricky:
824
825 newtype Nt a = Mk Bool -- NB: a is not used in the RHS,
826 type role Nt representational -- but the user gives it an R role anyway
827
828 If we have [W] Nt alpha ~R Nt beta, we *don't* want to decompose to
829 [W] alpha ~R beta, because it's possible that alpha and beta aren't
830 representationally equal. Here's another example.
831
832 newtype Nt a = MkNt (Id a)
833 type family Id a where Id a = a
834
835 [W] Nt Int ~R Nt Age
836
837 Because of its use of a type family, Nt's parameter will get inferred to have
838 a nominal role. Thus, decomposing the wanted will yield [W] Int ~N Age, which
839 is unsatisfiable. Unwrapping, though, leads to a solution.
840
841 Conclusion:
842 * Unwrap newtypes before attempting to decompose them.
843 This is done in can_eq_nc'.
844
845 It all comes from the fact that newtypes aren't necessarily injective
846 w.r.t. representational equality.
847
848 Furthermore, as explained in Note [NthCo and newtypes] in Coercion, we can't use
849 NthCo on representational coercions over newtypes. NthCo comes into play
850 only when decomposing givens.
851
852 Conclusion:
853 * Do not decompose [G] N s ~R N t
854
855 Is it sensible to decompose *Wanted* constraints over newtypes? Yes!
856 It's the only way we could ever prove (IO Int ~R IO Age), recalling
857 that IO is a newtype.
858
859 However we must be careful. Consider
860
861 type role Nt representational
862
863 [G] Nt a ~R Nt b (1)
864 [W] NT alpha ~R Nt b (2)
865 [W] alpha ~ a (3)
866
867 If we focus on (3) first, we'll substitute in (2), and now it's
868 identical to the given (1), so we succeed. But if we focus on (2)
869 first, and decompose it, we'll get (alpha ~R b), which is not soluble.
870 This is exactly like the question of overlapping Givens for class
871 constraints: see Note [Instance and Given overlap] in TcInteract.
872
873 Conclusion:
874 * Decompose [W] N s ~R N t iff there no given constraint that could
875 later solve it.
876 -}
877
878 canDecomposableTyConAppOK :: CtEvidence -> EqRel
879 -> TyCon -> [TcType] -> [TcType]
880 -> TcS ()
881 -- Precondition: tys1 and tys2 are the same length, hence "OK"
882 canDecomposableTyConAppOK ev eq_rel tc tys1 tys2
883 = case ev of
884 CtDerived { ctev_loc = loc }
885 -> unifyDeriveds loc tc_roles tys1 tys2
886
887 CtWanted { ctev_evar = evar, ctev_loc = loc }
888 -> do { cos <- zipWith3M (unifyWanted loc) tc_roles tys1 tys2
889 ; setWantedEvBind evar (EvCoercion (mkTcTyConAppCo role tc cos)) }
890
891 CtGiven { ctev_evar = evar, ctev_loc = loc }
892 -> do { let ev_co = mkTcCoVarCo evar
893 ; given_evs <- newGivenEvVars loc $
894 [ ( mkTcEqPredRole r ty1 ty2
895 , EvCoercion (mkTcNthCo i ev_co) )
896 | (r, ty1, ty2, i) <- zip4 tc_roles tys1 tys2 [0..]
897 , r /= Phantom ]
898 ; emitWorkNC given_evs }
899 where
900 role = eqRelRole eq_rel
901 tc_roles = tyConRolesX role tc
902
903 -- | Call when canonicalizing an equality fails, but if the equality is
904 -- representational, there is some hope for the future.
905 -- Examples in Note [Use canEqFailure in canDecomposableTyConApp]
906 canEqFailure :: CtEvidence -> EqRel
907 -> TcType -> TcType -> TcS (StopOrContinue Ct)
908 canEqFailure ev NomEq ty1 ty2
909 = canEqHardFailure ev NomEq ty1 ty2
910 canEqFailure ev ReprEq ty1 ty2
911 = do { (xi1, co1) <- flatten FM_FlattenAll ev ty1
912 ; (xi2, co2) <- flatten FM_FlattenAll ev ty2
913 -- We must flatten the types before putting them in the
914 -- inert set, so that we are sure to kick them out when
915 -- new equalities become available
916 ; traceTcS "canEqFailure with ReprEq" $
917 vcat [ ppr ev, ppr ty1, ppr ty2, ppr xi1, ppr xi2 ]
918 ; rewriteEqEvidence ev ReprEq NotSwapped xi1 xi2 co1 co2
919 `andWhenContinue` \ new_ev ->
920 continueWith (CIrredEvCan { cc_ev = new_ev }) }
921
922 -- | Call when canonicalizing an equality fails with utterly no hope.
923 canEqHardFailure :: CtEvidence -> EqRel
924 -> TcType -> TcType -> TcS (StopOrContinue Ct)
925 -- See Note [Make sure that insolubles are fully rewritten]
926 canEqHardFailure ev eq_rel ty1 ty2
927 = do { (s1, co1) <- flatten FM_SubstOnly ev ty1
928 ; (s2, co2) <- flatten FM_SubstOnly ev ty2
929 ; rewriteEqEvidence ev eq_rel NotSwapped s1 s2 co1 co2
930 `andWhenContinue` \ new_ev ->
931 do { emitInsoluble (mkNonCanonical new_ev)
932 ; stopWith new_ev "Definitely not equal" }}
933
934 {-
935 Note [Decomposing TyConApps]
936 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
937 If we see (T s1 t1 ~ T s2 t2), then we can just decompose to
938 (s1 ~ s2, t1 ~ t2)
939 and push those back into the work list. But if
940 s1 = K k1 s2 = K k2
941 then we will jus decomopose s1~s2, and it might be better to
942 do so on the spot. An important special case is where s1=s2,
943 and we get just Refl.
944
945 So canDecomposableTyCon is a fast-path decomposition that uses
946 unifyWanted etc to short-cut that work.
947
948 Note [Canonicalising type applications]
949 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
950 Given (s1 t1) ~ ty2, how should we proceed?
951 The simple things is to see if ty2 is of form (s2 t2), and
952 decompose. By this time s1 and s2 can't be saturated type
953 function applications, because those have been dealt with
954 by an earlier equation in can_eq_nc, so it is always sound to
955 decompose.
956
957 However, over-eager decomposition gives bad error messages
958 for things like
959 a b ~ Maybe c
960 e f ~ p -> q
961 Suppose (in the first example) we already know a~Array. Then if we
962 decompose the application eagerly, yielding
963 a ~ Maybe
964 b ~ c
965 we get an error "Can't match Array ~ Maybe",
966 but we'd prefer to get "Can't match Array b ~ Maybe c".
967
968 So instead can_eq_wanted_app flattens the LHS and RHS, in the hope of
969 replacing (a b) by (Array b), before using try_decompose_app to
970 decompose it.
971
972 Note [Make sure that insolubles are fully rewritten]
973 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
974 When an equality fails, we still want to rewrite the equality
975 all the way down, so that it accurately reflects
976 (a) the mutable reference substitution in force at start of solving
977 (b) any ty-binds in force at this point in solving
978 See Note [Kick out insolubles] in TcSMonad.
979 And if we don't do this there is a bad danger that
980 TcSimplify.applyTyVarDefaulting will find a variable
981 that has in fact been substituted.
982
983 Note [Do not decompose Given polytype equalities]
984 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
985 Consider [G] (forall a. t1 ~ forall a. t2). Can we decompose this?
986 No -- what would the evidence look like? So instead we simply discard
987 this given evidence.
988
989
990 Note [Combining insoluble constraints]
991 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
992 As this point we have an insoluble constraint, like Int~Bool.
993
994 * If it is Wanted, delete it from the cache, so that subsequent
995 Int~Bool constraints give rise to separate error messages
996
997 * But if it is Derived, DO NOT delete from cache. A class constraint
998 may get kicked out of the inert set, and then have its functional
999 dependency Derived constraints generated a second time. In that
1000 case we don't want to get two (or more) error messages by
1001 generating two (or more) insoluble fundep constraints from the same
1002 class constraint.
1003
1004 Note [No top-level newtypes on RHS of representational equalities]
1005 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1006 Suppose we're in this situation:
1007
1008 work item: [W] c1 : a ~R b
1009 inert: [G] c2 : b ~R Id a
1010
1011 where
1012 newtype Id a = Id a
1013
1014 We want to make sure canEqTyVar sees [W] a ~R a, after b is flattened
1015 and the Id newtype is unwrapped. This is assured by requiring only flat
1016 types in canEqTyVar *and* having the newtype-unwrapping check above
1017 the tyvar check in can_eq_nc.
1018
1019 -}
1020
1021 canCFunEqCan :: CtEvidence
1022 -> TyCon -> [TcType] -- LHS
1023 -> TcTyVar -- RHS
1024 -> TcS (StopOrContinue Ct)
1025 -- ^ Canonicalise a CFunEqCan. We know that
1026 -- the arg types are already flat,
1027 -- and the RHS is a fsk, which we must *not* substitute.
1028 -- So just substitute in the LHS
1029 canCFunEqCan ev fn tys fsk
1030 = do { (tys', cos) <- flattenManyNom ev tys
1031 -- cos :: tys' ~ tys
1032 ; let lhs_co = mkTcTyConAppCo Nominal fn cos
1033 -- :: F tys' ~ F tys
1034 new_lhs = mkTyConApp fn tys'
1035 fsk_ty = mkTyVarTy fsk
1036 ; rewriteEqEvidence ev NomEq NotSwapped new_lhs fsk_ty
1037 lhs_co (mkTcNomReflCo fsk_ty)
1038 `andWhenContinue` \ ev' ->
1039 do { extendFlatCache fn tys' (ctEvCoercion ev', fsk_ty, ctEvFlavour ev')
1040 ; continueWith (CFunEqCan { cc_ev = ev', cc_fun = fn
1041 , cc_tyargs = tys', cc_fsk = fsk }) } }
1042
1043 ---------------------
1044 canEqTyVar :: CtEvidence -> EqRel -> SwapFlag
1045 -> TcTyVar -- already flat
1046 -> TcType -- already flat
1047 -> TcS (StopOrContinue Ct)
1048 -- A TyVar on LHS, but so far un-zonked
1049 canEqTyVar ev eq_rel swapped tv1 ps_ty2 -- ev :: tv ~ s2
1050 = do { traceTcS "canEqTyVar" (ppr tv1 $$ ppr ps_ty2 $$ ppr swapped)
1051 -- FM_Avoid commented out: see Note [Lazy flattening] in TcFlatten
1052 -- let fmode = FE { fe_ev = ev, fe_mode = FM_Avoid tv1' True }
1053 -- Flatten the RHS less vigorously, to avoid gratuitous flattening
1054 -- True <=> xi2 should not itself be a type-function application
1055 ; dflags <- getDynFlags
1056 ; canEqTyVar2 dflags ev eq_rel swapped tv1 ps_ty2 }
1057
1058 canEqTyVar2 :: DynFlags
1059 -> CtEvidence -- lhs ~ rhs (or, if swapped, orhs ~ olhs)
1060 -> EqRel
1061 -> SwapFlag
1062 -> TcTyVar -- lhs, flat
1063 -> TcType -- rhs, flat
1064 -> TcS (StopOrContinue Ct)
1065 -- LHS is an inert type variable,
1066 -- and RHS is fully rewritten, but with type synonyms
1067 -- preserved as much as possible
1068
1069 canEqTyVar2 dflags ev eq_rel swapped tv1 xi2
1070 | Just tv2 <- getTyVar_maybe xi2
1071 = canEqTyVarTyVar ev eq_rel swapped tv1 tv2
1072
1073 | OC_OK xi2' <- occurCheckExpand dflags tv1 xi2 -- No occurs check
1074 -- We use xi2' on the RHS of the new CTyEqCan, a ~ xi2'
1075 -- to establish the invariant that a does not appear in the
1076 -- rhs of the CTyEqCan. This is guaranteed by occurCheckExpand;
1077 -- see Note [Occurs check expansion] in TcType
1078 = do { let k1 = tyVarKind tv1
1079 k2 = typeKind xi2'
1080 ; rewriteEqEvidence ev eq_rel swapped xi1 xi2' co1 (mkTcReflCo role xi2')
1081 `andWhenContinue` \ new_ev ->
1082 if k2 `isSubKind` k1
1083 then -- Establish CTyEqCan kind invariant
1084 -- Reorientation has done its best, but the kinds might
1085 -- simply be incompatible
1086 continueWith (CTyEqCan { cc_ev = new_ev
1087 , cc_tyvar = tv1, cc_rhs = xi2'
1088 , cc_eq_rel = eq_rel })
1089 else incompatibleKind new_ev xi1 k1 xi2' k2 }
1090
1091 | otherwise -- Occurs check error
1092 = rewriteEqEvidence ev eq_rel swapped xi1 xi2 co1 co2
1093 `andWhenContinue` \ new_ev ->
1094 case eq_rel of
1095 NomEq -> do { emitInsoluble (mkNonCanonical new_ev)
1096 -- If we have a ~ [a], it is not canonical, and in particular
1097 -- we don't want to rewrite existing inerts with it, otherwise
1098 -- we'd risk divergence in the constraint solver
1099 ; stopWith new_ev "Occurs check" }
1100
1101 -- A representational equality with an occurs-check problem isn't
1102 -- insoluble! For example:
1103 -- a ~R b a
1104 -- We might learn that b is the newtype Id.
1105 -- But, the occurs-check certainly prevents the equality from being
1106 -- canonical, and we might loop if we were to use it in rewriting.
1107 ReprEq -> do { traceTcS "Occurs-check in representational equality"
1108 (ppr xi1 $$ ppr xi2)
1109 ; continueWith (CIrredEvCan { cc_ev = new_ev }) }
1110 where
1111 role = eqRelRole eq_rel
1112 xi1 = mkTyVarTy tv1
1113 co1 = mkTcReflCo role xi1
1114 co2 = mkTcReflCo role xi2
1115
1116 canEqTyVarTyVar :: CtEvidence -- tv1 ~ rhs (or rhs ~ tv1, if swapped)
1117 -> EqRel
1118 -> SwapFlag
1119 -> TcTyVar -> TcTyVar -- tv1, tv2
1120 -> TcS (StopOrContinue Ct)
1121 -- Both LHS and RHS rewrote to a type variable
1122 -- See Note [Canonical orientation for tyvar/tyvar equality constraints]
1123 canEqTyVarTyVar ev eq_rel swapped tv1 tv2
1124 | tv1 == tv2
1125 = do { setEvBindIfWanted ev (EvCoercion $ mkTcReflCo role xi1)
1126 ; stopWith ev "Equal tyvars" }
1127
1128 | incompat_kind = incompatibleKind ev xi1 k1 xi2 k2
1129
1130 -- We don't do this any more
1131 -- See Note [Orientation of equalities with fmvs] in TcFlatten
1132 -- | isFmvTyVar tv1 = do_fmv swapped tv1 xi1 xi2 co1 co2
1133 -- | isFmvTyVar tv2 = do_fmv (flipSwap swapped) tv2 xi2 xi1 co2 co1
1134
1135 | same_kind = if swap_over then do_swap else no_swap
1136 | k1_sub_k2 = do_swap -- Note [Kind orientation for CTyEqCan]
1137 | otherwise = no_swap -- k2_sub_k1
1138 where
1139 role = eqRelRole eq_rel
1140 xi1 = mkTyVarTy tv1
1141 co1 = mkTcReflCo role xi1
1142 xi2 = mkTyVarTy tv2
1143 co2 = mkTcReflCo role xi2
1144 k1 = tyVarKind tv1
1145 k2 = tyVarKind tv2
1146 k1_sub_k2 = k1 `isSubKind` k2
1147 k2_sub_k1 = k2 `isSubKind` k1
1148 same_kind = k1_sub_k2 && k2_sub_k1
1149 incompat_kind = not (k1_sub_k2 || k2_sub_k1)
1150
1151 no_swap = canon_eq swapped tv1 xi1 xi2 co1 co2
1152 do_swap = canon_eq (flipSwap swapped) tv2 xi2 xi1 co2 co1
1153
1154 canon_eq swapped tv1 xi1 xi2 co1 co2
1155 -- ev : tv1 ~ rhs (not swapped) or rhs ~ tv1 (swapped)
1156 = rewriteEqEvidence ev eq_rel swapped xi1 xi2 co1 co2
1157 `andWhenContinue` \ new_ev ->
1158 continueWith (CTyEqCan { cc_ev = new_ev, cc_tyvar = tv1
1159 , cc_rhs = xi2, cc_eq_rel = eq_rel })
1160
1161 {- We don't do this any more
1162 See Note [Orientation of equalities with fmvs] in TcFlatten
1163 -- tv1 is the flatten meta-var
1164 do_fmv swapped tv1 xi1 xi2 co1 co2
1165 | same_kind
1166 = canon_eq swapped tv1 xi1 xi2 co1 co2
1167 | otherwise -- Presumably tv1 :: *, since it is a flatten meta-var,
1168 -- at a kind that has some interesting sub-kind structure.
1169 -- Since the two kinds are not the same, we must have
1170 -- tv1 `subKind` tv2, which is the wrong way round
1171 -- e.g. (fmv::*) ~ (a::OpenKind)
1172 -- So make a new meta-var and use that:
1173 -- fmv ~ (beta::*)
1174 -- (a::OpenKind) ~ (beta::*)
1175 = ASSERT2( k1_sub_k2,
1176 ppr tv1 <+> dcolon <+> ppr (tyVarKind tv1) $$
1177 ppr xi2 <+> dcolon <+> ppr (typeKind xi2) )
1178 ASSERT2( isWanted ev, ppr ev ) -- Only wanteds have flatten meta-vars
1179 do { tv_ty <- newFlexiTcSTy (tyVarKind tv1)
1180 ; new_ev <- newWantedEvVarNC (ctEvLoc ev)
1181 (mkTcEqPredRole (eqRelRole eq_rel)
1182 tv_ty xi2)
1183 ; emitWorkNC [new_ev]
1184 ; canon_eq swapped tv1 xi1 tv_ty co1 (ctEvCoercion new_ev) }
1185 -}
1186
1187 swap_over
1188 -- If tv1 is touchable, swap only if tv2 is also
1189 -- touchable and it's strictly better to update the latter
1190 -- But see Note [Avoid unnecessary swaps]
1191 | Just lvl1 <- metaTyVarTcLevel_maybe tv1
1192 = case metaTyVarTcLevel_maybe tv2 of
1193 Nothing -> False
1194 Just lvl2 | lvl2 `strictlyDeeperThan` lvl1 -> True
1195 | lvl1 `strictlyDeeperThan` lvl2 -> False
1196 | otherwise -> nicer_to_update_tv2
1197
1198 -- So tv1 is not a meta tyvar
1199 -- If only one is a meta tyvar, put it on the left
1200 -- This is not because it'll be solved; but because
1201 -- the floating step looks for meta tyvars on the left
1202 | isMetaTyVar tv2 = True
1203
1204 -- So neither is a meta tyvar
1205
1206 -- If only one is a flatten tyvar, put it on the left
1207 -- See Note [Eliminate flat-skols]
1208 | not (isFlattenTyVar tv1), isFlattenTyVar tv2 = True
1209
1210 | otherwise = False
1211
1212 nicer_to_update_tv2
1213 = (isSigTyVar tv1 && not (isSigTyVar tv2))
1214 || (isSystemName (Var.varName tv2) && not (isSystemName (Var.varName tv1)))
1215
1216 -- | Solve a reflexive equality constraint
1217 canEqReflexive :: CtEvidence -- ty ~ ty
1218 -> EqRel
1219 -> TcType -- ty
1220 -> TcS (StopOrContinue Ct) -- always Stop
1221 canEqReflexive ev eq_rel ty
1222 = do { setEvBindIfWanted ev (EvCoercion $
1223 mkTcReflCo (eqRelRole eq_rel) ty)
1224 ; stopWith ev "Solved by reflexivity" }
1225
1226 incompatibleKind :: CtEvidence -- t1~t2
1227 -> TcType -> TcKind
1228 -> TcType -> TcKind -- s1~s2, flattened and zonked
1229 -> TcS (StopOrContinue Ct)
1230 -- LHS and RHS have incompatible kinds, so emit an "irreducible" constraint
1231 -- CIrredEvCan (NOT CTyEqCan or CFunEqCan)
1232 -- for the type equality; and continue with the kind equality constraint.
1233 -- When the latter is solved, it'll kick out the irreducible equality for
1234 -- a second attempt at solving
1235 --
1236 -- See Note [Equalities with incompatible kinds]
1237
1238 incompatibleKind new_ev s1 k1 s2 k2 -- See Note [Equalities with incompatible kinds]
1239 = ASSERT( isKind k1 && isKind k2 )
1240 do { traceTcS "canEqLeaf: incompatible kinds" (vcat [ppr k1, ppr k2])
1241
1242 -- Create a derived kind-equality, and solve it
1243 ; emitNewDerivedEq kind_co_loc (mkTcEqPred k1 k2)
1244
1245 -- Put the not-currently-soluble thing into the inert set
1246 ; continueWith (CIrredEvCan { cc_ev = new_ev }) }
1247 where
1248 loc = ctEvLoc new_ev
1249 kind_co_loc = setCtLocOrigin loc (KindEqOrigin s1 s2 (ctLocOrigin loc))
1250
1251 {-
1252 Note [Canonical orientation for tyvar/tyvar equality constraints]
1253 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1254 When we have a ~ b where both 'a' and 'b' are TcTyVars, which way
1255 round should be oriented in the CTyEqCan? The rules, implemented by
1256 canEqTyVarTyVar, are these
1257
1258 * If either is a flatten-meta-variables, it goes on the left.
1259
1260 * If one is a strict sub-kind of the other e.g.
1261 (alpha::?) ~ (beta::*)
1262 orient them so RHS is a subkind of LHS. That way we will replace
1263 'a' with 'b', correctly narrowing the kind.
1264 This establishes the subkind invariant of CTyEqCan.
1265
1266 * Put a meta-tyvar on the left if possible
1267 alpha[3] ~ r
1268
1269 * If both are meta-tyvars, put the more touchable one (deepest level
1270 number) on the left, so there is the best chance of unifying it
1271 alpha[3] ~ beta[2]
1272
1273 * If both are meta-tyvars and both at the same level, put a SigTv
1274 on the right if possible
1275 alpha[2] ~ beta[2](sig-tv)
1276 That way, when we unify alpha := beta, we don't lose the SigTv flag.
1277
1278 * Put a meta-tv with a System Name on the left if possible so it
1279 gets eliminated (improves error messages)
1280
1281 * If one is a flatten-skolem, put it on the left so that it is
1282 substituted out Note [Elminate flat-skols]
1283 fsk ~ a
1284
1285 Note [Avoid unnecessary swaps]
1286 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1287 If we swap without actually improving matters, we can get an infnite loop.
1288 Consider
1289 work item: a ~ b
1290 inert item: b ~ c
1291 We canonicalise the work-time to (a ~ c). If we then swap it before
1292 aeding to the inert set, we'll add (c ~ a), and therefore kick out the
1293 inert guy, so we get
1294 new work item: b ~ c
1295 inert item: c ~ a
1296 And now the cycle just repeats
1297
1298 Note [Eliminate flat-skols]
1299 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
1300 Suppose we have [G] Num (F [a])
1301 then we flatten to
1302 [G] Num fsk
1303 [G] F [a] ~ fsk
1304 where fsk is a flatten-skolem (FlatSkol). Suppose we have
1305 type instance F [a] = a
1306 then we'll reduce the second constraint to
1307 [G] a ~ fsk
1308 and then replace all uses of 'a' with fsk. That's bad because
1309 in error messages intead of saying 'a' we'll say (F [a]). In all
1310 places, including those where the programmer wrote 'a' in the first
1311 place. Very confusing! See Trac #7862.
1312
1313 Solution: re-orient a~fsk to fsk~a, so that we preferentially eliminate
1314 the fsk.
1315
1316 Note [Equalities with incompatible kinds]
1317 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1318 canEqLeaf is about to make a CTyEqCan or CFunEqCan; but both have the
1319 invariant that LHS and RHS satisfy the kind invariants for CTyEqCan,
1320 CFunEqCan. What if we try to unify two things with incompatible
1321 kinds?
1322
1323 eg a ~ b where a::*, b::*->*
1324 or a ~ b where a::*, b::k, k is a kind variable
1325
1326 The CTyEqCan compatKind invariant is important. If we make a CTyEqCan
1327 for a~b, then we might well *substitute* 'b' for 'a', and that might make
1328 a well-kinded type ill-kinded; and that is bad (eg typeKind can crash, see
1329 Trac #7696).
1330
1331 So instead for these ill-kinded equalities we generate a CIrredCan,
1332 and put it in the inert set, which keeps it out of the way until a
1333 subsequent substitution (on kind variables, say) re-activates it.
1334
1335 NB: it is important that the types s1,s2 are flattened and zonked
1336 so that their kinds k1, k2 are inert wrt the substitution. That
1337 means that they can only become the same if we change the inert
1338 set, which in turn will kick out the irreducible equality
1339 E.g. it is WRONG to make an irred (a:k1)~(b:k2)
1340 if we already have a substitution k1:=k2
1341
1342 NB: it's important that the new CIrredCan goes in the inert set rather
1343 than back into the work list. We used to do the latter, but that led
1344 to an infinite loop when we encountered it again, and put it back in
1345 the work list again.
1346
1347 See also Note [Kind orientation for CTyEqCan] and
1348 Note [Kind orientation for CFunEqCan] in TcRnTypes
1349
1350 Note [Type synonyms and canonicalization]
1351 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1352 We treat type synonym applications as xi types, that is, they do not
1353 count as type function applications. However, we do need to be a bit
1354 careful with type synonyms: like type functions they may not be
1355 generative or injective. However, unlike type functions, they are
1356 parametric, so there is no problem in expanding them whenever we see
1357 them, since we do not need to know anything about their arguments in
1358 order to expand them; this is what justifies not having to treat them
1359 as specially as type function applications. The thing that causes
1360 some subtleties is that we prefer to leave type synonym applications
1361 *unexpanded* whenever possible, in order to generate better error
1362 messages.
1363
1364 If we encounter an equality constraint with type synonym applications
1365 on both sides, or a type synonym application on one side and some sort
1366 of type application on the other, we simply must expand out the type
1367 synonyms in order to continue decomposing the equality constraint into
1368 primitive equality constraints. For example, suppose we have
1369
1370 type F a = [Int]
1371
1372 and we encounter the equality
1373
1374 F a ~ [b]
1375
1376 In order to continue we must expand F a into [Int], giving us the
1377 equality
1378
1379 [Int] ~ [b]
1380
1381 which we can then decompose into the more primitive equality
1382 constraint
1383
1384 Int ~ b.
1385
1386 However, if we encounter an equality constraint with a type synonym
1387 application on one side and a variable on the other side, we should
1388 NOT (necessarily) expand the type synonym, since for the purpose of
1389 good error messages we want to leave type synonyms unexpanded as much
1390 as possible. Hence the ps_ty1, ps_ty2 argument passed to canEqTyVar.
1391
1392 -}
1393
1394 {-
1395 ************************************************************************
1396 * *
1397 Evidence transformation
1398 * *
1399 ************************************************************************
1400 -}
1401
1402 data StopOrContinue a
1403 = ContinueWith a -- The constraint was not solved, although it may have
1404 -- been rewritten
1405
1406 | Stop CtEvidence -- The (rewritten) constraint was solved
1407 SDoc -- Tells how it was solved
1408 -- Any new sub-goals have been put on the work list
1409
1410 instance Functor StopOrContinue where
1411 fmap f (ContinueWith x) = ContinueWith (f x)
1412 fmap _ (Stop ev s) = Stop ev s
1413
1414 instance Outputable a => Outputable (StopOrContinue a) where
1415 ppr (Stop ev s) = ptext (sLit "Stop") <> parens s <+> ppr ev
1416 ppr (ContinueWith w) = ptext (sLit "ContinueWith") <+> ppr w
1417
1418 continueWith :: a -> TcS (StopOrContinue a)
1419 continueWith = return . ContinueWith
1420
1421 stopWith :: CtEvidence -> String -> TcS (StopOrContinue a)
1422 stopWith ev s = return (Stop ev (text s))
1423
1424 andWhenContinue :: TcS (StopOrContinue a)
1425 -> (a -> TcS (StopOrContinue b))
1426 -> TcS (StopOrContinue b)
1427 andWhenContinue tcs1 tcs2
1428 = do { r <- tcs1
1429 ; case r of
1430 Stop ev s -> return (Stop ev s)
1431 ContinueWith ct -> tcs2 ct }
1432 infixr 0 `andWhenContinue` -- allow chaining with ($)
1433
1434 rewriteEvidence :: CtEvidence -- old evidence
1435 -> TcPredType -- new predicate
1436 -> TcCoercion -- Of type :: new predicate ~ <type of old evidence>
1437 -> TcS (StopOrContinue CtEvidence)
1438 -- Returns Just new_ev iff either (i) 'co' is reflexivity
1439 -- or (ii) 'co' is not reflexivity, and 'new_pred' not cached
1440 -- In either case, there is nothing new to do with new_ev
1441 {-
1442 rewriteEvidence old_ev new_pred co
1443 Main purpose: create new evidence for new_pred;
1444 unless new_pred is cached already
1445 * Returns a new_ev : new_pred, with same wanted/given/derived flag as old_ev
1446 * If old_ev was wanted, create a binding for old_ev, in terms of new_ev
1447 * If old_ev was given, AND not cached, create a binding for new_ev, in terms of old_ev
1448 * Returns Nothing if new_ev is already cached
1449
1450 Old evidence New predicate is Return new evidence
1451 flavour of same flavor
1452 -------------------------------------------------------------------
1453 Wanted Already solved or in inert Nothing
1454 or Derived Not Just new_evidence
1455
1456 Given Already in inert Nothing
1457 Not Just new_evidence
1458
1459 Note [Rewriting with Refl]
1460 ~~~~~~~~~~~~~~~~~~~~~~~~~~
1461 If the coercion is just reflexivity then you may re-use the same
1462 variable. But be careful! Although the coercion is Refl, new_pred
1463 may reflect the result of unification alpha := ty, so new_pred might
1464 not _look_ the same as old_pred, and it's vital to proceed from now on
1465 using new_pred.
1466
1467 The flattener preserves type synonyms, so they should appear in new_pred
1468 as well as in old_pred; that is important for good error messages.
1469 -}
1470
1471
1472 rewriteEvidence old_ev@(CtDerived {}) new_pred _co
1473 = -- If derived, don't even look at the coercion.
1474 -- This is very important, DO NOT re-order the equations for
1475 -- rewriteEvidence to put the isTcReflCo test first!
1476 -- Why? Because for *Derived* constraints, c, the coercion, which
1477 -- was produced by flattening, may contain suspended calls to
1478 -- (ctEvTerm c), which fails for Derived constraints.
1479 -- (Getting this wrong caused Trac #7384.)
1480 continueWith (old_ev { ctev_pred = new_pred })
1481
1482 rewriteEvidence old_ev new_pred co
1483 | isTcReflCo co -- See Note [Rewriting with Refl]
1484 = continueWith (old_ev { ctev_pred = new_pred })
1485
1486 rewriteEvidence ev@(CtGiven { ctev_evar = old_evar , ctev_loc = loc }) new_pred co
1487 = do { new_ev <- newGivenEvVar loc (new_pred, new_tm)
1488 ; continueWith new_ev }
1489 where
1490 -- mkEvCast optimises ReflCo
1491 new_tm = mkEvCast (EvId old_evar) (tcDowngradeRole Representational
1492 (ctEvRole ev)
1493 (mkTcSymCo co))
1494
1495 rewriteEvidence ev@(CtWanted { ctev_evar = evar, ctev_loc = loc }) new_pred co
1496 = do { (new_ev, freshness) <- newWantedEvVar loc new_pred
1497 ; MASSERT( tcCoercionRole co == ctEvRole ev )
1498 ; setWantedEvBind evar (mkEvCast (ctEvTerm new_ev)
1499 (tcDowngradeRole Representational (ctEvRole ev) co))
1500 ; case freshness of
1501 Fresh -> continueWith new_ev
1502 Cached -> stopWith ev "Cached wanted" }
1503
1504
1505 rewriteEqEvidence :: CtEvidence -- Old evidence :: olhs ~ orhs (not swapped)
1506 -- or orhs ~ olhs (swapped)
1507 -> EqRel
1508 -> SwapFlag
1509 -> TcType -> TcType -- New predicate nlhs ~ nrhs
1510 -- Should be zonked, because we use typeKind on nlhs/nrhs
1511 -> TcCoercion -- lhs_co, of type :: nlhs ~ olhs
1512 -> TcCoercion -- rhs_co, of type :: nrhs ~ orhs
1513 -> TcS (StopOrContinue CtEvidence) -- Of type nlhs ~ nrhs
1514 -- For (rewriteEqEvidence (Given g olhs orhs) False nlhs nrhs lhs_co rhs_co)
1515 -- we generate
1516 -- If not swapped
1517 -- g1 : nlhs ~ nrhs = lhs_co ; g ; sym rhs_co
1518 -- If 'swapped'
1519 -- g1 : nlhs ~ nrhs = lhs_co ; Sym g ; sym rhs_co
1520 --
1521 -- For (Wanted w) we do the dual thing.
1522 -- New w1 : nlhs ~ nrhs
1523 -- If not swapped
1524 -- w : olhs ~ orhs = sym lhs_co ; w1 ; rhs_co
1525 -- If swapped
1526 -- w : orhs ~ olhs = sym rhs_co ; sym w1 ; lhs_co
1527 --
1528 -- It's all a form of rewwriteEvidence, specialised for equalities
1529 rewriteEqEvidence old_ev eq_rel swapped nlhs nrhs lhs_co rhs_co
1530 | CtDerived {} <- old_ev -- Don't force the evidence for a Derived
1531 = continueWith (old_ev { ctev_pred = new_pred })
1532
1533 | NotSwapped <- swapped
1534 , isTcReflCo lhs_co -- See Note [Rewriting with Refl]
1535 , isTcReflCo rhs_co
1536 = continueWith (old_ev { ctev_pred = new_pred })
1537
1538 | CtGiven { ctev_evar = old_evar } <- old_ev
1539 = do { let new_tm = EvCoercion (lhs_co
1540 `mkTcTransCo` maybeSym swapped (mkTcCoVarCo old_evar)
1541 `mkTcTransCo` mkTcSymCo rhs_co)
1542 ; new_ev <- newGivenEvVar loc' (new_pred, new_tm)
1543 ; continueWith new_ev }
1544
1545 | CtWanted { ctev_evar = evar } <- old_ev
1546 = do { new_evar <- newWantedEvVarNC loc' new_pred
1547 ; let co = maybeSym swapped $
1548 mkTcSymCo lhs_co
1549 `mkTcTransCo` ctEvCoercion new_evar
1550 `mkTcTransCo` rhs_co
1551 ; setWantedEvBind evar (EvCoercion co)
1552 ; traceTcS "rewriteEqEvidence" (vcat [ppr old_ev, ppr nlhs, ppr nrhs, ppr co])
1553 ; continueWith new_evar }
1554
1555 | otherwise
1556 = panic "rewriteEvidence"
1557 where
1558 new_pred = mkTcEqPredRole (eqRelRole eq_rel) nlhs nrhs
1559
1560 -- equality is like a type class. Bumping the depth is necessary because
1561 -- of recursive newtypes, where "reducing" a newtype can actually make
1562 -- it bigger. See Note [Newtypes can blow the stack].
1563 loc' = bumpCtLocDepth (ctEvLoc old_ev)
1564
1565 {- Note [unifyWanted and unifyDerived]
1566 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1567 When decomposing equalities we often create new wanted constraints for
1568 (s ~ t). But what if s=t? Then it'd be faster to return Refl right away.
1569 Similar remarks apply for Derived.
1570
1571 Rather than making an equality test (which traverses the structure of the
1572 type, perhaps fruitlessly, unifyWanted traverses the common structure, and
1573 bales out when it finds a difference by creating a new Wanted constraint.
1574 But where it succeeds in finding common structure, it just builds a coercion
1575 to reflect it.
1576 -}
1577
1578 unifyWanted :: CtLoc -> Role -> TcType -> TcType -> TcS TcCoercion
1579 -- Return coercion witnessing the equality of the two types,
1580 -- emitting new work equalities where necessary to achieve that
1581 -- Very good short-cut when the two types are equal, or nearly so
1582 -- See Note [unifyWanted and unifyDerived]
1583 -- The returned coercion's role matches the input parameter
1584 unifyWanted _ Phantom ty1 ty2 = return (mkTcPhantomCo ty1 ty2)
1585 unifyWanted loc role orig_ty1 orig_ty2
1586 = go orig_ty1 orig_ty2
1587 where
1588 go ty1 ty2 | Just ty1' <- tcView ty1 = go ty1' ty2
1589 go ty1 ty2 | Just ty2' <- tcView ty2 = go ty1 ty2'
1590
1591 go (FunTy s1 t1) (FunTy s2 t2)
1592 = do { co_s <- unifyWanted loc role s1 s2
1593 ; co_t <- unifyWanted loc role t1 t2
1594 ; return (mkTcTyConAppCo role funTyCon [co_s,co_t]) }
1595 go (TyConApp tc1 tys1) (TyConApp tc2 tys2)
1596 | tc1 == tc2, tys1 `equalLength` tys2
1597 , isInjectiveTyCon tc1 role -- don't look under newtypes at Rep equality
1598 = do { cos <- zipWith3M (unifyWanted loc) (tyConRolesX role tc1) tys1 tys2
1599 ; return (mkTcTyConAppCo role tc1 cos) }
1600 go (TyVarTy tv) ty2
1601 = do { mb_ty <- isFilledMetaTyVar_maybe tv
1602 ; case mb_ty of
1603 Just ty1' -> go ty1' ty2
1604 Nothing -> bale_out }
1605 go ty1 (TyVarTy tv)
1606 = do { mb_ty <- isFilledMetaTyVar_maybe tv
1607 ; case mb_ty of
1608 Just ty2' -> go ty1 ty2'
1609 Nothing -> bale_out }
1610 go _ _ = bale_out
1611
1612 bale_out = do { ev <- newWantedEvVarNC loc (mkTcEqPredRole role
1613 orig_ty1 orig_ty2)
1614 ; emitWorkNC [ev]
1615 ; return (ctEvCoercion ev) }
1616
1617 unifyDeriveds :: CtLoc -> [Role] -> [TcType] -> [TcType] -> TcS ()
1618 -- See Note [unifyWanted and unifyDerived]
1619 unifyDeriveds loc roles tys1 tys2 = zipWith3M_ (unify_derived loc) roles tys1 tys2
1620
1621 unifyDerived :: CtLoc -> Role -> Pair TcType -> TcS ()
1622 -- See Note [unifyWanted and unifyDerived]
1623 unifyDerived loc role (Pair ty1 ty2) = unify_derived loc role ty1 ty2
1624
1625 unify_derived :: CtLoc -> Role -> TcType -> TcType -> TcS ()
1626 -- Create new Derived and put it in the work list
1627 -- Should do nothing if the two types are equal
1628 -- See Note [unifyWanted and unifyDerived]
1629 unify_derived _ Phantom _ _ = return ()
1630 unify_derived loc role orig_ty1 orig_ty2
1631 = go orig_ty1 orig_ty2
1632 where
1633 go ty1 ty2 | Just ty1' <- tcView ty1 = go ty1' ty2
1634 go ty1 ty2 | Just ty2' <- tcView ty2 = go ty1 ty2'
1635
1636 go (FunTy s1 t1) (FunTy s2 t2)
1637 = do { unify_derived loc role s1 s2
1638 ; unify_derived loc role t1 t2 }
1639 go (TyConApp tc1 tys1) (TyConApp tc2 tys2)
1640 | tc1 == tc2, tys1 `equalLength` tys2
1641 , isInjectiveTyCon tc1 role
1642 = unifyDeriveds loc (tyConRolesX role tc1) tys1 tys2
1643 go (TyVarTy tv) ty2
1644 = do { mb_ty <- isFilledMetaTyVar_maybe tv
1645 ; case mb_ty of
1646 Just ty1' -> go ty1' ty2
1647 Nothing -> bale_out }
1648 go ty1 (TyVarTy tv)
1649 = do { mb_ty <- isFilledMetaTyVar_maybe tv
1650 ; case mb_ty of
1651 Just ty2' -> go ty1 ty2'
1652 Nothing -> bale_out }
1653 go _ _ = bale_out
1654
1655 bale_out = emitNewDerivedEq loc (mkTcEqPredRole role orig_ty1 orig_ty2)
1656
1657 maybeSym :: SwapFlag -> TcCoercion -> TcCoercion
1658 maybeSym IsSwapped co = mkTcSymCo co
1659 maybeSym NotSwapped co = co