[project @ 2001-03-13 14:58:25 by simonpj]
[ghc-hetmet.git] / ghc / compiler / types / FunDeps.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 2000
3 %
4 \section[FunDeps]{FunDeps - functional dependencies}
5
6 It's better to read it as: "if we know these, then we're going to know these"
7
8 \begin{code}
9 module FunDeps (
10         oclose, grow, improve, checkInstFDs, checkClsFD, pprFundeps
11     ) where
12
13 #include "HsVersions.h"
14
15 import Var              ( TyVar )
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 )
21 import VarSet
22 import VarEnv
23 import List             ( tails )
24 import Maybes           ( maybeToBool )
25 import ListSetOps       ( equivClassesByUniq )
26 \end{code}
27
28
29 %************************************************************************
30 %*                                                                      *
31 \subsection{Close type variables}
32 %*                                                                      *
33 %************************************************************************
34
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 ...
39 then
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.
42
43 Using oclose
44 ~~~~~~~~~~~~
45 oclose is used
46
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
50 a determines b.  
51
52 b) When generalising a type T.  Usually we take FV(T) \ FV(Env),
53 but in fact we need
54         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
57
58         f = E
59
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.
67
68                 ---------------
69                 A WORRY: ToDo!
70                 ---------------
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})]
75
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.
90
91
92 \begin{code}
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
97   where
98     loop fixed_tvs
99         | new_fixed_tvs `subVarSet` fixed_tvs = fixed_tvs
100         | otherwise                           = loop new_fixed_tvs
101         where
102           new_fixed_tvs = foldl extend fixed_tvs tv_fds
103
104     extend fixed_tvs (ls,rs) | ls `subVarSet` fixed_tvs = fixed_tvs `unionVarSet` rs
105                              | otherwise                = fixed_tvs
106
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               | ClassP cls tys <- preds,                -- Ignore implicit params
112                 let (cls_tvs, cls_fds) = classTvsFds cls,
113                 fd <- cls_fds,
114                 let (xs,ys) = instFD fd cls_tvs tys
115               ]
116 \end{code}
117
118 \begin{code}
119 grow :: [PredType] -> TyVarSet -> TyVarSet
120 grow preds fixed_tvs 
121   | null pred_sets = fixed_tvs
122   | otherwise      = loop fixed_tvs
123   where
124     loop fixed_tvs
125         | new_fixed_tvs `subVarSet` fixed_tvs = fixed_tvs
126         | otherwise                           = loop new_fixed_tvs
127         where
128           new_fixed_tvs = foldl extend fixed_tvs pred_sets
129
130     extend fixed_tvs pred_tvs 
131         | fixed_tvs `intersectsVarSet` pred_tvs = fixed_tvs `unionVarSet` pred_tvs
132         | otherwise                             = fixed_tvs
133
134     pred_sets = [tyVarsOfPred pred | pred <- preds]
135 \end{code}
136     
137 %************************************************************************
138 %*                                                                      *
139 \subsection{Generate equations from functional dependencies}
140 %*                                                                      *
141 %************************************************************************
142
143
144 \begin{code}
145 ----------
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.
152         -- 
153         -- INVARIANT: they aren't already equal
154
155
156
157 ----------
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)
162
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).
169 \end{code}
170
171 Given a bunch of predicates that must hold, such as
172
173         C Int t1, C Int t2, C Bool t3, ?x::t4, ?x::t5
174
175 improve figures out what extra equations must hold.
176 For example, if we have
177
178         class C a b | a->b where ...
179
180 then improve will return
181
182         [(t1,t2), (t4,t5)]
183
184 NOTA BENE:
185
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
189         C t1 t7, C t2 t8
190     If t1=t2, we also get t7=t8.
191
192     improve does *not* do this extra step.  It relies on the caller
193     doing so.
194
195   * The equations unify types that are not already equal.  So there
196     is no effect iff the result of improve is empty
197
198
199
200 \begin{code}
201 improve inst_env preds
202   = [ eqn | group <- equivClassesByUniq predTyUnique preds,
203             eqn   <- checkGroup inst_env group ]
204
205 ----------
206 checkGroup :: InstEnv a -> [PredType] -> [Equation]
207   -- The preds are all for the same class or implicit param
208
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']
212
213 checkGroup inst_env clss@(ClassP 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 (ClassP c tys1, ClassP c tys2) in the list clss
218         -- we check whether
219         --      U l1[tys1/as] = U l2[tys2/as]
220         --  (where U is a unifier)
221         -- 
222         -- If so, we return the pair
223         --      U r1[tys1/as] = U l2[tys2/as]
224         --
225         -- We need to do something very similar comparing each predicate
226         -- with relevant instance decls
227     pairwise_eqns ++ instance_eqns
228
229   where
230     (cls_tvs, cls_fds) = classTvsFds cls
231     cls_inst_env       = inst_env cls
232
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                 ClassP _ tys1 : rest <- tails clss,
239                 ClassP _ tys2   <- rest,
240                 eqn <- checkClsFD emptyVarSet fd cls_tvs tys1 tys2
241         ]
242
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                 ClassP _ tys2    <- clss,
248                 eqn <- checkClsFD qtvs fd cls_tvs tys1 tys2
249         ]
250
251
252 ----------
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
256            -> [Type] -> [Type]
257            -> [Equation]
258
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
263         Nothing   -> []
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))]
267                   where
268                     full_unif = mkSubst emptyInScopeSet unif
269                         -- No for-alls in sight; hmm
270
271                     qtvs' = filterVarSet (\v -> not (v `elemSubstEnv` unif)) qtvs
272                         -- qtvs' are the quantified type variables
273                         -- that have not been substituted out
274   where
275     (ls1, rs1) = instFD fd clas_tvs tys1
276     (ls2, rs2) = instFD fd clas_tvs tys2
277
278 instFD :: FunDep TyVar -> [TyVar] -> [Type] -> FunDep Type
279 instFD (ls,rs) tvs tys
280   = (map lookup ls, map lookup rs)
281   where
282     env       = zipVarEnv tvs tys
283     lookup tv = lookupVarEnv_NF env tv
284 \end{code}
285
286 \begin{code}
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
291 --      instance C t1 t2 
292 -- Then we require fv(t2) `subset` oclose(fv(t1), theta)
293
294 checkInstFDs theta clas inst_taus
295   = all fundep_ok fds
296   where
297     (tyvars, fds) = classTvsFds clas
298     fundep_ok fd  = tyVarsOfTypes rs `subVarSet` oclose theta (tyVarsOfTypes ls)
299                  where
300                    (ls,rs) = instFD fd tyvars inst_taus
301 \end{code}
302
303 %************************************************************************
304 %*                                                                      *
305 \subsection{Miscellaneous}
306 %*                                                                      *
307 %************************************************************************
308
309 \begin{code}
310 pprFundeps :: Outputable a => [FunDep a] -> SDoc
311 pprFundeps [] = empty
312 pprFundeps fds = hsep (ptext SLIT("|") : punctuate comma (map ppr_fd fds))
313
314 ppr_fd (us, vs) = hsep [interppSP us, ptext SLIT("->"), interppSP vs]
315 \end{code}