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 oclose, grow, improve, checkInstFDs, checkClsFD, pprFundeps
13 #include "HsVersions.h"
16 import Class ( Class, FunDep, classTvsFds )
17 import Type ( Type, ThetaType, PredType(..), predTyUnique, tyVarsOfTypes, tyVarsOfPred )
18 import Subst ( mkSubst, emptyInScopeSet, substTy )
19 import Unify ( unifyTyListsX, unifyExtendTysX )
20 import Outputable ( Outputable, SDoc, interppSP, ptext, empty, hsep, punctuate, comma )
24 import Maybes ( maybeToBool )
25 import ListSetOps ( equivClassesByUniq )
29 %************************************************************************
31 \subsection{Close type variables}
33 %************************************************************************
35 (oclose preds tvs) closes the set of type variables tvs,
36 wrt functional dependencies in preds. The result is a superset
37 of the argument set. For example, if we have
38 class C a b | a->b where ...
40 oclose [C (x,y) z, C (x,p) q] {x,y} = {x,y,z}
41 because if we know x and y then that fixes z.
47 a) When determining ambiguity. The type
48 forall a,b. C a b => a
49 is not ambiguous (given the above class decl for C) because
52 b) When generalising a type T. Usually we take FV(T) \ FV(Env),
55 where the '+' is the oclosure operation. Notice that we do not
56 take FV(T)+. This puzzled me for a bit. Consider
60 and suppose e have that E :: C a b => a, and suppose that b is
61 free in the environment. Then we quantify over 'a' only, giving
62 the type forall a. C a b => a. Since a->b but we don't have b->a,
63 we might have instance decls like
64 instance C Bool Int where ...
65 instance C Char Int where ...
66 so knowing that b=Int doesn't fix 'a'; so we quantify over it.
71 If we have class C a b => D a b where ....
72 class D a b | a -> b where ...
73 and the preds are [C (x,y) z], then we want to see the fd in D,
74 even though it is not explicit in C, giving [({x,y},{z})]
76 Similarly for instance decls? E.g. Suppose we have
77 instance C a b => Eq (T a b) where ...
78 and we infer a type t with constraints Eq (T a b) for a particular
79 expression, and suppose that 'a' is free in the environment.
80 We could generalise to
81 forall b. Eq (T a b) => t
82 but if we reduced the constraint, to C a b, we'd see that 'a' determines
83 b, so that a better type might be
84 t (with free constraint C a b)
85 Perhaps it doesn't matter, because we'll still force b to be a
86 particular type at the call sites. Generalising over too many
87 variables (provided we don't shadow anything by quantifying over a
88 variable that is actually free in the envt) may postpone errors; it
89 won't hide them altogether.
93 oclose :: [PredType] -> TyVarSet -> TyVarSet
94 oclose preds fixed_tvs
95 | null tv_fds = fixed_tvs -- Fast escape hatch for common case
96 | otherwise = loop fixed_tvs
99 | new_fixed_tvs `subVarSet` fixed_tvs = fixed_tvs
100 | otherwise = loop new_fixed_tvs
102 new_fixed_tvs = foldl extend fixed_tvs tv_fds
104 extend fixed_tvs (ls,rs) | ls `subVarSet` fixed_tvs = fixed_tvs `unionVarSet` rs
105 | otherwise = fixed_tvs
107 tv_fds :: [(TyVarSet,TyVarSet)]
108 -- In our example, tv_fds will be [ ({x,y}, {z}), ({x,p},{q}) ]
109 -- Meaning "knowing x,y fixes z, knowing x,p fixes q"
110 tv_fds = [ (tyVarsOfTypes xs, tyVarsOfTypes ys)
111 | Class cls tys <- preds, -- Ignore implicit params
112 let (cls_tvs, cls_fds) = classTvsFds cls,
114 let (xs,ys) = instFD fd cls_tvs tys
119 grow :: [PredType] -> TyVarSet -> TyVarSet
121 | null pred_sets = fixed_tvs
122 | otherwise = loop fixed_tvs
125 | new_fixed_tvs `subVarSet` fixed_tvs = fixed_tvs
126 | otherwise = loop new_fixed_tvs
128 new_fixed_tvs = foldl extend fixed_tvs pred_sets
130 extend fixed_tvs pred_tvs
131 | fixed_tvs `intersectsVarSet` pred_tvs = fixed_tvs `unionVarSet` pred_tvs
132 | otherwise = fixed_tvs
134 pred_sets = [tyVarsOfPred pred | pred <- preds]
137 %************************************************************************
139 \subsection{Generate equations from functional dependencies}
141 %************************************************************************
146 type Equation = (TyVarSet, Type,Type) -- These two types should be equal, for some
147 -- substitution of the tyvars in the tyvar set
148 -- For example, ({a,b}, (a,Int,b), (Int,z,Bool))
149 -- We unify z with Int, but since a and b are quantified we do nothing to them
150 -- We usually act on an equation by instantiating the quantified type varaibles
151 -- to fresh type variables, and then calling the standard unifier.
153 -- INVARIANT: they aren't already equal
158 improve :: InstEnv a -- Gives instances for given class
159 -> [PredType] -- Current constraints
160 -> [Equation] -- Derived equalities that must also hold
161 -- (NB the above INVARIANT for type Equation)
163 type InstEnv a = Class -> [(TyVarSet, [Type], a)]
164 -- This is a bit clumsy, because InstEnv is really
165 -- defined in module InstEnv. However, we don't want
166 -- to define it (and ClsInstEnv) here because InstEnv
167 -- is their home. Nor do we want to make a recursive
168 -- module group (InstEnv imports stuff from FunDeps).
171 Given a bunch of predicates that must hold, such as
173 C Int t1, C Int t2, C Bool t3, ?x::t4, ?x::t5
175 improve figures out what extra equations must hold.
176 For example, if we have
178 class C a b | a->b where ...
180 then improve will return
186 * improve does not iterate. It's possible that when we make
187 t1=t2, for example, that will in turn trigger a new equation.
188 This would happen if we also had
190 If t1=t2, we also get t7=t8.
192 improve does *not* do this extra step. It relies on the caller
195 * The equations unify types that are not already equal. So there
196 is no effect iff the result of improve is empty
201 improve inst_env preds
202 = [ eqn | group <- equivClassesByUniq predTyUnique preds,
203 eqn <- checkGroup inst_env group ]
206 checkGroup :: InstEnv a -> [PredType] -> [Equation]
207 -- The preds are all for the same class or implicit param
209 checkGroup inst_env (IParam _ ty : ips)
210 = -- For implicit parameters, all the types must match
211 [(emptyVarSet, ty, ty') | IParam _ ty' <- ips, ty /= ty']
213 checkGroup inst_env clss@(Class cls tys : _)
214 = -- For classes life is more complicated
215 -- Suppose the class is like
216 -- classs C as | (l1 -> r1), (l2 -> r2), ... where ...
217 -- Then FOR EACH PAIR (Class c tys1, Class c tys2) in the list clss
219 -- U l1[tys1/as] = U l2[tys2/as]
220 -- (where U is a unifier)
222 -- If so, we return the pair
223 -- U r1[tys1/as] = U l2[tys2/as]
225 -- We need to do something very similar comparing each predicate
226 -- with relevant instance decls
227 pairwise_eqns ++ instance_eqns
230 (cls_tvs, cls_fds) = classTvsFds cls
231 cls_inst_env = inst_env cls
233 -- NOTE that we iterate over the fds first; they are typically
234 -- empty, which aborts the rest of the loop.
235 pairwise_eqns :: [Equation]
236 pairwise_eqns -- This group comes from pairwise comparison
237 = [ eqn | fd <- cls_fds,
238 Class _ tys1 : rest <- tails clss,
239 Class _ tys2 <- rest,
240 eqn <- checkClsFD emptyVarSet fd cls_tvs tys1 tys2
243 instance_eqns :: [Equation]
244 instance_eqns -- This group comes from comparing with instance decls
245 = [ eqn | fd <- cls_fds,
246 (qtvs, tys1, _) <- cls_inst_env,
247 Class _ tys2 <- clss,
248 eqn <- checkClsFD qtvs fd cls_tvs tys1 tys2
253 checkClsFD :: TyVarSet -- The quantified type variables, which
254 -- can be instantiated to make the types match
255 -> FunDep TyVar -> [TyVar] -- One functional dependency from the class
259 checkClsFD qtvs fd clas_tvs tys1 tys2
260 -- We use 'unify' even though we are often only matching
261 -- unifyTyListsX will only bind variables in qtvs, so it's OK!
262 = case unifyTyListsX qtvs ls1 ls2 of
264 Just unif -> [ (qtvs', substTy full_unif r1, substTy full_unif r2)
265 | (r1,r2) <- rs1 `zip` rs2,
266 not (maybeToBool (unifyExtendTysX qtvs unif r1 r2))]
268 full_unif = mkSubst emptyInScopeSet unif
269 -- No for-alls in sight; hmm
271 qtvs' = filterVarSet (\v -> not (v `elemSubstEnv` unif)) qtvs
272 -- qtvs' are the quantified type variables
273 -- that have not been substituted out
275 (ls1, rs1) = instFD fd clas_tvs tys1
276 (ls2, rs2) = instFD fd clas_tvs tys2
278 instFD :: FunDep TyVar -> [TyVar] -> [Type] -> FunDep Type
279 instFD (ls,rs) tvs tys
280 = (map lookup ls, map lookup rs)
282 env = zipVarEnv tvs tys
283 lookup tv = lookupVarEnv_NF env tv
287 checkInstFDs :: ThetaType -> Class -> [Type] -> Bool
288 -- Check that functional dependencies are obeyed in an instance decl
289 -- For example, if we have
290 -- class theta => C a b | a -> b
292 -- Then we require fv(t2) `subset` oclose(fv(t1), theta)
294 checkInstFDs theta clas inst_taus
297 (tyvars, fds) = classTvsFds clas
298 fundep_ok fd = tyVarsOfTypes rs `subVarSet` oclose theta (tyVarsOfTypes ls)
300 (ls,rs) = instFD fd tyvars inst_taus
303 %************************************************************************
305 \subsection{Miscellaneous}
307 %************************************************************************
310 pprFundeps :: Outputable a => [FunDep a] -> SDoc
311 pprFundeps [] = empty
312 pprFundeps fds = hsep (ptext SLIT("|") : punctuate comma (map ppr_fd fds))
314 ppr_fd (us, vs) = hsep [interppSP us, ptext SLIT("->"), interppSP vs]