1534dc66f18da9be3eb2aa4cee65cd6a43e97aab
[ghc-hetmet.git] / 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,
11         oclose, grow, improve, 
12         checkInstCoverage, checkFunDeps,
13         pprFundeps
14     ) where
15
16 #include "HsVersions.h"
17
18 import Name             ( Name, getSrcLoc )
19 import Var              ( TyVar )
20 import Class            ( Class, FunDep, pprFundeps, classTvsFds )
21 import TcGadt           ( tcUnifyTys, BindFlag(..) )
22 import Type             ( substTys, notElemTvSubst )
23 import TcType           ( Type, PredType(..), tcEqType, 
24                           predTyUnique, mkClassPred, tyVarsOfTypes, tyVarsOfPred )
25 import InstEnv          ( Instance(..), InstEnv, instanceHead, classInstances,
26                           instanceCantMatch, roughMatchTcs )
27 import VarSet
28 import VarEnv
29 import Outputable
30 import Util             ( notNull )
31 import List             ( tails )
32 import Maybe            ( isJust )
33 import ListSetOps       ( equivClassesByUniq )
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 \begin{code}
127 grow :: [PredType] -> TyVarSet -> TyVarSet
128 -- See Note [Ambiguity] in TcSimplify
129 grow preds fixed_tvs 
130   | null preds = fixed_tvs
131   | otherwise  = loop fixed_tvs
132   where
133     loop fixed_tvs
134         | new_fixed_tvs `subVarSet` fixed_tvs = fixed_tvs
135         | otherwise                           = loop new_fixed_tvs
136         where
137           new_fixed_tvs = foldl extend fixed_tvs pred_sets
138
139     extend fixed_tvs pred_tvs 
140         | fixed_tvs `intersectsVarSet` pred_tvs = fixed_tvs `unionVarSet` pred_tvs
141         | otherwise                             = fixed_tvs
142
143     pred_sets = [tyVarsOfPred pred | pred <- preds]
144 \end{code}
145     
146 %************************************************************************
147 %*                                                                      *
148 \subsection{Generate equations from functional dependencies}
149 %*                                                                      *
150 %************************************************************************
151
152
153 \begin{code}
154 ----------
155 type Equation = (TyVarSet, [(Type, Type)])
156 -- These pairs of types should be equal, for some
157 -- substitution of the tyvars in the tyvar set
158 -- INVARIANT: corresponding types aren't already equal
159
160 -- It's important that we have a *list* of pairs of types.  Consider
161 --      class C a b c | a -> b c where ...
162 --      instance C Int x x where ...
163 -- Then, given the constraint (C Int Bool v) we should improve v to Bool,
164 -- via the equation ({x}, [(Bool,x), (v,x)])
165 -- This would not happen if the class had looked like
166 --      class C a b c | a -> b, a -> c
167
168 -- To "execute" the equation, make fresh type variable for each tyvar in the set,
169 -- instantiate the two types with these fresh variables, and then unify.
170 --
171 -- For example, ({a,b}, (a,Int,b), (Int,z,Bool))
172 -- We unify z with Int, but since a and b are quantified we do nothing to them
173 -- We usually act on an equation by instantiating the quantified type varaibles
174 -- to fresh type variables, and then calling the standard unifier.
175
176 pprEquation (qtvs, pairs) 
177   = vcat [ptext SLIT("forall") <+> braces (pprWithCommas ppr (varSetElems qtvs)),
178           nest 2 (vcat [ ppr t1 <+> ptext SLIT(":=:") <+> ppr t2 | (t1,t2) <- pairs])]
179
180 ----------
181 type Pred_Loc = (PredType, SDoc)        -- SDoc says where the Pred comes from
182
183 improve :: (Class -> [Instance])                -- Gives instances for given class
184         -> [Pred_Loc]                           -- Current constraints; 
185         -> [(Equation,Pred_Loc,Pred_Loc)]       -- Derived equalities that must also hold
186                                                 -- (NB the above INVARIANT for type Equation)
187                                                 -- The Pred_Locs explain which two predicates were
188                                                 -- combined (for error messages)
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 :: (Class -> [Instance])
227            -> [Pred_Loc]
228            -> [(Equation, Pred_Loc, Pred_Loc)]
229   -- The preds are all for the same class or implicit param
230
231 checkGroup inst_env (p1@(IParam _ ty, _) : ips)
232   =     -- For implicit parameters, all the types must match
233     [ ((emptyVarSet, [(ty,ty')]), p1, p2) 
234     | p2@(IParam _ ty', _) <- ips, not (ty `tcEqType` ty')]
235
236 checkGroup inst_env clss@((ClassP cls _, _) : _)
237   =     -- For classes life is more complicated  
238         -- Suppose the class is like
239         --      classs C as | (l1 -> r1), (l2 -> r2), ... where ...
240         -- Then FOR EACH PAIR (ClassP c tys1, ClassP c tys2) in the list clss
241         -- we check whether
242         --      U l1[tys1/as] = U l2[tys2/as]
243         --  (where U is a unifier)
244         -- 
245         -- If so, we return the pair
246         --      U r1[tys1/as] = U l2[tys2/as]
247         --
248         -- We need to do something very similar comparing each predicate
249         -- with relevant instance decls
250
251     instance_eqns ++ pairwise_eqns
252         -- NB: we put the instance equations first.   This biases the 
253         -- order so that we first improve individual constraints against the
254         -- instances (which are perhaps in a library and less likely to be
255         -- wrong; and THEN perform the pairwise checks.
256         -- The other way round, it's possible for the pairwise check to succeed
257         -- and cause a subsequent, misleading failure of one of the pair with an
258         -- instance declaration.  See tcfail143.hs for an exmample
259
260   where
261     (cls_tvs, cls_fds) = classTvsFds cls
262     instances          = inst_env cls
263
264         -- NOTE that we iterate over the fds first; they are typically
265         -- empty, which aborts the rest of the loop.
266     pairwise_eqns :: [(Equation,Pred_Loc,Pred_Loc)]
267     pairwise_eqns       -- This group comes from pairwise comparison
268       = [ (eqn, p1, p2)
269         | fd <- cls_fds,
270           p1@(ClassP _ tys1, _) : rest <- tails clss,
271           p2@(ClassP _ tys2, _) <- rest,
272           eqn <- checkClsFD emptyVarSet fd cls_tvs tys1 tys2
273         ]
274
275     instance_eqns :: [(Equation,Pred_Loc,Pred_Loc)]
276     instance_eqns       -- This group comes from comparing with instance decls
277       = [ (eqn, p1, p2)
278         | fd <- cls_fds,        -- Iterate through the fundeps first, 
279                                 -- because there often are none!
280           p2@(ClassP _ tys2, _) <- clss,
281           let rough_tcs2 = trimRoughMatchTcs cls_tvs fd (roughMatchTcs tys2),
282           ispec@(Instance { is_tvs = qtvs, is_tys = tys1, 
283                             is_tcs = mb_tcs1 }) <- instances,
284           not (instanceCantMatch mb_tcs1 rough_tcs2),
285           eqn <- checkClsFD qtvs fd cls_tvs tys1 tys2,
286           let p1 = (mkClassPred cls tys1, 
287                     ptext SLIT("arising from the instance declaration at") <+> 
288                         ppr (getSrcLoc ispec))
289         ]
290 ----------
291 checkClsFD :: TyVarSet                  -- Quantified type variables; see note below
292            -> FunDep TyVar -> [TyVar]   -- One functional dependency from the class
293            -> [Type] -> [Type]
294            -> [Equation]
295
296 checkClsFD qtvs fd clas_tvs tys1 tys2
297 -- 'qtvs' are the quantified type variables, the ones which an be instantiated 
298 -- to make the types match.  For example, given
299 --      class C a b | a->b where ...
300 --      instance C (Maybe x) (Tree x) where ..
301 --
302 -- and an Inst of form (C (Maybe t1) t2), 
303 -- then we will call checkClsFD with
304 --
305 --      qtvs = {x}, tys1 = [Maybe x,  Tree x]
306 --                  tys2 = [Maybe t1, t2]
307 --
308 -- We can instantiate x to t1, and then we want to force
309 --      (Tree x) [t1/x]  :=:   t2
310 --
311 -- This function is also used when matching two Insts (rather than an Inst
312 -- against an instance decl. In that case, qtvs is empty, and we are doing
313 -- an equality check
314 -- 
315 -- This function is also used by InstEnv.badFunDeps, which needs to *unify*
316 -- For the one-sided matching case, the qtvs are just from the template,
317 -- so we get matching
318 --
319   = ASSERT2( length tys1 == length tys2     && 
320              length tys1 == length clas_tvs 
321             , ppr tys1 <+> ppr tys2 )
322
323     case tcUnifyTys bind_fn ls1 ls2 of
324         Nothing  -> []
325         Just subst | isJust (tcUnifyTys bind_fn rs1' rs2') 
326                         -- Don't include any equations that already hold. 
327                         -- Reason: then we know if any actual improvement has happened,
328                         --         in which case we need to iterate the solver
329                         -- In making this check we must taking account of the fact that any 
330                         -- qtvs that aren't already instantiated can be instantiated to anything 
331                         -- at all
332                   -> []
333
334                   | otherwise   -- Aha!  A useful equation
335                   -> [ (qtvs', zip rs1' rs2')]
336                         -- We could avoid this substTy stuff by producing the eqn
337                         -- (qtvs, ls1++rs1, ls2++rs2)
338                         -- which will re-do the ls1/ls2 unification when the equation is
339                         -- executed.  What we're doing instead is recording the partial
340                         -- work of the ls1/ls2 unification leaving a smaller unification problem
341                   where
342                     rs1'  = substTys subst rs1 
343                     rs2'  = substTys subst rs2
344                     qtvs' = filterVarSet (`notElemTvSubst` subst) qtvs
345                         -- qtvs' are the quantified type variables
346                         -- that have not been substituted out
347                         --      
348                         -- Eg.  class C a b | a -> b
349                         --      instance C Int [y]
350                         -- Given constraint C Int z
351                         -- we generate the equation
352                         --      ({y}, [y], z)
353   where
354     bind_fn tv | tv `elemVarSet` qtvs = BindMe
355                | otherwise            = Skolem
356
357     (ls1, rs1) = instFD fd clas_tvs tys1
358     (ls2, rs2) = instFD fd clas_tvs tys2
359
360 instFD :: FunDep TyVar -> [TyVar] -> [Type] -> FunDep Type
361 instFD (ls,rs) tvs tys
362   = (map lookup ls, map lookup rs)
363   where
364     env       = zipVarEnv tvs tys
365     lookup tv = lookupVarEnv_NF env tv
366 \end{code}
367
368 \begin{code}
369 checkInstCoverage :: Class -> [Type] -> Bool
370 -- Check that the Coverage Condition is obeyed in an instance decl
371 -- For example, if we have 
372 --      class theta => C a b | a -> b
373 --      instance C t1 t2 
374 -- Then we require fv(t2) `subset` fv(t1)
375 -- See Note [Coverage Condition] below
376
377 checkInstCoverage clas inst_taus
378   = all fundep_ok fds
379   where
380     (tyvars, fds) = classTvsFds clas
381     fundep_ok fd  = tyVarsOfTypes rs `subVarSet` tyVarsOfTypes ls
382                  where
383                    (ls,rs) = instFD fd tyvars inst_taus
384 \end{code}
385
386 Note [Coverage condition]
387 ~~~~~~~~~~~~~~~~~~~~~~~~~
388 For the coverage condition, we used to require only that 
389         fv(t2) `subset` oclose(fv(t1), theta)
390
391 Example:
392         class Mul a b c | a b -> c where
393                 (.*.) :: a -> b -> c
394
395         instance Mul Int Int Int where (.*.) = (*)
396         instance Mul Int Float Float where x .*. y = fromIntegral x * y
397         instance Mul a b c => Mul a [b] [c] where x .*. v = map (x.*.) v
398
399 In the third instance, it's not the case that fv([c]) `subset` fv(a,[b]).
400 But it is the case that fv([c]) `subset` oclose( theta, fv(a,[b]) )
401
402 But it is a mistake to accept the instance because then this defn:
403         f = \ b x y -> if b then x .*. [y] else y
404 makes instance inference go into a loop, because it requires the constraint
405         Mul a [b] b
406
407
408 %************************************************************************
409 %*                                                                      *
410         Check that a new instance decl is OK wrt fundeps
411 %*                                                                      *
412 %************************************************************************
413
414 Here is the bad case:
415         class C a b | a->b where ...
416         instance C Int Bool where ...
417         instance C Int Char where ...
418
419 The point is that a->b, so Int in the first parameter must uniquely
420 determine the second.  In general, given the same class decl, and given
421
422         instance C s1 s2 where ...
423         instance C t1 t2 where ...
424
425 Then the criterion is: if U=unify(s1,t1) then U(s2) = U(t2).
426
427 Matters are a little more complicated if there are free variables in
428 the s2/t2.  
429
430         class D a b c | a -> b
431         instance D a b => D [(a,a)] [b] Int
432         instance D a b => D [a]     [b] Bool
433
434 The instance decls don't overlap, because the third parameter keeps
435 them separate.  But we want to make sure that given any constraint
436         D s1 s2 s3
437 if s1 matches 
438
439
440 \begin{code}
441 checkFunDeps :: (InstEnv, InstEnv) -> Instance
442              -> Maybe [Instance]        -- Nothing  <=> ok
443                                         -- Just dfs <=> conflict with dfs
444 -- Check wheher adding DFunId would break functional-dependency constraints
445 -- Used only for instance decls defined in the module being compiled
446 checkFunDeps inst_envs ispec
447   | null bad_fundeps = Nothing
448   | otherwise        = Just bad_fundeps
449   where
450     (ins_tvs, _, clas, ins_tys) = instanceHead ispec
451     ins_tv_set   = mkVarSet ins_tvs
452     cls_inst_env = classInstances inst_envs clas
453     bad_fundeps  = badFunDeps cls_inst_env clas ins_tv_set ins_tys
454
455 badFunDeps :: [Instance] -> Class
456            -> TyVarSet -> [Type]        -- Proposed new instance type
457            -> [Instance]
458 badFunDeps cls_insts clas ins_tv_set ins_tys 
459   = [ ispec | fd <- fds,        -- fds is often empty
460               let trimmed_tcs = trimRoughMatchTcs clas_tvs fd rough_tcs,
461               ispec@(Instance { is_tcs = mb_tcs, is_tvs = tvs, 
462                                 is_tys = tys }) <- cls_insts,
463                 -- Filter out ones that can't possibly match, 
464                 -- based on the head of the fundep
465               not (instanceCantMatch trimmed_tcs mb_tcs),       
466               notNull (checkClsFD (tvs `unionVarSet` ins_tv_set) 
467                                    fd clas_tvs tys ins_tys)
468     ]
469   where
470     (clas_tvs, fds) = classTvsFds clas
471     rough_tcs = roughMatchTcs ins_tys
472
473 trimRoughMatchTcs :: [TyVar] -> FunDep TyVar -> [Maybe Name] -> [Maybe Name]
474 -- Computing rough_tcs for a particular fundep
475 --      class C a b c | a c -> b where ... 
476 -- For each instance .... => C ta tb tc
477 -- we want to match only on the types ta, tb; so our
478 -- rough-match thing must similarly be filtered.  
479 -- Hence, we Nothing-ise the tb type right here
480 trimRoughMatchTcs clas_tvs (ltvs,_) mb_tcs
481   = zipWith select clas_tvs mb_tcs
482   where
483     select clas_tv mb_tc | clas_tv `elem` ltvs = mb_tc
484                          | otherwise           = Nothing
485 \end{code}
486
487
488