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, checkInstFDs, checkClsFD, pprFundeps
14 #include "HsVersions.h"
16 import Name ( getSrcLoc )
17 import Var ( Id, TyVar )
18 import Class ( Class, FunDep, classTvsFds )
19 import Unify ( unifyTys, unifyTysX )
20 import Type ( mkTvSubst, substTy )
21 import TcType ( Type, ThetaType, PredType(..), tcEqType,
22 predTyUnique, mkClassPred, tyVarsOfTypes, tyVarsOfPred )
27 import Maybes ( maybeToBool )
28 import ListSetOps ( equivClassesByUniq )
32 %************************************************************************
34 \subsection{Close type variables}
36 %************************************************************************
38 (oclose preds tvs) closes the set of type variables tvs,
39 wrt functional dependencies in preds. The result is a superset
40 of the argument set. For example, if we have
41 class C a b | a->b where ...
43 oclose [C (x,y) z, C (x,p) q] {x,y} = {x,y,z}
44 because if we know x and y then that fixes z.
50 a) When determining ambiguity. The type
51 forall a,b. C a b => a
52 is not ambiguous (given the above class decl for C) because
55 b) When generalising a type T. Usually we take FV(T) \ FV(Env),
58 where the '+' is the oclosure operation. Notice that we do not
59 take FV(T)+. This puzzled me for a bit. Consider
63 and suppose e have that E :: C a b => a, and suppose that b is
64 free in the environment. Then we quantify over 'a' only, giving
65 the type forall a. C a b => a. Since a->b but we don't have b->a,
66 we might have instance decls like
67 instance C Bool Int where ...
68 instance C Char Int where ...
69 so knowing that b=Int doesn't fix 'a'; so we quantify over it.
74 If we have class C a b => D a b where ....
75 class D a b | a -> b where ...
76 and the preds are [C (x,y) z], then we want to see the fd in D,
77 even though it is not explicit in C, giving [({x,y},{z})]
79 Similarly for instance decls? E.g. Suppose we have
80 instance C a b => Eq (T a b) where ...
81 and we infer a type t with constraints Eq (T a b) for a particular
82 expression, and suppose that 'a' is free in the environment.
83 We could generalise to
84 forall b. Eq (T a b) => t
85 but if we reduced the constraint, to C a b, we'd see that 'a' determines
86 b, so that a better type might be
87 t (with free constraint C a b)
88 Perhaps it doesn't matter, because we'll still force b to be a
89 particular type at the call sites. Generalising over too many
90 variables (provided we don't shadow anything by quantifying over a
91 variable that is actually free in the envt) may postpone errors; it
92 won't hide them altogether.
96 oclose :: [PredType] -> TyVarSet -> TyVarSet
97 oclose preds fixed_tvs
98 | null tv_fds = fixed_tvs -- Fast escape hatch for common case
99 | otherwise = loop fixed_tvs
102 | new_fixed_tvs `subVarSet` fixed_tvs = fixed_tvs
103 | otherwise = loop new_fixed_tvs
105 new_fixed_tvs = foldl extend fixed_tvs tv_fds
107 extend fixed_tvs (ls,rs) | ls `subVarSet` fixed_tvs = fixed_tvs `unionVarSet` rs
108 | otherwise = fixed_tvs
110 tv_fds :: [(TyVarSet,TyVarSet)]
111 -- In our example, tv_fds will be [ ({x,y}, {z}), ({x,p},{q}) ]
112 -- Meaning "knowing x,y fixes z, knowing x,p fixes q"
113 tv_fds = [ (tyVarsOfTypes xs, tyVarsOfTypes ys)
114 | ClassP cls tys <- preds, -- Ignore implicit params
115 let (cls_tvs, cls_fds) = classTvsFds cls,
117 let (xs,ys) = instFD fd cls_tvs tys
122 grow :: [PredType] -> TyVarSet -> TyVarSet
124 | null preds = fixed_tvs
125 | otherwise = loop fixed_tvs
128 | new_fixed_tvs `subVarSet` fixed_tvs = fixed_tvs
129 | otherwise = loop new_fixed_tvs
131 new_fixed_tvs = foldl extend fixed_tvs pred_sets
133 extend fixed_tvs pred_tvs
134 | fixed_tvs `intersectsVarSet` pred_tvs = fixed_tvs `unionVarSet` pred_tvs
135 | otherwise = fixed_tvs
137 pred_sets = [tyVarsOfPred pred | pred <- preds]
140 %************************************************************************
142 \subsection{Generate equations from functional dependencies}
144 %************************************************************************
149 type Equation = (TyVarSet, [(Type, Type)])
150 -- These pairs of types should be equal, for some
151 -- substitution of the tyvars in the tyvar set
152 -- INVARIANT: corresponding types aren't already equal
154 -- It's important that we have a *list* of pairs of types. Consider
155 -- class C a b c | a -> b c where ...
156 -- instance C Int x x where ...
157 -- Then, given the constraint (C Int Bool v) we should improve v to Bool,
158 -- via the equation ({x}, [(Bool,x), (v,x)])
159 -- This would not happen if the class had looked like
160 -- class C a b c | a -> b, a -> c
162 -- To "execute" the equation, make fresh type variable for each tyvar in the set,
163 -- instantiate the two types with these fresh variables, and then unify.
165 -- For example, ({a,b}, (a,Int,b), (Int,z,Bool))
166 -- We unify z with Int, but since a and b are quantified we do nothing to them
167 -- We usually act on an equation by instantiating the quantified type varaibles
168 -- to fresh type variables, and then calling the standard unifier.
170 pprEquationDoc (eqn, doc) = vcat [pprEquation eqn, nest 2 doc]
172 pprEquation (qtvs, pairs)
173 = vcat [ptext SLIT("forall") <+> braces (pprWithCommas ppr (varSetElems qtvs)),
174 nest 2 (vcat [ ppr t1 <+> ptext SLIT(":=:") <+> ppr t2 | (t1,t2) <- pairs])]
177 improve :: InstEnv Id -- Gives instances for given class
178 -> [(PredType,SDoc)] -- Current constraints; doc says where they come from
179 -> [(Equation,SDoc)] -- Derived equalities that must also hold
180 -- (NB the above INVARIANT for type Equation)
181 -- The SDoc explains why the equation holds (for error messages)
183 type InstEnv a = Class -> [(TyVarSet, [Type], a)]
184 -- This is a bit clumsy, because InstEnv is really
185 -- defined in module InstEnv. However, we don't want
186 -- to define it here because InstEnv
187 -- is their home. Nor do we want to make a recursive
188 -- module group (InstEnv imports stuff from FunDeps).
191 Given a bunch of predicates that must hold, such as
193 C Int t1, C Int t2, C Bool t3, ?x::t4, ?x::t5
195 improve figures out what extra equations must hold.
196 For example, if we have
198 class C a b | a->b where ...
200 then improve will return
206 * improve does not iterate. It's possible that when we make
207 t1=t2, for example, that will in turn trigger a new equation.
208 This would happen if we also had
210 If t1=t2, we also get t7=t8.
212 improve does *not* do this extra step. It relies on the caller
215 * The equations unify types that are not already equal. So there
216 is no effect iff the result of improve is empty
221 improve inst_env preds
222 = [ eqn | group <- equivClassesByUniq (predTyUnique . fst) preds,
223 eqn <- checkGroup inst_env group ]
226 checkGroup :: InstEnv Id -> [(PredType,SDoc)] -> [(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
248 pairwise_eqns ++ instance_eqns
251 (cls_tvs, cls_fds) = classTvsFds cls
252 cls_inst_env = inst_env cls
254 -- NOTE that we iterate over the fds first; they are typically
255 -- empty, which aborts the rest of the loop.
256 pairwise_eqns :: [(Equation,SDoc)]
257 pairwise_eqns -- This group comes from pairwise comparison
258 = [ (eqn, mkEqnMsg p1 p2)
260 p1@(ClassP _ tys1, _) : rest <- tails clss,
261 p2@(ClassP _ tys2, _) <- rest,
262 eqn <- checkClsFD emptyVarSet fd cls_tvs tys1 tys2
265 instance_eqns :: [(Equation,SDoc)]
266 instance_eqns -- This group comes from comparing with instance decls
267 = [ (eqn, mkEqnMsg p1 p2)
269 (qtvs, tys1, dfun_id) <- cls_inst_env,
270 let p1 = (mkClassPred cls tys1,
271 ptext SLIT("arising from the instance declaration at") <+> ppr (getSrcLoc dfun_id)),
272 p2@(ClassP _ tys2, _) <- clss,
273 eqn <- checkClsFD qtvs fd cls_tvs tys1 tys2
276 mkEqnMsg (pred1,from1) (pred2,from2)
277 = vcat [ptext SLIT("When using functional dependencies to combine"),
278 nest 2 (sep [ppr pred1 <> comma, nest 2 from1]),
279 nest 2 (sep [ppr pred2 <> comma, nest 2 from2])]
282 checkClsFD :: TyVarSet -- Quantified type variables; see note below
283 -> FunDep TyVar -> [TyVar] -- One functional dependency from the class
287 checkClsFD qtvs fd clas_tvs tys1 tys2
288 -- 'qtvs' are the quantified type variables, the ones which an be instantiated
289 -- to make the types match. For example, given
290 -- class C a b | a->b where ...
291 -- instance C (Maybe x) (Tree x) where ..
293 -- and an Inst of form (C (Maybe t1) t2),
294 -- then we will call checkClsFD with
296 -- qtvs = {x}, tys1 = [Maybe x, Tree x]
297 -- tys2 = [Maybe t1, t2]
299 -- We can instantiate x to t1, and then we want to force
300 -- (Tree x) [t1/x] :=: t2
302 -- The same function is also used from InstEnv.badFunDeps, when we need
303 -- to *unify*; in which case the qtvs are the variables of both ls1 and ls2.
304 -- However unifying with the qtvs being the left-hand lot *is* just matching,
305 -- so we can call unifyTys in both cases
306 = case unifyTys qtvs ls1 ls2 of
308 Just unif | maybeToBool (unifyTysX qtvs unif rs1 rs2)
309 -- Don't include any equations that already hold.
310 -- Reason: then we know if any actual improvement has happened,
311 -- in which case we need to iterate the solver
312 -- In making this check we must taking account of the fact that any
313 -- qtvs that aren't already instantiated can be instantiated to anything
315 -- NB: qtvs, not qtvs' because matchTysX only tries to
316 -- look template tyvars up in the substitution
319 | otherwise -- Aha! A useful equation
320 -> [ (qtvs', map (substTy full_unif) rs1 `zip` map (substTy full_unif) rs2)]
321 -- We could avoid this substTy stuff by producing the eqn
322 -- (qtvs, ls1++rs1, ls2++rs2)
323 -- which will re-do the ls1/ls2 unification when the equation is
324 -- executed. What we're doing instead is recording the partial
325 -- work of the ls1/ls2 unification leaving a smaller unification problem
327 full_unif = mkTvSubst unif
329 qtvs' = filterVarSet (\v -> not (v `elemVarEnv` unif)) qtvs
330 -- qtvs' are the quantified type variables
331 -- that have not been substituted out
333 -- Eg. class C a b | a -> b
334 -- instance C Int [y]
335 -- Given constraint C Int z
336 -- we generate the equation
339 (ls1, rs1) = instFD fd clas_tvs tys1
340 (ls2, rs2) = instFD fd clas_tvs tys2
342 instFD :: FunDep TyVar -> [TyVar] -> [Type] -> FunDep Type
343 instFD (ls,rs) tvs tys
344 = (map lookup ls, map lookup rs)
346 env = zipVarEnv tvs tys
347 lookup tv = lookupVarEnv_NF env tv
351 checkInstFDs :: ThetaType -> Class -> [Type] -> Bool
352 -- Check that functional dependencies are obeyed in an instance decl
353 -- For example, if we have
354 -- class theta => C a b | a -> b
356 -- Then we require fv(t2) `subset` oclose(fv(t1), theta)
358 checkInstFDs theta clas inst_taus
361 (tyvars, fds) = classTvsFds clas
362 fundep_ok fd = tyVarsOfTypes rs `subVarSet` oclose theta (tyVarsOfTypes ls)
364 (ls,rs) = instFD fd tyvars inst_taus
367 %************************************************************************
369 \subsection{Miscellaneous}
371 %************************************************************************
374 pprFundeps :: Outputable a => [FunDep a] -> SDoc
375 pprFundeps [] = empty
376 pprFundeps fds = hsep (ptext SLIT("|") : punctuate comma (map ppr_fd fds))
378 ppr_fd (us, vs) = hsep [interppSP us, ptext SLIT("->"), interppSP vs]