3 mkCanonical, mkCanonicals, mkCanonicalFEV, mkCanonicalFEVs, canWanteds, canGivens,
4 canOccursCheck, canEqToWorkList,
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 WorkList
222 canWanteds = fmap unionWorkLists . mapM (\(EvVarX ev loc) -> mkCanonical (Wanted loc) ev)
224 canGivens :: GivenLoc -> [EvVar] -> TcS WorkList
225 canGivens loc givens = do { ccs <- mapM (mkCanonical (Given loc)) givens
226 ; return (unionWorkLists ccs) }
228 mkCanonicals :: CtFlavor -> [EvVar] -> TcS WorkList
229 mkCanonicals fl vs = fmap unionWorkLists (mapM (mkCanonical fl) vs)
231 mkCanonicalFEV :: FlavoredEvVar -> TcS WorkList
232 mkCanonicalFEV (EvVarX ev fl) = mkCanonical fl ev
234 mkCanonicalFEVs :: Bag FlavoredEvVar -> TcS WorkList
235 mkCanonicalFEVs = foldrBagM canon_one emptyWorkList
236 where -- Preserves order (shouldn't be important, but curently
237 -- is important for the vectoriser)
238 canon_one fev wl = do { wl' <- mkCanonicalFEV fev
239 ; return (unionWorkList wl' wl) }
241 mkCanonical :: CtFlavor -> EvVar -> TcS WorkList
242 mkCanonical fl ev = case evVarPred ev of
243 ClassP clas tys -> canClassToWorkList fl ev clas tys
244 IParam ip ty -> canIPToWorkList fl ev ip ty
245 EqPred ty1 ty2 -> canEqToWorkList fl ev ty1 ty2
248 canClassToWorkList :: CtFlavor -> EvVar -> Class -> [TcType] -> TcS WorkList
249 canClassToWorkList fl v cn tys
250 = do { (xis,cos,ccs) <- flattenMany fl tys -- cos :: xis ~ tys
251 ; let no_flattening_happened = isEmptyCCan ccs
252 dict_co = mkTyConCoercion (classTyCon cn) cos
253 ; v_new <- if no_flattening_happened then return v
254 else if isGiven fl then return v
255 -- The cos are all identities if fl=Given,
256 -- hence nothing to do
257 else do { v' <- newDictVar cn xis -- D xis
258 ; when (isWanted fl) $ setDictBind v (EvCast v' dict_co)
259 ; when (isGiven fl) $ setDictBind v' (EvCast v (mkSymCoercion dict_co))
260 -- NB: No more setting evidence for derived now
263 -- Add the superclasses of this one here, See Note [Adding superclasses].
264 -- But only if we are not simplifying the LHS of a rule.
265 ; sctx <- getTcSContext
266 ; sc_cts <- if simplEqsOnly sctx then return emptyWorkList
267 else newSCWorkFromFlavored v_new fl cn xis
269 ; return (sc_cts `unionWorkList`
270 workListFromEqs ccs `unionWorkList`
271 workListFromNonEq CDictCan { cc_id = v_new
274 , cc_tyargs = xis }) }
277 Note [Adding superclasses]
278 ~~~~~~~~~~~~~~~~~~~~~~~~~~
279 Since dictionaries are canonicalized only once in their lifetime, the
280 place to add their superclasses is canonicalisation (The alternative
281 would be to do it during constraint solving, but we'd have to be
282 extremely careful to not repeatedly introduced the same superclass in
283 our worklist). Here is what we do:
286 We add all their superclasses as Givens.
289 Generally speaking we want to be able to add superclasses of
290 wanteds for two reasons:
292 (1) Oportunities for improvement. Example:
293 class (a ~ b) => C a b
294 Wanted constraint is: C alpha beta
295 We'd like to simply have C alpha alpha. Similar
296 situations arise in relation to functional dependencies.
298 (2) To have minimal constraints to quantify over:
299 For instance, if our wanted constraint is (Eq a, Ord a)
300 we'd only like to quantify over Ord a.
302 To deal with (1) above we only add the superclasses of wanteds
303 which may lead to improvement, that is: equality superclasses or
304 superclasses with functional dependencies.
306 We deal with (2) completely independently in TcSimplify. See
307 Note [Minimize by SuperClasses] in TcSimplify.
310 Moreover, in all cases the extra improvement constraints are
311 Derived. Derived constraints have an identity (for now), but
312 we don't do anything with their evidence. For instance they
313 are never used to rewrite other constraints.
315 See also [New Wanted Superclass Work] in TcInteract.
321 Here's an example that demonstrates why we chose to NOT add
322 superclasses during simplification: [Comes from ticket #4497]
324 class Num (RealOf t) => Normed t
327 Assume the generated wanted constraint is:
328 RealOf e ~ e, Normed e
329 If we were to be adding the superclasses during simplification we'd get:
330 Num uf, Normed e, RealOf e ~ e, RealOf e ~ uf
332 e ~ uf, Num uf, Normed e, RealOf e ~ e
333 ==> [Spontaneous solve]
334 Num uf, Normed uf, RealOf uf ~ uf
336 While looks exactly like our original constraint. If we add the superclass again we'd loop.
337 By adding superclasses definitely only once, during canonicalisation, this situation can't
342 newSCWorkFromFlavored :: EvVar -> CtFlavor -> Class -> [Xi] -> TcS WorkList
343 -- Returns superclasses, see Note [Adding superclasses]
344 newSCWorkFromFlavored ev orig_flavor cls xis
345 | isDerived orig_flavor
346 = return emptyWorkList -- Deriveds don't yield more superclasses because we will
347 -- add them transitively in the case of wanteds.
349 | isGiven orig_flavor
350 = do { let sc_theta = immSuperClasses cls xis
352 ; sc_vars <- mapM newEvVar sc_theta
353 ; _ <- zipWithM_ setEvBind sc_vars [EvSuperClass ev n | n <- [0..]]
354 ; mkCanonicals flavor sc_vars }
356 | isEmptyVarSet (tyVarsOfTypes xis)
357 = return emptyWorkList -- Wanteds with no variables yield no deriveds.
358 -- See Note [Improvement from Ground Wanteds]
360 | otherwise -- Wanted case, just add those SC that can lead to improvement.
361 = do { let sc_rec_theta = transSuperClasses cls xis
362 impr_theta = filter is_improvement_pty sc_rec_theta
363 Wanted wloc = orig_flavor
364 ; der_ids <- mapM newDerivedId impr_theta
365 ; mkCanonicals (Derived wloc) der_ids }
368 is_improvement_pty :: PredType -> Bool
369 -- Either it's an equality, or has some functional dependency
370 is_improvement_pty (EqPred {}) = True
371 is_improvement_pty (ClassP cls _ty) = not $ null fundeps
372 where (_,fundeps,_,_,_,_) = classExtraBigSig cls
373 is_improvement_pty _ = False
378 canIPToWorkList :: CtFlavor -> EvVar -> IPName Name -> TcType -> TcS WorkList
379 -- See Note [Canonical implicit parameter constraints] to see why we don't
380 -- immediately canonicalize (flatten) IP constraints.
381 canIPToWorkList fl v nm ty
382 = return $ workListFromNonEq (CIPCan { cc_id = v
388 canEqToWorkList :: CtFlavor -> EvVar -> Type -> Type -> TcS WorkList
389 canEqToWorkList fl cv ty1 ty2 = do { cts <- canEq fl cv ty1 ty2
390 ; return $ workListFromEqs cts }
392 canEq :: CtFlavor -> EvVar -> Type -> Type -> TcS CanonicalCts
394 | tcEqType ty1 ty2 -- Dealing with equality here avoids
395 -- later spurious occurs checks for a~a
396 = do { when (isWanted fl) (setCoBind cv ty1)
399 -- If one side is a variable, orient and flatten,
400 -- WITHOUT expanding type synonyms, so that we tend to
401 -- substitute a ~ Age rather than a ~ Int when @type Age = Int@
402 canEq fl cv ty1@(TyVarTy {}) ty2
403 = do { untch <- getUntouchables
404 ; canEqLeaf untch fl cv (classify ty1) (classify ty2) }
405 canEq fl cv ty1 ty2@(TyVarTy {})
406 = do { untch <- getUntouchables
407 ; canEqLeaf untch fl cv (classify ty1) (classify ty2) }
408 -- NB: don't use VarCls directly because tv1 or tv2 may be scolems!
410 canEq fl cv (TyConApp fn tys) ty2
411 | isSynFamilyTyCon fn, length tys == tyConArity fn
412 = do { untch <- getUntouchables
413 ; canEqLeaf untch fl cv (FunCls fn tys) (classify ty2) }
414 canEq fl cv ty1 (TyConApp fn tys)
415 | isSynFamilyTyCon fn, length tys == tyConArity fn
416 = do { untch <- getUntouchables
417 ; canEqLeaf untch fl cv (classify ty1) (FunCls fn tys) }
420 | Just (t1a,t1b,t1c) <- splitCoPredTy_maybe s1,
421 Just (t2a,t2b,t2c) <- splitCoPredTy_maybe s2
423 <- if isWanted fl then -- Wanted
424 do { v1 <- newCoVar t1a t2a
425 ; v2 <- newCoVar t1b t2b
426 ; v3 <- newCoVar t1c t2c
427 ; let res_co = mkCoPredCo (mkCoVarCoercion v1)
428 (mkCoVarCoercion v2) (mkCoVarCoercion v3)
429 ; setCoBind cv res_co
430 ; return (v1,v2,v3) }
431 else if isGiven fl then -- Given
432 let co_orig = mkCoVarCoercion cv
433 coa = mkCsel1Coercion co_orig
434 cob = mkCsel2Coercion co_orig
435 coc = mkCselRCoercion co_orig
436 in do { v1 <- newGivenCoVar t1a t2a coa
437 ; v2 <- newGivenCoVar t1b t2b cob
438 ; v3 <- newGivenCoVar t1c t2c coc
439 ; return (v1,v2,v3) }
441 do { v1 <- newDerivedId (EqPred t1a t2a)
442 ; v2 <- newDerivedId (EqPred t1b t2b)
443 ; v3 <- newDerivedId (EqPred t1c t2c)
444 ; return (v1,v2,v3) }
445 ; cc1 <- canEq fl v1 t1a t2a
446 ; cc2 <- canEq fl v2 t1b t2b
447 ; cc3 <- canEq fl v3 t1c t2c
448 ; return (cc1 `andCCan` cc2 `andCCan` cc3) }
451 -- Split up an equality between function types into two equalities.
452 canEq fl cv (FunTy s1 t1) (FunTy s2 t2)
453 = do { (argv, resv) <-
455 do { argv <- newCoVar s1 s2
456 ; resv <- newCoVar t1 t2
458 mkFunCoercion (mkCoVarCoercion argv) (mkCoVarCoercion resv)
459 ; return (argv,resv) }
461 else if isGiven fl then
462 let [arg,res] = decomposeCo 2 (mkCoVarCoercion cv)
463 in do { argv <- newGivenCoVar s1 s2 arg
464 ; resv <- newGivenCoVar t1 t2 res
465 ; return (argv,resv) }
468 do { argv <- newDerivedId (EqPred s1 s2)
469 ; resv <- newDerivedId (EqPred t1 t2)
470 ; return (argv,resv) }
472 ; cc1 <- canEq fl argv s1 s2 -- inherit original kinds and locations
473 ; cc2 <- canEq fl resv t1 t2
474 ; return (cc1 `andCCan` cc2) }
476 canEq fl cv (PredTy (IParam n1 t1)) (PredTy (IParam n2 t2))
478 = if isWanted fl then
479 do { v <- newCoVar t1 t2
480 ; setCoBind cv $ mkIParamPredCo n1 (mkCoVarCoercion cv)
482 else return emptyCCan -- DV: How to decompose given IP coercions?
484 canEq fl cv (PredTy (ClassP c1 tys1)) (PredTy (ClassP c2 tys2))
486 = if isWanted fl then
487 do { vs <- zipWithM newCoVar tys1 tys2
488 ; setCoBind cv $ mkClassPPredCo c1 (map mkCoVarCoercion vs)
489 ; andCCans <$> zipWith3M (canEq fl) vs tys1 tys2
491 else return emptyCCan
492 -- How to decompose given dictionary (and implicit parameter) coercions?
493 -- You may think that the following is right:
494 -- let cos = decomposeCo (length tys1) (mkCoVarCoercion cv)
495 -- in zipWith3M newGivOrDerCoVar tys1 tys2 cos
496 -- But this assumes that the coercion is a type constructor-based
497 -- coercion, and not a PredTy (ClassP cn cos) coercion. So we chose
498 -- to not decompose these coercions. We have to get back to this
499 -- when we clean up the Coercion API.
501 canEq fl cv (TyConApp tc1 tys1) (TyConApp tc2 tys2)
502 | isAlgTyCon tc1 && isAlgTyCon tc2
504 , length tys1 == length tys2
505 = -- Generate equalities for each of the corresponding arguments
507 <- if isWanted fl then
508 do { argsv <- zipWithM newCoVar tys1 tys2
510 mkTyConCoercion tc1 (map mkCoVarCoercion argsv)
513 else if isGiven fl then
514 let cos = decomposeCo (length tys1) (mkCoVarCoercion cv)
515 in zipWith3M newGivenCoVar tys1 tys2 cos
518 zipWithM (\t1 t2 -> newDerivedId (EqPred t1 t2)) tys1 tys2
520 ; andCCans <$> zipWith3M (canEq fl) argsv tys1 tys2 }
522 -- See Note [Equality between type applications]
523 -- Note [Care with type applications] in TcUnify
525 | Just (s1,t1) <- tcSplitAppTy_maybe ty1
526 , Just (s2,t2) <- tcSplitAppTy_maybe ty2
529 then do { cv1 <- newCoVar s1 s2
530 ; cv2 <- newCoVar t1 t2
532 mkAppCoercion (mkCoVarCoercion cv1) (mkCoVarCoercion cv2)
535 else if isGiven fl then
536 let co1 = mkLeftCoercion $ mkCoVarCoercion cv
537 co2 = mkRightCoercion $ mkCoVarCoercion cv
538 in do { cv1 <- newGivenCoVar s1 s2 co1
539 ; cv2 <- newGivenCoVar t1 t2 co2
542 do { cv1 <- newDerivedId (EqPred s1 s2)
543 ; cv2 <- newDerivedId (EqPred t1 t2)
546 ; cc1 <- canEq fl cv1 s1 s2
547 ; cc2 <- canEq fl cv2 t1 t2
548 ; return (cc1 `andCCan` cc2) }
550 canEq fl cv s1@(ForAllTy {}) s2@(ForAllTy {})
551 | tcIsForAllTy s1, tcIsForAllTy s2,
555 = do { traceTcS "Ommitting decomposition of given polytype equality" (pprEq s1 s2)
558 -- Finally expand any type synonym applications.
559 canEq fl cv ty1 ty2 | Just ty1' <- tcView ty1 = canEq fl cv ty1' ty2
560 canEq fl cv ty1 ty2 | Just ty2' <- tcView ty2 = canEq fl cv ty1 ty2'
561 canEq fl cv _ _ = canEqFailure fl cv
563 canEqFailure :: CtFlavor -> EvVar -> TcS CanonicalCts
564 canEqFailure fl cv = return (singleCCan (mkFrozenError fl cv))
567 Note [Equality between type applications]
568 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
569 If we see an equality of the form s1 t1 ~ s2 t2 we can always split
570 it up into s1 ~ s2 /\ t1 ~ t2, since s1 and s2 can't be type
571 functions (type functions use the TyConApp constructor, which never
572 shows up as the LHS of an AppTy). Other than type functions, types
573 in Haskell are always
575 (1) generative: a b ~ c d implies a ~ c, since different type
576 constructors always generate distinct types
578 (2) injective: a b ~ a d implies b ~ d; we never generate the
579 same type from different type arguments.
582 Note [Canonical ordering for equality constraints]
583 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
584 Implemented as (<+=) below:
586 - Type function applications always come before anything else.
587 - Variables always come before non-variables (other than type
588 function applications).
590 Note that we don't need to unfold type synonyms on the RHS to check
591 the ordering; that is, in the rules above it's OK to consider only
592 whether something is *syntactically* a type function application or
593 not. To illustrate why this is OK, suppose we have an equality of the
594 form 'tv ~ S a b c', where S is a type synonym which expands to a
595 top-level application of the type function F, something like
599 Then to canonicalize 'tv ~ S a b c' we flatten the RHS, and since S's
600 expansion contains type function applications the flattener will do
601 the expansion and then generate a skolem variable for the type
602 function application, so we end up with something like this:
607 where x is the skolem variable. This is one extra equation than
608 absolutely necessary (we could have gotten away with just 'F d e ~ tv'
609 if we had noticed that S expanded to a top-level type function
610 application and flipped it around in the first place) but this way
611 keeps the code simpler.
613 Unlike the OutsideIn(X) draft of May 7, 2010, we do not care about the
614 ordering of tv ~ tv constraints. There are several reasons why we
617 (1) In order to be able to extract a substitution that doesn't
618 mention untouchable variables after we are done solving, we might
619 prefer to put touchable variables on the left. However, in and
620 of itself this isn't necessary; we can always re-orient equality
621 constraints at the end if necessary when extracting a substitution.
623 (2) To ensure termination we might think it necessary to put
624 variables in lexicographic order. However, this isn't actually
625 necessary as outlined below.
627 While building up an inert set of canonical constraints, we maintain
628 the invariant that the equality constraints in the inert set form an
629 acyclic rewrite system when viewed as L-R rewrite rules. Moreover,
630 the given constraints form an idempotent substitution (i.e. none of
631 the variables on the LHS occur in any of the RHS's, and type functions
632 never show up in the RHS at all), the wanted constraints also form an
633 idempotent substitution, and finally the LHS of a given constraint
634 never shows up on the RHS of a wanted constraint. There may, however,
635 be a wanted LHS that shows up in a given RHS, since we do not rewrite
636 given constraints with wanted constraints.
638 Suppose we have an inert constraint set
641 tg_1 ~ xig_1 -- givens
644 tw_1 ~ xiw_1 -- wanteds
648 where each t_i can be either a type variable or a type function
649 application. Now suppose we take a new canonical equality constraint,
650 t' ~ xi' (note among other things this means t' does not occur in xi')
651 and try to react it with the existing inert set. We show by induction
652 on the number of t_i which occur in t' ~ xi' that this process will
655 There are several ways t' ~ xi' could react with an existing constraint:
657 TODO: finish this proof. The below was for the case where the entire
658 inert set is an idempotent subustitution...
660 (b) We could have t' = t_j for some j. Then we obtain the new
661 equality xi_j ~ xi'; note that neither xi_j or xi' contain t_j. We
662 now canonicalize the new equality, which may involve decomposing it
663 into several canonical equalities, and recurse on these. However,
664 none of the new equalities will contain t_j, so they have fewer
665 occurrences of the t_i than the original equation.
667 (a) We could have t_j occurring in xi' for some j, with t' /=
668 t_j. Then we substitute xi_j for t_j in xi' and continue. However,
669 since none of the t_i occur in xi_j, we have decreased the
670 number of t_i that occur in xi', since we eliminated t_j and did not
671 introduce any new ones.
675 = FskCls TcTyVar -- ^ Flatten skolem
676 | VarCls TcTyVar -- ^ Non-flatten-skolem variable
677 | FunCls TyCon [Type] -- ^ Type function, exactly saturated
678 | OtherCls TcType -- ^ Neither of the above
680 unClassify :: TypeClassifier -> TcType
681 unClassify (VarCls tv) = TyVarTy tv
682 unClassify (FskCls tv) = TyVarTy tv
683 unClassify (FunCls fn tys) = TyConApp fn tys
684 unClassify (OtherCls ty) = ty
686 classify :: TcType -> TypeClassifier
688 classify (TyVarTy tv)
690 FlatSkol {} <- tcTyVarDetails tv = FskCls tv
691 | otherwise = VarCls tv
692 classify (TyConApp tc tys) | isSynFamilyTyCon tc
693 , tyConArity tc == length tys
695 classify ty | Just ty' <- tcView ty
696 = case classify ty' of
697 OtherCls {} -> OtherCls ty
698 var_or_fn -> var_or_fn
702 -- See note [Canonical ordering for equality constraints].
703 reOrient :: CtFlavor -> TypeClassifier -> TypeClassifier -> Bool
704 -- (t1 `reOrient` t2) responds True
705 -- iff we should flip to (t2~t1)
706 -- We try to say False if possible, to minimise evidence generation
708 -- Postcondition: After re-orienting, first arg is not OTherCls
709 reOrient _fl (OtherCls {}) (FunCls {}) = True
710 reOrient _fl (OtherCls {}) (FskCls {}) = True
711 reOrient _fl (OtherCls {}) (VarCls {}) = True
712 reOrient _fl (OtherCls {}) (OtherCls {}) = panic "reOrient" -- One must be Var/Fun
714 reOrient _fl (FunCls {}) (VarCls _tv) = False
715 -- But consider the following variation: isGiven fl && isMetaTyVar tv
717 -- See Note [No touchables as FunEq RHS] in TcSMonad
718 reOrient _fl (FunCls {}) _ = False -- Fun/Other on rhs
720 reOrient _fl (VarCls {}) (FunCls {}) = True
722 reOrient _fl (VarCls {}) (FskCls {}) = False
724 reOrient _fl (VarCls {}) (OtherCls {}) = False
725 reOrient _fl (VarCls tv1) (VarCls tv2)
726 | isMetaTyVar tv2 && not (isMetaTyVar tv1) = True
728 -- Just for efficiency, see CTyEqCan invariants
730 reOrient _fl (FskCls {}) (VarCls tv2) = isMetaTyVar tv2
731 -- Just for efficiency, see CTyEqCan invariants
733 reOrient _fl (FskCls {}) (FskCls {}) = False
734 reOrient _fl (FskCls {}) (FunCls {}) = True
735 reOrient _fl (FskCls {}) (OtherCls {}) = False
738 canEqLeaf :: TcsUntouchables
740 -> TypeClassifier -> TypeClassifier -> TcS CanonicalCts
741 -- Canonicalizing "leaf" equality constraints which cannot be
742 -- decomposed further (ie one of the types is a variable or
743 -- saturated type function application).
746 -- * one of the two arguments is not OtherCls
747 -- * the two types are not equal (looking through synonyms)
748 canEqLeaf _untch fl cv cls1 cls2
749 | cls1 `re_orient` cls2
750 = do { cv' <- if isWanted fl
751 then do { cv' <- newCoVar s2 s1
752 ; setCoBind cv $ mkSymCoercion (mkCoVarCoercion cv')
754 else if isGiven fl then
755 newGivenCoVar s2 s1 (mkSymCoercion (mkCoVarCoercion cv))
757 newDerivedId (EqPred s2 s1)
758 ; canEqLeafOriented fl cv' cls2 s1 }
761 = do { traceTcS "canEqLeaf" (ppr (unClassify cls1) $$ ppr (unClassify cls2))
762 ; canEqLeafOriented fl cv cls1 s2 }
764 re_orient = reOrient fl
769 canEqLeafOriented :: CtFlavor -> CoVar
770 -> TypeClassifier -> TcType -> TcS CanonicalCts
771 -- First argument is not OtherCls
772 canEqLeafOriented fl cv cls1@(FunCls fn tys1) s2 -- cv : F tys1
773 | let k1 = kindAppResult (tyConKind fn) tys1,
774 let k2 = typeKind s2,
775 not (k1 `compatKind` k2) -- Establish the kind invariant for CFunEqCan
777 -- Eagerly fails, see Note [Kind errors] in TcInteract
780 = ASSERT2( isSynFamilyTyCon fn, ppr (unClassify cls1) )
781 do { (xis1,cos1,ccs1) <- flattenMany fl tys1 -- Flatten type function arguments
782 -- cos1 :: xis1 ~ tys1
783 ; (xi2, co2, ccs2) <- flatten fl s2 -- Flatten entire RHS
785 ; let ccs = ccs1 `andCCan` ccs2
786 no_flattening_happened = isEmptyCCan ccs
787 ; cv_new <- if no_flattening_happened then return cv
788 else if isGiven fl then return cv
789 else if isWanted fl then
790 do { cv' <- newCoVar (unClassify (FunCls fn xis1)) xi2
792 ; let -- fun_co :: F xis1 ~ F tys1
793 fun_co = mkTyConCoercion fn cos1
794 -- want_co :: F tys1 ~ s2
795 want_co = mkSymCoercion fun_co
796 `mkTransCoercion` mkCoVarCoercion cv'
797 `mkTransCoercion` co2
798 ; setCoBind cv want_co
801 newDerivedId (EqPred (unClassify (FunCls fn xis1)) xi2)
803 ; let final_cc = CFunEqCan { cc_id = cv_new
808 ; return $ ccs `extendCCans` final_cc }
810 -- Otherwise, we have a variable on the left, so call canEqLeafTyVarLeft
811 canEqLeafOriented fl cv (FskCls tv) s2
812 = canEqLeafTyVarLeft fl cv tv s2
813 canEqLeafOriented fl cv (VarCls tv) s2
814 = canEqLeafTyVarLeft fl cv tv s2
815 canEqLeafOriented _ cv (OtherCls ty1) ty2
816 = pprPanic "canEqLeaf" (ppr cv $$ ppr ty1 $$ ppr ty2)
818 canEqLeafTyVarLeft :: CtFlavor -> CoVar -> TcTyVar -> TcType -> TcS CanonicalCts
819 -- Establish invariants of CTyEqCans
820 canEqLeafTyVarLeft fl cv tv s2 -- cv : tv ~ s2
821 | not (k1 `compatKind` k2) -- Establish the kind invariant for CTyEqCan
823 -- Eagerly fails, see Note [Kind errors] in TcInteract
825 = do { (xi2, co, ccs2) <- flatten fl s2 -- Flatten RHS co : xi2 ~ s2
826 ; mxi2' <- canOccursCheck fl tv xi2 -- Do an occurs check, and return a possibly
827 -- unfolded version of the RHS, if we had to
828 -- unfold any type synonyms to get rid of tv.
830 Nothing -> canEqFailure fl cv ;
832 do { let no_flattening_happened = isEmptyCCan ccs2
833 ; cv_new <- if no_flattening_happened then return cv
834 else if isGiven fl then return cv
835 else if isWanted fl then
836 do { cv' <- newCoVar (mkTyVarTy tv) xi2' -- cv' : tv ~ xi2
837 ; setCoBind cv (mkCoVarCoercion cv' `mkTransCoercion` co)
840 newDerivedId (EqPred (mkTyVarTy tv) xi2')
842 ; return $ ccs2 `extendCCans` CTyEqCan { cc_id = cv_new
845 , cc_rhs = xi2' } } } }
850 -- See Note [Type synonyms and canonicalization].
851 -- Check whether the given variable occurs in the given type. We may
852 -- have needed to do some type synonym unfolding in order to get rid
853 -- of the variable, so we also return the unfolded version of the
854 -- type, which is guaranteed to be syntactically free of the given
855 -- type variable. If the type is already syntactically free of the
856 -- variable, then the same type is returned.
858 -- Precondition: the two types are not equal (looking though synonyms)
859 canOccursCheck :: CtFlavor -> TcTyVar -> Xi -> TcS (Maybe Xi)
860 canOccursCheck _gw tv xi = return (expandAway tv xi)
863 @expandAway tv xi@ expands synonyms in xi just enough to get rid of
864 occurrences of tv, if that is possible; otherwise, it returns Nothing.
865 For example, suppose we have
868 expandAway b (F Int b) = Just [Int]
870 expandAway a (F a Int) = Nothing
872 We don't promise to do the absolute minimum amount of expanding
873 necessary, but we try not to do expansions we don't need to. We
874 prefer doing inner expansions first. For example,
875 type F a b = (a, Int, a, [a])
878 expandAway b (F (G b)) = F Char
879 even though we could also expand F to get rid of b.
882 expandAway :: TcTyVar -> Xi -> Maybe Xi
883 expandAway tv t@(TyVarTy tv')
884 | tv == tv' = Nothing
887 | not (tv `elemVarSet` tyVarsOfType xi) = Just xi
888 expandAway tv (AppTy ty1 ty2)
889 = do { ty1' <- expandAway tv ty1
890 ; ty2' <- expandAway tv ty2
891 ; return (mkAppTy ty1' ty2') }
892 -- mkAppTy <$> expandAway tv ty1 <*> expandAway tv ty2
893 expandAway tv (FunTy ty1 ty2)
894 = do { ty1' <- expandAway tv ty1
895 ; ty2' <- expandAway tv ty2
896 ; return (mkFunTy ty1' ty2') }
897 -- mkFunTy <$> expandAway tv ty1 <*> expandAway tv ty2
898 expandAway tv ty@(ForAllTy {})
899 = let (tvs,rho) = splitForAllTys ty
900 tvs_knds = map tyVarKind tvs
901 in if tv `elemVarSet` tyVarsOfTypes tvs_knds then
902 -- Can't expand away the kinds unless we create
903 -- fresh variables which we don't want to do at this point.
905 else do { rho' <- expandAway tv rho
906 ; return (mkForAllTys tvs rho') }
907 expandAway tv (PredTy pred)
908 = do { pred' <- expandAwayPred tv pred
909 ; return (PredTy pred') }
910 -- For a type constructor application, first try expanding away the
911 -- offending variable from the arguments. If that doesn't work, next
912 -- see if the type constructor is a type synonym, and if so, expand
914 expandAway tv ty@(TyConApp tc tys)
915 = (mkTyConApp tc <$> mapM (expandAway tv) tys) <|> (tcView ty >>= expandAway tv)
917 expandAwayPred :: TcTyVar -> TcPredType -> Maybe TcPredType
918 expandAwayPred tv (ClassP cls tys)
919 = do { tys' <- mapM (expandAway tv) tys; return (ClassP cls tys') }
920 expandAwayPred tv (EqPred ty1 ty2)
921 = do { ty1' <- expandAway tv ty1
922 ; ty2' <- expandAway tv ty2
923 ; return (EqPred ty1' ty2') }
924 expandAwayPred tv (IParam nm ty)
925 = do { ty' <- expandAway tv ty
926 ; return (IParam nm ty') }
932 Note [Type synonyms and canonicalization]
933 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
935 We treat type synonym applications as xi types, that is, they do not
936 count as type function applications. However, we do need to be a bit
937 careful with type synonyms: like type functions they may not be
938 generative or injective. However, unlike type functions, they are
939 parametric, so there is no problem in expanding them whenever we see
940 them, since we do not need to know anything about their arguments in
941 order to expand them; this is what justifies not having to treat them
942 as specially as type function applications. The thing that causes
943 some subtleties is that we prefer to leave type synonym applications
944 *unexpanded* whenever possible, in order to generate better error
947 If we encounter an equality constraint with type synonym applications
948 on both sides, or a type synonym application on one side and some sort
949 of type application on the other, we simply must expand out the type
950 synonyms in order to continue decomposing the equality constraint into
951 primitive equality constraints. For example, suppose we have
955 and we encounter the equality
959 In order to continue we must expand F a into [Int], giving us the
964 which we can then decompose into the more primitive equality
969 However, if we encounter an equality constraint with a type synonym
970 application on one side and a variable on the other side, we should
971 NOT (necessarily) expand the type synonym, since for the purpose of
972 good error messages we want to leave type synonyms unexpanded as much
975 However, there is a subtle point with type synonyms and the occurs
976 check that takes place for equality constraints of the form tv ~ xi.
977 As an example, suppose we have
981 and we come across the equality constraint
985 This should not actually fail the occurs check, since expanding out
986 the type synonym results in the legitimate equality constraint a ~
987 Int. We must actually do this expansion, because unifying a with F a
988 will lead the type checker into infinite loops later. Put another
989 way, canonical equality constraints should never *syntactically*
990 contain the LHS variable in the RHS type. However, we don't always
991 need to expand type synonyms when doing an occurs check; for example,
996 is obviously fine no matter what F expands to. And in this case we
997 would rather unify a with F b (rather than F b's expansion) in order
998 to get better error messages later.
1000 So, when doing an occurs check with a type synonym application on the
1001 RHS, we use some heuristics to find an expansion of the RHS which does
1002 not contain the variable from the LHS. In particular, given
1006 we first try expanding each of the ti to types which no longer contain
1007 a. If this turns out to be impossible, we next try expanding F
1011 %************************************************************************
1013 %* Functional dependencies, instantiation of equations
1015 %************************************************************************
1017 When we spot an equality arising from a functional dependency,
1018 we now use that equality (a "wanted") to rewrite the work-item
1019 constraint right away. This avoids two dangers
1021 Danger 1: If we send the original constraint on down the pipeline
1022 it may react with an instance declaration, and in delicate
1023 situations (when a Given overlaps with an instance) that
1024 may produce new insoluble goals: see Trac #4952
1026 Danger 2: If we don't rewrite the constraint, it may re-react
1027 with the same thing later, and produce the same equality
1028 again --> termination worries.
1030 To achieve this required some refactoring of FunDeps.lhs (nicer
1034 rewriteWithFunDeps :: [Equation]
1036 -> TcS (Maybe ([Xi], [Coercion], WorkList))
1037 rewriteWithFunDeps eqn_pred_locs xis fl
1038 = do { fd_ev_poss <- mapM (instFunDepEqn fl) eqn_pred_locs
1039 ; let fd_ev_pos :: [(Int,FlavoredEvVar)]
1040 fd_ev_pos = concat fd_ev_poss
1041 (rewritten_xis, cos) = unzip (rewriteDictParams fd_ev_pos xis)
1042 ; fds <- mapM (\(_,fev) -> mkCanonicalFEV fev) fd_ev_pos
1043 ; let fd_work = unionWorkLists fds
1044 ; if isEmptyWorkList fd_work
1046 else return (Just (rewritten_xis, cos, fd_work)) }
1048 instFunDepEqn :: CtFlavor -- Precondition: Only Wanted or Derived
1050 -> TcS [(Int, FlavoredEvVar)]
1051 -- Post: Returns the position index as well as the corresponding FunDep equality
1052 instFunDepEqn fl (FDEqn { fd_qtvs = qtvs, fd_eqs = eqs
1053 , fd_pred1 = d1, fd_pred2 = d2 })
1054 = do { let tvs = varSetElems qtvs
1055 ; tvs' <- mapM instFlexiTcS tvs
1056 ; let subst = zipTopTvSubst tvs (mkTyVarTys tvs')
1057 ; mapM (do_one subst) eqs }
1060 Given _ -> panic "mkFunDepEqns"
1061 Wanted loc -> Wanted (push_ctx loc)
1062 Derived loc -> Derived (push_ctx loc)
1064 push_ctx loc = pushErrCtxt FunDepOrigin (False, mkEqnMsg d1 d2) loc
1066 do_one subst (FDEq { fd_pos = i, fd_ty_left = ty1, fd_ty_right = ty2 })
1067 = do { let sty1 = substTy subst ty1
1068 sty2 = substTy subst ty2
1069 ; ev <- newCoVar sty1 sty2
1070 ; return (i, mkEvVarX ev fl') }
1072 rewriteDictParams :: [(Int,FlavoredEvVar)] -- A set of coercions : (pos, ty' ~ ty)
1073 -> [Type] -- A sequence of types: tys
1074 -> [(Type,Coercion)] -- Returns : [(ty', co : ty' ~ ty)]
1075 rewriteDictParams param_eqs tys
1076 = zipWith do_one tys [0..]
1078 do_one :: Type -> Int -> (Type,Coercion)
1079 do_one ty n = case lookup n param_eqs of
1080 Just wev -> (get_fst_ty wev, mkCoVarCoercion (evVarOf wev))
1081 Nothing -> (ty,ty) -- Identity
1083 get_fst_ty wev = case evVarOfPred wev of
1085 _ -> panic "rewriteDictParams: non equality fundep"
1087 mkEqnMsg :: (TcPredType, SDoc) -> (TcPredType, SDoc) -> TidyEnv
1088 -> TcM (TidyEnv, SDoc)
1089 mkEqnMsg (pred1,from1) (pred2,from2) tidy_env
1090 = do { zpred1 <- TcM.zonkTcPredType pred1
1091 ; zpred2 <- TcM.zonkTcPredType pred2
1092 ; let { tpred1 = tidyPred tidy_env zpred1
1093 ; tpred2 = tidyPred tidy_env zpred2 }
1094 ; let msg = vcat [ptext (sLit "When using functional dependencies to combine"),
1095 nest 2 (sep [ppr tpred1 <> comma, nest 2 from1]),
1096 nest 2 (sep [ppr tpred2 <> comma, nest 2 from2])]
1097 ; return (tidy_env, msg) }