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 Subst ( mkSubst, emptyInScopeSet, substTy )
19 import TcType ( Type, ThetaType, SourceType(..), PredType,
20 predTyUnique, mkClassPred, tyVarsOfTypes, tyVarsOfPred,
21 unifyTyListsX, unifyExtendTysX, tcEqType
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 pred_sets = 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) -- These two types should be equal, for some
150 -- substitution of the tyvars in the tyvar set
151 -- For example, ({a,b}, (a,Int,b), (Int,z,Bool))
152 -- We unify z with Int, but since a and b are quantified we do nothing to them
153 -- We usually act on an equation by instantiating the quantified type varaibles
154 -- to fresh type variables, and then calling the standard unifier.
156 -- INVARIANT: they aren't already equal
162 improve :: InstEnv Id -- Gives instances for given class
163 -> [(PredType,SDoc)] -- Current constraints; doc says where they come from
164 -> [(Equation,SDoc)] -- Derived equalities that must also hold
165 -- (NB the above INVARIANT for type Equation)
166 -- The SDoc explains why the equation holds (for error messages)
168 type InstEnv a = Class -> [(TyVarSet, [Type], a)]
169 -- This is a bit clumsy, because InstEnv is really
170 -- defined in module InstEnv. However, we don't want
171 -- to define it (and ClsInstEnv) here because InstEnv
172 -- is their home. Nor do we want to make a recursive
173 -- module group (InstEnv imports stuff from FunDeps).
176 Given a bunch of predicates that must hold, such as
178 C Int t1, C Int t2, C Bool t3, ?x::t4, ?x::t5
180 improve figures out what extra equations must hold.
181 For example, if we have
183 class C a b | a->b where ...
185 then improve will return
191 * improve does not iterate. It's possible that when we make
192 t1=t2, for example, that will in turn trigger a new equation.
193 This would happen if we also had
195 If t1=t2, we also get t7=t8.
197 improve does *not* do this extra step. It relies on the caller
200 * The equations unify types that are not already equal. So there
201 is no effect iff the result of improve is empty
206 improve inst_env preds
207 = [ eqn | group <- equivClassesByUniq (predTyUnique . fst) preds,
208 eqn <- checkGroup inst_env group ]
211 checkGroup :: InstEnv Id -> [(PredType,SDoc)] -> [(Equation, SDoc)]
212 -- The preds are all for the same class or implicit param
214 checkGroup inst_env (p1@(IParam _ ty, _) : ips)
215 = -- For implicit parameters, all the types must match
216 [ ((emptyVarSet, ty, ty'), mkEqnMsg p1 p2)
217 | p2@(IParam _ ty', _) <- ips, not (ty `tcEqType` ty')]
219 checkGroup inst_env clss@((ClassP cls _, _) : _)
220 = -- For classes life is more complicated
221 -- Suppose the class is like
222 -- classs C as | (l1 -> r1), (l2 -> r2), ... where ...
223 -- Then FOR EACH PAIR (ClassP c tys1, ClassP c tys2) in the list clss
225 -- U l1[tys1/as] = U l2[tys2/as]
226 -- (where U is a unifier)
228 -- If so, we return the pair
229 -- U r1[tys1/as] = U l2[tys2/as]
231 -- We need to do something very similar comparing each predicate
232 -- with relevant instance decls
233 pairwise_eqns ++ instance_eqns
236 (cls_tvs, cls_fds) = classTvsFds cls
237 cls_inst_env = inst_env cls
239 -- NOTE that we iterate over the fds first; they are typically
240 -- empty, which aborts the rest of the loop.
241 pairwise_eqns :: [(Equation,SDoc)]
242 pairwise_eqns -- This group comes from pairwise comparison
243 = [ (eqn, mkEqnMsg p1 p2)
245 p1@(ClassP _ tys1, _) : rest <- tails clss,
246 p2@(ClassP _ tys2, _) <- rest,
247 eqn <- checkClsFD emptyVarSet fd cls_tvs tys1 tys2
250 instance_eqns :: [(Equation,SDoc)]
251 instance_eqns -- This group comes from comparing with instance decls
252 = [ (eqn, mkEqnMsg p1 p2)
254 (qtvs, tys1, dfun_id) <- cls_inst_env,
255 let p1 = (mkClassPred cls tys1,
256 ptext SLIT("arising from the instance declaration at") <+> ppr (getSrcLoc dfun_id)),
257 p2@(ClassP _ tys2, _) <- clss,
258 eqn <- checkClsFD qtvs fd cls_tvs tys1 tys2
261 mkEqnMsg (pred1,from1) (pred2,from2)
262 = vcat [ptext SLIT("When using functional dependencies to combine"),
263 nest 2 (sep [ppr pred1 <> comma, nest 2 from1]),
264 nest 2 (sep [ppr pred2 <> comma, nest 2 from2])]
267 checkClsFD :: TyVarSet -- The quantified type variables, which
268 -- can be instantiated to make the types match
269 -> FunDep TyVar -> [TyVar] -- One functional dependency from the class
273 checkClsFD qtvs fd clas_tvs tys1 tys2
274 -- We use 'unify' even though we are often only matching
275 -- unifyTyListsX will only bind variables in qtvs, so it's OK!
276 = case unifyTyListsX qtvs ls1 ls2 of
278 Just unif -> [ (qtvs', substTy full_unif r1, substTy full_unif r2)
279 | (r1,r2) <- rs1 `zip` rs2,
280 not (maybeToBool (unifyExtendTysX qtvs unif r1 r2))]
282 full_unif = mkSubst emptyInScopeSet unif
283 -- No for-alls in sight; hmm
285 qtvs' = filterVarSet (\v -> not (v `elemSubstEnv` unif)) qtvs
286 -- qtvs' are the quantified type variables
287 -- that have not been substituted out
289 (ls1, rs1) = instFD fd clas_tvs tys1
290 (ls2, rs2) = instFD fd clas_tvs tys2
292 instFD :: FunDep TyVar -> [TyVar] -> [Type] -> FunDep Type
293 instFD (ls,rs) tvs tys
294 = (map lookup ls, map lookup rs)
296 env = zipVarEnv tvs tys
297 lookup tv = lookupVarEnv_NF env tv
301 checkInstFDs :: ThetaType -> Class -> [Type] -> Bool
302 -- Check that functional dependencies are obeyed in an instance decl
303 -- For example, if we have
304 -- class theta => C a b | a -> b
306 -- Then we require fv(t2) `subset` oclose(fv(t1), theta)
308 checkInstFDs theta clas inst_taus
311 (tyvars, fds) = classTvsFds clas
312 fundep_ok fd = tyVarsOfTypes rs `subVarSet` oclose theta (tyVarsOfTypes ls)
314 (ls,rs) = instFD fd tyvars inst_taus
317 %************************************************************************
319 \subsection{Miscellaneous}
321 %************************************************************************
324 pprFundeps :: Outputable a => [FunDep a] -> SDoc
325 pprFundeps [] = empty
326 pprFundeps fds = hsep (ptext SLIT("|") : punctuate comma (map ppr_fd fds))
328 ppr_fd (us, vs) = hsep [interppSP us, ptext SLIT("->"), interppSP vs]