[project @ 2005-03-10 14:03:28 by simonmar]
[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         Equation, pprEquation, pprEquationDoc,
11         oclose, grow, improve, checkInstFDs, checkClsFD, pprFundeps
12     ) where
13
14 #include "HsVersions.h"
15
16 import Name             ( getSrcLoc )
17 import Var              ( Id, TyVar )
18 import Class            ( Class, FunDep, classTvsFds )
19 import Unify            ( tcUnifyTys, BindFlag(..) )
20 import Type             ( substTys, notElemTvSubst )
21 import TcType           ( Type, ThetaType, PredType(..), tcEqType,
22                           predTyUnique, mkClassPred, tyVarsOfTypes, tyVarsOfPred )
23 import VarSet
24 import VarEnv
25 import Outputable
26 import List             ( tails )
27 import Maybe            ( isJust )
28 import ListSetOps       ( equivClassesByUniq )
29 \end{code}
30
31
32 %************************************************************************
33 %*                                                                      *
34 \subsection{Close type variables}
35 %*                                                                      *
36 %************************************************************************
37
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 ...
42 then
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.
45
46 Using oclose
47 ~~~~~~~~~~~~
48 oclose is used
49
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
53 a determines b.  
54
55 b) When generalising a type T.  Usually we take FV(T) \ FV(Env),
56 but in fact we need
57         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
60
61         f = E
62
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.
70
71                 ---------------
72                 A WORRY: ToDo!
73                 ---------------
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})]
78
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.
93
94
95 \begin{code}
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
100   where
101     loop fixed_tvs
102         | new_fixed_tvs `subVarSet` fixed_tvs = fixed_tvs
103         | otherwise                           = loop new_fixed_tvs
104         where
105           new_fixed_tvs = foldl extend fixed_tvs tv_fds
106
107     extend fixed_tvs (ls,rs) | ls `subVarSet` fixed_tvs = fixed_tvs `unionVarSet` rs
108                              | otherwise                = fixed_tvs
109
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,
116                 fd <- cls_fds,
117                 let (xs,ys) = instFD fd cls_tvs tys
118               ]
119 \end{code}
120
121 \begin{code}
122 grow :: [PredType] -> TyVarSet -> TyVarSet
123 grow preds fixed_tvs 
124   | null preds = fixed_tvs
125   | otherwise  = loop fixed_tvs
126   where
127     loop fixed_tvs
128         | new_fixed_tvs `subVarSet` fixed_tvs = fixed_tvs
129         | otherwise                           = loop new_fixed_tvs
130         where
131           new_fixed_tvs = foldl extend fixed_tvs pred_sets
132
133     extend fixed_tvs pred_tvs 
134         | fixed_tvs `intersectsVarSet` pred_tvs = fixed_tvs `unionVarSet` pred_tvs
135         | otherwise                             = fixed_tvs
136
137     pred_sets = [tyVarsOfPred pred | pred <- preds]
138 \end{code}
139     
140 %************************************************************************
141 %*                                                                      *
142 \subsection{Generate equations from functional dependencies}
143 %*                                                                      *
144 %************************************************************************
145
146
147 \begin{code}
148 ----------
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
153
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
161
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.
164 --
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.
169
170 pprEquationDoc (eqn, doc) = vcat [pprEquation eqn, nest 2 doc]
171
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])]
175
176 ----------
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)
182
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).
189 \end{code}
190
191 Given a bunch of predicates that must hold, such as
192
193         C Int t1, C Int t2, C Bool t3, ?x::t4, ?x::t5
194
195 improve figures out what extra equations must hold.
196 For example, if we have
197
198         class C a b | a->b where ...
199
200 then improve will return
201
202         [(t1,t2), (t4,t5)]
203
204 NOTA BENE:
205
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
209         C t1 t7, C t2 t8
210     If t1=t2, we also get t7=t8.
211
212     improve does *not* do this extra step.  It relies on the caller
213     doing so.
214
215   * The equations unify types that are not already equal.  So there
216     is no effect iff the result of improve is empty
217
218
219
220 \begin{code}
221 improve inst_env preds
222   = [ eqn | group <- equivClassesByUniq (predTyUnique . fst) preds,
223             eqn   <- checkGroup inst_env group ]
224
225 ----------
226 checkGroup :: InstEnv Id -> [(PredType,SDoc)] -> [(Equation, SDoc)]
227   -- The preds are all for the same class or implicit param
228
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')]
233
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
239         -- we check whether
240         --      U l1[tys1/as] = U l2[tys2/as]
241         --  (where U is a unifier)
242         -- 
243         -- If so, we return the pair
244         --      U r1[tys1/as] = U l2[tys2/as]
245         --
246         -- We need to do something very similar comparing each predicate
247         -- with relevant instance decls
248     pairwise_eqns ++ instance_eqns
249
250   where
251     (cls_tvs, cls_fds) = classTvsFds cls
252     cls_inst_env       = inst_env cls
253
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)
259         | fd <- cls_fds,
260           p1@(ClassP _ tys1, _) : rest <- tails clss,
261           p2@(ClassP _ tys2, _) <- rest,
262           eqn <- checkClsFD emptyVarSet fd cls_tvs tys1 tys2
263         ]
264
265     instance_eqns :: [(Equation,SDoc)]
266     instance_eqns       -- This group comes from comparing with instance decls
267       = [ (eqn, mkEqnMsg p1 p2)
268         | fd <- cls_fds,
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
274         ]
275
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])]
280  
281 ----------
282 checkClsFD :: TyVarSet                  -- Quantified type variables; see note below
283            -> FunDep TyVar -> [TyVar]   -- One functional dependency from the class
284            -> [Type] -> [Type]
285            -> [Equation]
286
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 ..
292 --
293 -- and an Inst of form (C (Maybe t1) t2), 
294 -- then we will call checkClsFD with
295 --
296 --      qtvs = {x}, tys1 = [Maybe x,  Tree x]
297 --                  tys2 = [Maybe t1, t2]
298 --
299 -- We can instantiate x to t1, and then we want to force
300 --      (Tree x) [t1/x]  :=:   t2
301 --
302 -- This function is also used when matching two Insts (rather than an Inst
303 -- against an instance decl. In that case, qtvs is empty, and we are doing
304 -- an equality check
305 -- 
306 -- This function is also used by InstEnv.badFunDeps, which needs to *unify*
307 -- For the one-sided matching case, the qtvs are just from the template,
308 -- so we get matching
309 --
310   = ASSERT2( length tys1 == length tys2     && 
311              length tys1 == length clas_tvs 
312             , ppr tys1 <+> ppr tys2 )
313
314     case tcUnifyTys bind_fn ls1 ls2 of
315         Nothing  -> []
316         Just subst | isJust (tcUnifyTys bind_fn rs1' rs2') 
317                         -- Don't include any equations that already hold. 
318                         -- Reason: then we know if any actual improvement has happened,
319                         --         in which case we need to iterate the solver
320                         -- In making this check we must taking account of the fact that any 
321                         -- qtvs that aren't already instantiated can be instantiated to anything 
322                         -- at all
323                   -> []
324
325                   | otherwise   -- Aha!  A useful equation
326                   -> [ (qtvs', zip rs1' rs2')]
327                         -- We could avoid this substTy stuff by producing the eqn
328                         -- (qtvs, ls1++rs1, ls2++rs2)
329                         -- which will re-do the ls1/ls2 unification when the equation is
330                         -- executed.  What we're doing instead is recording the partial
331                         -- work of the ls1/ls2 unification leaving a smaller unification problem
332                   where
333                     rs1'  = substTys subst rs1 
334                     rs2'  = substTys subst rs2
335                     qtvs' = filterVarSet (`notElemTvSubst` subst) qtvs
336                         -- qtvs' are the quantified type variables
337                         -- that have not been substituted out
338                         --      
339                         -- Eg.  class C a b | a -> b
340                         --      instance C Int [y]
341                         -- Given constraint C Int z
342                         -- we generate the equation
343                         --      ({y}, [y], z)
344   where
345     bind_fn tv | tv `elemVarSet` qtvs = BindMe
346                | otherwise            = Skolem
347
348     (ls1, rs1) = instFD fd clas_tvs tys1
349     (ls2, rs2) = instFD fd clas_tvs tys2
350
351 instFD :: FunDep TyVar -> [TyVar] -> [Type] -> FunDep Type
352 instFD (ls,rs) tvs tys
353   = (map lookup ls, map lookup rs)
354   where
355     env       = zipVarEnv tvs tys
356     lookup tv = lookupVarEnv_NF env tv
357 \end{code}
358
359 \begin{code}
360 checkInstFDs :: ThetaType -> Class -> [Type] -> Bool
361 -- Check that functional dependencies are obeyed in an instance decl
362 -- For example, if we have 
363 --      class theta => C a b | a -> b
364 --      instance C t1 t2 
365 -- Then we require fv(t2) `subset` oclose(fv(t1), theta)
366
367 checkInstFDs theta clas inst_taus
368   = all fundep_ok fds
369   where
370     (tyvars, fds) = classTvsFds clas
371     fundep_ok fd  = tyVarsOfTypes rs `subVarSet` oclose theta (tyVarsOfTypes ls)
372                  where
373                    (ls,rs) = instFD fd tyvars inst_taus
374 \end{code}
375
376 %************************************************************************
377 %*                                                                      *
378 \subsection{Miscellaneous}
379 %*                                                                      *
380 %************************************************************************
381
382 \begin{code}
383 pprFundeps :: Outputable a => [FunDep a] -> SDoc
384 pprFundeps [] = empty
385 pprFundeps fds = hsep (ptext SLIT("|") : punctuate comma (map ppr_fd fds))
386
387 ppr_fd (us, vs) = hsep [interppSP us, ptext SLIT("->"), interppSP vs]
388 \end{code}