3 mkCanonical, mkCanonicals, canWanteds, canGivens, canOccursCheck,
7 #include "HsVersions.h"
22 import Control.Monad ( when, zipWithM )
24 import Control.Applicative ( (<|>) )
29 import Control.Monad ( unless )
30 import TcSMonad -- The TcS Monad
33 Note [Canonicalisation]
34 ~~~~~~~~~~~~~~~~~~~~~~~
35 * Converts (Constraint f) _which_does_not_contain_proper_implications_ to CanonicalCts
36 * Unary: treats individual constraints one at a time
37 * Does not do any zonking
38 * Lives in TcS monad so that it can create new skolem variables
41 %************************************************************************
43 %* Flattening (eliminating all function symbols) *
45 %************************************************************************
49 flatten ty ==> (xi, cc)
51 xi has no type functions
52 cc = Auxiliary given (equality) constraints constraining
53 the fresh type variables in xi. Evidence for these
54 is always the identity coercion, because internally the
55 fresh flattening skolem variables are actually identified
56 with the types they have been generated to stand in for.
58 Note that it is flatten's job to flatten *every type function it sees*.
59 flatten is only called on *arguments* to type functions, by canEqGiven.
61 Recall that in comments we use alpha[flat = ty] to represent a
62 flattening skolem variable alpha which has been generated to stand in
65 ----- Example of flattening a constraint: ------
66 flatten (List (F (G Int))) ==> (xi, cc)
69 cc = { G Int ~ beta[flat = G Int],
70 F beta ~ alpha[flat = F beta] }
72 * alpha and beta are 'flattening skolem variables'.
73 * All the constraints in cc are 'given', and all their coercion terms
76 NB: Flattening Skolems only occur in canonical constraints, which
77 are never zonked, so we don't need to worry about zonking doing
78 accidental unflattening.
80 NB: Note that (unlike the OutsideIn(X) draft of 7 May 2010) we are
81 actually doing the SAME thing here no matter whether we are flattening
82 a wanted or a given constraint. In both cases we simply generate some
83 flattening skolem variables and some extra given constraints; we never
84 generate actual unification variables or non-identity coercions.
85 Hopefully this will work, although SPJ had some vague worries about
86 unification variables from wanted constraints finding their way into
87 the generated given constraints...?
89 Note that we prefer to leave type synonyms unexpanded when possible,
90 so when the flattener encounters one, it first asks whether its
91 transitive expansion contains any type function applications. If so,
92 it expands the synonym and proceeds; if not, it simply returns the
95 TODO: caching the information about whether transitive synonym
96 expansions contain any type function applications would speed things
97 up a bit; right now we waste a lot of energy traversing the same types
101 -- Flatten a bunch of types all at once.
102 flattenMany :: CtFlavor -> [Type] -> TcS ([Xi], CanonicalCts)
104 = do { (xis, cts_s) <- mapAndUnzipM (flatten ctxt) tys
105 ; return (xis, andCCans cts_s) }
107 -- Flatten a type to get rid of type function applications, returning
108 -- the new type-function-free type, and a collection of new equality
109 -- constraints. See Note [Flattening] for more detail. This needs to
110 -- be in the TcS monad so we can generate new flattening skolem
112 flatten :: CtFlavor -> TcType -> TcS (Xi, CanonicalCts)
115 | Just ty' <- tcView ty
116 = do { (xi, ccs) <- flatten ctxt ty'
117 -- Preserve type synonyms if possible
118 -- We can tell if t' is function-free by
119 -- whether there are any floated constraints
120 ; if isEmptyCCan ccs then
121 return (ty, emptyCCan)
125 flatten _ v@(TyVarTy _)
126 = return (v, emptyCCan)
128 flatten ctxt (AppTy ty1 ty2)
129 = do { (xi1,c1) <- flatten ctxt ty1
130 ; (xi2,c2) <- flatten ctxt ty2
131 ; return (mkAppTy xi1 xi2, c1 `andCCan` c2) }
133 flatten ctxt (FunTy ty1 ty2)
134 = do { (xi1,c1) <- flatten ctxt ty1
135 ; (xi2,c2) <- flatten ctxt ty2
136 ; return (mkFunTy xi1 xi2, c1 `andCCan` c2) }
138 flatten fl (TyConApp tc tys)
139 -- For a normal type constructor or data family application, we just
140 -- recursively flatten the arguments.
141 | not (isSynFamilyTyCon tc)
142 = do { (xis,ccs) <- flattenMany fl tys
143 ; return (mkTyConApp tc xis, ccs) }
145 -- Otherwise, it's a type function application, and we have to
146 -- flatten it away as well, and generate a new given equality constraint
147 -- between the application and a newly generated flattening skolem variable.
149 = ASSERT( tyConArity tc <= length tys ) -- Type functions are saturated
150 do { (xis, ccs) <- flattenMany fl tys
151 ; let (xi_args, xi_rest) = splitAt (tyConArity tc) xis
152 -- The type function might be *over* saturated
153 -- in which case the remaining arguments should
154 -- be dealt with by AppTys
155 fam_ty = mkTyConApp tc xi_args
156 fam_co = fam_ty -- identity
158 ; xi_skol <- newFlattenSkolemTy fam_ty
159 ; cv <- newGivOrDerCoVar fam_ty xi_skol fam_co
161 ; let ceq_given = CFunEqCan { cc_id = cv
162 , cc_flavor = mkGivenFlavor fl UnkSkol
164 , cc_tyargs = xi_args
167 -- ceq_given : F xi_args ~ xi_skol
169 ; return ( foldl AppTy xi_skol xi_rest
170 , ccs `extendCCans` ceq_given) }
172 flatten ctxt (PredTy pred)
173 = do { (pred',ccs) <- flattenPred ctxt pred
174 ; return (PredTy pred', ccs) }
176 flatten ctxt ty@(ForAllTy {})
177 -- We allow for-alls when, but only when, no type function
178 -- applications inside the forall involve the bound type variables
179 = do { let (tvs, rho) = splitForAllTys ty
180 ; (rho', ccs) <- flatten ctxt rho
181 ; let bad_eqs = filterBag is_bad ccs
182 is_bad c = tyVarsOfCanonical c `intersectsVarSet` tv_set
183 tv_set = mkVarSet tvs
184 ; unless (isEmptyBag bad_eqs)
185 (flattenForAllErrorTcS ctxt ty bad_eqs)
186 ; return (mkForAllTys tvs rho', ccs) }
189 flattenPred :: CtFlavor -> TcPredType -> TcS (TcPredType, CanonicalCts)
190 flattenPred ctxt (ClassP cls tys)
191 = do { (tys', ccs) <- flattenMany ctxt tys
192 ; return (ClassP cls tys', ccs) }
193 flattenPred ctxt (IParam nm ty)
194 = do { (ty', ccs) <- flatten ctxt ty
195 ; return (IParam nm ty', ccs) }
196 flattenPred ctxt (EqPred ty1 ty2)
197 = do { (ty1', ccs1) <- flatten ctxt ty1
198 ; (ty2', ccs2) <- flatten ctxt ty2
199 ; return (EqPred ty1' ty2', ccs1 `andCCan` ccs2) }
202 %************************************************************************
204 %* Canonicalising given constraints *
206 %************************************************************************
209 canWanteds :: [WantedEvVar] -> TcS CanonicalCts
210 canWanteds = fmap andCCans . mapM (\(WantedEvVar ev loc) -> mkCanonical (Wanted loc) ev)
212 canGivens :: GivenLoc -> [EvVar] -> TcS CanonicalCts
213 canGivens loc givens = do { ccs <- mapM (mkCanonical (Given loc)) givens
214 ; return (andCCans ccs) }
216 mkCanonicals :: CtFlavor -> [EvVar] -> TcS CanonicalCts
217 mkCanonicals fl vs = fmap andCCans (mapM (mkCanonical fl) vs)
219 mkCanonical :: CtFlavor -> EvVar -> TcS CanonicalCts
220 mkCanonical fl ev = case evVarPred ev of
221 ClassP clas tys -> canClass fl ev clas tys
222 IParam ip ty -> canIP fl ev ip ty
223 EqPred ty1 ty2 -> canEq fl ev ty1 ty2
226 canClass :: CtFlavor -> EvVar -> Class -> [TcType] -> TcS CanonicalCts
228 = do { (xis,ccs) <- flattenMany fl tys
229 ; return $ ccs `extendCCans` CDictCan { cc_id = v
232 , cc_tyargs = xis } }
233 canIP :: CtFlavor -> EvVar -> IPName Name -> TcType -> TcS CanonicalCts
235 = return $ singleCCan $ CIPCan { cc_id = v
242 canEq :: CtFlavor -> EvVar -> Type -> Type -> TcS CanonicalCts
244 | tcEqType ty1 ty2 -- Dealing with equality here avoids
245 -- later spurious occurs checks for a~a
246 = do { when (isWanted fl) (setWantedCoBind cv ty1)
249 -- If one side is a variable, orient and flatten,
250 -- WITHOUT expanding type synonyms, so that we tend to
251 -- substitute a~Age rather than a~Int when type Age=Ing
252 canEq fl cv (TyVarTy tv1) ty2 = canEqLeaf fl cv (VarCls tv1) (classify ty2)
253 canEq fl cv ty1 (TyVarTy tv2) = canEqLeaf fl cv (classify ty1) (VarCls tv2)
255 canEq fl cv (TyConApp fn tys) ty2
256 | isSynFamilyTyCon fn, length tys == tyConArity fn
257 = canEqLeaf fl cv (FunCls fn tys) (classify ty2)
258 canEq fl cv ty1 (TyConApp fn tys)
259 | isSynFamilyTyCon fn, length tys == tyConArity fn
260 = canEqLeaf fl cv (classify ty1) (FunCls fn tys)
263 | Just (t1a,t1b,t1c) <- splitCoPredTy_maybe s1,
264 Just (t2a,t2b,t2c) <- splitCoPredTy_maybe s2
265 = do { (v1,v2,v3) <- if isWanted fl then
266 do { v1 <- newWantedCoVar t1a t2a
267 ; v2 <- newWantedCoVar t1b t2b
268 ; v3 <- newWantedCoVar t1c t2c
269 ; let res_co = mkCoPredCo (mkCoVarCoercion v1)
270 (mkCoVarCoercion v2) (mkCoVarCoercion v3)
271 ; setWantedCoBind cv res_co
272 ; return (v1,v2,v3) }
273 else let co_orig = mkCoVarCoercion cv
274 coa = mkCsel1Coercion co_orig
275 cob = mkCsel2Coercion co_orig
276 coc = mkCselRCoercion co_orig
277 in do { v1 <- newGivOrDerCoVar t1a t2a coa
278 ; v2 <- newGivOrDerCoVar t1b t2b cob
279 ; v3 <- newGivOrDerCoVar t1c t2c coc
280 ; return (v1,v2,v3) }
281 ; cc1 <- canEq fl v1 t1a t2a
282 ; cc2 <- canEq fl v2 t1b t2b
283 ; cc3 <- canEq fl v3 t1c t2c
284 ; return (cc1 `andCCan` cc2 `andCCan` cc3) }
287 -- Split up an equality between function types into two equalities.
288 canEq fl cv (FunTy s1 t1) (FunTy s2 t2)
289 = do { (argv, resv) <-
291 do { argv <- newWantedCoVar s1 s2
292 ; resv <- newWantedCoVar t1 t2
293 ; setWantedCoBind cv $
294 mkFunCoercion (mkCoVarCoercion argv) (mkCoVarCoercion resv)
295 ; return (argv,resv) }
296 else let [arg,res] = decomposeCo 2 (mkCoVarCoercion cv)
297 in do { argv <- newGivOrDerCoVar s1 s2 arg
298 ; resv <- newGivOrDerCoVar t1 t2 res
299 ; return (argv,resv) }
300 ; cc1 <- canEq fl argv s1 s2 -- inherit original kinds and locations
301 ; cc2 <- canEq fl resv t1 t2
302 ; return (cc1 `andCCan` cc2) }
304 canEq fl cv (PredTy p1) (PredTy p2) = canEqPred p1 p2
305 where canEqPred (IParam n1 t1) (IParam n2 t2)
307 = if isWanted fl then
308 do { v <- newWantedCoVar t1 t2
309 ; setWantedCoBind cv $ mkIParamPredCo n1 (mkCoVarCoercion cv)
311 else return emptyCCan -- DV: How to decompose given IP coercions?
313 canEqPred (ClassP c1 tys1) (ClassP c2 tys2)
315 = if isWanted fl then
316 do { vs <- zipWithM newWantedCoVar tys1 tys2
317 ; setWantedCoBind cv $ mkClassPPredCo c1 (map mkCoVarCoercion vs)
318 ; andCCans <$> zipWith3M (canEq fl) vs tys1 tys2
320 else return emptyCCan
321 -- How to decompose given dictionary (and implicit parameter) coercions?
322 -- You may think that the following is right:
323 -- let cos = decomposeCo (length tys1) (mkCoVarCoercion cv)
324 -- in zipWith3M newGivOrDerCoVar tys1 tys2 cos
325 -- But this assumes that the coercion is a type constructor-based
326 -- coercion, and not a PredTy (ClassP cn cos) coercion. So we chose
327 -- to not decompose these coercions. We have to get back to this
328 -- when we clean up the Coercion API.
330 canEqPred p1 p2 = misMatchErrorTcS fl (mkPredTy p1) (mkPredTy p2)
333 canEq fl cv (TyConApp tc1 tys1) (TyConApp tc2 tys2)
334 | isAlgTyCon tc1 && isAlgTyCon tc2
336 , length tys1 == length tys2
337 = -- Generate equalities for each of the corresponding arguments
338 do { argsv <- if isWanted fl then
339 do { argsv <- zipWithM newWantedCoVar tys1 tys2
340 ; setWantedCoBind cv $ mkTyConCoercion tc1 (map mkCoVarCoercion argsv)
343 let cos = decomposeCo (length tys1) (mkCoVarCoercion cv)
344 in zipWith3M newGivOrDerCoVar tys1 tys2 cos
345 ; andCCans <$> zipWith3M (canEq fl) argsv tys1 tys2 }
347 -- See Note [Equality between type applications]
348 -- Note [Care with type applications] in TcUnify
350 | Just (s1,t1) <- tcSplitAppTy_maybe ty1
351 , Just (s2,t2) <- tcSplitAppTy_maybe ty2
354 then do { cv1 <- newWantedCoVar s1 s2
355 ; cv2 <- newWantedCoVar t1 t2
356 ; setWantedCoBind cv $
357 mkAppCoercion (mkCoVarCoercion cv1) (mkCoVarCoercion cv2)
359 else let co1 = mkLeftCoercion $ mkCoVarCoercion cv
360 co2 = mkRightCoercion $ mkCoVarCoercion cv
361 in do { cv1 <- newGivOrDerCoVar s1 s2 co1
362 ; cv2 <- newGivOrDerCoVar t1 t2 co2
364 ; cc1 <- canEq fl cv1 s1 s2
365 ; cc2 <- canEq fl cv2 t1 t2
366 ; return (cc1 `andCCan` cc2) }
368 canEq fl _ s1@(ForAllTy {}) s2@(ForAllTy {})
369 | tcIsForAllTy s1, tcIsForAllTy s2,
371 = misMatchErrorTcS fl s1 s2
373 = do { traceTcS "Ommitting decomposition of given polytype equality" (pprEq s1 s2)
376 -- Finally expand any type synonym applications.
377 canEq fl cv ty1 ty2 | Just ty1' <- tcView ty1 = canEq fl cv ty1' ty2
378 canEq fl cv ty1 ty2 | Just ty2' <- tcView ty2 = canEq fl cv ty1 ty2'
380 = misMatchErrorTcS fl ty1 ty2
385 Note [Equality between type applications]
386 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
387 If we see an equality of the form s1 t1 ~ s2 t2 we can always split
388 it up into s1 ~ s2 /\ t1 ~ t2, since s1 and s2 can't be type
389 functions (type functions use the TyConApp constructor, which never
390 shows up as the LHS of an AppTy). Other than type functions, types
391 in Haskell are always
393 (1) generative: a b ~ c d implies a ~ c, since different type
394 constructors always generate distinct types
396 (2) injective: a b ~ a d implies b ~ d; we never generate the
397 same type from different type arguments.
402 The canonicalizer assumes that it's provided with well-kinded equalities
403 as wanted or given, that is LHS kind and the RHS kind agree, modulo subkinding.
405 Both canonicalization and interaction solving must preserve this invariant.
406 DV: TODO TODO: Check!
408 Note [Canonical ordering for equality constraints]
409 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
410 Implemented as (<+=) below:
412 - Type function applications always come before anything else.
413 - Variables always come before non-variables (other than type
414 function applications).
416 Note that we don't need to unfold type synonyms on the RHS to check
417 the ordering; that is, in the rules above it's OK to consider only
418 whether something is *syntactically* a type function application or
419 not. To illustrate why this is OK, suppose we have an equality of the
420 form 'tv ~ S a b c', where S is a type synonym which expands to a
421 top-level application of the type function F, something like
425 Then to canonicalize 'tv ~ S a b c' we flatten the RHS, and since S's
426 expansion contains type function applications the flattener will do
427 the expansion and then generate a skolem variable for the type
428 function application, so we end up with something like this:
433 where x is the skolem variable. This is one extra equation than
434 absolutely necessary (we could have gotten away with just 'F d e ~ tv'
435 if we had noticed that S expanded to a top-level type function
436 application and flipped it around in the first place) but this way
437 keeps the code simpler.
439 Unlike the OutsideIn(X) draft of May 7, 2010, we do not care about the
440 ordering of tv ~ tv constraints. There are several reasons why we
443 (1) In order to be able to extract a substitution that doesn't
444 mention untouchable variables after we are done solving, we might
445 prefer to put touchable variables on the left. However, in and
446 of itself this isn't necessary; we can always re-orient equality
447 constraints at the end if necessary when extracting a substitution.
449 (2) To ensure termination we might think it necessary to put
450 variables in lexicographic order. However, this isn't actually
451 necessary as outlined below.
453 While building up an inert set of canonical constraints, we maintain
454 the invariant that the equality constraints in the inert set form an
455 acyclic rewrite system when viewed as L-R rewrite rules. Moreover,
456 the given constraints form an idempotent substitution (i.e. none of
457 the variables on the LHS occur in any of the RHS's, and type functions
458 never show up in the RHS at all), the wanted constraints also form an
459 idempotent substitution, and finally the LHS of a given constraint
460 never shows up on the RHS of a wanted constraint. There may, however,
461 be a wanted LHS that shows up in a given RHS, since we do not rewrite
462 given constraints with wanted constraints.
464 Suppose we have an inert constraint set
467 tg_1 ~ xig_1 -- givens
470 tw_1 ~ xiw_1 -- wanteds
474 where each t_i can be either a type variable or a type function
475 application. Now suppose we take a new canonical equality constraint,
476 t' ~ xi' (note among other things this means t' does not occur in xi')
477 and try to react it with the existing inert set. We show by induction
478 on the number of t_i which occur in t' ~ xi' that this process will
481 There are several ways t' ~ xi' could react with an existing constraint:
483 TODO: finish this proof. The below was for the case where the entire
484 inert set is an idempotent subustitution...
486 (b) We could have t' = t_j for some j. Then we obtain the new
487 equality xi_j ~ xi'; note that neither xi_j or xi' contain t_j. We
488 now canonicalize the new equality, which may involve decomposing it
489 into several canonical equalities, and recurse on these. However,
490 none of the new equalities will contain t_j, so they have fewer
491 occurrences of the t_i than the original equation.
493 (a) We could have t_j occurring in xi' for some j, with t' /=
494 t_j. Then we substitute xi_j for t_j in xi' and continue. However,
495 since none of the t_i occur in xi_j, we have decreased the
496 number of t_i that occur in xi', since we eliminated t_j and did not
497 introduce any new ones.
501 = VarCls TcTyVar -- Type variable
502 | FunCls TyCon [Type] -- Type function, exactly saturated
503 | OtherCls TcType -- Neither of the above
505 unClassify :: TypeClassifier -> TcType
506 unClassify (VarCls tv) = TyVarTy tv
507 unClassify (FunCls fn tys) = TyConApp fn tys
508 unClassify (OtherCls ty) = ty
510 classify :: TcType -> TypeClassifier
511 classify (TyVarTy tv) = VarCls tv
512 classify (TyConApp tc tys) | isSynFamilyTyCon tc
513 , tyConArity tc == length tys
515 classify ty | Just ty' <- tcView ty
516 = case classify ty' of
517 OtherCls {} -> OtherCls ty
518 var_or_fn -> var_or_fn
522 -- See note [Canonical ordering for equality constraints].
523 reOrient :: TypeClassifier -> TypeClassifier -> Bool
524 -- (t1 `reOrient` t2) responds True
525 -- iff we should flip to (t2~t1)
526 -- We try to say False if possible, to minimise evidence generation
528 -- Postcondition: After re-orienting, first arg is not OTherCls
529 reOrient (OtherCls {}) (FunCls {}) = True
530 reOrient (OtherCls {}) (VarCls {}) = True
531 reOrient (OtherCls {}) (OtherCls {}) = panic "reOrient" -- One must be Var/Fun
533 reOrient (FunCls {}) (VarCls tv2) = isMetaTyVar tv2
534 -- See Note [No touchables as FunEq RHS] in TcSMonad
535 -- For convenience we enforce the stronger invariant that no
536 -- meta type variable is the RHS of a function equality
537 reOrient (FunCls {}) _ = False -- Fun/Other on rhs
540 reOrient (VarCls tv1) (FunCls {}) = not (isMetaTyVar tv1)
541 reOrient (VarCls {}) (OtherCls {}) = False
543 -- Variables-variables are oriented according to their kind
544 -- so that the invariant of CTyEqCan has the best chance of
546 -- * If tv is a MetaTyVar, then typeKind xi <: typeKind tv
547 -- a skolem, then typeKind xi = typeKind tv
548 reOrient (VarCls tv1) (VarCls tv2)
549 | k1 `eqKind` k2 = False
550 | otherwise = k1 `isSubKind` k2
556 canEqLeaf :: CtFlavor -> CoVar
557 -> TypeClassifier -> TypeClassifier -> TcS CanonicalCts
558 -- Canonicalizing "leaf" equality constraints which cannot be
559 -- decomposed further (ie one of the types is a variable or
560 -- saturated type function application).
563 -- * one of the two arguments is not OtherCls
564 -- * the two types are not equal (looking through synonyms)
565 canEqLeaf fl cv cls1 cls2
566 | cls1 `reOrient` cls2
567 = do { cv' <- if isWanted fl
568 then do { cv' <- newWantedCoVar s2 s1
569 ; setWantedCoBind cv $ mkSymCoercion (mkCoVarCoercion cv')
571 else newGivOrDerCoVar s2 s1 (mkSymCoercion (mkCoVarCoercion cv))
572 ; canEqLeafOriented fl cv' cls2 s1 }
575 = canEqLeafOriented fl cv cls1 s2
581 canEqLeafOriented :: CtFlavor -> CoVar
582 -> TypeClassifier -> TcType -> TcS CanonicalCts
583 -- First argument is not OtherCls
584 canEqLeafOriented fl cv cls1@(FunCls fn tys) s2
585 | not (kindAppResult (tyConKind fn) tys `eqKind` typeKind s2 )
586 = do { kindErrorTcS fl (unClassify cls1) s2
589 = ASSERT2( isSynFamilyTyCon fn, ppr (unClassify cls1) )
590 do { (xis1,ccs1) <- flattenMany fl tys -- flatten type function arguments
591 ; (xi2,ccs2) <- flatten fl s2 -- flatten entire RHS
592 ; let final_cc = CFunEqCan { cc_id = cv
597 ; return $ ccs1 `andCCan` ccs2 `extendCCans` final_cc }
599 -- Otherwise, we have a variable on the left, so we flatten the RHS
600 -- and then do an occurs check.
601 canEqLeafOriented fl cv (VarCls tv) s2
602 | not (k1 `eqKind` k2 || (isMetaTyVar tv && k2 `isSubKind` k1))
603 -- Establish the kind invariant for CTyEqCan
604 = do { kindErrorTcS fl (mkTyVarTy tv) s2
608 = do { (xi2,ccs2) <- flatten fl s2 -- flatten RHS
609 ; xi2' <- canOccursCheck fl tv xi2 -- do an occurs check, and return a possibly
610 -- unfolded version of the RHS, if we had to
611 -- unfold any type synonyms to get rid of tv.
612 ; let final_cc = CTyEqCan { cc_id = cv
617 ; return $ ccs2 `extendCCans` final_cc }
622 canEqLeafOriented _ cv (OtherCls ty1) ty2
623 = pprPanic "canEqLeaf" (ppr cv $$ ppr ty1 $$ ppr ty2)
625 -- See Note [Type synonyms and canonicalization].
626 -- Check whether the given variable occurs in the given type. We may
627 -- have needed to do some type synonym unfolding in order to get rid
628 -- of the variable, so we also return the unfolded version of the
629 -- type, which is guaranteed to be syntactically free of the given
630 -- type variable. If the type is already syntactically free of the
631 -- variable, then the same type is returned.
633 -- Precondition: the two types are not equal (looking though synonyms)
634 canOccursCheck :: CtFlavor -> TcTyVar -> Xi -> TcS Xi
635 canOccursCheck gw tv xi
636 | Just xi' <- expandAway tv xi = return xi'
637 | otherwise = occursCheckErrorTcS gw tv xi
640 @expandAway tv xi@ expands synonyms in xi just enough to get rid of
641 occurrences of tv, if that is possible; otherwise, it returns Nothing.
642 For example, suppose we have
645 expandAway b (F Int b) = Just [Int]
647 expandAway a (F a Int) = Nothing
649 We don't promise to do the absolute minimum amount of expanding
650 necessary, but we try not to do expansions we don't need to. We
651 prefer doing inner expansions first. For example,
652 type F a b = (a, Int, a, [a])
655 expandAway b (F (G b)) = F Char
656 even though we could also expand F to get rid of b.
659 expandAway :: TcTyVar -> Xi -> Maybe Xi
660 expandAway tv t@(TyVarTy tv')
661 | tv == tv' = Nothing
664 | not (tv `elemVarSet` tyVarsOfType xi) = Just xi
665 expandAway tv (AppTy ty1 ty2)
666 = mkAppTy <$> expandAway tv ty1 <*> expandAway tv ty2
667 expandAway tv (FunTy ty1 ty2)
668 = mkFunTy <$> expandAway tv ty1 <*> expandAway tv ty2
669 expandAway _ (ForAllTy {}) = error "blorg" -- TODO
670 expandAway _ (PredTy {}) = error "flerg" -- TODO
672 -- For a type constructor application, first try expanding away the
673 -- offending variable from the arguments. If that doesn't work, next
674 -- see if the type constructor is a type synonym, and if so, expand
676 expandAway tv ty@(TyConApp tc tys)
677 = (mkTyConApp tc <$> mapM (expandAway tv) tys) <|> (tcView ty >>= expandAway tv)
680 Note [Type synonyms and canonicalization]
681 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
683 We treat type synonym applications as xi types, that is, they do not
684 count as type function applications. However, we do need to be a bit
685 careful with type synonyms: like type functions they may not be
686 generative or injective. However, unlike type functions, they are
687 parametric, so there is no problem in expanding them whenever we see
688 them, since we do not need to know anything about their arguments in
689 order to expand them; this is what justifies not having to treat them
690 as specially as type function applications. The thing that causes
691 some subtleties is that we prefer to leave type synonym applications
692 *unexpanded* whenever possible, in order to generate better error
695 If we encounter an equality constraint with type synonym applications
696 on both sides, or a type synonym application on one side and some sort
697 of type application on the other, we simply must expand out the type
698 synonyms in order to continue decomposing the equality constraint into
699 primitive equality constraints. For example, suppose we have
703 and we encounter the equality
707 In order to continue we must expand F a into [Int], giving us the
712 which we can then decompose into the more primitive equality
717 However, if we encounter an equality constraint with a type synonym
718 application on one side and a variable on the other side, we should
719 NOT (necessarily) expand the type synonym, since for the purpose of
720 good error messages we want to leave type synonyms unexpanded as much
723 However, there is a subtle point with type synonyms and the occurs
724 check that takes place for equality constraints of the form tv ~ xi.
725 As an example, suppose we have
729 and we come across the equality constraint
733 This should not actually fail the occurs check, since expanding out
734 the type synonym results in the legitimate equality constraint a ~
735 Int. We must actually do this expansion, because unifying a with F a
736 will lead the type checker into infinite loops later. Put another
737 way, canonical equality constraints should never *syntactically*
738 contain the LHS variable in the RHS type. However, we don't always
739 need to expand type synonyms when doing an occurs check; for example,
744 is obviously fine no matter what F expands to. And in this case we
745 would rather unify a with F b (rather than F b's expansion) in order
746 to get better error messages later.
748 So, when doing an occurs check with a type synonym application on the
749 RHS, we use some heuristics to find an expansion of the RHS which does
750 not contain the variable from the LHS. In particular, given
754 we first try expanding each of the ti to types which no longer contain
755 a. If this turns out to be impossible, we next try expanding F