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"
12 Equation, pprEquation,
13 oclose, grow, improveOne,
14 checkInstCoverage, checkFunDeps,
18 #include "HsVersions.h"
30 import Data.Maybe ( isJust )
34 %************************************************************************
36 \subsection{Close type variables}
38 %************************************************************************
40 (oclose preds tvs) closes the set of type variables tvs,
41 wrt functional dependencies in preds. The result is a superset
42 of the argument set. For example, if we have
43 class C a b | a->b where ...
45 oclose [C (x,y) z, C (x,p) q] {x,y} = {x,y,z}
46 because if we know x and y then that fixes z.
52 a) When determining ambiguity. The type
53 forall a,b. C a b => a
54 is not ambiguous (given the above class decl for C) because
57 b) When generalising a type T. Usually we take FV(T) \ FV(Env),
60 where the '+' is the oclosure operation. Notice that we do not
61 take FV(T)+. This puzzled me for a bit. Consider
65 and suppose e have that E :: C a b => a, and suppose that b is
66 free in the environment. Then we quantify over 'a' only, giving
67 the type forall a. C a b => a. Since a->b but we don't have b->a,
68 we might have instance decls like
69 instance C Bool Int where ...
70 instance C Char Int where ...
71 so knowing that b=Int doesn't fix 'a'; so we quantify over it.
76 If we have class C a b => D a b where ....
77 class D a b | a -> b where ...
78 and the preds are [C (x,y) z], then we want to see the fd in D,
79 even though it is not explicit in C, giving [({x,y},{z})]
81 Similarly for instance decls? E.g. Suppose we have
82 instance C a b => Eq (T a b) where ...
83 and we infer a type t with constraints Eq (T a b) for a particular
84 expression, and suppose that 'a' is free in the environment.
85 We could generalise to
86 forall b. Eq (T a b) => t
87 but if we reduced the constraint, to C a b, we'd see that 'a' determines
88 b, so that a better type might be
89 t (with free constraint C a b)
90 Perhaps it doesn't matter, because we'll still force b to be a
91 particular type at the call sites. Generalising over too many
92 variables (provided we don't shadow anything by quantifying over a
93 variable that is actually free in the envt) may postpone errors; it
94 won't hide them altogether.
98 oclose :: [PredType] -> TyVarSet -> TyVarSet
99 oclose preds fixed_tvs
100 | null tv_fds = fixed_tvs -- Fast escape hatch for common case
101 | otherwise = loop fixed_tvs
104 | new_fixed_tvs `subVarSet` fixed_tvs = fixed_tvs
105 | otherwise = loop new_fixed_tvs
107 new_fixed_tvs = foldl extend fixed_tvs tv_fds
109 extend fixed_tvs (ls,rs) | ls `subVarSet` fixed_tvs = fixed_tvs `unionVarSet` rs
110 | otherwise = fixed_tvs
112 tv_fds :: [(TyVarSet,TyVarSet)]
113 -- In our example, tv_fds will be [ ({x,y}, {z}), ({x,p},{q}) ]
114 -- Meaning "knowing x,y fixes z, knowing x,p fixes q"
115 tv_fds = [ (tyVarsOfTypes xs, tyVarsOfTypes ys)
116 | ClassP cls tys <- preds, -- Ignore implicit params
117 let (cls_tvs, cls_fds) = classTvsFds cls,
119 let (xs,ys) = instFD fd cls_tvs tys
123 Note [Growing the tau-tvs using constraints]
124 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
125 (grow preds tvs) is the result of extend the set of tyvars tvs
126 using all conceivable links from pred
128 E.g. tvs = {a}, preds = {H [a] b, K (b,Int) c, Eq e}
129 Then grow precs tvs = {a,b,c}
131 All the type variables from an implicit parameter are added, whether or
132 not they are mentioned in tvs; see Note [Implicit parameters and ambiguity]
135 See also Note [Ambiguity] in TcSimplify
138 grow :: [PredType] -> TyVarSet -> TyVarSet
140 | null preds = real_fixed_tvs
141 | otherwise = loop real_fixed_tvs
143 -- Add the implicit parameters;
144 -- see Note [Implicit parameters and ambiguity] in TcSimplify
145 real_fixed_tvs = foldr unionVarSet fixed_tvs ip_tvs
148 | new_fixed_tvs `subVarSet` fixed_tvs = fixed_tvs
149 | otherwise = loop new_fixed_tvs
151 new_fixed_tvs = foldl extend fixed_tvs non_ip_tvs
153 extend fixed_tvs pred_tvs
154 | fixed_tvs `intersectsVarSet` pred_tvs = fixed_tvs `unionVarSet` pred_tvs
155 | otherwise = fixed_tvs
157 (ip_tvs, non_ip_tvs) = partitionWith get_ip preds
158 get_ip (IParam _ ty) = Left (tyVarsOfType ty)
159 get_ip other = Right (tyVarsOfPred other)
162 %************************************************************************
164 \subsection{Generate equations from functional dependencies}
166 %************************************************************************
170 type Equation = (TyVarSet, [(Type, Type)])
171 -- These pairs of types should be equal, for some
172 -- substitution of the tyvars in the tyvar set
173 -- INVARIANT: corresponding types aren't already equal
175 -- It's important that we have a *list* of pairs of types. Consider
176 -- class C a b c | a -> b c where ...
177 -- instance C Int x x where ...
178 -- Then, given the constraint (C Int Bool v) we should improve v to Bool,
179 -- via the equation ({x}, [(Bool,x), (v,x)])
180 -- This would not happen if the class had looked like
181 -- class C a b c | a -> b, a -> c
183 -- To "execute" the equation, make fresh type variable for each tyvar in the set,
184 -- instantiate the two types with these fresh variables, and then unify.
186 -- For example, ({a,b}, (a,Int,b), (Int,z,Bool))
187 -- We unify z with Int, but since a and b are quantified we do nothing to them
188 -- We usually act on an equation by instantiating the quantified type varaibles
189 -- to fresh type variables, and then calling the standard unifier.
191 pprEquation (qtvs, pairs)
192 = vcat [ptext SLIT("forall") <+> braces (pprWithCommas ppr (varSetElems qtvs)),
193 nest 2 (vcat [ ppr t1 <+> ptext SLIT(":=:") <+> ppr t2 | (t1,t2) <- pairs])]
196 Given a bunch of predicates that must hold, such as
198 C Int t1, C Int t2, C Bool t3, ?x::t4, ?x::t5
200 improve figures out what extra equations must hold.
201 For example, if we have
203 class C a b | a->b where ...
205 then improve will return
211 * improve does not iterate. It's possible that when we make
212 t1=t2, for example, that will in turn trigger a new equation.
213 This would happen if we also had
215 If t1=t2, we also get t7=t8.
217 improve does *not* do this extra step. It relies on the caller
220 * The equations unify types that are not already equal. So there
221 is no effect iff the result of improve is empty
226 type Pred_Loc = (PredType, SDoc) -- SDoc says where the Pred comes from
228 improveOne :: (Class -> [Instance]) -- Gives instances for given class
229 -> Pred_Loc -- Do improvement triggered by this
230 -> [Pred_Loc] -- Current constraints
231 -> [(Equation,Pred_Loc,Pred_Loc)] -- Derived equalities that must also hold
232 -- (NB the above INVARIANT for type Equation)
233 -- The Pred_Locs explain which two predicates were
234 -- combined (for error messages)
235 -- Just do improvement triggered by a single, distinguised predicate
237 improveOne inst_env pred@(IParam ip ty, _) preds
238 = [ ((emptyVarSet, [(ty,ty2)]), pred, p2)
239 | p2@(IParam ip2 ty2, _) <- preds
241 , not (ty `tcEqType` ty2)]
243 improveOne inst_env pred@(ClassP cls tys, _) preds
244 | tys `lengthAtLeast` 2
245 = instance_eqns ++ pairwise_eqns
246 -- NB: we put the instance equations first. This biases the
247 -- order so that we first improve individual constraints against the
248 -- instances (which are perhaps in a library and less likely to be
249 -- wrong; and THEN perform the pairwise checks.
250 -- The other way round, it's possible for the pairwise check to succeed
251 -- and cause a subsequent, misleading failure of one of the pair with an
252 -- instance declaration. See tcfail143.hs for an example
254 (cls_tvs, cls_fds) = classTvsFds cls
255 instances = inst_env cls
256 rough_tcs = roughMatchTcs tys
258 -- NOTE that we iterate over the fds first; they are typically
259 -- empty, which aborts the rest of the loop.
260 pairwise_eqns :: [(Equation,Pred_Loc,Pred_Loc)]
261 pairwise_eqns -- This group comes from pairwise comparison
264 , p2@(ClassP cls2 tys2, _) <- preds
266 , eqn <- checkClsFD emptyVarSet fd cls_tvs tys tys2
269 instance_eqns :: [(Equation,Pred_Loc,Pred_Loc)]
270 instance_eqns -- This group comes from comparing with instance decls
271 = [ (eqn, p_inst, pred)
272 | fd <- cls_fds -- Iterate through the fundeps first,
273 -- because there often are none!
274 , let rough_fd_tcs = trimRoughMatchTcs cls_tvs fd rough_tcs
275 , ispec@(Instance { is_tvs = qtvs, is_tys = tys_inst,
276 is_tcs = mb_tcs_inst }) <- instances
277 , not (instanceCantMatch mb_tcs_inst rough_fd_tcs)
278 , eqn <- checkClsFD qtvs fd cls_tvs tys_inst tys
279 , let p_inst = (mkClassPred cls tys_inst,
280 ptext SLIT("arising from the instance declaration at")
281 <+> ppr (getSrcLoc ispec))
284 improveOne inst_env eq_pred preds
288 checkClsFD :: TyVarSet -- Quantified type variables; see note below
289 -> FunDep TyVar -> [TyVar] -- One functional dependency from the class
293 checkClsFD qtvs fd clas_tvs tys1 tys2
294 -- 'qtvs' are the quantified type variables, the ones which an be instantiated
295 -- to make the types match. For example, given
296 -- class C a b | a->b where ...
297 -- instance C (Maybe x) (Tree x) where ..
299 -- and an Inst of form (C (Maybe t1) t2),
300 -- then we will call checkClsFD with
302 -- qtvs = {x}, tys1 = [Maybe x, Tree x]
303 -- tys2 = [Maybe t1, t2]
305 -- We can instantiate x to t1, and then we want to force
306 -- (Tree x) [t1/x] :=: t2
308 -- This function is also used when matching two Insts (rather than an Inst
309 -- against an instance decl. In that case, qtvs is empty, and we are doing
312 -- This function is also used by InstEnv.badFunDeps, which needs to *unify*
313 -- For the one-sided matching case, the qtvs are just from the template,
314 -- so we get matching
316 = ASSERT2( length tys1 == length tys2 &&
317 length tys1 == length clas_tvs
318 , ppr tys1 <+> ppr tys2 )
320 case tcUnifyTys bind_fn ls1 ls2 of
322 Just subst | isJust (tcUnifyTys bind_fn rs1' rs2')
323 -- Don't include any equations that already hold.
324 -- Reason: then we know if any actual improvement has happened,
325 -- in which case we need to iterate the solver
326 -- In making this check we must taking account of the fact that any
327 -- qtvs that aren't already instantiated can be instantiated to anything
331 | otherwise -- Aha! A useful equation
332 -> [ (qtvs', zip rs1' rs2')]
333 -- We could avoid this substTy stuff by producing the eqn
334 -- (qtvs, ls1++rs1, ls2++rs2)
335 -- which will re-do the ls1/ls2 unification when the equation is
336 -- executed. What we're doing instead is recording the partial
337 -- work of the ls1/ls2 unification leaving a smaller unification problem
339 rs1' = substTys subst rs1
340 rs2' = substTys subst rs2
341 qtvs' = filterVarSet (`notElemTvSubst` subst) qtvs
342 -- qtvs' are the quantified type variables
343 -- that have not been substituted out
345 -- Eg. class C a b | a -> b
346 -- instance C Int [y]
347 -- Given constraint C Int z
348 -- we generate the equation
351 bind_fn tv | tv `elemVarSet` qtvs = BindMe
354 (ls1, rs1) = instFD fd clas_tvs tys1
355 (ls2, rs2) = instFD fd clas_tvs tys2
357 instFD :: FunDep TyVar -> [TyVar] -> [Type] -> FunDep Type
358 instFD (ls,rs) tvs tys
359 = (map lookup ls, map lookup rs)
361 env = zipVarEnv tvs tys
362 lookup tv = lookupVarEnv_NF env tv
366 checkInstCoverage :: Class -> [Type] -> Bool
367 -- Check that the Coverage Condition is obeyed in an instance decl
368 -- For example, if we have
369 -- class theta => C a b | a -> b
371 -- Then we require fv(t2) `subset` fv(t1)
372 -- See Note [Coverage Condition] below
374 checkInstCoverage clas inst_taus
377 (tyvars, fds) = classTvsFds clas
378 fundep_ok fd = tyVarsOfTypes rs `subVarSet` tyVarsOfTypes ls
380 (ls,rs) = instFD fd tyvars inst_taus
383 Note [Coverage condition]
384 ~~~~~~~~~~~~~~~~~~~~~~~~~
385 For the coverage condition, we used to require only that
386 fv(t2) `subset` oclose(fv(t1), theta)
389 class Mul a b c | a b -> c where
392 instance Mul Int Int Int where (.*.) = (*)
393 instance Mul Int Float Float where x .*. y = fromIntegral x * y
394 instance Mul a b c => Mul a [b] [c] where x .*. v = map (x.*.) v
396 In the third instance, it's not the case that fv([c]) `subset` fv(a,[b]).
397 But it is the case that fv([c]) `subset` oclose( theta, fv(a,[b]) )
399 But it is a mistake to accept the instance because then this defn:
400 f = \ b x y -> if b then x .*. [y] else y
401 makes instance inference go into a loop, because it requires the constraint
405 %************************************************************************
407 Check that a new instance decl is OK wrt fundeps
409 %************************************************************************
411 Here is the bad case:
412 class C a b | a->b where ...
413 instance C Int Bool where ...
414 instance C Int Char where ...
416 The point is that a->b, so Int in the first parameter must uniquely
417 determine the second. In general, given the same class decl, and given
419 instance C s1 s2 where ...
420 instance C t1 t2 where ...
422 Then the criterion is: if U=unify(s1,t1) then U(s2) = U(t2).
424 Matters are a little more complicated if there are free variables in
427 class D a b c | a -> b
428 instance D a b => D [(a,a)] [b] Int
429 instance D a b => D [a] [b] Bool
431 The instance decls don't overlap, because the third parameter keeps
432 them separate. But we want to make sure that given any constraint
438 checkFunDeps :: (InstEnv, InstEnv) -> Instance
439 -> Maybe [Instance] -- Nothing <=> ok
440 -- Just dfs <=> conflict with dfs
441 -- Check wheher adding DFunId would break functional-dependency constraints
442 -- Used only for instance decls defined in the module being compiled
443 checkFunDeps inst_envs ispec
444 | null bad_fundeps = Nothing
445 | otherwise = Just bad_fundeps
447 (ins_tvs, _, clas, ins_tys) = instanceHead ispec
448 ins_tv_set = mkVarSet ins_tvs
449 cls_inst_env = classInstances inst_envs clas
450 bad_fundeps = badFunDeps cls_inst_env clas ins_tv_set ins_tys
452 badFunDeps :: [Instance] -> Class
453 -> TyVarSet -> [Type] -- Proposed new instance type
455 badFunDeps cls_insts clas ins_tv_set ins_tys
456 = [ ispec | fd <- fds, -- fds is often empty
457 let trimmed_tcs = trimRoughMatchTcs clas_tvs fd rough_tcs,
458 ispec@(Instance { is_tcs = mb_tcs, is_tvs = tvs,
459 is_tys = tys }) <- cls_insts,
460 -- Filter out ones that can't possibly match,
461 -- based on the head of the fundep
462 not (instanceCantMatch trimmed_tcs mb_tcs),
463 notNull (checkClsFD (tvs `unionVarSet` ins_tv_set)
464 fd clas_tvs tys ins_tys)
467 (clas_tvs, fds) = classTvsFds clas
468 rough_tcs = roughMatchTcs ins_tys
470 trimRoughMatchTcs :: [TyVar] -> FunDep TyVar -> [Maybe Name] -> [Maybe Name]
471 -- Computing rough_tcs for a particular fundep
472 -- class C a b c | a c -> b where ...
473 -- For each instance .... => C ta tb tc
474 -- we want to match only on the types ta, tb; so our
475 -- rough-match thing must similarly be filtered.
476 -- Hence, we Nothing-ise the tb type right here
477 trimRoughMatchTcs clas_tvs (ltvs,_) mb_tcs
478 = zipWith select clas_tvs mb_tcs
480 select clas_tv mb_tc | clas_tv `elem` ltvs = mb_tc
481 | otherwise = Nothing