1 {-
2 (c) The University of Glasgow 2006
3 (c) The GRASP/AQUA Project, Glasgow University, 2000
6 FunDeps - functional dependencies
8 It's better to read it as: "if we know these, then we're going to know these"
9 -}
11 {-# LANGUAGE CPP #-}
13 module FunDeps (
14 FunDepEqn(..), pprEquation,
15 improveFromInstEnv, improveFromAnother,
16 checkInstCoverage, checkFunDeps,
17 pprFundeps
18 ) where
20 #include "HsVersions.h"
22 import GhcPrelude
24 import Name
25 import Var
26 import Class
27 import Type
28 import TcType( transSuperClasses )
29 import CoAxiom( TypeEqn )
30 import Unify
31 import FamInst( injTyVarsOfTypes )
32 import InstEnv
33 import VarSet
34 import VarEnv
35 import Outputable
36 import ErrUtils( Validity(..), allValid )
37 import SrcLoc
38 import Util
40 import Pair ( Pair(..) )
41 import Data.List ( nubBy )
42 import Data.Maybe
43 import Data.Foldable ( fold )
45 {-
46 ************************************************************************
47 * *
48 \subsection{Generate equations from functional dependencies}
49 * *
50 ************************************************************************
53 Each functional dependency with one variable in the RHS is responsible
54 for generating a single equality. For instance:
55 class C a b | a -> b
56 The constraints ([Wanted] C Int Bool) and [Wanted] C Int alpha
57 will generate the following FunDepEqn
58 FDEqn { fd_qtvs = []
59 , fd_eqs = [Pair Bool alpha]
60 , fd_pred1 = C Int Bool
61 , fd_pred2 = C Int alpha
62 , fd_loc = ... }
63 However notice that a functional dependency may have more than one variable
64 in the RHS which will create more than one pair of types in fd_eqs. Example:
65 class C a b c | a -> b c
66 [Wanted] C Int alpha alpha
67 [Wanted] C Int Bool beta
68 Will generate:
69 FDEqn { fd_qtvs = []
70 , fd_eqs = [Pair Bool alpha, Pair alpha beta]
71 , fd_pred1 = C Int Bool
72 , fd_pred2 = C Int alpha
73 , fd_loc = ... }
75 INVARIANT: Corresponding types aren't already equal
76 That is, there exists at least one non-identity equality in FDEqs.
78 Assume:
79 class C a b c | a -> b c
80 instance C Int x x
81 And: [Wanted] C Int Bool alpha
82 We will /match/ the LHS of fundep equations, producing a matching substitution
83 and create equations for the RHS sides. In our last example we'd have generated:
84 ({x}, [fd1,fd2])
85 where
86 fd1 = FDEq 1 Bool x
87 fd2 = FDEq 2 alpha x
88 To ``execute'' the equation, make fresh type variable for each tyvar in the set,
89 instantiate the two types with these fresh variables, and then unify or generate
90 a new constraint. In the above example we would generate a new unification
91 variable 'beta' for x and produce the following constraints:
92 [Wanted] (Bool ~ beta)
93 [Wanted] (alpha ~ beta)
95 Notice the subtle difference between the above class declaration and:
96 class C a b c | a -> b, a -> c
97 where we would generate:
98 ({x},[fd1]),({x},[fd2])
99 This means that the template variable would be instantiated to different
100 unification variables when producing the FD constraints.
102 Finally, the position parameters will help us rewrite the wanted constraint ``on the spot''
103 -}
105 data FunDepEqn loc
106 = FDEqn { fd_qtvs :: [TyVar] -- Instantiate these type and kind vars
107 -- to fresh unification vars,
108 -- Non-empty only for FunDepEqns arising from instance decls
110 , fd_eqs :: [TypeEqn] -- Make these pairs of types equal
111 , fd_pred1 :: PredType -- The FunDepEqn arose from
112 , fd_pred2 :: PredType -- combining these two constraints
113 , fd_loc :: loc }
115 {-
116 Given a bunch of predicates that must hold, such as
118 C Int t1, C Int t2, C Bool t3, ?x::t4, ?x::t5
120 improve figures out what extra equations must hold.
121 For example, if we have
123 class C a b | a->b where ...
125 then improve will return
127 [(t1,t2), (t4,t5)]
129 NOTA BENE:
131 * improve does not iterate. It's possible that when we make
132 t1=t2, for example, that will in turn trigger a new equation.
133 This would happen if we also had
134 C t1 t7, C t2 t8
135 If t1=t2, we also get t7=t8.
137 improve does *not* do this extra step. It relies on the caller
138 doing so.
140 * The equations unify types that are not already equal. So there
141 is no effect iff the result of improve is empty
142 -}
144 instFD :: FunDep TyVar -> [TyVar] -> [Type] -> FunDep Type
145 -- (instFD fd tvs tys) returns fd instantiated with (tvs -> tys)
146 instFD (ls,rs) tvs tys
147 = (map lookup ls, map lookup rs)
148 where
149 env = zipVarEnv tvs tys
150 lookup tv = lookupVarEnv_NF env tv
152 zipAndComputeFDEqs :: (Type -> Type -> Bool) -- Discard this FDEq if true
153 -> [Type] -> [Type]
154 -> [TypeEqn]
155 -- Create a list of (Type,Type) pairs from two lists of types,
156 -- making sure that the types are not already equal
159 | otherwise = Pair ty1 ty2 : zipAndComputeFDEqs discard tys1 tys2
160 zipAndComputeFDEqs _ _ _ = []
162 -- Improve a class constraint from another class constraint
163 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
164 improveFromAnother :: loc
165 -> PredType -- Template item (usually given, or inert)
166 -> PredType -- Workitem [that can be improved]
167 -> [FunDepEqn loc]
168 -- Post: FDEqs always oriented from the other to the workitem
169 -- Equations have empty quantified variables
170 improveFromAnother loc pred1 pred2
171 | Just (cls1, tys1) <- getClassPredTys_maybe pred1
172 , Just (cls2, tys2) <- getClassPredTys_maybe pred2
173 , cls1 == cls2
174 = [ FDEqn { fd_qtvs = [], fd_eqs = eqs, fd_pred1 = pred1, fd_pred2 = pred2, fd_loc = loc }
175 | let (cls_tvs, cls_fds) = classTvsFds cls1
176 , fd <- cls_fds
177 , let (ltys1, rs1) = instFD fd cls_tvs tys1
178 (ltys2, rs2) = instFD fd cls_tvs tys2
179 , eqTypes ltys1 ltys2 -- The LHSs match
180 , let eqs = zipAndComputeFDEqs eqType rs1 rs2
181 , not (null eqs) ]
183 improveFromAnother _ _ _ = []
186 -- Improve a class constraint from instance declarations
187 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
189 instance Outputable (FunDepEqn a) where
190 ppr = pprEquation
192 pprEquation :: FunDepEqn a -> SDoc
193 pprEquation (FDEqn { fd_qtvs = qtvs, fd_eqs = pairs })
194 = vcat [text "forall" <+> braces (pprWithCommas ppr qtvs),
195 nest 2 (vcat [ ppr t1 <+> text "~" <+> ppr t2
196 | Pair t1 t2 <- pairs])]
198 improveFromInstEnv :: InstEnvs
199 -> (PredType -> SrcSpan -> loc)
200 -> PredType
201 -> [FunDepEqn loc] -- Needs to be a FunDepEqn because
202 -- of quantified variables
203 -- Post: Equations oriented from the template (matching instance) to the workitem!
204 improveFromInstEnv inst_env mk_loc pred
205 | Just (cls, tys) <- ASSERT2( isClassPred pred, ppr pred )
206 getClassPredTys_maybe pred
207 , let (cls_tvs, cls_fds) = classTvsFds cls
208 instances = classInstances inst_env cls
209 rough_tcs = roughMatchTcs tys
210 = [ FDEqn { fd_qtvs = meta_tvs, fd_eqs = eqs
211 , fd_pred1 = p_inst, fd_pred2 = pred
212 , fd_loc = mk_loc p_inst (getSrcSpan (is_dfun ispec)) }
213 | fd <- cls_fds -- Iterate through the fundeps first,
214 -- because there often are none!
215 , let trimmed_tcs = trimRoughMatchTcs cls_tvs fd rough_tcs
216 -- Trim the rough_tcs based on the head of the fundep.
217 -- Remember that instanceCantMatch treats both arguments
218 -- symmetrically, so it's ok to trim the rough_tcs,
219 -- rather than trimming each inst_tcs in turn
220 , ispec <- instances
221 , (meta_tvs, eqs) <- improveClsFD cls_tvs fd ispec
222 tys trimmed_tcs -- NB: orientation
223 , let p_inst = mkClassPred cls (is_tys ispec)
224 ]
225 improveFromInstEnv _ _ _ = []
228 improveClsFD :: [TyVar] -> FunDep TyVar -- One functional dependency from the class
229 -> ClsInst -- An instance template
230 -> [Type] -> [Maybe Name] -- Arguments of this (C tys) predicate
231 -> [([TyCoVar], [TypeEqn])] -- Empty or singleton
233 improveClsFD clas_tvs fd
234 (ClsInst { is_tvs = qtvs, is_tys = tys_inst, is_tcs = rough_tcs_inst })
235 tys_actual rough_tcs_actual
237 -- Compare instance {a,b} C sx sp sy sq
238 -- with wanted [W] C tx tp ty tq
239 -- for fundep (x,y -> p,q) from class (C x p y q)
240 -- If (sx,sy) unifies with (tx,ty), take the subst S
242 -- 'qtvs' are the quantified type variables, the ones which can be instantiated
243 -- to make the types match. For example, given
244 -- class C a b | a->b where ...
245 -- instance C (Maybe x) (Tree x) where ..
246 --
247 -- and a wanted constraint of form (C (Maybe t1) t2),
248 -- then we will call checkClsFD with
249 --
250 -- is_qtvs = {x}, is_tys = [Maybe x, Tree x]
251 -- tys_actual = [Maybe t1, t2]
252 --
253 -- We can instantiate x to t1, and then we want to force
254 -- (Tree x) [t1/x] ~ t2
256 | instanceCantMatch rough_tcs_inst rough_tcs_actual
257 = [] -- Filter out ones that can't possibly match,
259 | otherwise
260 = ASSERT2( equalLength tys_inst tys_actual &&
261 equalLength tys_inst clas_tvs
262 , ppr tys_inst <+> ppr tys_actual )
264 case tcMatchTyKis ltys1 ltys2 of
265 Nothing -> []
266 Just subst | isJust (tcMatchTyKisX subst rtys1 rtys2)
267 -- Don't include any equations that already hold.
268 -- Reason: then we know if any actual improvement has happened,
269 -- in which case we need to iterate the solver
270 -- In making this check we must taking account of the fact that any
271 -- qtvs that aren't already instantiated can be instantiated to anything
272 -- at all
273 -- NB: We can't do this 'is-useful-equation' check element-wise
274 -- because of:
275 -- class C a b c | a -> b c
276 -- instance C Int x x
277 -- [Wanted] C Int alpha Int
278 -- We would get that x -> alpha (isJust) and x -> Int (isJust)
279 -- so we would produce no FDs, which is clearly wrong.
280 -> []
282 | null fdeqs
283 -> []
285 | otherwise
286 -> [(meta_tvs, fdeqs)]
287 -- We could avoid this substTy stuff by producing the eqn
288 -- (qtvs, ls1++rs1, ls2++rs2)
289 -- which will re-do the ls1/ls2 unification when the equation is
290 -- executed. What we're doing instead is recording the partial
291 -- work of the ls1/ls2 unification leaving a smaller unification problem
292 where
293 rtys1' = map (substTyUnchecked subst) rtys1
295 fdeqs = zipAndComputeFDEqs (\_ _ -> False) rtys1' rtys2
297 -- We could discard equal types but it's an overkill to call
298 -- eqType again, since we know for sure that /at least one/
299 -- equation in there is useful)
301 meta_tvs = [ setVarType tv (substTyUnchecked subst (varType tv))
302 | tv <- qtvs, tv `notElemTCvSubst` subst ]
303 -- meta_tvs are the quantified type variables
304 -- that have not been substituted out
305 --
306 -- Eg. class C a b | a -> b
307 -- instance C Int [y]
308 -- Given constraint C Int z
309 -- we generate the equation
310 -- ({y}, [y], z)
311 --
312 -- But note (a) we get them from the dfun_id, so they are *in order*
313 -- because the kind variables may be mentioned in the
314 -- type variabes' kinds
315 -- (b) we must apply 'subst' to the kinds, in case we have
316 -- matched out a kind variable, but not a type variable
317 -- whose kind mentions that kind variable!
318 -- Trac #6015, #6068
319 where
320 (ltys1, rtys1) = instFD fd clas_tvs tys_inst
321 (ltys2, rtys2) = instFD fd clas_tvs tys_actual
323 {-
324 %************************************************************************
325 %* *
326 The Coverage condition for instance declarations
327 * *
328 ************************************************************************
330 Note [Coverage condition]
331 ~~~~~~~~~~~~~~~~~~~~~~~~~
332 Example
333 class C a b | a -> b
334 instance theta => C t1 t2
336 For the coverage condition, we check
337 (normal) fv(t2) `subset` fv(t1)
338 (liberal) fv(t2) `subset` oclose(fv(t1), theta)
340 The liberal version ensures the self-consistency of the instance, but
341 it does not guarantee termination. Example:
343 class Mul a b c | a b -> c where
344 (.*.) :: a -> b -> c
346 instance Mul Int Int Int where (.*.) = (*)
347 instance Mul Int Float Float where x .*. y = fromIntegral x * y
348 instance Mul a b c => Mul a [b] [c] where x .*. v = map (x.*.) v
350 In the third instance, it's not the case that fv([c]) `subset` fv(a,[b]).
351 But it is the case that fv([c]) `subset` oclose( theta, fv(a,[b]) )
353 But it is a mistake to accept the instance because then this defn:
354 f = \ b x y -> if b then x .*. [y] else y
355 makes instance inference go into a loop, because it requires the constraint
356 Mul a [b] b
357 -}
359 checkInstCoverage :: Bool -- Be liberal
360 -> Class -> [PredType] -> [Type]
361 -> Validity
362 -- "be_liberal" flag says whether to use "liberal" coverage of
363 -- See Note [Coverage Condition] below
364 --
365 -- Return values
366 -- Nothing => no problems
367 -- Just msg => coverage problem described by msg
369 checkInstCoverage be_liberal clas theta inst_taus
370 = allValid (map fundep_ok fds)
371 where
372 (tyvars, fds) = classTvsFds clas
373 fundep_ok fd
374 | and (isEmptyVarSet <\$> undetermined_tvs) = IsValid
375 | otherwise = NotValid msg
376 where
377 (ls,rs) = instFD fd tyvars inst_taus
378 ls_tvs = tyCoVarsOfTypes ls
379 rs_tvs = splitVisVarsOfTypes rs
381 undetermined_tvs | be_liberal = liberal_undet_tvs
382 | otherwise = conserv_undet_tvs
384 closed_ls_tvs = oclose theta ls_tvs
385 liberal_undet_tvs = (`minusVarSet` closed_ls_tvs) <\$> rs_tvs
386 conserv_undet_tvs = (`minusVarSet` ls_tvs) <\$> rs_tvs
388 undet_set = fold undetermined_tvs
390 msg = vcat [ -- text "ls_tvs" <+> ppr ls_tvs
391 -- , text "closed ls_tvs" <+> ppr (closeOverKinds ls_tvs)
392 -- , text "theta" <+> ppr theta
393 -- , text "oclose" <+> ppr (oclose theta (closeOverKinds ls_tvs))
394 -- , text "rs_tvs" <+> ppr rs_tvs
395 sep [ text "The"
396 <+> ppWhen be_liberal (text "liberal")
397 <+> text "coverage condition fails in class"
398 <+> quotes (ppr clas)
399 , nest 2 \$ text "for functional dependency:"
400 <+> quotes (pprFunDep fd) ]
401 , sep [ text "Reason: lhs type"<>plural ls <+> pprQuotedList ls
402 , nest 2 \$
403 (if isSingleton ls
404 then text "does not"
405 else text "do not jointly")
406 <+> text "determine rhs type"<>plural rs
407 <+> pprQuotedList rs ]
408 , text "Un-determined variable" <> pluralVarSet undet_set <> colon
409 <+> pprVarSet undet_set (pprWithCommas ppr)
410 , ppWhen (isEmptyVarSet \$ pSnd undetermined_tvs) \$
411 ppSuggestExplicitKinds
412 , ppWhen (not be_liberal &&
413 and (isEmptyVarSet <\$> liberal_undet_tvs)) \$
414 text "Using UndecidableInstances might help" ]
416 {- Note [Closing over kinds in coverage]
417 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
418 Suppose we have a fundep (a::k) -> b
419 Then if 'a' is instantiated to (x y), where x:k2->*, y:k2,
420 then fixing x really fixes k2 as well, and so k2 should be added to
421 the lhs tyvars in the fundep check.
423 Example (Trac #8391), using liberal coverage
424 data Foo a = ... -- Foo :: forall k. k -> *
425 class Bar a b | a -> b
426 instance Bar a (Foo a)
428 In the instance decl, (a:k) does fix (Foo k a), but only if we notice
429 that (a:k) fixes k. Trac #10109 is another example.
431 Here is a more subtle example, from HList-0.4.0.0 (Trac #10564)
433 class HasFieldM (l :: k) r (v :: Maybe *)
434 | l r -> v where ...
435 class HasFieldM1 (b :: Maybe [*]) (l :: k) r v
436 | b l r -> v where ...
437 class HMemberM (e1 :: k) (l :: [k]) (r :: Maybe [k])
438 | e1 l -> r
440 data Label :: k -> *
441 type family LabelsOf (a :: [*]) :: *
443 instance (HMemberM (Label {k} (l::k)) (LabelsOf xs) b,
444 HasFieldM1 b l (r xs) v)
445 => HasFieldM l (r xs) v where
447 Is the instance OK? Does {l,r,xs} determine v? Well:
449 * From the instance constraint HMemberM (Label k l) (LabelsOf xs) b,
450 plus the fundep "| el l -> r" in class HMameberM,
451 we get {l,k,xs} -> b
453 * Note the 'k'!! We must call closeOverKinds on the seed set
454 ls_tvs = {l,r,xs}, BEFORE doing oclose, else the {l,k,xs}->b
455 fundep won't fire. This was the reason for #10564.
457 * So starting from seeds {l,r,xs,k} we do oclose to get
458 first {l,r,xs,k,b}, via the HMemberM constraint, and then
459 {l,r,xs,k,b,v}, via the HasFieldM1 constraint.
461 * And that fixes v.
463 However, we must closeOverKinds whenever augmenting the seed set
464 in oclose! Consider Trac #10109:
466 data Succ a -- Succ :: forall k. k -> *
467 class Add (a :: k1) (b :: k2) (ab :: k3) | a b -> ab
468 instance (Add a b ab) => Add (Succ {k1} (a :: k1))
469 b
470 (Succ {k3} (ab :: k3})
473 Now use the fundep to extend to {a,k1,b,k2,ab}. But we need to
474 closeOverKinds *again* now to {a,k1,b,k2,ab,k3}, so that we fix all
475 the variables free in (Succ {k3} ab).
477 Bottom line:
478 * closeOverKinds on initial seeds (done automatically
479 by tyCoVarsOfTypes in checkInstCoverage)
480 * and closeOverKinds whenever extending those seeds (in oclose)
482 Note [The liberal coverage condition]
483 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
484 (oclose preds tvs) closes the set of type variables tvs,
485 wrt functional dependencies in preds. The result is a superset
486 of the argument set. For example, if we have
487 class C a b | a->b where ...
488 then
489 oclose [C (x,y) z, C (x,p) q] {x,y} = {x,y,z}
490 because if we know x and y then that fixes z.
492 We also use equality predicates in the predicates; if we have an
493 assumption `t1 ~ t2`, then we use the fact that if we know `t1` we
494 also know `t2` and the other way.
495 eg oclose [C (x,y) z, a ~ x] {a,y} = {a,y,z,x}
497 oclose is used (only) when checking the coverage condition for
498 an instance declaration
500 Note [Equality superclasses]
501 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
502 Suppose we have
503 class (a ~ [b]) => C a b
505 Remember from Note [The equality types story] in TysPrim, that
506 * (a ~~ b) is a superclass of (a ~ b)
507 * (a ~# b) is a superclass of (a ~~ b)
509 So when oclose expands superclasses we'll get a (a ~# [b]) superclass.
510 But that's an EqPred not a ClassPred, and we jolly well do want to
511 account for the mutual functional dependencies implied by (t1 ~# t2).
512 Hence the EqPred handling in oclose. See Trac #10778.
514 Note [Care with type functions]
515 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
516 Consider (Trac #12803)
517 class C x y | x -> y
518 type family F a b
519 type family G c d = r | r -> d
521 Now consider
522 oclose (C (F a b) (G c d)) {a,b}
524 Knowing {a,b} fixes (F a b) regardless of the injectivity of F.
525 But knowing (G c d) fixes only {d}, because G is only injective
526 in its second parameter.
528 Hence the tyCoVarsOfTypes/injTyVarsOfTypes dance in tv_fds.
529 -}
531 oclose :: [PredType] -> TyCoVarSet -> TyCoVarSet
532 -- See Note [The liberal coverage condition]
533 oclose preds fixed_tvs
534 | null tv_fds = fixed_tvs -- Fast escape hatch for common case.
535 | otherwise = fixVarSet extend fixed_tvs
536 where
537 extend fixed_tvs = foldl add fixed_tvs tv_fds
538 where
540 | ls `subVarSet` fixed_tvs = fixed_tvs `unionVarSet` closeOverKinds rs
541 | otherwise = fixed_tvs
542 -- closeOverKinds: see Note [Closing over kinds in coverage]
544 tv_fds :: [(TyCoVarSet,TyCoVarSet)]
545 tv_fds = [ (tyCoVarsOfTypes ls, injTyVarsOfTypes rs)
546 -- See Note [Care with type functions]
547 | pred <- preds
548 , pred' <- pred : transSuperClasses pred
549 -- Look for fundeps in superclasses too
550 , (ls, rs) <- determined pred' ]
552 determined :: PredType -> [([Type],[Type])]
553 determined pred
554 = case classifyPredType pred of
555 EqPred NomEq t1 t2 -> [([t1],[t2]), ([t2],[t1])]
556 -- See Note [Equality superclasses]
557 ClassPred cls tys -> [ instFD fd cls_tvs tys
558 | let (cls_tvs, cls_fds) = classTvsFds cls
559 , fd <- cls_fds ]
560 _ -> []
563 {- *********************************************************************
564 * *
565 Check that a new instance decl is OK wrt fundeps
566 * *
567 ************************************************************************
569 Here is the bad case:
570 class C a b | a->b where ...
571 instance C Int Bool where ...
572 instance C Int Char where ...
574 The point is that a->b, so Int in the first parameter must uniquely
575 determine the second. In general, given the same class decl, and given
577 instance C s1 s2 where ...
578 instance C t1 t2 where ...
580 Then the criterion is: if U=unify(s1,t1) then U(s2) = U(t2).
582 Matters are a little more complicated if there are free variables in
583 the s2/t2.
585 class D a b c | a -> b
586 instance D a b => D [(a,a)] [b] Int
587 instance D a b => D [a] [b] Bool
589 The instance decls don't overlap, because the third parameter keeps
590 them separate. But we want to make sure that given any constraint
591 D s1 s2 s3
592 if s1 matches
594 Note [Bogus consistency check]
595 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
596 In checkFunDeps we check that a new ClsInst is consistent with all the
597 ClsInsts in the environment.
599 The bogus aspect is discussed in Trac #10675. Currenty it if the two
600 types are *contradicatory*, using (isNothing . tcUnifyTys). But all
601 the papers say we should check if the two types are *equal* thus
602 not (substTys subst rtys1 `eqTypes` substTys subst rtys2)
603 For now I'm leaving the bogus form because that's the way it has
604 been for years.
605 -}
607 checkFunDeps :: InstEnvs -> ClsInst -> [ClsInst]
608 -- The Consistency Check.
609 -- Check whether adding DFunId would break functional-dependency constraints
610 -- Used only for instance decls defined in the module being compiled
611 -- Returns a list of the ClsInst in InstEnvs that are inconsistent
612 -- with the proposed new ClsInst
613 checkFunDeps inst_envs (ClsInst { is_tvs = qtvs1, is_cls = cls
614 , is_tys = tys1, is_tcs = rough_tcs1 })
615 | null fds
616 = []
617 | otherwise
618 = nubBy eq_inst \$
619 [ ispec | ispec <- cls_insts
620 , fd <- fds
621 , is_inconsistent fd ispec ]
622 where
623 cls_insts = classInstances inst_envs cls
624 (cls_tvs, fds) = classTvsFds cls
625 qtv_set1 = mkVarSet qtvs1
627 is_inconsistent fd (ClsInst { is_tvs = qtvs2, is_tys = tys2, is_tcs = rough_tcs2 })
628 | instanceCantMatch trimmed_tcs rough_tcs2
629 = False
630 | otherwise
631 = case tcUnifyTyKis bind_fn ltys1 ltys2 of
632 Nothing -> False
633 Just subst
634 -> isNothing \$ -- Bogus legacy test (Trac #10675)
635 -- See Note [Bogus consistency check]
636 tcUnifyTyKis bind_fn (substTysUnchecked subst rtys1) (substTysUnchecked subst rtys2)
638 where
639 trimmed_tcs = trimRoughMatchTcs cls_tvs fd rough_tcs1
640 (ltys1, rtys1) = instFD fd cls_tvs tys1
641 (ltys2, rtys2) = instFD fd cls_tvs tys2
642 qtv_set2 = mkVarSet qtvs2
643 bind_fn tv | tv `elemVarSet` qtv_set1 = BindMe
644 | tv `elemVarSet` qtv_set2 = BindMe
645 | otherwise = Skolem
647 eq_inst i1 i2 = instanceDFunId i1 == instanceDFunId i2
648 -- A single instance may appear twice in the un-nubbed conflict list
649 -- because it may conflict with more than one fundep. E.g.
650 -- class C a b c | a -> b, a -> c
651 -- instance C Int Bool Bool
652 -- instance C Int Char Char
653 -- The second instance conflicts with the first by *both* fundeps
655 trimRoughMatchTcs :: [TyVar] -> FunDep TyVar -> [Maybe Name] -> [Maybe Name]
656 -- Computing rough_tcs for a particular fundep
657 -- class C a b c | a -> b where ...
658 -- For each instance .... => C ta tb tc
659 -- we want to match only on the type ta; so our
660 -- rough-match thing must similarly be filtered.
661 -- Hence, we Nothing-ise the tb and tc types right here
662 --
663 -- Result list is same length as input list, just with more Nothings
664 trimRoughMatchTcs clas_tvs (ltvs, _) mb_tcs
665 = zipWith select clas_tvs mb_tcs
666 where
667 select clas_tv mb_tc | clas_tv `elem` ltvs = mb_tc
668 | otherwise = Nothing