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, classTvsFds )
21 import Unify ( tcUnifyTys, BindFlag(..) )
22 import Type ( substTys, notElemTvSubst )
23 import TcType ( Type, PredType(..), tcEqType,
24 predTyUnique, mkClassPred, tyVarsOfTypes, tyVarsOfPred )
25 import InstEnv ( Instance(..), InstEnv, instanceHead, classInstances,
26 instanceCantMatch, roughMatchTcs )
30 import Util ( notNull )
32 import Maybe ( isJust )
33 import ListSetOps ( equivClassesByUniq )
37 %************************************************************************
39 \subsection{Close type variables}
41 %************************************************************************
43 (oclose preds tvs) closes the set of type variables tvs,
44 wrt functional dependencies in preds. The result is a superset
45 of the argument set. For example, if we have
46 class C a b | a->b where ...
48 oclose [C (x,y) z, C (x,p) q] {x,y} = {x,y,z}
49 because if we know x and y then that fixes z.
55 a) When determining ambiguity. The type
56 forall a,b. C a b => a
57 is not ambiguous (given the above class decl for C) because
60 b) When generalising a type T. Usually we take FV(T) \ FV(Env),
63 where the '+' is the oclosure operation. Notice that we do not
64 take FV(T)+. This puzzled me for a bit. Consider
68 and suppose e have that E :: C a b => a, and suppose that b is
69 free in the environment. Then we quantify over 'a' only, giving
70 the type forall a. C a b => a. Since a->b but we don't have b->a,
71 we might have instance decls like
72 instance C Bool Int where ...
73 instance C Char Int where ...
74 so knowing that b=Int doesn't fix 'a'; so we quantify over it.
79 If we have class C a b => D a b where ....
80 class D a b | a -> b where ...
81 and the preds are [C (x,y) z], then we want to see the fd in D,
82 even though it is not explicit in C, giving [({x,y},{z})]
84 Similarly for instance decls? E.g. Suppose we have
85 instance C a b => Eq (T a b) where ...
86 and we infer a type t with constraints Eq (T a b) for a particular
87 expression, and suppose that 'a' is free in the environment.
88 We could generalise to
89 forall b. Eq (T a b) => t
90 but if we reduced the constraint, to C a b, we'd see that 'a' determines
91 b, so that a better type might be
92 t (with free constraint C a b)
93 Perhaps it doesn't matter, because we'll still force b to be a
94 particular type at the call sites. Generalising over too many
95 variables (provided we don't shadow anything by quantifying over a
96 variable that is actually free in the envt) may postpone errors; it
97 won't hide them altogether.
101 oclose :: [PredType] -> TyVarSet -> TyVarSet
102 oclose preds fixed_tvs
103 | null tv_fds = fixed_tvs -- Fast escape hatch for common case
104 | otherwise = loop fixed_tvs
107 | new_fixed_tvs `subVarSet` fixed_tvs = fixed_tvs
108 | otherwise = loop new_fixed_tvs
110 new_fixed_tvs = foldl extend fixed_tvs tv_fds
112 extend fixed_tvs (ls,rs) | ls `subVarSet` fixed_tvs = fixed_tvs `unionVarSet` rs
113 | otherwise = fixed_tvs
115 tv_fds :: [(TyVarSet,TyVarSet)]
116 -- In our example, tv_fds will be [ ({x,y}, {z}), ({x,p},{q}) ]
117 -- Meaning "knowing x,y fixes z, knowing x,p fixes q"
118 tv_fds = [ (tyVarsOfTypes xs, tyVarsOfTypes ys)
119 | ClassP cls tys <- preds, -- Ignore implicit params
120 let (cls_tvs, cls_fds) = classTvsFds cls,
122 let (xs,ys) = instFD fd cls_tvs tys
127 grow :: [PredType] -> TyVarSet -> TyVarSet
129 | null preds = fixed_tvs
130 | otherwise = loop fixed_tvs
133 | new_fixed_tvs `subVarSet` fixed_tvs = fixed_tvs
134 | otherwise = loop new_fixed_tvs
136 new_fixed_tvs = foldl extend fixed_tvs pred_sets
138 extend fixed_tvs pred_tvs
139 | fixed_tvs `intersectsVarSet` pred_tvs = fixed_tvs `unionVarSet` pred_tvs
140 | otherwise = fixed_tvs
142 pred_sets = [tyVarsOfPred pred | pred <- preds]
145 %************************************************************************
147 \subsection{Generate equations from functional dependencies}
149 %************************************************************************
154 type Equation = (TyVarSet, [(Type, Type)])
155 -- These pairs of types should be equal, for some
156 -- substitution of the tyvars in the tyvar set
157 -- INVARIANT: corresponding types aren't already equal
159 -- It's important that we have a *list* of pairs of types. Consider
160 -- class C a b c | a -> b c where ...
161 -- instance C Int x x where ...
162 -- Then, given the constraint (C Int Bool v) we should improve v to Bool,
163 -- via the equation ({x}, [(Bool,x), (v,x)])
164 -- This would not happen if the class had looked like
165 -- class C a b c | a -> b, a -> c
167 -- To "execute" the equation, make fresh type variable for each tyvar in the set,
168 -- instantiate the two types with these fresh variables, and then unify.
170 -- For example, ({a,b}, (a,Int,b), (Int,z,Bool))
171 -- We unify z with Int, but since a and b are quantified we do nothing to them
172 -- We usually act on an equation by instantiating the quantified type varaibles
173 -- to fresh type variables, and then calling the standard unifier.
175 pprEquation (qtvs, pairs)
176 = vcat [ptext SLIT("forall") <+> braces (pprWithCommas ppr (varSetElems qtvs)),
177 nest 2 (vcat [ ppr t1 <+> ptext SLIT(":=:") <+> ppr t2 | (t1,t2) <- pairs])]
180 type Pred_Loc = (PredType, SDoc) -- SDoc says where the Pred comes from
182 improve :: (Class -> [Instance]) -- Gives instances for given class
183 -> [Pred_Loc] -- Current constraints;
184 -> [(Equation,Pred_Loc,Pred_Loc)] -- Derived equalities that must also hold
185 -- (NB the above INVARIANT for type Equation)
186 -- The Pred_Locs explain which two predicates were
187 -- combined (for error messages)
190 Given a bunch of predicates that must hold, such as
192 C Int t1, C Int t2, C Bool t3, ?x::t4, ?x::t5
194 improve figures out what extra equations must hold.
195 For example, if we have
197 class C a b | a->b where ...
199 then improve will return
205 * improve does not iterate. It's possible that when we make
206 t1=t2, for example, that will in turn trigger a new equation.
207 This would happen if we also had
209 If t1=t2, we also get t7=t8.
211 improve does *not* do this extra step. It relies on the caller
214 * The equations unify types that are not already equal. So there
215 is no effect iff the result of improve is empty
220 improve inst_env preds
221 = [ eqn | group <- equivClassesByUniq (predTyUnique . fst) preds,
222 eqn <- checkGroup inst_env group ]
225 checkGroup :: (Class -> [Instance])
227 -> [(Equation, Pred_Loc, Pred_Loc)]
228 -- The preds are all for the same class or implicit param
230 checkGroup inst_env (p1@(IParam _ ty, _) : ips)
231 = -- For implicit parameters, all the types must match
232 [ ((emptyVarSet, [(ty,ty')]), p1, p2)
233 | p2@(IParam _ ty', _) <- ips, not (ty `tcEqType` ty')]
235 checkGroup inst_env clss@((ClassP cls _, _) : _)
236 = -- For classes life is more complicated
237 -- Suppose the class is like
238 -- classs C as | (l1 -> r1), (l2 -> r2), ... where ...
239 -- Then FOR EACH PAIR (ClassP c tys1, ClassP c tys2) in the list clss
241 -- U l1[tys1/as] = U l2[tys2/as]
242 -- (where U is a unifier)
244 -- If so, we return the pair
245 -- U r1[tys1/as] = U l2[tys2/as]
247 -- We need to do something very similar comparing each predicate
248 -- with relevant instance decls
250 instance_eqns ++ pairwise_eqns
251 -- NB: we put the instance equations first. This biases the
252 -- order so that we first improve individual constraints against the
253 -- instances (which are perhaps in a library and less likely to be
254 -- wrong; and THEN perform the pairwise checks.
255 -- The other way round, it's possible for the pairwise check to succeed
256 -- and cause a subsequent, misleading failure of one of the pair with an
257 -- instance declaration. See tcfail143.hs for an exmample
260 (cls_tvs, cls_fds) = classTvsFds cls
261 instances = inst_env cls
263 -- NOTE that we iterate over the fds first; they are typically
264 -- empty, which aborts the rest of the loop.
265 pairwise_eqns :: [(Equation,Pred_Loc,Pred_Loc)]
266 pairwise_eqns -- This group comes from pairwise comparison
269 p1@(ClassP _ tys1, _) : rest <- tails clss,
270 p2@(ClassP _ tys2, _) <- rest,
271 eqn <- checkClsFD emptyVarSet fd cls_tvs tys1 tys2
274 instance_eqns :: [(Equation,Pred_Loc,Pred_Loc)]
275 instance_eqns -- This group comes from comparing with instance decls
277 | fd <- cls_fds, -- Iterate through the fundeps first,
278 -- because there often are none!
279 p2@(ClassP _ tys2, _) <- clss,
280 let rough_tcs2 = trimRoughMatchTcs cls_tvs fd (roughMatchTcs tys2),
281 ispec@(Instance { is_tvs = qtvs, is_tys = tys1,
282 is_tcs = mb_tcs1 }) <- instances,
283 not (instanceCantMatch mb_tcs1 rough_tcs2),
284 eqn <- checkClsFD qtvs fd cls_tvs tys1 tys2,
285 let p1 = (mkClassPred cls tys1,
286 ptext SLIT("arising from the instance declaration at") <+>
287 ppr (getSrcLoc ispec))
290 checkClsFD :: TyVarSet -- Quantified type variables; see note below
291 -> FunDep TyVar -> [TyVar] -- One functional dependency from the class
295 checkClsFD qtvs fd clas_tvs tys1 tys2
296 -- 'qtvs' are the quantified type variables, the ones which an be instantiated
297 -- to make the types match. For example, given
298 -- class C a b | a->b where ...
299 -- instance C (Maybe x) (Tree x) where ..
301 -- and an Inst of form (C (Maybe t1) t2),
302 -- then we will call checkClsFD with
304 -- qtvs = {x}, tys1 = [Maybe x, Tree x]
305 -- tys2 = [Maybe t1, t2]
307 -- We can instantiate x to t1, and then we want to force
308 -- (Tree x) [t1/x] :=: t2
310 -- This function is also used when matching two Insts (rather than an Inst
311 -- against an instance decl. In that case, qtvs is empty, and we are doing
314 -- This function is also used by InstEnv.badFunDeps, which needs to *unify*
315 -- For the one-sided matching case, the qtvs are just from the template,
316 -- so we get matching
318 = ASSERT2( length tys1 == length tys2 &&
319 length tys1 == length clas_tvs
320 , ppr tys1 <+> ppr tys2 )
322 case tcUnifyTys bind_fn ls1 ls2 of
324 Just subst | isJust (tcUnifyTys bind_fn rs1' rs2')
325 -- Don't include any equations that already hold.
326 -- Reason: then we know if any actual improvement has happened,
327 -- in which case we need to iterate the solver
328 -- In making this check we must taking account of the fact that any
329 -- qtvs that aren't already instantiated can be instantiated to anything
333 | otherwise -- Aha! A useful equation
334 -> [ (qtvs', zip rs1' rs2')]
335 -- We could avoid this substTy stuff by producing the eqn
336 -- (qtvs, ls1++rs1, ls2++rs2)
337 -- which will re-do the ls1/ls2 unification when the equation is
338 -- executed. What we're doing instead is recording the partial
339 -- work of the ls1/ls2 unification leaving a smaller unification problem
341 rs1' = substTys subst rs1
342 rs2' = substTys subst rs2
343 qtvs' = filterVarSet (`notElemTvSubst` subst) qtvs
344 -- qtvs' are the quantified type variables
345 -- that have not been substituted out
347 -- Eg. class C a b | a -> b
348 -- instance C Int [y]
349 -- Given constraint C Int z
350 -- we generate the equation
353 bind_fn tv | tv `elemVarSet` qtvs = BindMe
356 (ls1, rs1) = instFD fd clas_tvs tys1
357 (ls2, rs2) = instFD fd clas_tvs tys2
359 instFD :: FunDep TyVar -> [TyVar] -> [Type] -> FunDep Type
360 instFD (ls,rs) tvs tys
361 = (map lookup ls, map lookup rs)
363 env = zipVarEnv tvs tys
364 lookup tv = lookupVarEnv_NF env tv
368 checkInstCoverage :: Class -> [Type] -> Bool
369 -- Check that the Coverage Condition is obeyed in an instance decl
370 -- For example, if we have
371 -- class theta => C a b | a -> b
373 -- Then we require fv(t2) `subset` fv(t1)
374 -- See Note [Coverage Condition] below
376 checkInstCoverage clas inst_taus
379 (tyvars, fds) = classTvsFds clas
380 fundep_ok fd = tyVarsOfTypes rs `subVarSet` tyVarsOfTypes ls
382 (ls,rs) = instFD fd tyvars inst_taus
385 Note [Coverage condition]
386 ~~~~~~~~~~~~~~~~~~~~~~~~~
387 For the coverage condition, we used to require only that
388 fv(t2) `subset` oclose(fv(t1), theta)
391 class Mul a b c | a b -> c where
394 instance Mul Int Int Int where (.*.) = (*)
395 instance Mul Int Float Float where x .*. y = fromIntegral x * y
396 instance Mul a b c => Mul a [b] [c] where x .*. v = map (x.*.) v
398 In the third instance, it's not the case that fv([c]) `subset` fv(a,[b]).
399 But it is the case that fv([c]) `subset` oclose( theta, fv(a,[b]) )
401 But it is a mistake to accept the instance because then this defn:
402 f = \ b x y -> if b then x .*. [y] else y
403 makes instance inference go into a loop, because it requires the constraint
407 %************************************************************************
409 Check that a new instance decl is OK wrt fundeps
411 %************************************************************************
413 Here is the bad case:
414 class C a b | a->b where ...
415 instance C Int Bool where ...
416 instance C Int Char where ...
418 The point is that a->b, so Int in the first parameter must uniquely
419 determine the second. In general, given the same class decl, and given
421 instance C s1 s2 where ...
422 instance C t1 t2 where ...
424 Then the criterion is: if U=unify(s1,t1) then U(s2) = U(t2).
426 Matters are a little more complicated if there are free variables in
429 class D a b c | a -> b
430 instance D a b => D [(a,a)] [b] Int
431 instance D a b => D [a] [b] Bool
433 The instance decls don't overlap, because the third parameter keeps
434 them separate. But we want to make sure that given any constraint
440 checkFunDeps :: (InstEnv, InstEnv) -> Instance
441 -> Maybe [Instance] -- Nothing <=> ok
442 -- Just dfs <=> conflict with dfs
443 -- Check wheher adding DFunId would break functional-dependency constraints
444 -- Used only for instance decls defined in the module being compiled
445 checkFunDeps inst_envs ispec
446 | null bad_fundeps = Nothing
447 | otherwise = Just bad_fundeps
449 (ins_tvs, _, clas, ins_tys) = instanceHead ispec
450 ins_tv_set = mkVarSet ins_tvs
451 cls_inst_env = classInstances inst_envs clas
452 bad_fundeps = badFunDeps cls_inst_env clas ins_tv_set ins_tys
454 badFunDeps :: [Instance] -> Class
455 -> TyVarSet -> [Type] -- Proposed new instance type
457 badFunDeps cls_insts clas ins_tv_set ins_tys
458 = [ ispec | fd <- fds, -- fds is often empty
459 let trimmed_tcs = trimRoughMatchTcs clas_tvs fd rough_tcs,
460 ispec@(Instance { is_tcs = mb_tcs, is_tvs = tvs,
461 is_tys = tys }) <- cls_insts,
462 -- Filter out ones that can't possibly match,
463 -- based on the head of the fundep
464 not (instanceCantMatch trimmed_tcs mb_tcs),
465 notNull (checkClsFD (tvs `unionVarSet` ins_tv_set)
466 fd clas_tvs tys ins_tys)
469 (clas_tvs, fds) = classTvsFds clas
470 rough_tcs = roughMatchTcs ins_tys
472 trimRoughMatchTcs :: [TyVar] -> FunDep TyVar -> [Maybe Name] -> [Maybe Name]
473 -- Computing rough_tcs for a particular fundep
474 -- class C a b c | a c -> b where ...
475 -- For each instance .... => C ta tb tc
476 -- we want to match only on the types ta, tb; so our
477 -- rough-match thing must similarly be filtered.
478 -- Hence, we Nothing-ise the tb type right here
479 trimRoughMatchTcs clas_tvs (ltvs,_) mb_tcs
480 = zipWith select clas_tvs mb_tcs
482 select clas_tv mb_tc | clas_tv `elem` ltvs = mb_tc
483 | otherwise = Nothing
487 %************************************************************************
489 \subsection{Miscellaneous}
491 %************************************************************************
494 pprFundeps :: Outputable a => [FunDep a] -> SDoc
495 pprFundeps [] = empty
496 pprFundeps fds = hsep (ptext SLIT("|") : punctuate comma (map ppr_fd fds))
498 ppr_fd (us, vs) = hsep [interppSP us, ptext SLIT("->"), interppSP vs]