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