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, pprEquationDoc,
11 oclose, grow, improve,
12 checkInstFDs, 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, ThetaType, 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 pprEquationDoc (eqn, doc) = vcat [pprEquation eqn, nest 2 doc]
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 improve :: (Class -> [Instance]) -- Gives instances for given class
183 -> [(PredType,SDoc)] -- Current constraints; doc says where they come from
184 -> [(Equation,SDoc)] -- Derived equalities that must also hold
185 -- (NB the above INVARIANT for type Equation)
186 -- The SDoc explains why the equation holds (for error messages)
189 Given a bunch of predicates that must hold, such as
191 C Int t1, C Int t2, C Bool t3, ?x::t4, ?x::t5
193 improve figures out what extra equations must hold.
194 For example, if we have
196 class C a b | a->b where ...
198 then improve will return
204 * improve does not iterate. It's possible that when we make
205 t1=t2, for example, that will in turn trigger a new equation.
206 This would happen if we also had
208 If t1=t2, we also get t7=t8.
210 improve does *not* do this extra step. It relies on the caller
213 * The equations unify types that are not already equal. So there
214 is no effect iff the result of improve is empty
219 improve inst_env preds
220 = [ eqn | group <- equivClassesByUniq (predTyUnique . fst) preds,
221 eqn <- checkGroup inst_env group ]
224 checkGroup :: (Class -> [Instance])
226 -> [(Equation, SDoc)]
227 -- The preds are all for the same class or implicit param
229 checkGroup inst_env (p1@(IParam _ ty, _) : ips)
230 = -- For implicit parameters, all the types must match
231 [ ((emptyVarSet, [(ty,ty')]), mkEqnMsg p1 p2)
232 | p2@(IParam _ ty', _) <- ips, not (ty `tcEqType` ty')]
234 checkGroup inst_env clss@((ClassP cls _, _) : _)
235 = -- For classes life is more complicated
236 -- Suppose the class is like
237 -- classs C as | (l1 -> r1), (l2 -> r2), ... where ...
238 -- Then FOR EACH PAIR (ClassP c tys1, ClassP c tys2) in the list clss
240 -- U l1[tys1/as] = U l2[tys2/as]
241 -- (where U is a unifier)
243 -- If so, we return the pair
244 -- U r1[tys1/as] = U l2[tys2/as]
246 -- We need to do something very similar comparing each predicate
247 -- with relevant instance decls
249 instance_eqns ++ pairwise_eqns
250 -- NB: we put the instance equations first. This biases the
251 -- order so that we first improve individual constraints against the
252 -- instances (which are perhaps in a library and less likely to be
253 -- wrong; and THEN perform the pairwise checks.
254 -- The other way round, it's possible for the pairwise check to succeed
255 -- and cause a subsequent, misleading failure of one of the pair with an
256 -- instance declaration. See tcfail143.hs for an exmample
259 (cls_tvs, cls_fds) = classTvsFds cls
260 instances = inst_env cls
262 -- NOTE that we iterate over the fds first; they are typically
263 -- empty, which aborts the rest of the loop.
264 pairwise_eqns :: [(Equation,SDoc)]
265 pairwise_eqns -- This group comes from pairwise comparison
266 = [ (eqn, mkEqnMsg p1 p2)
268 p1@(ClassP _ tys1, _) : rest <- tails clss,
269 p2@(ClassP _ tys2, _) <- rest,
270 eqn <- checkClsFD emptyVarSet fd cls_tvs tys1 tys2
273 instance_eqns :: [(Equation,SDoc)]
274 instance_eqns -- This group comes from comparing with instance decls
275 = [ (eqn, mkEqnMsg p1 p2)
276 | fd <- cls_fds, -- Iterate through the fundeps first,
277 -- because there often are none!
278 p2@(ClassP _ tys2, _) <- clss,
279 let rough_tcs2 = trimRoughMatchTcs cls_tvs fd (roughMatchTcs tys2),
280 ispec@(Instance { is_tvs = qtvs, is_tys = tys1,
281 is_tcs = mb_tcs1 }) <- instances,
282 not (instanceCantMatch mb_tcs1 rough_tcs2),
283 eqn <- checkClsFD qtvs fd cls_tvs tys1 tys2,
284 let p1 = (mkClassPred cls tys1,
285 ptext SLIT("arising from the instance declaration at") <+>
286 ppr (getSrcLoc ispec))
289 mkEqnMsg (pred1,from1) (pred2,from2)
290 = vcat [ptext SLIT("When using functional dependencies to combine"),
291 nest 2 (sep [ppr pred1 <> comma, nest 2 from1]),
292 nest 2 (sep [ppr pred2 <> comma, nest 2 from2])]
295 checkClsFD :: TyVarSet -- Quantified type variables; see note below
296 -> FunDep TyVar -> [TyVar] -- One functional dependency from the class
300 checkClsFD qtvs fd clas_tvs tys1 tys2
301 -- 'qtvs' are the quantified type variables, the ones which an be instantiated
302 -- to make the types match. For example, given
303 -- class C a b | a->b where ...
304 -- instance C (Maybe x) (Tree x) where ..
306 -- and an Inst of form (C (Maybe t1) t2),
307 -- then we will call checkClsFD with
309 -- qtvs = {x}, tys1 = [Maybe x, Tree x]
310 -- tys2 = [Maybe t1, t2]
312 -- We can instantiate x to t1, and then we want to force
313 -- (Tree x) [t1/x] :=: t2
315 -- This function is also used when matching two Insts (rather than an Inst
316 -- against an instance decl. In that case, qtvs is empty, and we are doing
319 -- This function is also used by InstEnv.badFunDeps, which needs to *unify*
320 -- For the one-sided matching case, the qtvs are just from the template,
321 -- so we get matching
323 = ASSERT2( length tys1 == length tys2 &&
324 length tys1 == length clas_tvs
325 , ppr tys1 <+> ppr tys2 )
327 case tcUnifyTys bind_fn ls1 ls2 of
329 Just subst | isJust (tcUnifyTys bind_fn rs1' rs2')
330 -- Don't include any equations that already hold.
331 -- Reason: then we know if any actual improvement has happened,
332 -- in which case we need to iterate the solver
333 -- In making this check we must taking account of the fact that any
334 -- qtvs that aren't already instantiated can be instantiated to anything
338 | otherwise -- Aha! A useful equation
339 -> [ (qtvs', zip rs1' rs2')]
340 -- We could avoid this substTy stuff by producing the eqn
341 -- (qtvs, ls1++rs1, ls2++rs2)
342 -- which will re-do the ls1/ls2 unification when the equation is
343 -- executed. What we're doing instead is recording the partial
344 -- work of the ls1/ls2 unification leaving a smaller unification problem
346 rs1' = substTys subst rs1
347 rs2' = substTys subst rs2
348 qtvs' = filterVarSet (`notElemTvSubst` subst) qtvs
349 -- qtvs' are the quantified type variables
350 -- that have not been substituted out
352 -- Eg. class C a b | a -> b
353 -- instance C Int [y]
354 -- Given constraint C Int z
355 -- we generate the equation
358 bind_fn tv | tv `elemVarSet` qtvs = BindMe
361 (ls1, rs1) = instFD fd clas_tvs tys1
362 (ls2, rs2) = instFD fd clas_tvs tys2
364 instFD :: FunDep TyVar -> [TyVar] -> [Type] -> FunDep Type
365 instFD (ls,rs) tvs tys
366 = (map lookup ls, map lookup rs)
368 env = zipVarEnv tvs tys
369 lookup tv = lookupVarEnv_NF env tv
373 checkInstFDs :: ThetaType -> Class -> [Type] -> Bool
374 -- Check that functional dependencies are obeyed in an instance decl
375 -- For example, if we have
376 -- class theta => C a b | a -> b
378 -- Then we require fv(t2) `subset` oclose(fv(t1), theta)
380 checkInstFDs theta clas inst_taus
383 (tyvars, fds) = classTvsFds clas
384 fundep_ok fd = tyVarsOfTypes rs `subVarSet` oclose theta (tyVarsOfTypes ls)
386 (ls,rs) = instFD fd tyvars inst_taus
390 %************************************************************************
392 Check that a new instance decl is OK wrt fundeps
394 %************************************************************************
396 Here is the bad case:
397 class C a b | a->b where ...
398 instance C Int Bool where ...
399 instance C Int Char where ...
401 The point is that a->b, so Int in the first parameter must uniquely
402 determine the second. In general, given the same class decl, and given
404 instance C s1 s2 where ...
405 instance C t1 t2 where ...
407 Then the criterion is: if U=unify(s1,t1) then U(s2) = U(t2).
409 Matters are a little more complicated if there are free variables in
412 class D a b c | a -> b
413 instance D a b => D [(a,a)] [b] Int
414 instance D a b => D [a] [b] Bool
416 The instance decls don't overlap, because the third parameter keeps
417 them separate. But we want to make sure that given any constraint
423 checkFunDeps :: (InstEnv, InstEnv) -> Instance
424 -> Maybe [Instance] -- Nothing <=> ok
425 -- Just dfs <=> conflict with dfs
426 -- Check wheher adding DFunId would break functional-dependency constraints
427 -- Used only for instance decls defined in the module being compiled
428 checkFunDeps inst_envs ispec
429 | null bad_fundeps = Nothing
430 | otherwise = Just bad_fundeps
432 (ins_tvs, _, clas, ins_tys) = instanceHead ispec
433 ins_tv_set = mkVarSet ins_tvs
434 cls_inst_env = classInstances inst_envs clas
435 bad_fundeps = badFunDeps cls_inst_env clas ins_tv_set ins_tys
437 badFunDeps :: [Instance] -> Class
438 -> TyVarSet -> [Type] -- Proposed new instance type
440 badFunDeps cls_insts clas ins_tv_set ins_tys
441 = [ ispec | fd <- fds, -- fds is often empty
442 let trimmed_tcs = trimRoughMatchTcs clas_tvs fd rough_tcs,
443 ispec@(Instance { is_tcs = mb_tcs, is_tvs = tvs,
444 is_tys = tys }) <- cls_insts,
445 -- Filter out ones that can't possibly match,
446 -- based on the head of the fundep
447 not (instanceCantMatch trimmed_tcs mb_tcs),
448 notNull (checkClsFD (tvs `unionVarSet` ins_tv_set)
449 fd clas_tvs tys ins_tys)
452 (clas_tvs, fds) = classTvsFds clas
453 rough_tcs = roughMatchTcs ins_tys
455 trimRoughMatchTcs :: [TyVar] -> FunDep TyVar -> [Maybe Name] -> [Maybe Name]
456 -- Computing rough_tcs for a particular fundep
457 -- class C a b c | a c -> b where ...
458 -- For each instance .... => C ta tb tc
459 -- we want to match only on the types ta, tb; so our
460 -- rough-match thing must similarly be filtered.
461 -- Hence, we Nothing-ise the tb type right here
462 trimRoughMatchTcs clas_tvs (ltvs,_) mb_tcs
463 = zipWith select clas_tvs mb_tcs
465 select clas_tv mb_tc | clas_tv `elem` ltvs = mb_tc
466 | otherwise = Nothing
470 %************************************************************************
472 \subsection{Miscellaneous}
474 %************************************************************************
477 pprFundeps :: Outputable a => [FunDep a] -> SDoc
478 pprFundeps [] = empty
479 pprFundeps fds = hsep (ptext SLIT("|") : punctuate comma (map ppr_fd fds))
481 ppr_fd (us, vs) = hsep [interppSP us, ptext SLIT("->"), interppSP vs]