3 mkCanonical, mkCanonicals, mkCanonicalFEV, canWanteds, canGivens,
8 #include "HsVersions.h"
14 import qualified TcMType as TcM
23 import VarEnv ( TidyEnv )
25 import Control.Monad ( unless, when, zipWithM, zipWithM_ )
27 import Control.Applicative ( (<|>) )
37 Note [Canonicalisation]
38 ~~~~~~~~~~~~~~~~~~~~~~~
39 * Converts (Constraint f) _which_does_not_contain_proper_implications_ to CanonicalCts
40 * Unary: treats individual constraints one at a time
41 * Does not do any zonking
42 * Lives in TcS monad so that it can create new skolem variables
45 %************************************************************************
47 %* Flattening (eliminating all function symbols) *
49 %************************************************************************
53 flatten ty ==> (xi, cc)
55 xi has no type functions
56 cc = Auxiliary given (equality) constraints constraining
57 the fresh type variables in xi. Evidence for these
58 is always the identity coercion, because internally the
59 fresh flattening skolem variables are actually identified
60 with the types they have been generated to stand in for.
62 Note that it is flatten's job to flatten *every type function it sees*.
63 flatten is only called on *arguments* to type functions, by canEqGiven.
65 Recall that in comments we use alpha[flat = ty] to represent a
66 flattening skolem variable alpha which has been generated to stand in
69 ----- Example of flattening a constraint: ------
70 flatten (List (F (G Int))) ==> (xi, cc)
73 cc = { G Int ~ beta[flat = G Int],
74 F beta ~ alpha[flat = F beta] }
76 * alpha and beta are 'flattening skolem variables'.
77 * All the constraints in cc are 'given', and all their coercion terms
80 NB: Flattening Skolems only occur in canonical constraints, which
81 are never zonked, so we don't need to worry about zonking doing
82 accidental unflattening.
84 Note that we prefer to leave type synonyms unexpanded when possible,
85 so when the flattener encounters one, it first asks whether its
86 transitive expansion contains any type function applications. If so,
87 it expands the synonym and proceeds; if not, it simply returns the
90 TODO: caching the information about whether transitive synonym
91 expansions contain any type function applications would speed things
92 up a bit; right now we waste a lot of energy traversing the same types
96 -- Flatten a bunch of types all at once.
97 flattenMany :: CtFlavor -> [Type] -> TcS ([Xi], [Coercion], CanonicalCts)
98 -- Coercions :: Xi ~ Type
100 = do { (xis, cos, cts_s) <- mapAndUnzip3M (flatten ctxt) tys
101 ; return (xis, cos, andCCans cts_s) }
103 -- Flatten a type to get rid of type function applications, returning
104 -- the new type-function-free type, and a collection of new equality
105 -- constraints. See Note [Flattening] for more detail.
106 flatten :: CtFlavor -> TcType -> TcS (Xi, Coercion, CanonicalCts)
107 -- Postcondition: Coercion :: Xi ~ TcType
109 | Just ty' <- tcView ty
110 = do { (xi, co, ccs) <- flatten ctxt ty'
111 -- Preserve type synonyms if possible
112 -- We can tell if ty' is function-free by
113 -- whether there are any floated constraints
114 ; if isEmptyCCan ccs then
115 return (ty, ty, emptyCCan)
117 return (xi, co, ccs) }
119 flatten _ v@(TyVarTy _)
120 = return (v, v, emptyCCan)
122 flatten ctxt (AppTy ty1 ty2)
123 = do { (xi1,co1,c1) <- flatten ctxt ty1
124 ; (xi2,co2,c2) <- flatten ctxt ty2
125 ; return (mkAppTy xi1 xi2, mkAppCoercion co1 co2, c1 `andCCan` c2) }
127 flatten ctxt (FunTy ty1 ty2)
128 = do { (xi1,co1,c1) <- flatten ctxt ty1
129 ; (xi2,co2,c2) <- flatten ctxt ty2
130 ; return (mkFunTy xi1 xi2, mkFunCoercion co1 co2, c1 `andCCan` c2) }
132 flatten fl (TyConApp tc tys)
133 -- For a normal type constructor or data family application, we just
134 -- recursively flatten the arguments.
135 | not (isSynFamilyTyCon tc)
136 = do { (xis,cos,ccs) <- flattenMany fl tys
137 ; return (mkTyConApp tc xis, mkTyConCoercion tc cos, ccs) }
139 -- Otherwise, it's a type function application, and we have to
140 -- flatten it away as well, and generate a new given equality constraint
141 -- between the application and a newly generated flattening skolem variable.
143 = ASSERT( tyConArity tc <= length tys ) -- Type functions are saturated
144 do { (xis, cos, ccs) <- flattenMany fl tys
145 ; let (xi_args, xi_rest) = splitAt (tyConArity tc) xis
146 (cos_args, cos_rest) = splitAt (tyConArity tc) cos
147 -- The type function might be *over* saturated
148 -- in which case the remaining arguments should
149 -- be dealt with by AppTys
150 fam_ty = mkTyConApp tc xi_args
151 fam_co = fam_ty -- identity
153 ; (ret_co, rhs_var, ct) <-
155 do { rhs_var <- newFlattenSkolemTy fam_ty
156 ; cv <- newGivenCoVar fam_ty rhs_var fam_co
157 ; let ct = CFunEqCan { cc_id = cv
158 , cc_flavor = fl -- Given
160 , cc_tyargs = xi_args
162 ; return $ (mkCoVarCoercion cv, rhs_var, ct) }
163 else -- Derived or Wanted: make a new *unification* flatten variable
164 do { rhs_var <- newFlexiTcSTy (typeKind fam_ty)
165 ; cv <- newCoVar fam_ty rhs_var
166 ; let ct = CFunEqCan { cc_id = cv
167 , cc_flavor = mkWantedFlavor fl
168 -- Always Wanted, not Derived
170 , cc_tyargs = xi_args
172 ; return $ (mkCoVarCoercion cv, rhs_var, ct) }
174 ; return ( foldl AppTy rhs_var xi_rest
175 , foldl AppTy (mkSymCoercion ret_co
176 `mkTransCoercion` mkTyConCoercion tc cos_args) cos_rest
177 , ccs `extendCCans` ct) }
180 flatten ctxt (PredTy pred)
181 = do { (pred', co, ccs) <- flattenPred ctxt pred
182 ; return (PredTy pred', co, ccs) }
184 flatten ctxt ty@(ForAllTy {})
185 -- We allow for-alls when, but only when, no type function
186 -- applications inside the forall involve the bound type variables
187 -- TODO: What if it is a (t1 ~ t2) => t3
188 -- Must revisit when the New Coercion API is here!
189 = do { let (tvs, rho) = splitForAllTys ty
190 ; (rho', co, ccs) <- flatten ctxt rho
191 ; let bad_eqs = filterBag is_bad ccs
192 is_bad c = tyVarsOfCanonical c `intersectsVarSet` tv_set
193 tv_set = mkVarSet tvs
194 ; unless (isEmptyBag bad_eqs)
195 (flattenForAllErrorTcS ctxt ty bad_eqs)
196 ; return (mkForAllTys tvs rho', mkForAllTys tvs co, ccs) }
199 flattenPred :: CtFlavor -> TcPredType -> TcS (TcPredType, Coercion, CanonicalCts)
200 flattenPred ctxt (ClassP cls tys)
201 = do { (tys', cos, ccs) <- flattenMany ctxt tys
202 ; return (ClassP cls tys', mkClassPPredCo cls cos, ccs) }
203 flattenPred ctxt (IParam nm ty)
204 = do { (ty', co, ccs) <- flatten ctxt ty
205 ; return (IParam nm ty', mkIParamPredCo nm co, ccs) }
206 -- TODO: Handling of coercions between EqPreds must be revisited once the New Coercion API is ready!
207 flattenPred ctxt (EqPred ty1 ty2)
208 = do { (ty1', co1, ccs1) <- flatten ctxt ty1
209 ; (ty2', co2, ccs2) <- flatten ctxt ty2
210 ; return (EqPred ty1' ty2', mkEqPredCo co1 co2, ccs1 `andCCan` ccs2) }
214 %************************************************************************
216 %* Canonicalising given constraints *
218 %************************************************************************
221 canWanteds :: [WantedEvVar] -> TcS CanonicalCts
222 canWanteds = fmap andCCans . mapM (\(EvVarX ev loc) -> mkCanonical (Wanted loc) ev)
224 canGivens :: GivenLoc -> [EvVar] -> TcS CanonicalCts
225 canGivens loc givens = do { ccs <- mapM (mkCanonical (Given loc)) givens
226 ; return (andCCans ccs) }
228 mkCanonicals :: CtFlavor -> [EvVar] -> TcS CanonicalCts
229 mkCanonicals fl vs = fmap andCCans (mapM (mkCanonical fl) vs)
231 mkCanonicalFEV :: FlavoredEvVar -> TcS CanonicalCts
232 mkCanonicalFEV (EvVarX ev fl) = mkCanonical fl ev
234 mkCanonical :: CtFlavor -> EvVar -> TcS CanonicalCts
235 mkCanonical fl ev = case evVarPred ev of
236 ClassP clas tys -> canClass fl ev clas tys
237 IParam ip ty -> canIP fl ev ip ty
238 EqPred ty1 ty2 -> canEq fl ev ty1 ty2
241 canClass :: CtFlavor -> EvVar -> Class -> [TcType] -> TcS CanonicalCts
243 = do { (xis,cos,ccs) <- flattenMany fl tys -- cos :: xis ~ tys
244 ; let no_flattening_happened = isEmptyCCan ccs
245 dict_co = mkTyConCoercion (classTyCon cn) cos
246 ; v_new <- if no_flattening_happened then return v
247 else if isGiven fl then return v
248 -- The cos are all identities if fl=Given,
249 -- hence nothing to do
250 else do { v' <- newDictVar cn xis -- D xis
251 ; when (isWanted fl) $ setDictBind v (EvCast v' dict_co)
252 ; when (isGiven fl) $ setDictBind v' (EvCast v (mkSymCoercion dict_co))
253 -- NB: No more setting evidence for derived now
256 -- Add the superclasses of this one here, See Note [Adding superclasses].
257 -- But only if we are not simplifying the LHS of a rule.
258 ; sctx <- getTcSContext
259 ; sc_cts <- if simplEqsOnly sctx then return emptyCCan
260 else newSCWorkFromFlavored v_new fl cn xis
262 ; return (sc_cts `andCCan` ccs `extendCCans` CDictCan { cc_id = v_new
265 , cc_tyargs = xis }) }
268 Note [Adding superclasses]
269 ~~~~~~~~~~~~~~~~~~~~~~~~~~
270 Since dictionaries are canonicalized only once in their lifetime, the
271 place to add their superclasses is canonicalisation (The alternative
272 would be to do it during constraint solving, but we'd have to be
273 extremely careful to not repeatedly introduced the same superclass in
274 our worklist). Here is what we do:
277 We add all their superclasses as Givens.
280 Generally speaking we want to be able to add superclasses of
281 wanteds for two reasons:
283 (1) Oportunities for improvement. Example:
284 class (a ~ b) => C a b
285 Wanted constraint is: C alpha beta
286 We'd like to simply have C alpha alpha. Similar
287 situations arise in relation to functional dependencies.
289 (2) To have minimal constraints to quantify over:
290 For instance, if our wanted constraint is (Eq a, Ord a)
291 we'd only like to quantify over Ord a.
293 To deal with (1) above we only add the superclasses of wanteds
294 which may lead to improvement, that is: equality superclasses or
295 superclasses with functional dependencies.
297 We deal with (2) completely independently in TcSimplify. See
298 Note [Minimize by SuperClasses] in TcSimplify.
301 Moreover, in all cases the extra improvement constraints are
302 Derived. Derived constraints have an identity (for now), but
303 we don't do anything with their evidence. For instance they
304 are never used to rewrite other constraints.
306 See also [New Wanted Superclass Work] in TcInteract.
312 Here's an example that demonstrates why we chose to NOT add
313 superclasses during simplification: [Comes from ticket #4497]
315 class Num (RealOf t) => Normed t
318 Assume the generated wanted constraint is:
319 RealOf e ~ e, Normed e
320 If we were to be adding the superclasses during simplification we'd get:
321 Num uf, Normed e, RealOf e ~ e, RealOf e ~ uf
323 e ~ uf, Num uf, Normed e, RealOf e ~ e
324 ==> [Spontaneous solve]
325 Num uf, Normed uf, RealOf uf ~ uf
327 While looks exactly like our original constraint. If we add the superclass again we'd loop.
328 By adding superclasses definitely only once, during canonicalisation, this situation can't
333 newSCWorkFromFlavored :: EvVar -> CtFlavor -> Class -> [Xi] -> TcS CanonicalCts
334 -- Returns superclasses, see Note [Adding superclasses]
335 newSCWorkFromFlavored ev orig_flavor cls xis
336 | isDerived orig_flavor
337 = return emptyCCan -- Deriveds don't yield more superclasses because we will
338 -- add them transitively in the case of wanteds.
340 | isGiven orig_flavor
341 = do { let sc_theta = immSuperClasses cls xis
343 ; sc_vars <- mapM newEvVar sc_theta
344 ; _ <- zipWithM_ setEvBind sc_vars [EvSuperClass ev n | n <- [0..]]
345 ; mkCanonicals flavor sc_vars }
347 | isEmptyVarSet (tyVarsOfTypes xis)
348 = return emptyCCan -- Wanteds with no variables yield no deriveds.
349 -- See Note [Improvement from Ground Wanteds]
351 | otherwise -- Wanted case, just add those SC that can lead to improvement.
352 = do { let sc_rec_theta = transSuperClasses cls xis
353 impr_theta = filter is_improvement_pty sc_rec_theta
354 Wanted wloc = orig_flavor
355 ; der_ids <- mapM newDerivedId impr_theta
356 ; mkCanonicals (Derived wloc) der_ids }
359 is_improvement_pty :: PredType -> Bool
360 -- Either it's an equality, or has some functional dependency
361 is_improvement_pty (EqPred {}) = True
362 is_improvement_pty (ClassP cls _ty) = not $ null fundeps
363 where (_,fundeps,_,_,_,_) = classExtraBigSig cls
364 is_improvement_pty _ = False
369 canIP :: CtFlavor -> EvVar -> IPName Name -> TcType -> TcS CanonicalCts
370 -- See Note [Canonical implicit parameter constraints] to see why we don't
371 -- immediately canonicalize (flatten) IP constraints.
373 = return $ singleCCan $ CIPCan { cc_id = v
379 canEq :: CtFlavor -> EvVar -> Type -> Type -> TcS CanonicalCts
381 | tcEqType ty1 ty2 -- Dealing with equality here avoids
382 -- later spurious occurs checks for a~a
383 = do { when (isWanted fl) (setCoBind cv ty1)
386 -- If one side is a variable, orient and flatten,
387 -- WITHOUT expanding type synonyms, so that we tend to
388 -- substitute a ~ Age rather than a ~ Int when @type Age = Int@
389 canEq fl cv ty1@(TyVarTy {}) ty2
390 = do { untch <- getUntouchables
391 ; canEqLeaf untch fl cv (classify ty1) (classify ty2) }
392 canEq fl cv ty1 ty2@(TyVarTy {})
393 = do { untch <- getUntouchables
394 ; canEqLeaf untch fl cv (classify ty1) (classify ty2) }
395 -- NB: don't use VarCls directly because tv1 or tv2 may be scolems!
397 canEq fl cv (TyConApp fn tys) ty2
398 | isSynFamilyTyCon fn, length tys == tyConArity fn
399 = do { untch <- getUntouchables
400 ; canEqLeaf untch fl cv (FunCls fn tys) (classify ty2) }
401 canEq fl cv ty1 (TyConApp fn tys)
402 | isSynFamilyTyCon fn, length tys == tyConArity fn
403 = do { untch <- getUntouchables
404 ; canEqLeaf untch fl cv (classify ty1) (FunCls fn tys) }
407 | Just (t1a,t1b,t1c) <- splitCoPredTy_maybe s1,
408 Just (t2a,t2b,t2c) <- splitCoPredTy_maybe s2
410 <- if isWanted fl then -- Wanted
411 do { v1 <- newCoVar t1a t2a
412 ; v2 <- newCoVar t1b t2b
413 ; v3 <- newCoVar t1c t2c
414 ; let res_co = mkCoPredCo (mkCoVarCoercion v1)
415 (mkCoVarCoercion v2) (mkCoVarCoercion v3)
416 ; setCoBind cv res_co
417 ; return (v1,v2,v3) }
418 else if isGiven fl then -- Given
419 let co_orig = mkCoVarCoercion cv
420 coa = mkCsel1Coercion co_orig
421 cob = mkCsel2Coercion co_orig
422 coc = mkCselRCoercion co_orig
423 in do { v1 <- newGivenCoVar t1a t2a coa
424 ; v2 <- newGivenCoVar t1b t2b cob
425 ; v3 <- newGivenCoVar t1c t2c coc
426 ; return (v1,v2,v3) }
428 do { v1 <- newDerivedId (EqPred t1a t2a)
429 ; v2 <- newDerivedId (EqPred t1b t2b)
430 ; v3 <- newDerivedId (EqPred t1c t2c)
431 ; return (v1,v2,v3) }
432 ; cc1 <- canEq fl v1 t1a t2a
433 ; cc2 <- canEq fl v2 t1b t2b
434 ; cc3 <- canEq fl v3 t1c t2c
435 ; return (cc1 `andCCan` cc2 `andCCan` cc3) }
438 -- Split up an equality between function types into two equalities.
439 canEq fl cv (FunTy s1 t1) (FunTy s2 t2)
440 = do { (argv, resv) <-
442 do { argv <- newCoVar s1 s2
443 ; resv <- newCoVar t1 t2
445 mkFunCoercion (mkCoVarCoercion argv) (mkCoVarCoercion resv)
446 ; return (argv,resv) }
448 else if isGiven fl then
449 let [arg,res] = decomposeCo 2 (mkCoVarCoercion cv)
450 in do { argv <- newGivenCoVar s1 s2 arg
451 ; resv <- newGivenCoVar t1 t2 res
452 ; return (argv,resv) }
455 do { argv <- newDerivedId (EqPred s1 s2)
456 ; resv <- newDerivedId (EqPred t1 t2)
457 ; return (argv,resv) }
459 ; cc1 <- canEq fl argv s1 s2 -- inherit original kinds and locations
460 ; cc2 <- canEq fl resv t1 t2
461 ; return (cc1 `andCCan` cc2) }
463 canEq fl cv (PredTy (IParam n1 t1)) (PredTy (IParam n2 t2))
465 = if isWanted fl then
466 do { v <- newCoVar t1 t2
467 ; setCoBind cv $ mkIParamPredCo n1 (mkCoVarCoercion cv)
469 else return emptyCCan -- DV: How to decompose given IP coercions?
471 canEq fl cv (PredTy (ClassP c1 tys1)) (PredTy (ClassP c2 tys2))
473 = if isWanted fl then
474 do { vs <- zipWithM newCoVar tys1 tys2
475 ; setCoBind cv $ mkClassPPredCo c1 (map mkCoVarCoercion vs)
476 ; andCCans <$> zipWith3M (canEq fl) vs tys1 tys2
478 else return emptyCCan
479 -- How to decompose given dictionary (and implicit parameter) coercions?
480 -- You may think that the following is right:
481 -- let cos = decomposeCo (length tys1) (mkCoVarCoercion cv)
482 -- in zipWith3M newGivOrDerCoVar tys1 tys2 cos
483 -- But this assumes that the coercion is a type constructor-based
484 -- coercion, and not a PredTy (ClassP cn cos) coercion. So we chose
485 -- to not decompose these coercions. We have to get back to this
486 -- when we clean up the Coercion API.
488 canEq fl cv (TyConApp tc1 tys1) (TyConApp tc2 tys2)
489 | isAlgTyCon tc1 && isAlgTyCon tc2
491 , length tys1 == length tys2
492 = -- Generate equalities for each of the corresponding arguments
494 <- if isWanted fl then
495 do { argsv <- zipWithM newCoVar tys1 tys2
497 mkTyConCoercion tc1 (map mkCoVarCoercion argsv)
500 else if isGiven fl then
501 let cos = decomposeCo (length tys1) (mkCoVarCoercion cv)
502 in zipWith3M newGivenCoVar tys1 tys2 cos
505 zipWithM (\t1 t2 -> newDerivedId (EqPred t1 t2)) tys1 tys2
507 ; andCCans <$> zipWith3M (canEq fl) argsv tys1 tys2 }
509 -- See Note [Equality between type applications]
510 -- Note [Care with type applications] in TcUnify
512 | Just (s1,t1) <- tcSplitAppTy_maybe ty1
513 , Just (s2,t2) <- tcSplitAppTy_maybe ty2
516 then do { cv1 <- newCoVar s1 s2
517 ; cv2 <- newCoVar t1 t2
519 mkAppCoercion (mkCoVarCoercion cv1) (mkCoVarCoercion cv2)
522 else if isGiven fl then
523 let co1 = mkLeftCoercion $ mkCoVarCoercion cv
524 co2 = mkRightCoercion $ mkCoVarCoercion cv
525 in do { cv1 <- newGivenCoVar s1 s2 co1
526 ; cv2 <- newGivenCoVar t1 t2 co2
529 do { cv1 <- newDerivedId (EqPred s1 s2)
530 ; cv2 <- newDerivedId (EqPred t1 t2)
533 ; cc1 <- canEq fl cv1 s1 s2
534 ; cc2 <- canEq fl cv2 t1 t2
535 ; return (cc1 `andCCan` cc2) }
537 canEq fl cv s1@(ForAllTy {}) s2@(ForAllTy {})
538 | tcIsForAllTy s1, tcIsForAllTy s2,
542 = do { traceTcS "Ommitting decomposition of given polytype equality" (pprEq s1 s2)
545 -- Finally expand any type synonym applications.
546 canEq fl cv ty1 ty2 | Just ty1' <- tcView ty1 = canEq fl cv ty1' ty2
547 canEq fl cv ty1 ty2 | Just ty2' <- tcView ty2 = canEq fl cv ty1 ty2'
548 canEq fl cv _ _ = canEqFailure fl cv
550 canEqFailure :: CtFlavor -> EvVar -> TcS CanonicalCts
551 canEqFailure fl cv = return (singleCCan (mkFrozenError fl cv))
554 Note [Equality between type applications]
555 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
556 If we see an equality of the form s1 t1 ~ s2 t2 we can always split
557 it up into s1 ~ s2 /\ t1 ~ t2, since s1 and s2 can't be type
558 functions (type functions use the TyConApp constructor, which never
559 shows up as the LHS of an AppTy). Other than type functions, types
560 in Haskell are always
562 (1) generative: a b ~ c d implies a ~ c, since different type
563 constructors always generate distinct types
565 (2) injective: a b ~ a d implies b ~ d; we never generate the
566 same type from different type arguments.
569 Note [Canonical ordering for equality constraints]
570 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
571 Implemented as (<+=) below:
573 - Type function applications always come before anything else.
574 - Variables always come before non-variables (other than type
575 function applications).
577 Note that we don't need to unfold type synonyms on the RHS to check
578 the ordering; that is, in the rules above it's OK to consider only
579 whether something is *syntactically* a type function application or
580 not. To illustrate why this is OK, suppose we have an equality of the
581 form 'tv ~ S a b c', where S is a type synonym which expands to a
582 top-level application of the type function F, something like
586 Then to canonicalize 'tv ~ S a b c' we flatten the RHS, and since S's
587 expansion contains type function applications the flattener will do
588 the expansion and then generate a skolem variable for the type
589 function application, so we end up with something like this:
594 where x is the skolem variable. This is one extra equation than
595 absolutely necessary (we could have gotten away with just 'F d e ~ tv'
596 if we had noticed that S expanded to a top-level type function
597 application and flipped it around in the first place) but this way
598 keeps the code simpler.
600 Unlike the OutsideIn(X) draft of May 7, 2010, we do not care about the
601 ordering of tv ~ tv constraints. There are several reasons why we
604 (1) In order to be able to extract a substitution that doesn't
605 mention untouchable variables after we are done solving, we might
606 prefer to put touchable variables on the left. However, in and
607 of itself this isn't necessary; we can always re-orient equality
608 constraints at the end if necessary when extracting a substitution.
610 (2) To ensure termination we might think it necessary to put
611 variables in lexicographic order. However, this isn't actually
612 necessary as outlined below.
614 While building up an inert set of canonical constraints, we maintain
615 the invariant that the equality constraints in the inert set form an
616 acyclic rewrite system when viewed as L-R rewrite rules. Moreover,
617 the given constraints form an idempotent substitution (i.e. none of
618 the variables on the LHS occur in any of the RHS's, and type functions
619 never show up in the RHS at all), the wanted constraints also form an
620 idempotent substitution, and finally the LHS of a given constraint
621 never shows up on the RHS of a wanted constraint. There may, however,
622 be a wanted LHS that shows up in a given RHS, since we do not rewrite
623 given constraints with wanted constraints.
625 Suppose we have an inert constraint set
628 tg_1 ~ xig_1 -- givens
631 tw_1 ~ xiw_1 -- wanteds
635 where each t_i can be either a type variable or a type function
636 application. Now suppose we take a new canonical equality constraint,
637 t' ~ xi' (note among other things this means t' does not occur in xi')
638 and try to react it with the existing inert set. We show by induction
639 on the number of t_i which occur in t' ~ xi' that this process will
642 There are several ways t' ~ xi' could react with an existing constraint:
644 TODO: finish this proof. The below was for the case where the entire
645 inert set is an idempotent subustitution...
647 (b) We could have t' = t_j for some j. Then we obtain the new
648 equality xi_j ~ xi'; note that neither xi_j or xi' contain t_j. We
649 now canonicalize the new equality, which may involve decomposing it
650 into several canonical equalities, and recurse on these. However,
651 none of the new equalities will contain t_j, so they have fewer
652 occurrences of the t_i than the original equation.
654 (a) We could have t_j occurring in xi' for some j, with t' /=
655 t_j. Then we substitute xi_j for t_j in xi' and continue. However,
656 since none of the t_i occur in xi_j, we have decreased the
657 number of t_i that occur in xi', since we eliminated t_j and did not
658 introduce any new ones.
662 = FskCls TcTyVar -- ^ Flatten skolem
663 | VarCls TcTyVar -- ^ Non-flatten-skolem variable
664 | FunCls TyCon [Type] -- ^ Type function, exactly saturated
665 | OtherCls TcType -- ^ Neither of the above
667 unClassify :: TypeClassifier -> TcType
668 unClassify (VarCls tv) = TyVarTy tv
669 unClassify (FskCls tv) = TyVarTy tv
670 unClassify (FunCls fn tys) = TyConApp fn tys
671 unClassify (OtherCls ty) = ty
673 classify :: TcType -> TypeClassifier
675 classify (TyVarTy tv)
677 FlatSkol {} <- tcTyVarDetails tv = FskCls tv
678 | otherwise = VarCls tv
679 classify (TyConApp tc tys) | isSynFamilyTyCon tc
680 , tyConArity tc == length tys
682 classify ty | Just ty' <- tcView ty
683 = case classify ty' of
684 OtherCls {} -> OtherCls ty
685 var_or_fn -> var_or_fn
689 -- See note [Canonical ordering for equality constraints].
690 reOrient :: CtFlavor -> TypeClassifier -> TypeClassifier -> Bool
691 -- (t1 `reOrient` t2) responds True
692 -- iff we should flip to (t2~t1)
693 -- We try to say False if possible, to minimise evidence generation
695 -- Postcondition: After re-orienting, first arg is not OTherCls
696 reOrient _fl (OtherCls {}) (FunCls {}) = True
697 reOrient _fl (OtherCls {}) (FskCls {}) = True
698 reOrient _fl (OtherCls {}) (VarCls {}) = True
699 reOrient _fl (OtherCls {}) (OtherCls {}) = panic "reOrient" -- One must be Var/Fun
701 reOrient _fl (FunCls {}) (VarCls _tv) = False
702 -- But consider the following variation: isGiven fl && isMetaTyVar tv
704 -- See Note [No touchables as FunEq RHS] in TcSMonad
705 reOrient _fl (FunCls {}) _ = False -- Fun/Other on rhs
707 reOrient _fl (VarCls {}) (FunCls {}) = True
709 reOrient _fl (VarCls {}) (FskCls {}) = False
711 reOrient _fl (VarCls {}) (OtherCls {}) = False
712 reOrient _fl (VarCls tv1) (VarCls tv2)
713 | isMetaTyVar tv2 && not (isMetaTyVar tv1) = True
715 -- Just for efficiency, see CTyEqCan invariants
717 reOrient _fl (FskCls {}) (VarCls tv2) = isMetaTyVar tv2
718 -- Just for efficiency, see CTyEqCan invariants
720 reOrient _fl (FskCls {}) (FskCls {}) = False
721 reOrient _fl (FskCls {}) (FunCls {}) = True
722 reOrient _fl (FskCls {}) (OtherCls {}) = False
725 canEqLeaf :: TcsUntouchables
727 -> TypeClassifier -> TypeClassifier -> TcS CanonicalCts
728 -- Canonicalizing "leaf" equality constraints which cannot be
729 -- decomposed further (ie one of the types is a variable or
730 -- saturated type function application).
733 -- * one of the two arguments is not OtherCls
734 -- * the two types are not equal (looking through synonyms)
735 canEqLeaf _untch fl cv cls1 cls2
736 | cls1 `re_orient` cls2
737 = do { cv' <- if isWanted fl
738 then do { cv' <- newCoVar s2 s1
739 ; setCoBind cv $ mkSymCoercion (mkCoVarCoercion cv')
741 else if isGiven fl then
742 newGivenCoVar s2 s1 (mkSymCoercion (mkCoVarCoercion cv))
744 newDerivedId (EqPred s2 s1)
745 ; canEqLeafOriented fl cv' cls2 s1 }
748 = do { traceTcS "canEqLeaf" (ppr (unClassify cls1) $$ ppr (unClassify cls2))
749 ; canEqLeafOriented fl cv cls1 s2 }
751 re_orient = reOrient fl
756 canEqLeafOriented :: CtFlavor -> CoVar
757 -> TypeClassifier -> TcType -> TcS CanonicalCts
758 -- First argument is not OtherCls
759 canEqLeafOriented fl cv cls1@(FunCls fn tys1) s2 -- cv : F tys1
760 | let k1 = kindAppResult (tyConKind fn) tys1,
761 let k2 = typeKind s2,
762 not (k1 `compatKind` k2) -- Establish the kind invariant for CFunEqCan
764 -- Eagerly fails, see Note [Kind errors] in TcInteract
767 = ASSERT2( isSynFamilyTyCon fn, ppr (unClassify cls1) )
768 do { (xis1,cos1,ccs1) <- flattenMany fl tys1 -- Flatten type function arguments
769 -- cos1 :: xis1 ~ tys1
770 ; (xi2, co2, ccs2) <- flatten fl s2 -- Flatten entire RHS
772 ; let ccs = ccs1 `andCCan` ccs2
773 no_flattening_happened = isEmptyCCan ccs
774 ; cv_new <- if no_flattening_happened then return cv
775 else if isGiven fl then return cv
776 else if isWanted fl then
777 do { cv' <- newCoVar (unClassify (FunCls fn xis1)) xi2
779 ; let -- fun_co :: F xis1 ~ F tys1
780 fun_co = mkTyConCoercion fn cos1
781 -- want_co :: F tys1 ~ s2
782 want_co = mkSymCoercion fun_co
783 `mkTransCoercion` mkCoVarCoercion cv'
784 `mkTransCoercion` co2
785 ; setCoBind cv want_co
788 newDerivedId (EqPred (unClassify (FunCls fn xis1)) xi2)
790 ; let final_cc = CFunEqCan { cc_id = cv_new
795 ; return $ ccs `extendCCans` final_cc }
797 -- Otherwise, we have a variable on the left, so call canEqLeafTyVarLeft
798 canEqLeafOriented fl cv (FskCls tv) s2
799 = canEqLeafTyVarLeft fl cv tv s2
800 canEqLeafOriented fl cv (VarCls tv) s2
801 = canEqLeafTyVarLeft fl cv tv s2
802 canEqLeafOriented _ cv (OtherCls ty1) ty2
803 = pprPanic "canEqLeaf" (ppr cv $$ ppr ty1 $$ ppr ty2)
805 canEqLeafTyVarLeft :: CtFlavor -> CoVar -> TcTyVar -> TcType -> TcS CanonicalCts
806 -- Establish invariants of CTyEqCans
807 canEqLeafTyVarLeft fl cv tv s2 -- cv : tv ~ s2
808 | not (k1 `compatKind` k2) -- Establish the kind invariant for CTyEqCan
810 -- Eagerly fails, see Note [Kind errors] in TcInteract
812 = do { (xi2, co, ccs2) <- flatten fl s2 -- Flatten RHS co : xi2 ~ s2
813 ; mxi2' <- canOccursCheck fl tv xi2 -- Do an occurs check, and return a possibly
814 -- unfolded version of the RHS, if we had to
815 -- unfold any type synonyms to get rid of tv.
817 Nothing -> canEqFailure fl cv ;
819 do { let no_flattening_happened = isEmptyCCan ccs2
820 ; cv_new <- if no_flattening_happened then return cv
821 else if isGiven fl then return cv
822 else if isWanted fl then
823 do { cv' <- newCoVar (mkTyVarTy tv) xi2' -- cv' : tv ~ xi2
824 ; setCoBind cv (mkCoVarCoercion cv' `mkTransCoercion` co)
827 newDerivedId (EqPred (mkTyVarTy tv) xi2')
829 ; return $ ccs2 `extendCCans` CTyEqCan { cc_id = cv_new
832 , cc_rhs = xi2' } } } }
837 -- See Note [Type synonyms and canonicalization].
838 -- Check whether the given variable occurs in the given type. We may
839 -- have needed to do some type synonym unfolding in order to get rid
840 -- of the variable, so we also return the unfolded version of the
841 -- type, which is guaranteed to be syntactically free of the given
842 -- type variable. If the type is already syntactically free of the
843 -- variable, then the same type is returned.
845 -- Precondition: the two types are not equal (looking though synonyms)
846 canOccursCheck :: CtFlavor -> TcTyVar -> Xi -> TcS (Maybe Xi)
847 canOccursCheck _gw tv xi = return (expandAway tv xi)
850 @expandAway tv xi@ expands synonyms in xi just enough to get rid of
851 occurrences of tv, if that is possible; otherwise, it returns Nothing.
852 For example, suppose we have
855 expandAway b (F Int b) = Just [Int]
857 expandAway a (F a Int) = Nothing
859 We don't promise to do the absolute minimum amount of expanding
860 necessary, but we try not to do expansions we don't need to. We
861 prefer doing inner expansions first. For example,
862 type F a b = (a, Int, a, [a])
865 expandAway b (F (G b)) = F Char
866 even though we could also expand F to get rid of b.
869 expandAway :: TcTyVar -> Xi -> Maybe Xi
870 expandAway tv t@(TyVarTy tv')
871 | tv == tv' = Nothing
874 | not (tv `elemVarSet` tyVarsOfType xi) = Just xi
875 expandAway tv (AppTy ty1 ty2)
876 = do { ty1' <- expandAway tv ty1
877 ; ty2' <- expandAway tv ty2
878 ; return (mkAppTy ty1' ty2') }
879 -- mkAppTy <$> expandAway tv ty1 <*> expandAway tv ty2
880 expandAway tv (FunTy ty1 ty2)
881 = do { ty1' <- expandAway tv ty1
882 ; ty2' <- expandAway tv ty2
883 ; return (mkFunTy ty1' ty2') }
884 -- mkFunTy <$> expandAway tv ty1 <*> expandAway tv ty2
885 expandAway tv ty@(ForAllTy {})
886 = let (tvs,rho) = splitForAllTys ty
887 tvs_knds = map tyVarKind tvs
888 in if tv `elemVarSet` tyVarsOfTypes tvs_knds then
889 -- Can't expand away the kinds unless we create
890 -- fresh variables which we don't want to do at this point.
892 else do { rho' <- expandAway tv rho
893 ; return (mkForAllTys tvs rho') }
894 expandAway tv (PredTy pred)
895 = do { pred' <- expandAwayPred tv pred
896 ; return (PredTy pred') }
897 -- For a type constructor application, first try expanding away the
898 -- offending variable from the arguments. If that doesn't work, next
899 -- see if the type constructor is a type synonym, and if so, expand
901 expandAway tv ty@(TyConApp tc tys)
902 = (mkTyConApp tc <$> mapM (expandAway tv) tys) <|> (tcView ty >>= expandAway tv)
904 expandAwayPred :: TcTyVar -> TcPredType -> Maybe TcPredType
905 expandAwayPred tv (ClassP cls tys)
906 = do { tys' <- mapM (expandAway tv) tys; return (ClassP cls tys') }
907 expandAwayPred tv (EqPred ty1 ty2)
908 = do { ty1' <- expandAway tv ty1
909 ; ty2' <- expandAway tv ty2
910 ; return (EqPred ty1' ty2') }
911 expandAwayPred tv (IParam nm ty)
912 = do { ty' <- expandAway tv ty
913 ; return (IParam nm ty') }
919 Note [Type synonyms and canonicalization]
920 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
922 We treat type synonym applications as xi types, that is, they do not
923 count as type function applications. However, we do need to be a bit
924 careful with type synonyms: like type functions they may not be
925 generative or injective. However, unlike type functions, they are
926 parametric, so there is no problem in expanding them whenever we see
927 them, since we do not need to know anything about their arguments in
928 order to expand them; this is what justifies not having to treat them
929 as specially as type function applications. The thing that causes
930 some subtleties is that we prefer to leave type synonym applications
931 *unexpanded* whenever possible, in order to generate better error
934 If we encounter an equality constraint with type synonym applications
935 on both sides, or a type synonym application on one side and some sort
936 of type application on the other, we simply must expand out the type
937 synonyms in order to continue decomposing the equality constraint into
938 primitive equality constraints. For example, suppose we have
942 and we encounter the equality
946 In order to continue we must expand F a into [Int], giving us the
951 which we can then decompose into the more primitive equality
956 However, if we encounter an equality constraint with a type synonym
957 application on one side and a variable on the other side, we should
958 NOT (necessarily) expand the type synonym, since for the purpose of
959 good error messages we want to leave type synonyms unexpanded as much
962 However, there is a subtle point with type synonyms and the occurs
963 check that takes place for equality constraints of the form tv ~ xi.
964 As an example, suppose we have
968 and we come across the equality constraint
972 This should not actually fail the occurs check, since expanding out
973 the type synonym results in the legitimate equality constraint a ~
974 Int. We must actually do this expansion, because unifying a with F a
975 will lead the type checker into infinite loops later. Put another
976 way, canonical equality constraints should never *syntactically*
977 contain the LHS variable in the RHS type. However, we don't always
978 need to expand type synonyms when doing an occurs check; for example,
983 is obviously fine no matter what F expands to. And in this case we
984 would rather unify a with F b (rather than F b's expansion) in order
985 to get better error messages later.
987 So, when doing an occurs check with a type synonym application on the
988 RHS, we use some heuristics to find an expansion of the RHS which does
989 not contain the variable from the LHS. In particular, given
993 we first try expanding each of the ti to types which no longer contain
994 a. If this turns out to be impossible, we next try expanding F
998 %************************************************************************
1000 %* Functional dependencies, instantiation of equations
1002 %************************************************************************
1004 When we spot an equality arising from a functional dependency,
1005 we now use that equality (a "wanted") to rewrite the work-item
1006 constraint right away. This avoids two dangers
1008 Danger 1: If we send the original constraint on down the pipeline
1009 it may react with an instance declaration, and in delicate
1010 situations (when a Given overlaps with an instance) that
1011 may produce new insoluble goals: see Trac #4952
1013 Danger 2: If we don't rewrite the constraint, it may re-react
1014 with the same thing later, and produce the same equality
1015 again --> termination worries.
1017 To achieve this required some refactoring of FunDeps.lhs (nicer
1021 rewriteWithFunDeps :: [Equation]
1023 -> TcS (Maybe ([Xi], [Coercion], CanonicalCts))
1024 rewriteWithFunDeps eqn_pred_locs xis fl
1025 = do { fd_ev_poss <- mapM (instFunDepEqn fl) eqn_pred_locs
1026 ; let fd_ev_pos :: [(Int,FlavoredEvVar)]
1027 fd_ev_pos = concat fd_ev_poss
1028 (rewritten_xis, cos) = unzip (rewriteDictParams fd_ev_pos xis)
1029 ; fds <- mapM (\(_,fev) -> mkCanonicalFEV fev) fd_ev_pos
1030 ; let fd_work = unionManyBags fds
1031 ; if isEmptyBag fd_work
1033 else return (Just (rewritten_xis, cos, fd_work)) }
1035 instFunDepEqn :: CtFlavor -- Precondition: Only Wanted or Derived
1037 -> TcS [(Int, FlavoredEvVar)]
1038 -- Post: Returns the position index as well as the corresponding FunDep equality
1039 instFunDepEqn fl (FDEqn { fd_qtvs = qtvs, fd_eqs = eqs
1040 , fd_pred1 = d1, fd_pred2 = d2 })
1041 = do { let tvs = varSetElems qtvs
1042 ; tvs' <- mapM instFlexiTcS tvs
1043 ; let subst = zipTopTvSubst tvs (mkTyVarTys tvs')
1044 ; mapM (do_one subst) eqs }
1047 Given _ -> panic "mkFunDepEqns"
1048 Wanted loc -> Wanted (push_ctx loc)
1049 Derived loc -> Derived (push_ctx loc)
1051 push_ctx loc = pushErrCtxt FunDepOrigin (False, mkEqnMsg d1 d2) loc
1053 do_one subst (FDEq { fd_pos = i, fd_ty_left = ty1, fd_ty_right = ty2 })
1054 = do { let sty1 = substTy subst ty1
1055 sty2 = substTy subst ty2
1056 ; ev <- newCoVar sty1 sty2
1057 ; return (i, mkEvVarX ev fl') }
1059 rewriteDictParams :: [(Int,FlavoredEvVar)] -- A set of coercions : (pos, ty' ~ ty)
1060 -> [Type] -- A sequence of types: tys
1061 -> [(Type,Coercion)] -- Returns : [(ty', co : ty' ~ ty)]
1062 rewriteDictParams param_eqs tys
1063 = zipWith do_one tys [0..]
1065 do_one :: Type -> Int -> (Type,Coercion)
1066 do_one ty n = case lookup n param_eqs of
1067 Just wev -> (get_fst_ty wev, mkCoVarCoercion (evVarOf wev))
1068 Nothing -> (ty,ty) -- Identity
1070 get_fst_ty wev = case evVarOfPred wev of
1072 _ -> panic "rewriteDictParams: non equality fundep"
1074 mkEqnMsg :: (TcPredType, SDoc) -> (TcPredType, SDoc) -> TidyEnv
1075 -> TcM (TidyEnv, SDoc)
1076 mkEqnMsg (pred1,from1) (pred2,from2) tidy_env
1077 = do { zpred1 <- TcM.zonkTcPredType pred1
1078 ; zpred2 <- TcM.zonkTcPredType pred2
1079 ; let { tpred1 = tidyPred tidy_env zpred1
1080 ; tpred2 = tidyPred tidy_env zpred2 }
1081 ; let msg = vcat [ptext (sLit "When using functional dependencies to combine"),
1082 nest 2 (sep [ppr tpred1 <> comma, nest 2 from1]),
1083 nest 2 (sep [ppr tpred2 <> comma, nest 2 from2])]
1084 ; return (tidy_env, msg) }