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"
15 import Name ( getSrcLoc )
16 import Var ( Id, TyVar )
17 import Class ( Class, FunDep, classTvsFds )
18 import Type ( Type, ThetaType, PredType(..), predTyUnique, mkClassPred, tyVarsOfTypes, tyVarsOfPred )
19 import Subst ( mkSubst, emptyInScopeSet, substTy )
20 import Unify ( unifyTyListsX, unifyExtendTysX )
25 import Maybes ( maybeToBool )
26 import ListSetOps ( equivClassesByUniq )
30 %************************************************************************
32 \subsection{Close type variables}
34 %************************************************************************
36 (oclose preds tvs) closes the set of type variables tvs,
37 wrt functional dependencies in preds. The result is a superset
38 of the argument set. For example, if we have
39 class C a b | a->b where ...
41 oclose [C (x,y) z, C (x,p) q] {x,y} = {x,y,z}
42 because if we know x and y then that fixes z.
48 a) When determining ambiguity. The type
49 forall a,b. C a b => a
50 is not ambiguous (given the above class decl for C) because
53 b) When generalising a type T. Usually we take FV(T) \ FV(Env),
56 where the '+' is the oclosure operation. Notice that we do not
57 take FV(T)+. This puzzled me for a bit. Consider
61 and suppose e have that E :: C a b => a, and suppose that b is
62 free in the environment. Then we quantify over 'a' only, giving
63 the type forall a. C a b => a. Since a->b but we don't have b->a,
64 we might have instance decls like
65 instance C Bool Int where ...
66 instance C Char Int where ...
67 so knowing that b=Int doesn't fix 'a'; so we quantify over it.
72 If we have class C a b => D a b where ....
73 class D a b | a -> b where ...
74 and the preds are [C (x,y) z], then we want to see the fd in D,
75 even though it is not explicit in C, giving [({x,y},{z})]
77 Similarly for instance decls? E.g. Suppose we have
78 instance C a b => Eq (T a b) where ...
79 and we infer a type t with constraints Eq (T a b) for a particular
80 expression, and suppose that 'a' is free in the environment.
81 We could generalise to
82 forall b. Eq (T a b) => t
83 but if we reduced the constraint, to C a b, we'd see that 'a' determines
84 b, so that a better type might be
85 t (with free constraint C a b)
86 Perhaps it doesn't matter, because we'll still force b to be a
87 particular type at the call sites. Generalising over too many
88 variables (provided we don't shadow anything by quantifying over a
89 variable that is actually free in the envt) may postpone errors; it
90 won't hide them altogether.
94 oclose :: [PredType] -> TyVarSet -> TyVarSet
95 oclose preds fixed_tvs
96 | null tv_fds = fixed_tvs -- Fast escape hatch for common case
97 | otherwise = loop fixed_tvs
100 | new_fixed_tvs `subVarSet` fixed_tvs = fixed_tvs
101 | otherwise = loop new_fixed_tvs
103 new_fixed_tvs = foldl extend fixed_tvs tv_fds
105 extend fixed_tvs (ls,rs) | ls `subVarSet` fixed_tvs = fixed_tvs `unionVarSet` rs
106 | otherwise = fixed_tvs
108 tv_fds :: [(TyVarSet,TyVarSet)]
109 -- In our example, tv_fds will be [ ({x,y}, {z}), ({x,p},{q}) ]
110 -- Meaning "knowing x,y fixes z, knowing x,p fixes q"
111 tv_fds = [ (tyVarsOfTypes xs, tyVarsOfTypes ys)
112 | ClassP cls tys <- preds, -- Ignore implicit params
113 let (cls_tvs, cls_fds) = classTvsFds cls,
115 let (xs,ys) = instFD fd cls_tvs tys
120 grow :: [PredType] -> TyVarSet -> TyVarSet
122 | null pred_sets = fixed_tvs
123 | otherwise = loop fixed_tvs
126 | new_fixed_tvs `subVarSet` fixed_tvs = fixed_tvs
127 | otherwise = loop new_fixed_tvs
129 new_fixed_tvs = foldl extend fixed_tvs pred_sets
131 extend fixed_tvs pred_tvs
132 | fixed_tvs `intersectsVarSet` pred_tvs = fixed_tvs `unionVarSet` pred_tvs
133 | otherwise = fixed_tvs
135 pred_sets = [tyVarsOfPred pred | pred <- preds]
138 %************************************************************************
140 \subsection{Generate equations from functional dependencies}
142 %************************************************************************
147 type Equation = (TyVarSet, Type, Type) -- These two types should be equal, for some
148 -- substitution of the tyvars in the tyvar set
149 -- For example, ({a,b}, (a,Int,b), (Int,z,Bool))
150 -- We unify z with Int, but since a and b are quantified we do nothing to them
151 -- We usually act on an equation by instantiating the quantified type varaibles
152 -- to fresh type variables, and then calling the standard unifier.
154 -- INVARIANT: they aren't already equal
160 improve :: InstEnv Id -- Gives instances for given class
161 -> [(PredType,SDoc)] -- Current constraints; doc says where they come from
162 -> [(Equation,SDoc)] -- Derived equalities that must also hold
163 -- (NB the above INVARIANT for type Equation)
164 -- The SDoc explains why the equation holds (for error messages)
166 type InstEnv a = Class -> [(TyVarSet, [Type], a)]
167 -- This is a bit clumsy, because InstEnv is really
168 -- defined in module InstEnv. However, we don't want
169 -- to define it (and ClsInstEnv) here because InstEnv
170 -- is their home. Nor do we want to make a recursive
171 -- module group (InstEnv imports stuff from FunDeps).
174 Given a bunch of predicates that must hold, such as
176 C Int t1, C Int t2, C Bool t3, ?x::t4, ?x::t5
178 improve figures out what extra equations must hold.
179 For example, if we have
181 class C a b | a->b where ...
183 then improve will return
189 * improve does not iterate. It's possible that when we make
190 t1=t2, for example, that will in turn trigger a new equation.
191 This would happen if we also had
193 If t1=t2, we also get t7=t8.
195 improve does *not* do this extra step. It relies on the caller
198 * The equations unify types that are not already equal. So there
199 is no effect iff the result of improve is empty
204 improve inst_env preds
205 = [ eqn | group <- equivClassesByUniq (predTyUnique . fst) preds,
206 eqn <- checkGroup inst_env group ]
209 checkGroup :: InstEnv Id -> [(PredType,SDoc)] -> [(Equation, SDoc)]
210 -- The preds are all for the same class or implicit param
212 checkGroup inst_env (p1@(IParam _ ty, _) : ips)
213 = -- For implicit parameters, all the types must match
214 [((emptyVarSet, ty, ty'), mkEqnMsg p1 p2) | p2@(IParam _ ty', _) <- ips, ty /= ty']
216 checkGroup inst_env clss@((ClassP cls _, _) : _)
217 = -- For classes life is more complicated
218 -- Suppose the class is like
219 -- classs C as | (l1 -> r1), (l2 -> r2), ... where ...
220 -- Then FOR EACH PAIR (ClassP c tys1, ClassP c tys2) in the list clss
222 -- U l1[tys1/as] = U l2[tys2/as]
223 -- (where U is a unifier)
225 -- If so, we return the pair
226 -- U r1[tys1/as] = U l2[tys2/as]
228 -- We need to do something very similar comparing each predicate
229 -- with relevant instance decls
230 pairwise_eqns ++ instance_eqns
233 (cls_tvs, cls_fds) = classTvsFds cls
234 cls_inst_env = inst_env cls
236 -- NOTE that we iterate over the fds first; they are typically
237 -- empty, which aborts the rest of the loop.
238 pairwise_eqns :: [(Equation,SDoc)]
239 pairwise_eqns -- This group comes from pairwise comparison
240 = [ (eqn, mkEqnMsg p1 p2)
242 p1@(ClassP _ tys1, _) : rest <- tails clss,
243 p2@(ClassP _ tys2, _) <- rest,
244 eqn <- checkClsFD emptyVarSet fd cls_tvs tys1 tys2
247 instance_eqns :: [(Equation,SDoc)]
248 instance_eqns -- This group comes from comparing with instance decls
249 = [ (eqn, mkEqnMsg p1 p2)
251 (qtvs, tys1, dfun_id) <- cls_inst_env,
252 let p1 = (mkClassPred cls tys1,
253 ptext SLIT("arising from the instance declaration at") <+> ppr (getSrcLoc dfun_id)),
254 p2@(ClassP _ tys2, _) <- clss,
255 eqn <- checkClsFD qtvs fd cls_tvs tys1 tys2
258 mkEqnMsg (pred1,from1) (pred2,from2)
259 = vcat [ptext SLIT("When using functional dependencies to combine"),
260 nest 2 (sep [ppr pred1 <> comma, nest 2 from1]),
261 nest 2 (sep [ppr pred2 <> comma, nest 2 from2])]
264 checkClsFD :: TyVarSet -- The quantified type variables, which
265 -- can be instantiated to make the types match
266 -> FunDep TyVar -> [TyVar] -- One functional dependency from the class
270 checkClsFD qtvs fd clas_tvs tys1 tys2
271 -- We use 'unify' even though we are often only matching
272 -- unifyTyListsX will only bind variables in qtvs, so it's OK!
273 = case unifyTyListsX qtvs ls1 ls2 of
275 Just unif -> [ (qtvs', substTy full_unif r1, substTy full_unif r2)
276 | (r1,r2) <- rs1 `zip` rs2,
277 not (maybeToBool (unifyExtendTysX qtvs unif r1 r2))]
279 full_unif = mkSubst emptyInScopeSet unif
280 -- No for-alls in sight; hmm
282 qtvs' = filterVarSet (\v -> not (v `elemSubstEnv` unif)) qtvs
283 -- qtvs' are the quantified type variables
284 -- that have not been substituted out
286 (ls1, rs1) = instFD fd clas_tvs tys1
287 (ls2, rs2) = instFD fd clas_tvs tys2
289 instFD :: FunDep TyVar -> [TyVar] -> [Type] -> FunDep Type
290 instFD (ls,rs) tvs tys
291 = (map lookup ls, map lookup rs)
293 env = zipVarEnv tvs tys
294 lookup tv = lookupVarEnv_NF env tv
298 checkInstFDs :: ThetaType -> Class -> [Type] -> Bool
299 -- Check that functional dependencies are obeyed in an instance decl
300 -- For example, if we have
301 -- class theta => C a b | a -> b
303 -- Then we require fv(t2) `subset` oclose(fv(t1), theta)
305 checkInstFDs theta clas inst_taus
308 (tyvars, fds) = classTvsFds clas
309 fundep_ok fd = tyVarsOfTypes rs `subVarSet` oclose theta (tyVarsOfTypes ls)
311 (ls,rs) = instFD fd tyvars inst_taus
314 %************************************************************************
316 \subsection{Miscellaneous}
318 %************************************************************************
321 pprFundeps :: Outputable a => [FunDep a] -> SDoc
322 pprFundeps [] = empty
323 pprFundeps fds = hsep (ptext SLIT("|") : punctuate comma (map ppr_fd fds))
325 ppr_fd (us, vs) = hsep [interppSP us, ptext SLIT("->"), interppSP vs]