2 % (c) The GRASP/AQUA Project, Glasgow University, 2000
4 \section[FunDeps]{FunDeps - functional dependencies}
6 It's better to read it as: "if we know these, then we're going to know these"
10 Equation, pprEquation,
11 oclose, grow, improve,
12 checkInstCoverage, checkFunDeps,
16 #include "HsVersions.h"
18 import Name ( Name, getSrcLoc )
20 import Class ( Class, FunDep, pprFundeps, classTvsFds )
21 import TcGadt ( tcUnifyTys, BindFlag(..) )
22 import Type ( substTys, notElemTvSubst )
23 import Coercion ( isEqPred )
24 import TcType ( Type, PredType(..), tcEqType,
25 predTyUnique, mkClassPred, tyVarsOfTypes, tyVarsOfPred )
26 import InstEnv ( Instance(..), InstEnv, instanceHead, classInstances,
27 instanceCantMatch, roughMatchTcs )
31 import Util ( notNull )
33 import Maybe ( isJust )
34 import ListSetOps ( equivClassesByUniq )
38 %************************************************************************
40 \subsection{Close type variables}
42 %************************************************************************
44 (oclose preds tvs) closes the set of type variables tvs,
45 wrt functional dependencies in preds. The result is a superset
46 of the argument set. For example, if we have
47 class C a b | a->b where ...
49 oclose [C (x,y) z, C (x,p) q] {x,y} = {x,y,z}
50 because if we know x and y then that fixes z.
56 a) When determining ambiguity. The type
57 forall a,b. C a b => a
58 is not ambiguous (given the above class decl for C) because
61 b) When generalising a type T. Usually we take FV(T) \ FV(Env),
64 where the '+' is the oclosure operation. Notice that we do not
65 take FV(T)+. This puzzled me for a bit. Consider
69 and suppose e have that E :: C a b => a, and suppose that b is
70 free in the environment. Then we quantify over 'a' only, giving
71 the type forall a. C a b => a. Since a->b but we don't have b->a,
72 we might have instance decls like
73 instance C Bool Int where ...
74 instance C Char Int where ...
75 so knowing that b=Int doesn't fix 'a'; so we quantify over it.
80 If we have class C a b => D a b where ....
81 class D a b | a -> b where ...
82 and the preds are [C (x,y) z], then we want to see the fd in D,
83 even though it is not explicit in C, giving [({x,y},{z})]
85 Similarly for instance decls? E.g. Suppose we have
86 instance C a b => Eq (T a b) where ...
87 and we infer a type t with constraints Eq (T a b) for a particular
88 expression, and suppose that 'a' is free in the environment.
89 We could generalise to
90 forall b. Eq (T a b) => t
91 but if we reduced the constraint, to C a b, we'd see that 'a' determines
92 b, so that a better type might be
93 t (with free constraint C a b)
94 Perhaps it doesn't matter, because we'll still force b to be a
95 particular type at the call sites. Generalising over too many
96 variables (provided we don't shadow anything by quantifying over a
97 variable that is actually free in the envt) may postpone errors; it
98 won't hide them altogether.
102 oclose :: [PredType] -> TyVarSet -> TyVarSet
103 oclose preds fixed_tvs
104 | null tv_fds = fixed_tvs -- Fast escape hatch for common case
105 | otherwise = loop fixed_tvs
108 | new_fixed_tvs `subVarSet` fixed_tvs = fixed_tvs
109 | otherwise = loop new_fixed_tvs
111 new_fixed_tvs = foldl extend fixed_tvs tv_fds
113 extend fixed_tvs (ls,rs) | ls `subVarSet` fixed_tvs = fixed_tvs `unionVarSet` rs
114 | otherwise = fixed_tvs
116 tv_fds :: [(TyVarSet,TyVarSet)]
117 -- In our example, tv_fds will be [ ({x,y}, {z}), ({x,p},{q}) ]
118 -- Meaning "knowing x,y fixes z, knowing x,p fixes q"
119 tv_fds = [ (tyVarsOfTypes xs, tyVarsOfTypes ys)
120 | ClassP cls tys <- preds, -- Ignore implicit params
121 let (cls_tvs, cls_fds) = classTvsFds cls,
123 let (xs,ys) = instFD fd cls_tvs tys
128 grow :: [PredType] -> TyVarSet -> TyVarSet
129 -- See Note [Ambiguity] in TcSimplify
131 | null preds = fixed_tvs
132 | otherwise = loop fixed_tvs
135 | new_fixed_tvs `subVarSet` fixed_tvs = fixed_tvs
136 | otherwise = loop new_fixed_tvs
138 new_fixed_tvs = foldl extend fixed_tvs pred_sets
140 extend fixed_tvs pred_tvs
141 | fixed_tvs `intersectsVarSet` pred_tvs = fixed_tvs `unionVarSet` pred_tvs
142 | otherwise = fixed_tvs
144 pred_sets = [tyVarsOfPred pred | pred <- preds]
147 %************************************************************************
149 \subsection{Generate equations from functional dependencies}
151 %************************************************************************
156 type Equation = (TyVarSet, [(Type, Type)])
157 -- These pairs of types should be equal, for some
158 -- substitution of the tyvars in the tyvar set
159 -- INVARIANT: corresponding types aren't already equal
161 -- It's important that we have a *list* of pairs of types. Consider
162 -- class C a b c | a -> b c where ...
163 -- instance C Int x x where ...
164 -- Then, given the constraint (C Int Bool v) we should improve v to Bool,
165 -- via the equation ({x}, [(Bool,x), (v,x)])
166 -- This would not happen if the class had looked like
167 -- class C a b c | a -> b, a -> c
169 -- To "execute" the equation, make fresh type variable for each tyvar in the set,
170 -- instantiate the two types with these fresh variables, and then unify.
172 -- For example, ({a,b}, (a,Int,b), (Int,z,Bool))
173 -- We unify z with Int, but since a and b are quantified we do nothing to them
174 -- We usually act on an equation by instantiating the quantified type varaibles
175 -- to fresh type variables, and then calling the standard unifier.
177 pprEquation (qtvs, pairs)
178 = vcat [ptext SLIT("forall") <+> braces (pprWithCommas ppr (varSetElems qtvs)),
179 nest 2 (vcat [ ppr t1 <+> ptext SLIT(":=:") <+> ppr t2 | (t1,t2) <- pairs])]
182 type Pred_Loc = (PredType, SDoc) -- SDoc says where the Pred comes from
184 improve :: (Class -> [Instance]) -- Gives instances for given class
185 -> [Pred_Loc] -- Current constraints;
186 -> [(Equation,Pred_Loc,Pred_Loc)] -- Derived equalities that must also hold
187 -- (NB the above INVARIANT for type Equation)
188 -- The Pred_Locs explain which two predicates were
189 -- combined (for error messages)
192 Given a bunch of predicates that must hold, such as
194 C Int t1, C Int t2, C Bool t3, ?x::t4, ?x::t5
196 improve figures out what extra equations must hold.
197 For example, if we have
199 class C a b | a->b where ...
201 then improve will return
207 * improve does not iterate. It's possible that when we make
208 t1=t2, for example, that will in turn trigger a new equation.
209 This would happen if we also had
211 If t1=t2, we also get t7=t8.
213 improve does *not* do this extra step. It relies on the caller
216 * The equations unify types that are not already equal. So there
217 is no effect iff the result of improve is empty
222 improve inst_env preds
223 = [ eqn | group <- equivClassesByUniq (predTyUnique . fst) (filterEqPreds preds),
224 eqn <- checkGroup inst_env group ]
225 where filterEqPreds = filter (not . isEqPred . fst)
228 checkGroup :: (Class -> [Instance])
230 -> [(Equation, Pred_Loc, Pred_Loc)]
231 -- The preds are all for the same class or implicit param
233 checkGroup inst_env (p1@(IParam _ ty, _) : ips)
234 = -- For implicit parameters, all the types must match
235 [ ((emptyVarSet, [(ty,ty')]), p1, p2)
236 | p2@(IParam _ ty', _) <- ips, not (ty `tcEqType` ty')]
238 checkGroup inst_env clss@((ClassP cls _, _) : _)
239 = -- For classes life is more complicated
240 -- Suppose the class is like
241 -- classs C as | (l1 -> r1), (l2 -> r2), ... where ...
242 -- Then FOR EACH PAIR (ClassP c tys1, ClassP c tys2) in the list clss
244 -- U l1[tys1/as] = U l2[tys2/as]
245 -- (where U is a unifier)
247 -- If so, we return the pair
248 -- U r1[tys1/as] = U l2[tys2/as]
250 -- We need to do something very similar comparing each predicate
251 -- with relevant instance decls
253 instance_eqns ++ pairwise_eqns
254 -- NB: we put the instance equations first. This biases the
255 -- order so that we first improve individual constraints against the
256 -- instances (which are perhaps in a library and less likely to be
257 -- wrong; and THEN perform the pairwise checks.
258 -- The other way round, it's possible for the pairwise check to succeed
259 -- and cause a subsequent, misleading failure of one of the pair with an
260 -- instance declaration. See tcfail143.hs for an exmample
263 (cls_tvs, cls_fds) = classTvsFds cls
264 instances = inst_env cls
266 -- NOTE that we iterate over the fds first; they are typically
267 -- empty, which aborts the rest of the loop.
268 pairwise_eqns :: [(Equation,Pred_Loc,Pred_Loc)]
269 pairwise_eqns -- This group comes from pairwise comparison
272 p1@(ClassP _ tys1, _) : rest <- tails clss,
273 p2@(ClassP _ tys2, _) <- rest,
274 eqn <- checkClsFD emptyVarSet fd cls_tvs tys1 tys2
277 instance_eqns :: [(Equation,Pred_Loc,Pred_Loc)]
278 instance_eqns -- This group comes from comparing with instance decls
280 | fd <- cls_fds, -- Iterate through the fundeps first,
281 -- because there often are none!
282 p2@(ClassP _ tys2, _) <- clss,
283 let rough_tcs2 = trimRoughMatchTcs cls_tvs fd (roughMatchTcs tys2),
284 ispec@(Instance { is_tvs = qtvs, is_tys = tys1,
285 is_tcs = mb_tcs1 }) <- instances,
286 not (instanceCantMatch mb_tcs1 rough_tcs2),
287 eqn <- checkClsFD qtvs fd cls_tvs tys1 tys2,
288 let p1 = (mkClassPred cls tys1,
289 ptext SLIT("arising from the instance declaration at") <+>
290 ppr (getSrcLoc ispec))
293 checkClsFD :: TyVarSet -- Quantified type variables; see note below
294 -> FunDep TyVar -> [TyVar] -- One functional dependency from the class
298 checkClsFD qtvs fd clas_tvs tys1 tys2
299 -- 'qtvs' are the quantified type variables, the ones which an be instantiated
300 -- to make the types match. For example, given
301 -- class C a b | a->b where ...
302 -- instance C (Maybe x) (Tree x) where ..
304 -- and an Inst of form (C (Maybe t1) t2),
305 -- then we will call checkClsFD with
307 -- qtvs = {x}, tys1 = [Maybe x, Tree x]
308 -- tys2 = [Maybe t1, t2]
310 -- We can instantiate x to t1, and then we want to force
311 -- (Tree x) [t1/x] :=: t2
313 -- This function is also used when matching two Insts (rather than an Inst
314 -- against an instance decl. In that case, qtvs is empty, and we are doing
317 -- This function is also used by InstEnv.badFunDeps, which needs to *unify*
318 -- For the one-sided matching case, the qtvs are just from the template,
319 -- so we get matching
321 = ASSERT2( length tys1 == length tys2 &&
322 length tys1 == length clas_tvs
323 , ppr tys1 <+> ppr tys2 )
325 case tcUnifyTys bind_fn ls1 ls2 of
327 Just subst | isJust (tcUnifyTys bind_fn rs1' rs2')
328 -- Don't include any equations that already hold.
329 -- Reason: then we know if any actual improvement has happened,
330 -- in which case we need to iterate the solver
331 -- In making this check we must taking account of the fact that any
332 -- qtvs that aren't already instantiated can be instantiated to anything
336 | otherwise -- Aha! A useful equation
337 -> [ (qtvs', zip rs1' rs2')]
338 -- We could avoid this substTy stuff by producing the eqn
339 -- (qtvs, ls1++rs1, ls2++rs2)
340 -- which will re-do the ls1/ls2 unification when the equation is
341 -- executed. What we're doing instead is recording the partial
342 -- work of the ls1/ls2 unification leaving a smaller unification problem
344 rs1' = substTys subst rs1
345 rs2' = substTys subst rs2
346 qtvs' = filterVarSet (`notElemTvSubst` subst) qtvs
347 -- qtvs' are the quantified type variables
348 -- that have not been substituted out
350 -- Eg. class C a b | a -> b
351 -- instance C Int [y]
352 -- Given constraint C Int z
353 -- we generate the equation
356 bind_fn tv | tv `elemVarSet` qtvs = BindMe
359 (ls1, rs1) = instFD fd clas_tvs tys1
360 (ls2, rs2) = instFD fd clas_tvs tys2
362 instFD :: FunDep TyVar -> [TyVar] -> [Type] -> FunDep Type
363 instFD (ls,rs) tvs tys
364 = (map lookup ls, map lookup rs)
366 env = zipVarEnv tvs tys
367 lookup tv = lookupVarEnv_NF env tv
371 checkInstCoverage :: Class -> [Type] -> Bool
372 -- Check that the Coverage Condition is obeyed in an instance decl
373 -- For example, if we have
374 -- class theta => C a b | a -> b
376 -- Then we require fv(t2) `subset` fv(t1)
377 -- See Note [Coverage Condition] below
379 checkInstCoverage clas inst_taus
382 (tyvars, fds) = classTvsFds clas
383 fundep_ok fd = tyVarsOfTypes rs `subVarSet` tyVarsOfTypes ls
385 (ls,rs) = instFD fd tyvars inst_taus
388 Note [Coverage condition]
389 ~~~~~~~~~~~~~~~~~~~~~~~~~
390 For the coverage condition, we used to require only that
391 fv(t2) `subset` oclose(fv(t1), theta)
394 class Mul a b c | a b -> c where
397 instance Mul Int Int Int where (.*.) = (*)
398 instance Mul Int Float Float where x .*. y = fromIntegral x * y
399 instance Mul a b c => Mul a [b] [c] where x .*. v = map (x.*.) v
401 In the third instance, it's not the case that fv([c]) `subset` fv(a,[b]).
402 But it is the case that fv([c]) `subset` oclose( theta, fv(a,[b]) )
404 But it is a mistake to accept the instance because then this defn:
405 f = \ b x y -> if b then x .*. [y] else y
406 makes instance inference go into a loop, because it requires the constraint
410 %************************************************************************
412 Check that a new instance decl is OK wrt fundeps
414 %************************************************************************
416 Here is the bad case:
417 class C a b | a->b where ...
418 instance C Int Bool where ...
419 instance C Int Char where ...
421 The point is that a->b, so Int in the first parameter must uniquely
422 determine the second. In general, given the same class decl, and given
424 instance C s1 s2 where ...
425 instance C t1 t2 where ...
427 Then the criterion is: if U=unify(s1,t1) then U(s2) = U(t2).
429 Matters are a little more complicated if there are free variables in
432 class D a b c | a -> b
433 instance D a b => D [(a,a)] [b] Int
434 instance D a b => D [a] [b] Bool
436 The instance decls don't overlap, because the third parameter keeps
437 them separate. But we want to make sure that given any constraint
443 checkFunDeps :: (InstEnv, InstEnv) -> Instance
444 -> Maybe [Instance] -- Nothing <=> ok
445 -- Just dfs <=> conflict with dfs
446 -- Check wheher adding DFunId would break functional-dependency constraints
447 -- Used only for instance decls defined in the module being compiled
448 checkFunDeps inst_envs ispec
449 | null bad_fundeps = Nothing
450 | otherwise = Just bad_fundeps
452 (ins_tvs, _, clas, ins_tys) = instanceHead ispec
453 ins_tv_set = mkVarSet ins_tvs
454 cls_inst_env = classInstances inst_envs clas
455 bad_fundeps = badFunDeps cls_inst_env clas ins_tv_set ins_tys
457 badFunDeps :: [Instance] -> Class
458 -> TyVarSet -> [Type] -- Proposed new instance type
460 badFunDeps cls_insts clas ins_tv_set ins_tys
461 = [ ispec | fd <- fds, -- fds is often empty
462 let trimmed_tcs = trimRoughMatchTcs clas_tvs fd rough_tcs,
463 ispec@(Instance { is_tcs = mb_tcs, is_tvs = tvs,
464 is_tys = tys }) <- cls_insts,
465 -- Filter out ones that can't possibly match,
466 -- based on the head of the fundep
467 not (instanceCantMatch trimmed_tcs mb_tcs),
468 notNull (checkClsFD (tvs `unionVarSet` ins_tv_set)
469 fd clas_tvs tys ins_tys)
472 (clas_tvs, fds) = classTvsFds clas
473 rough_tcs = roughMatchTcs ins_tys
475 trimRoughMatchTcs :: [TyVar] -> FunDep TyVar -> [Maybe Name] -> [Maybe Name]
476 -- Computing rough_tcs for a particular fundep
477 -- class C a b c | a c -> b where ...
478 -- For each instance .... => C ta tb tc
479 -- we want to match only on the types ta, tb; so our
480 -- rough-match thing must similarly be filtered.
481 -- Hence, we Nothing-ise the tb type right here
482 trimRoughMatchTcs clas_tvs (ltvs,_) mb_tcs
483 = zipWith select clas_tvs mb_tcs
485 select clas_tv mb_tc | clas_tv `elem` ltvs = mb_tc
486 | otherwise = Nothing