9102b682b3685b4efae8fafb823874f9ce4076d4
[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 Subst            ( mkSubst, emptyInScopeSet, substTy )
20 import TcType           ( Type, ThetaType, PredType(..), 
21                           predTyUnique, mkClassPred, tyVarsOfTypes, tyVarsOfPred,
22                           unifyTyListsX, unifyExtendTyListsX, tcEqType
23                         )
24 import VarSet
25 import VarEnv
26 import Outputable
27 import List             ( tails )
28 import Maybes           ( maybeToBool )
29 import ListSetOps       ( equivClassesByUniq )
30 \end{code}
31
32
33 %************************************************************************
34 %*                                                                      *
35 \subsection{Close type variables}
36 %*                                                                      *
37 %************************************************************************
38
39 (oclose preds tvs) closes the set of type variables tvs, 
40 wrt functional dependencies in preds.  The result is a superset
41 of the argument set.  For example, if we have
42         class C a b | a->b where ...
43 then
44         oclose [C (x,y) z, C (x,p) q] {x,y} = {x,y,z}
45 because if we know x and y then that fixes z.
46
47 Using oclose
48 ~~~~~~~~~~~~
49 oclose is used
50
51 a) When determining ambiguity.  The type
52         forall a,b. C a b => a
53 is not ambiguous (given the above class decl for C) because
54 a determines b.  
55
56 b) When generalising a type T.  Usually we take FV(T) \ FV(Env),
57 but in fact we need
58         FV(T) \ (FV(Env)+)
59 where the '+' is the oclosure operation.  Notice that we do not 
60 take FV(T)+.  This puzzled me for a bit.  Consider
61
62         f = E
63
64 and suppose e have that E :: C a b => a, and suppose that b is
65 free in the environment. Then we quantify over 'a' only, giving
66 the type forall a. C a b => a.  Since a->b but we don't have b->a,
67 we might have instance decls like
68         instance C Bool Int where ...
69         instance C Char Int where ...
70 so knowing that b=Int doesn't fix 'a'; so we quantify over it.
71
72                 ---------------
73                 A WORRY: ToDo!
74                 ---------------
75 If we have      class C a b => D a b where ....
76                 class D a b | a -> b where ...
77 and the preds are [C (x,y) z], then we want to see the fd in D,
78 even though it is not explicit in C, giving [({x,y},{z})]
79
80 Similarly for instance decls?  E.g. Suppose we have
81         instance C a b => Eq (T a b) where ...
82 and we infer a type t with constraints Eq (T a b) for a particular
83 expression, and suppose that 'a' is free in the environment.  
84 We could generalise to
85         forall b. Eq (T a b) => t
86 but if we reduced the constraint, to C a b, we'd see that 'a' determines
87 b, so that a better type might be
88         t (with free constraint C a b) 
89 Perhaps it doesn't matter, because we'll still force b to be a
90 particular type at the call sites.  Generalising over too many
91 variables (provided we don't shadow anything by quantifying over a
92 variable that is actually free in the envt) may postpone errors; it
93 won't hide them altogether.
94
95
96 \begin{code}
97 oclose :: [PredType] -> TyVarSet -> TyVarSet
98 oclose preds fixed_tvs
99   | null tv_fds = fixed_tvs     -- Fast escape hatch for common case
100   | otherwise   = loop fixed_tvs
101   where
102     loop fixed_tvs
103         | new_fixed_tvs `subVarSet` fixed_tvs = fixed_tvs
104         | otherwise                           = loop new_fixed_tvs
105         where
106           new_fixed_tvs = foldl extend fixed_tvs tv_fds
107
108     extend fixed_tvs (ls,rs) | ls `subVarSet` fixed_tvs = fixed_tvs `unionVarSet` rs
109                              | otherwise                = fixed_tvs
110
111     tv_fds  :: [(TyVarSet,TyVarSet)]
112         -- In our example, tv_fds will be [ ({x,y}, {z}), ({x,p},{q}) ]
113         -- Meaning "knowing x,y fixes z, knowing x,p fixes q"
114     tv_fds  = [ (tyVarsOfTypes xs, tyVarsOfTypes ys)
115               | ClassP cls tys <- preds,                -- Ignore implicit params
116                 let (cls_tvs, cls_fds) = classTvsFds cls,
117                 fd <- cls_fds,
118                 let (xs,ys) = instFD fd cls_tvs tys
119               ]
120 \end{code}
121
122 \begin{code}
123 grow :: [PredType] -> TyVarSet -> TyVarSet
124 grow preds fixed_tvs 
125   | null preds = fixed_tvs
126   | otherwise  = loop fixed_tvs
127   where
128     loop fixed_tvs
129         | new_fixed_tvs `subVarSet` fixed_tvs = fixed_tvs
130         | otherwise                           = loop new_fixed_tvs
131         where
132           new_fixed_tvs = foldl extend fixed_tvs pred_sets
133
134     extend fixed_tvs pred_tvs 
135         | fixed_tvs `intersectsVarSet` pred_tvs = fixed_tvs `unionVarSet` pred_tvs
136         | otherwise                             = fixed_tvs
137
138     pred_sets = [tyVarsOfPred pred | pred <- preds]
139 \end{code}
140     
141 %************************************************************************
142 %*                                                                      *
143 \subsection{Generate equations from functional dependencies}
144 %*                                                                      *
145 %************************************************************************
146
147
148 \begin{code}
149 ----------
150 type Equation = (TyVarSet, [(Type, Type)])
151 -- These pairs of types should be equal, for some
152 -- substitution of the tyvars in the tyvar set
153 -- INVARIANT: corresponding types aren't already equal
154
155 -- It's important that we have a *list* of pairs of types.  Consider
156 --      class C a b c | a -> b c where ...
157 --      instance C Int x x where ...
158 -- Then, given the constraint (C Int Bool v) we should improve v to Bool,
159 -- via the equation ({x}, [(Bool,x), (v,x)])
160 -- This would not happen if the class had looked like
161 --      class C a b c | a -> b, a -> c
162
163 -- To "execute" the equation, make fresh type variable for each tyvar in the set,
164 -- instantiate the two types with these fresh variables, and then unify.
165 --
166 -- For example, ({a,b}, (a,Int,b), (Int,z,Bool))
167 -- We unify z with Int, but since a and b are quantified we do nothing to them
168 -- We usually act on an equation by instantiating the quantified type varaibles
169 -- to fresh type variables, and then calling the standard unifier.
170
171 pprEquationDoc (eqn, doc) = vcat [pprEquation eqn, nest 2 doc]
172
173 pprEquation (qtvs, pairs) 
174   = vcat [ptext SLIT("forall") <+> braces (pprWithCommas ppr (varSetElems qtvs)),
175           nest 2 (vcat [ ppr t1 <+> ptext SLIT(":=:") <+> ppr t2 | (t1,t2) <- pairs])]
176
177 ----------
178 improve :: InstEnv Id           -- Gives instances for given class
179         -> [(PredType,SDoc)]    -- Current constraints; doc says where they come from
180         -> [(Equation,SDoc)]    -- Derived equalities that must also hold
181                                 -- (NB the above INVARIANT for type Equation)
182                                 -- The SDoc explains why the equation holds (for error messages)
183
184 type InstEnv a = Class -> [(TyVarSet, [Type], a)]
185 -- This is a bit clumsy, because InstEnv is really
186 -- defined in module InstEnv.  However, we don't want
187 -- to define it here because InstEnv
188 -- is their home.  Nor do we want to make a recursive
189 -- module group (InstEnv imports stuff from FunDeps).
190 \end{code}
191
192 Given a bunch of predicates that must hold, such as
193
194         C Int t1, C Int t2, C Bool t3, ?x::t4, ?x::t5
195
196 improve figures out what extra equations must hold.
197 For example, if we have
198
199         class C a b | a->b where ...
200
201 then improve will return
202
203         [(t1,t2), (t4,t5)]
204
205 NOTA BENE:
206
207   * improve does not iterate.  It's possible that when we make
208     t1=t2, for example, that will in turn trigger a new equation.
209     This would happen if we also had
210         C t1 t7, C t2 t8
211     If t1=t2, we also get t7=t8.
212
213     improve does *not* do this extra step.  It relies on the caller
214     doing so.
215
216   * The equations unify types that are not already equal.  So there
217     is no effect iff the result of improve is empty
218
219
220
221 \begin{code}
222 improve inst_env preds
223   = [ eqn | group <- equivClassesByUniq (predTyUnique . fst) preds,
224             eqn   <- checkGroup inst_env group ]
225
226 ----------
227 checkGroup :: InstEnv Id -> [(PredType,SDoc)] -> [(Equation, SDoc)]
228   -- The preds are all for the same class or implicit param
229
230 checkGroup inst_env (p1@(IParam _ ty, _) : ips)
231   =     -- For implicit parameters, all the types must match
232     [ ((emptyVarSet, [(ty,ty')]), mkEqnMsg p1 p2) 
233     | p2@(IParam _ ty', _) <- ips, not (ty `tcEqType` ty')]
234
235 checkGroup inst_env clss@((ClassP cls _, _) : _)
236   =     -- For classes life is more complicated  
237         -- Suppose the class is like
238         --      classs C as | (l1 -> r1), (l2 -> r2), ... where ...
239         -- Then FOR EACH PAIR (ClassP c tys1, ClassP c tys2) in the list clss
240         -- we check whether
241         --      U l1[tys1/as] = U l2[tys2/as]
242         --  (where U is a unifier)
243         -- 
244         -- If so, we return the pair
245         --      U r1[tys1/as] = U l2[tys2/as]
246         --
247         -- We need to do something very similar comparing each predicate
248         -- with relevant instance decls
249     pairwise_eqns ++ instance_eqns
250
251   where
252     (cls_tvs, cls_fds) = classTvsFds cls
253     cls_inst_env       = inst_env cls
254
255         -- NOTE that we iterate over the fds first; they are typically
256         -- empty, which aborts the rest of the loop.
257     pairwise_eqns :: [(Equation,SDoc)]
258     pairwise_eqns       -- This group comes from pairwise comparison
259       = [ (eqn, mkEqnMsg p1 p2)
260         | fd <- cls_fds,
261           p1@(ClassP _ tys1, _) : rest <- tails clss,
262           p2@(ClassP _ tys2, _) <- rest,
263           eqn <- checkClsFD emptyVarSet fd cls_tvs tys1 tys2
264         ]
265
266     instance_eqns :: [(Equation,SDoc)]
267     instance_eqns       -- This group comes from comparing with instance decls
268       = [ (eqn, mkEqnMsg p1 p2)
269         | fd <- cls_fds,
270           (qtvs, tys1, dfun_id)  <- cls_inst_env,
271           let p1 = (mkClassPred cls tys1, 
272                     ptext SLIT("arising from the instance declaration at") <+> ppr (getSrcLoc dfun_id)),
273           p2@(ClassP _ tys2, _) <- clss,
274           eqn <- checkClsFD qtvs fd cls_tvs tys1 tys2
275         ]
276
277 mkEqnMsg (pred1,from1) (pred2,from2)
278   = vcat [ptext SLIT("When using functional dependencies to combine"),
279           nest 2 (sep [ppr pred1 <> comma, nest 2 from1]), 
280           nest 2 (sep [ppr pred2 <> comma, nest 2 from2])]
281  
282 ----------
283 checkClsFD :: TyVarSet                  -- Quantified type variables; see note below
284            -> FunDep TyVar -> [TyVar]   -- One functional dependency from the class
285            -> [Type] -> [Type]
286            -> [Equation]
287
288 checkClsFD qtvs fd clas_tvs tys1 tys2
289 -- 'qtvs' are the quantified type variables, the ones which an be instantiated 
290 -- to make the types match.  For example, given
291 --      class C a b | a->b where ...
292 --      instance C (Maybe x) (Tree x) where ..
293 --
294 -- and an Inst of form (C (Maybe t1) t2), 
295 -- then we will call checkClsFD with
296 --
297 --      qtvs = {x}, tys1 = [Maybe x,  Tree x]
298 --                  tys2 = [Maybe t1, t2]
299 --
300 -- We can instantiate x to t1, and then we want to force
301 --      (Tree x) [t1/x]  :=:   t2
302
303 -- We use 'unify' even though we are often only matching
304 -- unifyTyListsX will only bind variables in qtvs, so it's OK!
305   = case unifyTyListsX qtvs ls1 ls2 of
306         Nothing   -> []
307         Just unif | maybeToBool (unifyExtendTyListsX qtvs unif rs1 rs2)
308                         -- Don't include any equations that already hold. 
309                         -- Reason: then we know if any actual improvement has happened,
310                         --         in which case we need to iterate the solver
311                         -- In making this check we must taking account of the fact that any 
312                         -- qtvs that aren't already instantiated can be instantiated to anything 
313                         -- at all
314                         -- NB: qtvs, not qtvs' because unifyExtendTyListsX only tries to
315                         --     look template tyvars up in the substitution
316                   -> []
317
318                   | otherwise   -- Aha!  A useful equation
319                   -> [ (qtvs', map (substTy full_unif) rs1 `zip` map (substTy full_unif) rs2)]
320                         -- We could avoid this substTy stuff by producing the eqn
321                         -- (qtvs, ls1++rs1, ls2++rs2)
322                         -- which will re-do the ls1/ls2 unification when the equation is
323                         -- executed.  What we're doing instead is recording the partial
324                         -- work of the ls1/ls2 unification leaving a smaller unification problem
325                   where
326                     full_unif = mkSubst emptyInScopeSet unif
327                         -- No for-alls in sight; hmm
328
329                     qtvs' = filterVarSet (\v -> not (v `elemSubstEnv` unif)) qtvs
330                         -- qtvs' are the quantified type variables
331                         -- that have not been substituted out
332                         --      
333                         -- Eg.  class C a b | a -> b
334                         --      instance C Int [y]
335                         -- Given constraint C Int z
336                         -- we generate the equation
337                         --      ({y}, [y], z)
338   where
339     (ls1, rs1) = instFD fd clas_tvs tys1
340     (ls2, rs2) = instFD fd clas_tvs tys2
341
342 instFD :: FunDep TyVar -> [TyVar] -> [Type] -> FunDep Type
343 instFD (ls,rs) tvs tys
344   = (map lookup ls, map lookup rs)
345   where
346     env       = zipVarEnv tvs tys
347     lookup tv = lookupVarEnv_NF env tv
348 \end{code}
349
350 \begin{code}
351 checkInstFDs :: ThetaType -> Class -> [Type] -> Bool
352 -- Check that functional dependencies are obeyed in an instance decl
353 -- For example, if we have 
354 --      class theta => C a b | a -> b
355 --      instance C t1 t2 
356 -- Then we require fv(t2) `subset` oclose(fv(t1), theta)
357
358 checkInstFDs theta clas inst_taus
359   = all fundep_ok fds
360   where
361     (tyvars, fds) = classTvsFds clas
362     fundep_ok fd  = tyVarsOfTypes rs `subVarSet` oclose theta (tyVarsOfTypes ls)
363                  where
364                    (ls,rs) = instFD fd tyvars inst_taus
365 \end{code}
366
367 %************************************************************************
368 %*                                                                      *
369 \subsection{Miscellaneous}
370 %*                                                                      *
371 %************************************************************************
372
373 \begin{code}
374 pprFundeps :: Outputable a => [FunDep a] -> SDoc
375 pprFundeps [] = empty
376 pprFundeps fds = hsep (ptext SLIT("|") : punctuate comma (map ppr_fd fds))
377
378 ppr_fd (us, vs) = hsep [interppSP us, ptext SLIT("->"), interppSP vs]
379 \end{code}