Remove dead code from FunDeps
[ghc-hetmet.git] / compiler / types / FunDeps.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 2000
4 %
5
6 FunDeps - functional dependencies
7
8 It's better to read it as: "if we know these, then we're going to know these"
9
10 \begin{code}
11 module FunDeps (
12         Equation, pprEquation,
13         oclose, grow, improveOne,
14         checkInstCoverage, checkFunDeps,
15         pprFundeps
16     ) where
17
18 #include "HsVersions.h"
19
20 import Name
21 import Var
22 import Class
23 import TcGadt
24 import TcType
25 import InstEnv
26 import VarSet
27 import VarEnv
28 import Outputable
29 import Util
30 import Data.Maybe       ( isJust )
31 \end{code}
32
33
34 %************************************************************************
35 %*                                                                      *
36 \subsection{Close type variables}
37 %*                                                                      *
38 %************************************************************************
39
40 (oclose preds tvs) closes the set of type variables tvs, 
41 wrt functional dependencies in preds.  The result is a superset
42 of the argument set.  For example, if we have
43         class C a b | a->b where ...
44 then
45         oclose [C (x,y) z, C (x,p) q] {x,y} = {x,y,z}
46 because if we know x and y then that fixes z.
47
48 Using oclose
49 ~~~~~~~~~~~~
50 oclose is used
51
52 a) When determining ambiguity.  The type
53         forall a,b. C a b => a
54 is not ambiguous (given the above class decl for C) because
55 a determines b.  
56
57 b) When generalising a type T.  Usually we take FV(T) \ FV(Env),
58 but in fact we need
59         FV(T) \ (FV(Env)+)
60 where the '+' is the oclosure operation.  Notice that we do not 
61 take FV(T)+.  This puzzled me for a bit.  Consider
62
63         f = E
64
65 and suppose e have that E :: C a b => a, and suppose that b is
66 free in the environment. Then we quantify over 'a' only, giving
67 the type forall a. C a b => a.  Since a->b but we don't have b->a,
68 we might have instance decls like
69         instance C Bool Int where ...
70         instance C Char Int where ...
71 so knowing that b=Int doesn't fix 'a'; so we quantify over it.
72
73                 ---------------
74                 A WORRY: ToDo!
75                 ---------------
76 If we have      class C a b => D a b where ....
77                 class D a b | a -> b where ...
78 and the preds are [C (x,y) z], then we want to see the fd in D,
79 even though it is not explicit in C, giving [({x,y},{z})]
80
81 Similarly for instance decls?  E.g. Suppose we have
82         instance C a b => Eq (T a b) where ...
83 and we infer a type t with constraints Eq (T a b) for a particular
84 expression, and suppose that 'a' is free in the environment.  
85 We could generalise to
86         forall b. Eq (T a b) => t
87 but if we reduced the constraint, to C a b, we'd see that 'a' determines
88 b, so that a better type might be
89         t (with free constraint C a b) 
90 Perhaps it doesn't matter, because we'll still force b to be a
91 particular type at the call sites.  Generalising over too many
92 variables (provided we don't shadow anything by quantifying over a
93 variable that is actually free in the envt) may postpone errors; it
94 won't hide them altogether.
95
96
97 \begin{code}
98 oclose :: [PredType] -> TyVarSet -> TyVarSet
99 oclose preds fixed_tvs
100   | null tv_fds = fixed_tvs     -- Fast escape hatch for common case
101   | otherwise   = loop fixed_tvs
102   where
103     loop fixed_tvs
104         | new_fixed_tvs `subVarSet` fixed_tvs = fixed_tvs
105         | otherwise                           = loop new_fixed_tvs
106         where
107           new_fixed_tvs = foldl extend fixed_tvs tv_fds
108
109     extend fixed_tvs (ls,rs) | ls `subVarSet` fixed_tvs = fixed_tvs `unionVarSet` rs
110                              | otherwise                = fixed_tvs
111
112     tv_fds  :: [(TyVarSet,TyVarSet)]
113         -- In our example, tv_fds will be [ ({x,y}, {z}), ({x,p},{q}) ]
114         -- Meaning "knowing x,y fixes z, knowing x,p fixes q"
115     tv_fds  = [ (tyVarsOfTypes xs, tyVarsOfTypes ys)
116               | ClassP cls tys <- preds,                -- Ignore implicit params
117                 let (cls_tvs, cls_fds) = classTvsFds cls,
118                 fd <- cls_fds,
119                 let (xs,ys) = instFD fd cls_tvs tys
120               ]
121 \end{code}
122
123 Note [Growing the tau-tvs using constraints]
124 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
125 (grow preds tvs) is the result of extend the set of tyvars tvs
126                  using all conceivable links from pred
127
128 E.g. tvs = {a}, preds = {H [a] b, K (b,Int) c, Eq e}
129 Then grow precs tvs = {a,b,c}
130
131 All the type variables from an implicit parameter are added, whether or
132 not they are mentioned in tvs; see Note [Implicit parameters and ambiguity] 
133 in TcSimplify.
134
135 See also Note [Ambiguity] in TcSimplify
136
137 \begin{code}
138 grow :: [PredType] -> TyVarSet -> TyVarSet
139 grow preds fixed_tvs 
140   | null preds = real_fixed_tvs
141   | otherwise  = loop real_fixed_tvs
142   where
143         -- Add the implicit parameters; 
144         -- see Note [Implicit parameters and ambiguity] in TcSimplify
145     real_fixed_tvs = foldr unionVarSet fixed_tvs ip_tvs
146  
147     loop fixed_tvs
148         | new_fixed_tvs `subVarSet` fixed_tvs = fixed_tvs
149         | otherwise                           = loop new_fixed_tvs
150         where
151           new_fixed_tvs = foldl extend fixed_tvs non_ip_tvs
152
153     extend fixed_tvs pred_tvs 
154         | fixed_tvs `intersectsVarSet` pred_tvs = fixed_tvs `unionVarSet` pred_tvs
155         | otherwise                             = fixed_tvs
156
157     (ip_tvs, non_ip_tvs) = partitionWith get_ip preds
158     get_ip (IParam _ ty) = Left (tyVarsOfType ty)
159     get_ip other         = Right (tyVarsOfPred other)
160 \end{code}
161     
162 %************************************************************************
163 %*                                                                      *
164 \subsection{Generate equations from functional dependencies}
165 %*                                                                      *
166 %************************************************************************
167
168
169 \begin{code}
170 type Equation = (TyVarSet, [(Type, Type)])
171 -- These pairs of types should be equal, for some
172 -- substitution of the tyvars in the tyvar set
173 -- INVARIANT: corresponding types aren't already equal
174
175 -- It's important that we have a *list* of pairs of types.  Consider
176 --      class C a b c | a -> b c where ...
177 --      instance C Int x x where ...
178 -- Then, given the constraint (C Int Bool v) we should improve v to Bool,
179 -- via the equation ({x}, [(Bool,x), (v,x)])
180 -- This would not happen if the class had looked like
181 --      class C a b c | a -> b, a -> c
182
183 -- To "execute" the equation, make fresh type variable for each tyvar in the set,
184 -- instantiate the two types with these fresh variables, and then unify.
185 --
186 -- For example, ({a,b}, (a,Int,b), (Int,z,Bool))
187 -- We unify z with Int, but since a and b are quantified we do nothing to them
188 -- We usually act on an equation by instantiating the quantified type varaibles
189 -- to fresh type variables, and then calling the standard unifier.
190
191 pprEquation (qtvs, pairs) 
192   = vcat [ptext SLIT("forall") <+> braces (pprWithCommas ppr (varSetElems qtvs)),
193           nest 2 (vcat [ ppr t1 <+> ptext SLIT(":=:") <+> ppr t2 | (t1,t2) <- pairs])]
194 \end{code}
195
196 Given a bunch of predicates that must hold, such as
197
198         C Int t1, C Int t2, C Bool t3, ?x::t4, ?x::t5
199
200 improve figures out what extra equations must hold.
201 For example, if we have
202
203         class C a b | a->b where ...
204
205 then improve will return
206
207         [(t1,t2), (t4,t5)]
208
209 NOTA BENE:
210
211   * improve does not iterate.  It's possible that when we make
212     t1=t2, for example, that will in turn trigger a new equation.
213     This would happen if we also had
214         C t1 t7, C t2 t8
215     If t1=t2, we also get t7=t8.
216
217     improve does *not* do this extra step.  It relies on the caller
218     doing so.
219
220   * The equations unify types that are not already equal.  So there
221     is no effect iff the result of improve is empty
222
223
224
225 \begin{code}
226 type Pred_Loc = (PredType, SDoc)        -- SDoc says where the Pred comes from
227
228 improveOne :: (Class -> [Instance])             -- Gives instances for given class
229            -> Pred_Loc                          -- Do improvement triggered by this
230            -> [Pred_Loc]                        -- Current constraints 
231            -> [(Equation,Pred_Loc,Pred_Loc)]    -- Derived equalities that must also hold
232                                                 -- (NB the above INVARIANT for type Equation)
233                                                 -- The Pred_Locs explain which two predicates were
234                                                 -- combined (for error messages)
235 -- Just do improvement triggered by a single, distinguised predicate
236
237 improveOne inst_env pred@(IParam ip ty, _) preds
238   = [ ((emptyVarSet, [(ty,ty2)]), pred, p2) 
239     | p2@(IParam ip2 ty2, _) <- preds
240     , ip==ip2
241     , not (ty `tcEqType` ty2)]
242
243 improveOne inst_env pred@(ClassP cls tys, _) preds
244   | tys `lengthAtLeast` 2
245   = instance_eqns ++ pairwise_eqns
246         -- NB: we put the instance equations first.   This biases the 
247         -- order so that we first improve individual constraints against the
248         -- instances (which are perhaps in a library and less likely to be
249         -- wrong; and THEN perform the pairwise checks.
250         -- The other way round, it's possible for the pairwise check to succeed
251         -- and cause a subsequent, misleading failure of one of the pair with an
252         -- instance declaration.  See tcfail143.hs for an example
253   where
254     (cls_tvs, cls_fds) = classTvsFds cls
255     instances          = inst_env cls
256     rough_tcs          = roughMatchTcs tys
257
258         -- NOTE that we iterate over the fds first; they are typically
259         -- empty, which aborts the rest of the loop.
260     pairwise_eqns :: [(Equation,Pred_Loc,Pred_Loc)]
261     pairwise_eqns       -- This group comes from pairwise comparison
262       = [ (eqn, pred, p2)
263         | fd <- cls_fds
264         , p2@(ClassP cls2 tys2, _) <- preds
265         , cls == cls2
266         , eqn <- checkClsFD emptyVarSet fd cls_tvs tys tys2
267         ]
268
269     instance_eqns :: [(Equation,Pred_Loc,Pred_Loc)]
270     instance_eqns       -- This group comes from comparing with instance decls
271       = [ (eqn, p_inst, pred)
272         | fd <- cls_fds         -- Iterate through the fundeps first, 
273                                 -- because there often are none!
274         , let rough_fd_tcs = trimRoughMatchTcs cls_tvs fd rough_tcs
275         , ispec@(Instance { is_tvs = qtvs, is_tys = tys_inst, 
276                             is_tcs = mb_tcs_inst }) <- instances
277         , not (instanceCantMatch mb_tcs_inst rough_fd_tcs)
278         , eqn <- checkClsFD qtvs fd cls_tvs tys_inst tys
279         , let p_inst = (mkClassPred cls tys_inst, 
280                         ptext SLIT("arising from the instance declaration at")
281                         <+> ppr (getSrcLoc ispec))
282         ]
283
284 improveOne inst_env eq_pred preds
285   = []
286
287
288 checkClsFD :: TyVarSet                  -- Quantified type variables; see note below
289            -> FunDep TyVar -> [TyVar]   -- One functional dependency from the class
290            -> [Type] -> [Type]
291            -> [Equation]
292
293 checkClsFD qtvs fd clas_tvs tys1 tys2
294 -- 'qtvs' are the quantified type variables, the ones which an be instantiated 
295 -- to make the types match.  For example, given
296 --      class C a b | a->b where ...
297 --      instance C (Maybe x) (Tree x) where ..
298 --
299 -- and an Inst of form (C (Maybe t1) t2), 
300 -- then we will call checkClsFD with
301 --
302 --      qtvs = {x}, tys1 = [Maybe x,  Tree x]
303 --                  tys2 = [Maybe t1, t2]
304 --
305 -- We can instantiate x to t1, and then we want to force
306 --      (Tree x) [t1/x]  :=:   t2
307 --
308 -- This function is also used when matching two Insts (rather than an Inst
309 -- against an instance decl. In that case, qtvs is empty, and we are doing
310 -- an equality check
311 -- 
312 -- This function is also used by InstEnv.badFunDeps, which needs to *unify*
313 -- For the one-sided matching case, the qtvs are just from the template,
314 -- so we get matching
315 --
316   = ASSERT2( length tys1 == length tys2     && 
317              length tys1 == length clas_tvs 
318             , ppr tys1 <+> ppr tys2 )
319
320     case tcUnifyTys bind_fn ls1 ls2 of
321         Nothing  -> []
322         Just subst | isJust (tcUnifyTys bind_fn rs1' rs2') 
323                         -- Don't include any equations that already hold. 
324                         -- Reason: then we know if any actual improvement has happened,
325                         --         in which case we need to iterate the solver
326                         -- In making this check we must taking account of the fact that any 
327                         -- qtvs that aren't already instantiated can be instantiated to anything 
328                         -- at all
329                   -> []
330
331                   | otherwise   -- Aha!  A useful equation
332                   -> [ (qtvs', zip rs1' rs2')]
333                         -- We could avoid this substTy stuff by producing the eqn
334                         -- (qtvs, ls1++rs1, ls2++rs2)
335                         -- which will re-do the ls1/ls2 unification when the equation is
336                         -- executed.  What we're doing instead is recording the partial
337                         -- work of the ls1/ls2 unification leaving a smaller unification problem
338                   where
339                     rs1'  = substTys subst rs1 
340                     rs2'  = substTys subst rs2
341                     qtvs' = filterVarSet (`notElemTvSubst` subst) qtvs
342                         -- qtvs' are the quantified type variables
343                         -- that have not been substituted out
344                         --      
345                         -- Eg.  class C a b | a -> b
346                         --      instance C Int [y]
347                         -- Given constraint C Int z
348                         -- we generate the equation
349                         --      ({y}, [y], z)
350   where
351     bind_fn tv | tv `elemVarSet` qtvs = BindMe
352                | otherwise            = Skolem
353
354     (ls1, rs1) = instFD fd clas_tvs tys1
355     (ls2, rs2) = instFD fd clas_tvs tys2
356
357 instFD :: FunDep TyVar -> [TyVar] -> [Type] -> FunDep Type
358 instFD (ls,rs) tvs tys
359   = (map lookup ls, map lookup rs)
360   where
361     env       = zipVarEnv tvs tys
362     lookup tv = lookupVarEnv_NF env tv
363 \end{code}
364
365 \begin{code}
366 checkInstCoverage :: Class -> [Type] -> Bool
367 -- Check that the Coverage Condition is obeyed in an instance decl
368 -- For example, if we have 
369 --      class theta => C a b | a -> b
370 --      instance C t1 t2 
371 -- Then we require fv(t2) `subset` fv(t1)
372 -- See Note [Coverage Condition] below
373
374 checkInstCoverage clas inst_taus
375   = all fundep_ok fds
376   where
377     (tyvars, fds) = classTvsFds clas
378     fundep_ok fd  = tyVarsOfTypes rs `subVarSet` tyVarsOfTypes ls
379                  where
380                    (ls,rs) = instFD fd tyvars inst_taus
381 \end{code}
382
383 Note [Coverage condition]
384 ~~~~~~~~~~~~~~~~~~~~~~~~~
385 For the coverage condition, we used to require only that 
386         fv(t2) `subset` oclose(fv(t1), theta)
387
388 Example:
389         class Mul a b c | a b -> c where
390                 (.*.) :: a -> b -> c
391
392         instance Mul Int Int Int where (.*.) = (*)
393         instance Mul Int Float Float where x .*. y = fromIntegral x * y
394         instance Mul a b c => Mul a [b] [c] where x .*. v = map (x.*.) v
395
396 In the third instance, it's not the case that fv([c]) `subset` fv(a,[b]).
397 But it is the case that fv([c]) `subset` oclose( theta, fv(a,[b]) )
398
399 But it is a mistake to accept the instance because then this defn:
400         f = \ b x y -> if b then x .*. [y] else y
401 makes instance inference go into a loop, because it requires the constraint
402         Mul a [b] b
403
404
405 %************************************************************************
406 %*                                                                      *
407         Check that a new instance decl is OK wrt fundeps
408 %*                                                                      *
409 %************************************************************************
410
411 Here is the bad case:
412         class C a b | a->b where ...
413         instance C Int Bool where ...
414         instance C Int Char where ...
415
416 The point is that a->b, so Int in the first parameter must uniquely
417 determine the second.  In general, given the same class decl, and given
418
419         instance C s1 s2 where ...
420         instance C t1 t2 where ...
421
422 Then the criterion is: if U=unify(s1,t1) then U(s2) = U(t2).
423
424 Matters are a little more complicated if there are free variables in
425 the s2/t2.  
426
427         class D a b c | a -> b
428         instance D a b => D [(a,a)] [b] Int
429         instance D a b => D [a]     [b] Bool
430
431 The instance decls don't overlap, because the third parameter keeps
432 them separate.  But we want to make sure that given any constraint
433         D s1 s2 s3
434 if s1 matches 
435
436
437 \begin{code}
438 checkFunDeps :: (InstEnv, InstEnv) -> Instance
439              -> Maybe [Instance]        -- Nothing  <=> ok
440                                         -- Just dfs <=> conflict with dfs
441 -- Check wheher adding DFunId would break functional-dependency constraints
442 -- Used only for instance decls defined in the module being compiled
443 checkFunDeps inst_envs ispec
444   | null bad_fundeps = Nothing
445   | otherwise        = Just bad_fundeps
446   where
447     (ins_tvs, _, clas, ins_tys) = instanceHead ispec
448     ins_tv_set   = mkVarSet ins_tvs
449     cls_inst_env = classInstances inst_envs clas
450     bad_fundeps  = badFunDeps cls_inst_env clas ins_tv_set ins_tys
451
452 badFunDeps :: [Instance] -> Class
453            -> TyVarSet -> [Type]        -- Proposed new instance type
454            -> [Instance]
455 badFunDeps cls_insts clas ins_tv_set ins_tys 
456   = [ ispec | fd <- fds,        -- fds is often empty
457               let trimmed_tcs = trimRoughMatchTcs clas_tvs fd rough_tcs,
458               ispec@(Instance { is_tcs = mb_tcs, is_tvs = tvs, 
459                                 is_tys = tys }) <- cls_insts,
460                 -- Filter out ones that can't possibly match, 
461                 -- based on the head of the fundep
462               not (instanceCantMatch trimmed_tcs mb_tcs),       
463               notNull (checkClsFD (tvs `unionVarSet` ins_tv_set) 
464                                    fd clas_tvs tys ins_tys)
465     ]
466   where
467     (clas_tvs, fds) = classTvsFds clas
468     rough_tcs = roughMatchTcs ins_tys
469
470 trimRoughMatchTcs :: [TyVar] -> FunDep TyVar -> [Maybe Name] -> [Maybe Name]
471 -- Computing rough_tcs for a particular fundep
472 --      class C a b c | a c -> b where ... 
473 -- For each instance .... => C ta tb tc
474 -- we want to match only on the types ta, tb; so our
475 -- rough-match thing must similarly be filtered.  
476 -- Hence, we Nothing-ise the tb type right here
477 trimRoughMatchTcs clas_tvs (ltvs,_) mb_tcs
478   = zipWith select clas_tvs mb_tcs
479   where
480     select clas_tv mb_tc | clas_tv `elem` ltvs = mb_tc
481                          | otherwise           = Nothing
482 \end{code}
483
484
485