[project @ 2001-01-25 17:54:24 by simonpj]
[ghc-hetmet.git] / ghc / compiler / typecheck / TcSimplify.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[TcSimplify]{TcSimplify}
5
6
7
8 \begin{code}
9 module TcSimplify (
10         tcSimplifyInfer, tcSimplifyInferCheck, tcSimplifyCheck, 
11         tcSimplifyToDicts, tcSimplifyIPs, tcSimplifyTop, 
12         tcSimplifyThetas, tcSimplifyCheckThetas,
13         bindInstsOfLocalFuns
14     ) where
15
16 #include "HsVersions.h"
17
18 import HsSyn            ( MonoBinds(..), HsExpr(..), andMonoBinds, andMonoBindList )
19 import TcHsSyn          ( TcExpr, TcId, 
20                           TcMonoBinds, TcDictBinds
21                         )
22
23 import TcMonad
24 import Inst             ( lookupInst, lookupSimpleInst, LookupInstResult(..),
25                           tyVarsOfInst, predsOfInsts, 
26                           isDict, isClassDict, 
27                           isStdClassTyVarDict, isMethodFor,
28                           instToId, tyVarsOfInsts,
29                           instBindingRequired, instCanBeGeneralised,
30                           newDictsFromOld, instMentionsIPs,
31                           getDictClassTys, getIPs, isTyVarDict,
32                           instLoc, pprInst, zonkInst, tidyInst, tidyInsts,
33                           Inst, LIE, pprInsts, pprInstsInFull,
34                           mkLIE, 
35                           lieToList 
36                         )
37 import TcEnv            ( tcGetGlobalTyVars, tcGetInstEnv )
38 import InstEnv          ( lookupInstEnv, classInstEnv, InstLookupResult(..) )
39
40 import TcType           ( zonkTcTyVarsAndFV )
41 import TcUnify          ( unifyTauTy )
42 import Id               ( idType )
43 import Name             ( Name )
44 import NameSet          ( mkNameSet )
45 import Class            ( Class, classBigSig )
46 import FunDeps          ( oclose, grow, improve )
47 import PrelInfo         ( isNumericClass, isCreturnableClass, isCcallishClass )
48
49 import Type             ( Type, ClassContext,
50                           mkTyVarTy, getTyVar, 
51                           isTyVarTy, splitSigmaTy, tyVarsOfTypes
52                         )
53 import Subst            ( mkTopTyVarSubst, substClasses )
54 import PprType          ( pprClassPred )
55 import TysWiredIn       ( unitTy )
56 import VarSet
57 import FiniteMap
58 import Outputable
59 import ListSetOps       ( equivClasses )
60 import Util             ( zipEqual, mapAccumL )
61 import List             ( partition )
62 import CmdLineOpts
63 \end{code}
64
65
66 %************************************************************************
67 %*                                                                      *
68 \subsection{NOTES}
69 %*                                                                      *
70 %************************************************************************
71
72         --------------------------------------  
73                 Notes on quantification
74         --------------------------------------  
75
76 Suppose we are about to do a generalisation step.
77 We have in our hand
78
79         G       the environment
80         T       the type of the RHS
81         C       the constraints fromm that RHS
82
83 The game is to figure out
84
85         Q       the set of type variables over which to quantify
86         Ct      the constraints we will *not* quantify over
87         Cq      the constraints we will quantify over
88
89 So we're going to infer the type
90
91         forall Q. Cq => T
92
93 and float the constraints Ct further outwards.  
94
95 Here are the things that *must* be true:
96
97  (A)    Q intersect fv(G) = EMPTY                       limits how big Q can be
98  (B)    Q superset fv(Cq union T) \ oclose(fv(G),C)     limits how small Q can be
99
100 (A) says we can't quantify over a variable that's free in the
101 environment.  (B) says we must quantify over all the truly free
102 variables in T, else we won't get a sufficiently general type.  We do
103 not *need* to quantify over any variable that is fixed by the free
104 vars of the environment G.
105
106         BETWEEN THESE TWO BOUNDS, ANY Q WILL DO!
107
108 Example:        class H x y | x->y where ...
109
110         fv(G) = {a}     C = {H a b, H c d}
111                         T = c -> b
112
113         (A)  Q intersect {a} is empty
114         (B)  Q superset {a,b,c,d} \ oclose({a}, C) = {a,b,c,d} \ {a,b} = {c,d}
115
116         So Q can be {c,d}, {b,c,d}
117
118 Other things being equal, however, we'd like to quantify over as few
119 variables as possible: smaller types, fewer type applications, more
120 constraints can get into Ct instead of Cq.
121
122
123 -----------------------------------------
124 We will make use of
125
126   fv(T)         the free type vars of T
127
128   oclose(vs,C)  The result of extending the set of tyvars vs
129                 using the functional dependencies from C
130
131   grow(vs,C)    The result of extend the set of tyvars vs
132                 using all conceivable links from C.  
133
134                 E.g. vs = {a}, C = {H [a] b, K (b,Int) c, Eq e}
135                 Then grow(vs,C) = {a,b,c}
136
137                 Note that grow(vs,C) `superset` grow(vs,simplify(C))
138                 That is, simplfication can only shrink the result of grow.
139
140 Notice that 
141    oclose is conservative one way:      v `elem` oclose(vs,C) => v is definitely fixed by vs
142    grow is conservative the other way:  if v might be fixed by vs => v `elem` grow(vs,C)
143
144
145 -----------------------------------------
146
147 Choosing Q
148 ~~~~~~~~~~
149 Here's a good way to choose Q:
150
151         Q = grow( fv(T), C ) \ oclose( fv(G), C )
152
153 That is, quantify over all variable that that MIGHT be fixed by the
154 call site (which influences T), but which aren't DEFINITELY fixed by
155 G.  This choice definitely quantifies over enough type variables,
156 albeit perhaps too many.
157
158 Why grow( fv(T), C ) rather than fv(T)?  Consider
159
160         class H x y | x->y where ...
161         
162         T = c->c
163         C = (H c d)
164
165   If we used fv(T) = {c} we'd get the type
166
167         forall c. H c d => c -> b
168
169   And then if the fn was called at several different c's, each of 
170   which fixed d differently, we'd get a unification error, because
171   d isn't quantified.  Solution: quantify d.  So we must quantify
172   everything that might be influenced by c.
173
174 Why not oclose( fv(T), C )?  Because we might not be able to see
175 all the functional dependencies yet:
176
177         class H x y | x->y where ...
178         instance H x y => Eq (T x y) where ...
179
180         T = c->c
181         C = (Eq (T c d))
182
183   Now oclose(fv(T),C) = {c}, because the functional dependency isn't
184   apparent yet, and that's wrong.  We must really quantify over d too.
185
186
187 There really isn't any point in quantifying over any more than
188 grow( fv(T), C ), because the call sites can't possibly influence
189 any other type variables.
190
191
192
193         --------------------------------------  
194                 Notes on ambiguity  
195         --------------------------------------  
196
197 It's very hard to be certain when a type is ambiguous.  Consider
198
199         class K x
200         class H x y | x -> y
201         instance H x y => K (x,y)
202
203 Is this type ambiguous?
204         forall a b. (K (a,b), Eq b) => a -> a
205
206 Looks like it!  But if we simplify (K (a,b)) we get (H a b) and
207 now we see that a fixes b.  So we can't tell about ambiguity for sure
208 without doing a full simplification.  And even that isn't possible if
209 the context has some free vars that may get unified.  Urgle!
210
211 Here's another example: is this ambiguous?
212         forall a b. Eq (T b) => a -> a
213 Not if there's an insance decl (with no context)
214         instance Eq (T b) where ...
215
216 You may say of this example that we should use the instance decl right
217 away, but you can't always do that:
218
219         class J a b where ...
220         instance J Int b where ...
221
222         f :: forall a b. J a b => a -> a
223
224 (Notice: no functional dependency in J's class decl.)
225 Here f's type is perfectly fine, provided f is only called at Int.
226 It's premature to complain when meeting f's signature, or even
227 when inferring a type for f.
228
229
230
231 However, we don't *need* to report ambiguity right away.  It'll always
232 show up at the call site.... and eventually at main, which needs special
233 treatment.  Nevertheless, reporting ambiguity promptly is an excellent thing.
234
235 So heres the plan.  We WARN about probable ambiguity if
236
237         fv(Cq) is not a subset of  oclose(fv(T) union fv(G), C)
238
239 (all tested before quantification).
240 That is, all the type variables in Cq must be fixed by the the variables
241 in the environment, or by the variables in the type.  
242
243 Notice that we union before calling oclose.  Here's an example:
244
245         class J a b c | a,b -> c
246         fv(G) = {a}
247
248 Is this ambiguous?
249         forall b,c. (J a b c) => b -> b
250
251 Only if we union {a} from G with {b} from T before using oclose,
252 do we see that c is fixed.  
253
254 It's a bit vague exactly which C we should use for this oclose call.  If we 
255 don't fix enough variables we might complain when we shouldn't (see
256 the above nasty example).  Nothing will be perfect.  That's why we can
257 only issue a warning.
258
259
260 Can we ever be *certain* about ambiguity?  Yes: if there's a constraint
261
262         c in C such that fv(c) intersect (fv(G) union fv(T)) = EMPTY
263
264 then c is a "bubble"; there's no way it can ever improve, and it's 
265 certainly ambiguous.  UNLESS it is a constant (sigh).  And what about
266 the nasty example?
267
268         class K x
269         class H x y | x -> y
270         instance H x y => K (x,y)
271
272 Is this type ambiguous?
273         forall a b. (K (a,b), Eq b) => a -> a
274
275 Urk.  The (Eq b) looks "definitely ambiguous" but it isn't.  What we are after
276 is a "bubble" that's a set of constraints
277
278         Cq = Ca union Cq'  st  fv(Ca) intersect (fv(Cq') union fv(T) union fv(G)) = EMPTY
279
280 Hence another idea.  To decide Q start with fv(T) and grow it
281 by transitive closure in Cq (no functional dependencies involved).
282 Now partition Cq using Q, leaving the definitely-ambiguous and probably-ok.
283 The definitely-ambigous can then float out, and get smashed at top level
284 (which squashes out the constants, like Eq (T a) above)
285
286
287         --------------------------------------  
288                 Notes on implicit parameters
289         --------------------------------------  
290
291 Consider
292
293         f x = ...?y...
294
295 Then we get an LIE like (?y::Int).  Doesn't constrain a type variable,
296 but we must nevertheless infer a type like
297
298         f :: (?y::Int) => Int -> Int
299
300 so that f is passed the value of y at the call site.  Is this legal?
301         
302         f :: Int -> Int
303         f x = x + ?y
304
305 Should f be overloaded on "?y" ?  Or does the type signature say that it
306 shouldn't be?  Our position is that it should be illegal.  Otherwise
307 you can change the *dynamic* semantics by adding a type signature:
308
309         (let f x = x + ?y       -- f :: (?y::Int) => Int -> Int
310          in (f 3, f 3 with ?y=5))  with ?y = 6
311
312                 returns (3+6, 3+5)
313 vs
314         (let f :: Int -> Int 
315             f x = x + ?y
316          in (f 3, f 3 with ?y=5))  with ?y = 6
317
318                 returns (3+6, 3+6)
319
320 URK!  Let's not do this. So this is illegal:
321
322         f :: Int -> Int
323         f x = x + ?y
324
325 BOTTOM LINE: you *must* quantify over implicit parameters.
326
327
328         --------------------------------------  
329                 Notes on principal types
330         --------------------------------------  
331
332     class C a where
333       op :: a -> a
334     
335     f x = let g y = op (y::Int) in True
336
337 Here the principal type of f is (forall a. a->a)
338 but we'll produce the non-principal type
339     f :: forall a. C Int => a -> a
340
341         
342 %************************************************************************
343 %*                                                                      *
344 \subsection{tcSimplifyInfer}
345 %*                                                                      *
346 %************************************************************************
347
348 tcSimplify is called when we *inferring* a type.  Here's the overall game plan:
349
350     1. Compute Q = grow( fvs(T), C )
351     
352     2. Partition C based on Q into Ct and Cq.  Notice that ambiguous 
353        predicates will end up in Ct; we deal with them at the top level
354     
355     3. Try improvement, using functional dependencies
356     
357     4. If Step 3 did any unification, repeat from step 1
358        (Unification can change the result of 'grow'.)
359
360 Note: we don't reduce dictionaries in step 2.  For example, if we have
361 Eq (a,b), we don't simplify to (Eq a, Eq b).  So Q won't be different 
362 after step 2.  However note that we may therefore quantify over more
363 type variables than we absolutely have to.
364
365 For the guts, we need a loop, that alternates context reduction and
366 improvement with unification.  E.g. Suppose we have
367
368         class C x y | x->y where ...
369     
370 and tcSimplify is called with:
371         (C Int a, C Int b)
372 Then improvement unifies a with b, giving
373         (C Int a, C Int a)
374
375 If we need to unify anything, we rattle round the whole thing all over
376 again. 
377
378
379 \begin{code}
380 tcSimplifyInfer
381         :: SDoc 
382         -> [TcTyVar]            -- fv(T); type vars 
383         -> LIE                  -- Wanted
384         -> TcM ([TcTyVar],      -- Tyvars to quantify (zonked)
385                 LIE,            -- Free
386                 TcDictBinds,    -- Bindings
387                 [TcId])         -- Dict Ids that must be bound here (zonked)
388 \end{code}
389
390
391 \begin{code}
392 tcSimplifyInfer doc tau_tvs wanted_lie
393   = inferLoop doc tau_tvs (lieToList wanted_lie)        `thenTc` \ (qtvs, frees, binds, irreds) ->
394
395         -- Check for non-generalisable insts
396     mapTc_ addCantGenErr (filter (not . instCanBeGeneralised) irreds)   `thenTc_`
397
398     returnTc (qtvs, mkLIE frees, binds, map instToId irreds)
399
400 inferLoop doc tau_tvs wanteds
401   =     -- Step 1
402     zonkTcTyVarsAndFV tau_tvs           `thenNF_Tc` \ tau_tvs' ->
403     mapNF_Tc zonkInst wanteds           `thenNF_Tc` \ wanteds' ->
404     tcGetGlobalTyVars                   `thenNF_Tc` \ gbl_tvs ->
405     let
406         preds = predsOfInsts wanteds'
407         qtvs  = grow preds tau_tvs' `minusVarSet` oclose preds gbl_tvs
408         
409         try_me inst     
410           | isFree qtvs inst  = Free
411           | isClassDict inst  = DontReduceUnlessConstant        -- Dicts
412           | otherwise         = ReduceMe AddToIrreds            -- Lits and Methods
413     in
414                 -- Step 2
415     reduceContext doc try_me [] wanteds'    `thenTc` \ (no_improvement, frees, binds, irreds) ->
416         
417                 -- Step 3
418     if no_improvement then
419             returnTc (varSetElems qtvs, frees, binds, irreds)
420     else
421             inferLoop doc tau_tvs wanteds
422 \end{code}      
423
424 \begin{code}
425 isFree qtvs inst
426   =  not (tyVarsOfInst inst `intersectsVarSet` qtvs)    -- Constrains no quantified vars
427   && null (getIPs inst)                                 -- And no implicit parameter involved
428                                                         -- (see "Notes on implicit parameters")
429 \end{code}
430
431
432 %************************************************************************
433 %*                                                                      *
434 \subsection{tcSimplifyCheck}
435 %*                                                                      *
436 %************************************************************************
437
438 @tcSimplifyCheck@ is used when we know exactly the set of variables
439 we are going to quantify over.
440
441 \begin{code}
442 tcSimplifyCheck
443          :: SDoc 
444          -> [TcTyVar]           -- Quantify over these
445          -> [Inst]              -- Given
446          -> LIE                 -- Wanted
447          -> TcM (LIE,           -- Free
448                  TcDictBinds)   -- Bindings
449
450 tcSimplifyCheck doc qtvs givens wanted_lie
451   = checkLoop doc qtvs givens (lieToList wanted_lie)    `thenTc` \ (frees, binds, irreds) ->
452
453         -- Complain about any irreducible ones
454     complainCheck doc givens irreds             `thenNF_Tc_`
455
456         -- Done
457     returnTc (mkLIE frees, binds)
458
459 checkLoop doc qtvs givens wanteds
460   =     -- Step 1
461     zonkTcTyVarsAndFV qtvs              `thenNF_Tc` \ qtvs' ->
462     mapNF_Tc zonkInst givens            `thenNF_Tc` \ givens' ->
463     mapNF_Tc zonkInst wanteds           `thenNF_Tc` \ wanteds' ->
464     let
465               -- When checking against a given signature we always reduce
466               -- until we find a match against something given, or can't reduce
467         try_me inst | isFree qtvs' inst  = Free
468                     | otherwise          = ReduceMe AddToIrreds
469     in
470                 -- Step 2
471     reduceContext doc try_me givens' wanteds'    `thenTc` \ (no_improvement, frees, binds, irreds) ->
472         
473                 -- Step 3
474     if no_improvement then
475             returnTc (frees, binds, irreds)
476     else
477             checkLoop doc qtvs givens wanteds
478
479 complainCheck doc givens irreds
480   = mapNF_Tc zonkInst given_dicts                       `thenNF_Tc` \ givens' ->
481     mapNF_Tc (addNoInstanceErr doc given_dicts) irreds  `thenNF_Tc_`
482     returnTc ()
483   where
484     given_dicts = filter isDict givens
485         -- Filter out methods, which are only added to 
486         -- the given set as an optimisation
487 \end{code}
488
489
490
491 %************************************************************************
492 %*                                                                      *
493 \subsection{tcSimplifyAndCheck}
494 %*                                                                      *
495 %************************************************************************
496
497 @tcSimplifyInferCheck@ is used when we know the consraints we are to simplify
498 against, but we don't know the type variables over which we are going to quantify.
499
500 \begin{code}
501 tcSimplifyInferCheck
502          :: SDoc 
503          -> [TcTyVar]           -- fv(T)
504          -> [Inst]              -- Given
505          -> LIE                 -- Wanted
506          -> TcM ([TcTyVar],     -- Variables over which to quantify
507                  LIE,           -- Free
508                  TcDictBinds)   -- Bindings
509
510 tcSimplifyInferCheck doc tau_tvs givens wanted
511   = inferCheckLoop doc tau_tvs givens (lieToList wanted)        `thenTc` \ (qtvs, frees, binds, irreds) ->
512
513         -- Complain about any irreducible ones
514     complainCheck doc givens irreds             `thenNF_Tc_`
515
516         -- Done
517     returnTc (qtvs, mkLIE frees, binds)
518
519 inferCheckLoop doc tau_tvs givens wanteds
520   =     -- Step 1
521     zonkTcTyVarsAndFV tau_tvs           `thenNF_Tc` \ tau_tvs' ->
522     mapNF_Tc zonkInst givens            `thenNF_Tc` \ givens' ->
523     mapNF_Tc zonkInst wanteds           `thenNF_Tc` \ wanteds' ->
524     tcGetGlobalTyVars                   `thenNF_Tc` \ gbl_tvs ->
525
526     let
527         -- Figure out what we are going to generalise over
528         -- You might think it should just be the signature tyvars,
529         -- but in bizarre cases you can get extra ones
530         --      f :: forall a. Num a => a -> a
531         --      f x = fst (g (x, head [])) + 1
532         --      g a b = (b,a)
533         -- Here we infer g :: forall a b. a -> b -> (b,a)
534         -- We don't want g to be monomorphic in b just because
535         -- f isn't quantified over b.
536         qtvs    = (tau_tvs' `unionVarSet` tyVarsOfInsts givens') `minusVarSet` gbl_tvs
537                         -- We could close gbl_tvs, but its not necessary for
538                         -- soundness, and it'll only affect which tyvars, not which 
539                         -- dictionaries, we quantify over
540
541               -- When checking against a given signature we always reduce
542               -- until we find a match against something given, or can't reduce
543         try_me inst | isFree qtvs inst  = Free
544                     | otherwise         = ReduceMe AddToIrreds
545     in
546                 -- Step 2
547     reduceContext doc try_me givens' wanteds'    `thenTc` \ (no_improvement, frees, binds, irreds) ->
548         
549                 -- Step 3
550     if no_improvement then
551             returnTc (varSetElems qtvs, frees, binds, irreds)
552     else
553             inferCheckLoop doc tau_tvs givens wanteds
554 \end{code}
555
556
557
558 %************************************************************************
559 %*                                                                      *
560 \subsection{tcSimplifyToDicts}
561 %*                                                                      *
562 %************************************************************************
563
564 On the LHS of transformation rules we only simplify methods and constants,
565 getting dictionaries.  We want to keep all of them unsimplified, to serve
566 as the available stuff for the RHS of the rule.
567
568 The same thing is used for specialise pragmas. Consider
569         
570         f :: Num a => a -> a
571         {-# SPECIALISE f :: Int -> Int #-}
572         f = ...
573
574 The type checker generates a binding like:
575
576         f_spec = (f :: Int -> Int)
577
578 and we want to end up with
579
580         f_spec = _inline_me_ (f Int dNumInt)
581
582 But that means that we must simplify the Method for f to (f Int dNumInt)! 
583 So tcSimplifyToDicts squeezes out all Methods.
584
585 \begin{code}
586 tcSimplifyToDicts :: LIE -> TcM ([Inst], TcDictBinds)
587 tcSimplifyToDicts wanted_lie
588   = simpleReduceLoop doc try_me wanteds         `thenTc` \ (frees, binds, irreds) ->
589         -- Since try_me doesn't look at types, we don't need to 
590         -- do any zonking, so it's safe to call reduceContext directly
591     ASSERT( null frees )
592     returnTc (irreds, binds)
593
594   where
595     doc = text "tcSimplifyToDicts"
596     wanteds = lieToList wanted_lie
597
598         -- Reduce methods and lits only; stop as soon as we get a dictionary
599     try_me inst | isDict inst = DontReduce
600                 | otherwise   = ReduceMe AddToIrreds
601 \end{code}
602
603
604 %************************************************************************
605 %*                                                                      *
606 \subsection{Filtering at a dynamic binding}
607 %*                                                                      *
608 %************************************************************************
609
610 When we have
611         let ?x = R in B
612
613 we must discharge all the ?x constraints from B.  We also do an improvement
614 step; if we have ?x::t1 and ?x::t2 we must unify t1, t2.  No need to iterate, though.
615
616 \begin{code}
617 tcSimplifyIPs :: [Name]         -- The implicit parameters bound here
618               -> LIE
619               -> TcM (LIE, TcDictBinds)
620 tcSimplifyIPs ip_names wanted_lie
621   = simpleReduceLoop doc try_me wanteds `thenTc` \ (frees, binds, irreds) ->
622         -- The irreducible ones should be a subset of the implicit
623         -- parameters we provided
624     ASSERT( all here_ip irreds )
625     returnTc (mkLIE frees, binds)
626     
627   where
628     doc     = text "tcSimplifyIPs" <+> ppr ip_names
629     wanteds = lieToList wanted_lie
630     ip_set  = mkNameSet ip_names
631     here_ip ip = isDict ip && ip `instMentionsIPs` ip_set
632
633         -- Simplify any methods that mention the implicit parameter
634     try_me inst | inst `instMentionsIPs` ip_set = ReduceMe AddToIrreds
635                 | otherwise                     = Free
636 \end{code}
637
638
639 %************************************************************************
640 %*                                                                      *
641 \subsection[binds-for-local-funs]{@bindInstsOfLocalFuns@}
642 %*                                                                      *
643 %************************************************************************
644
645 When doing a binding group, we may have @Insts@ of local functions.
646 For example, we might have...
647 \begin{verbatim}
648 let f x = x + 1     -- orig local function (overloaded)
649     f.1 = f Int     -- two instances of f
650     f.2 = f Float
651  in
652     (f.1 5, f.2 6.7)
653 \end{verbatim}
654 The point is: we must drop the bindings for @f.1@ and @f.2@ here,
655 where @f@ is in scope; those @Insts@ must certainly not be passed
656 upwards towards the top-level.  If the @Insts@ were binding-ified up
657 there, they would have unresolvable references to @f@.
658
659 We pass in an @init_lie@ of @Insts@ and a list of locally-bound @Ids@.
660 For each method @Inst@ in the @init_lie@ that mentions one of the
661 @Ids@, we create a binding.  We return the remaining @Insts@ (in an
662 @LIE@), as well as the @HsBinds@ generated.
663
664 \begin{code}
665 bindInstsOfLocalFuns :: LIE -> [TcId] -> TcM (LIE, TcMonoBinds)
666
667 bindInstsOfLocalFuns init_lie local_ids
668   | null overloaded_ids 
669         -- Common case
670   = returnTc (init_lie, EmptyMonoBinds)
671
672   | otherwise
673   = simpleReduceLoop doc try_me wanteds         `thenTc` \ (frees, binds, irreds) -> 
674     ASSERT( null irreds )
675     returnTc (mkLIE frees, binds)
676   where
677     doc              = text "bindInsts" <+> ppr local_ids
678     wanteds          = lieToList init_lie
679     overloaded_ids   = filter is_overloaded local_ids
680     is_overloaded id = case splitSigmaTy (idType id) of
681                           (_, theta, _) -> not (null theta)
682
683     overloaded_set = mkVarSet overloaded_ids    -- There can occasionally be a lot of them
684                                                 -- so it's worth building a set, so that 
685                                                 -- lookup (in isMethodFor) is faster
686
687     try_me inst | isMethodFor overloaded_set inst = ReduceMe AddToIrreds
688                 | otherwise                       = Free
689 \end{code}
690
691
692 %************************************************************************
693 %*                                                                      *
694 \subsection{Data types for the reduction mechanism}
695 %*                                                                      *
696 %************************************************************************
697
698 The main control over context reduction is here
699
700 \begin{code}
701 data WhatToDo 
702  = ReduceMe               -- Try to reduce this
703         NoInstanceAction  -- What to do if there's no such instance
704
705  | DontReduce                   -- Return as irreducible 
706
707  | DontReduceUnlessConstant     -- Return as irreducible unless it can
708                                 -- be reduced to a constant in one step
709
710  | Free                   -- Return as free
711
712 data NoInstanceAction
713   = Stop                -- Fail; no error message
714                         -- (Only used when tautology checking.)
715
716   | AddToIrreds         -- Just add the inst to the irreductible ones; don't 
717                         -- produce an error message of any kind.
718                         -- It might be quite legitimate such as (Eq a)!
719 \end{code}
720
721
722
723 \begin{code}
724 type RedState = (Avails,        -- What's available
725                  [Inst])        -- Insts for which try_me returned Free
726
727 type Avails = FiniteMap Inst Avail
728
729 data Avail
730   = Irred               -- Used for irreducible dictionaries,
731                         -- which are going to be lambda bound
732
733   | BoundTo TcId        -- Used for dictionaries for which we have a binding
734                         -- e.g. those "given" in a signature
735
736   | NoRhs               -- Used for Insts like (CCallable f)
737                         -- where no witness is required.
738
739   | Rhs                 -- Used when there is a RHS 
740         TcExpr          -- The RHS
741         [Inst]          -- Insts free in the RHS; we need these too
742
743 pprAvails avails = vcat (map pprAvail (eltsFM avails))
744
745 instance Outputable Avail where
746     ppr = pprAvail
747
748 pprAvail NoRhs        = text "<no rhs>"
749 pprAvail Irred        = text "Irred"
750 pprAvail (BoundTo x)  = text "Bound to" <+> ppr x
751 pprAvail (Rhs rhs bs) = ppr rhs <+> braces (ppr bs)
752 \end{code}
753
754 Extracting the bindings from a bunch of Avails.
755 The bindings do *not* come back sorted in dependency order.
756 We assume that they'll be wrapped in a big Rec, so that the
757 dependency analyser can sort them out later
758
759 The loop startes
760 \begin{code}
761 bindsAndIrreds :: Avails
762                -> [Inst]                -- Wanted
763                -> (TcDictBinds,         -- Bindings
764                    [Inst])              -- Irreducible ones
765
766 bindsAndIrreds avails wanteds
767   = go avails EmptyMonoBinds [] wanteds
768   where
769     go avails binds irreds [] = (binds, irreds)
770
771     go avails binds irreds (w:ws)
772       = case lookupFM avails w of
773           Nothing    -> -- Free guys come out here
774                         -- (If we didn't do addFree we could use this as the
775                         --  criterion for free-ness, and pick up the free ones here too)
776                         go avails binds irreds ws
777
778           Just NoRhs -> go avails binds irreds ws
779
780           Just Irred -> go (addToFM avails w (BoundTo (instToId w))) binds (w:irreds) ws
781
782           Just (BoundTo id) -> go avails new_binds irreds ws
783                             where
784                                 -- For implicit parameters, all occurrences share the same
785                                 -- Id, so there is no need for synonym bindings
786                                new_binds | new_id == id = binds
787                                          | otherwise    = binds `AndMonoBinds` new_bind
788                                new_bind = VarMonoBind new_id (HsVar id)
789                                new_id   = instToId w
790
791           Just (Rhs rhs ws') -> go avails' (binds `AndMonoBinds` new_bind) irreds (ws' ++ ws)
792                              where
793                                 id       = instToId w
794                                 avails'  = addToFM avails w (BoundTo id)
795                                 new_bind = VarMonoBind id rhs
796 \end{code}
797
798
799 %************************************************************************
800 %*                                                                      *
801 \subsection[reduce]{@reduce@}
802 %*                                                                      *
803 %************************************************************************
804
805 When the "what to do" predicate doesn't depend on the quantified type variables,
806 matters are easier.  We don't need to do any zonking, unless the improvement step
807 does something, in which case we zonk before iterating.
808
809 The "given" set is always empty.
810
811 \begin{code}
812 simpleReduceLoop :: SDoc
813                  -> (Inst -> WhatToDo)          -- What to do, *not* based on the quantified type variables
814                  -> [Inst]                      -- Wanted
815                  -> TcM ([Inst],                -- Free
816                          TcDictBinds,
817                          [Inst])                -- Irreducible
818
819 simpleReduceLoop doc try_me wanteds
820   = mapNF_Tc zonkInst wanteds                   `thenNF_Tc` \ wanteds' ->
821     reduceContext doc try_me [] wanteds'        `thenTc` \ (no_improvement, frees, binds, irreds) ->
822     if no_improvement then
823         returnTc (frees, binds, irreds)
824     else
825         simpleReduceLoop doc try_me wanteds
826 \end{code}      
827
828
829
830 \begin{code}
831 reduceContext :: SDoc
832               -> (Inst -> WhatToDo)
833               -> [Inst]                 -- Given
834               -> [Inst]                 -- Wanted
835               -> NF_TcM (Bool,          -- True <=> improve step did no unification
836                          [Inst],        -- Free
837                          TcDictBinds,   -- Dictionary bindings
838                          [Inst])        -- Irreducible
839
840 reduceContext doc try_me givens wanteds
841   =
842 {-    traceTc (text "reduceContext" <+> (vcat [
843              text "----------------------",
844              doc,
845              text "given" <+> ppr givens,
846              text "wanted" <+> ppr wanteds,
847              text "----------------------"
848              ]))                                        `thenNF_Tc_`
849
850 -}
851         -- Build the Avail mapping from "givens"
852     foldlNF_Tc addGiven (emptyFM, []) givens            `thenNF_Tc` \ init_state ->
853
854         -- Do the real work
855     reduceList (0,[]) try_me wanteds init_state         `thenNF_Tc` \ state@(avails, frees) ->
856
857         -- Do improvement, using everything in avails
858         -- In particular, avails includes all superclasses of everything
859     tcImprove avails                                    `thenTc` \ no_improvement ->
860
861 {-
862     traceTc (text "reduceContext end" <+> (vcat [
863              text "----------------------",
864              doc,
865              text "given" <+> ppr givens,
866              text "wanted" <+> ppr wanteds,
867              text "----", 
868              text "avails" <+> pprAvails avails,
869              text "frees" <+> ppr frees,
870              text "no_improvement =" <+> ppr no_improvement,
871              text "----------------------"
872              ]))                                        `thenNF_Tc_`
873 -}
874      let
875         (binds, irreds) = bindsAndIrreds avails wanteds
876      in
877      returnTc (no_improvement, frees, binds, irreds)
878
879 tcImprove avails
880  =  tcGetInstEnv                                `thenTc` \ inst_env ->
881     let
882         preds = predsOfInsts (keysFM avails)
883                 -- Avails has all the superclasses etc (good)
884                 -- It also has all the intermediates of the deduction (good)
885                 -- It does not have duplicates (good)
886                 -- NB that (?x::t1) and (?x::t2) will be held separately in avails
887                 --    so that improve will see them separate
888         eqns  = improve (classInstEnv inst_env) preds
889      in
890      if null eqns then
891         returnTc True
892      else
893         mapTc_ (\ (t1,t2) -> unifyTauTy t1 t2) eqns     `thenTc_`
894         returnTc False
895 \end{code}
896
897 The main context-reduction function is @reduce@.  Here's its game plan.
898
899 \begin{code}
900 reduceList :: (Int,[Inst])              -- Stack (for err msgs)
901                                         -- along with its depth
902            -> (Inst -> WhatToDo)
903            -> [Inst]
904            -> RedState
905            -> TcM RedState
906 \end{code}
907
908 @reduce@ is passed
909      try_me:    given an inst, this function returns
910                   Reduce       reduce this
911                   DontReduce   return this in "irreds"
912                   Free         return this in "frees"
913
914      wanteds:   The list of insts to reduce
915      state:     An accumulating parameter of type RedState 
916                 that contains the state of the algorithm
917  
918   It returns a RedState.
919
920 The (n,stack) pair is just used for error reporting.  
921 n is always the depth of the stack.
922 The stack is the stack of Insts being reduced: to produce X
923 I had to produce Y, to produce Y I had to produce Z, and so on.
924
925 \begin{code}
926 reduceList (n,stack) try_me wanteds state
927   | n > opt_MaxContextReductionDepth
928   = failWithTc (reduceDepthErr n stack)
929
930   | otherwise
931   =
932 #ifdef DEBUG
933    (if n > 8 then
934         pprTrace "Jeepers! ReduceContext:" (reduceDepthMsg n stack)
935     else (\x->x))
936 #endif
937     go wanteds state
938   where
939     go []     state = returnTc state
940     go (w:ws) state = reduce (n+1, w:stack) try_me w state      `thenTc` \ state' ->
941                       go ws state'
942
943     -- Base case: we're done!
944 reduce stack try_me wanted state
945     -- It's the same as an existing inst, or a superclass thereof
946   | isAvailable state wanted
947   = returnTc state
948
949   | otherwise
950   = case try_me wanted of {
951
952       DontReduce -> addIrred state wanted
953
954     ; DontReduceUnlessConstant ->    -- It's irreducible (or at least should not be reduced)
955                                      -- First, see if the inst can be reduced to a constant in one step
956         try_simple addIrred
957
958     ; Free ->   -- It's free so just chuck it upstairs
959                 -- First, see if the inst can be reduced to a constant in one step
960         try_simple addFree
961
962     ; ReduceMe no_instance_action ->    -- It should be reduced
963         lookupInst wanted             `thenNF_Tc` \ lookup_result ->
964         case lookup_result of
965             GenInst wanteds' rhs -> reduceList stack try_me wanteds' state      `thenTc` \ state' -> 
966                                     addWanted state' wanted rhs wanteds'
967             SimpleInst rhs       -> addWanted state wanted rhs []
968
969             NoInstance ->    -- No such instance! 
970                     case no_instance_action of
971                         Stop        -> failTc           
972                         AddToIrreds -> addIrred state wanted
973
974     }
975   where
976     try_simple do_this_otherwise
977       = lookupInst wanted         `thenNF_Tc` \ lookup_result ->
978         case lookup_result of
979             SimpleInst rhs -> addWanted state wanted rhs []
980             other          -> do_this_otherwise state wanted
981 \end{code}
982
983
984 \begin{code}
985 isAvailable :: RedState -> Inst -> Bool
986 isAvailable (avails, _) wanted = wanted `elemFM` avails
987         -- NB: the Ord instance of Inst compares by the class/type info
988         -- *not* by unique.  So 
989         --      d1::C Int ==  d2::C Int
990
991 -------------------------
992 addFree :: RedState -> Inst -> NF_TcM RedState
993         -- When an Inst is tossed upstairs as 'free' we nevertheless add it
994         -- to avails, so that any other equal Insts will be commoned up right
995         -- here rather than also being tossed upstairs.  This is really just
996         -- an optimisation, and perhaps it is more trouble that it is worth,
997         -- as the following comments show!
998         --
999         -- NB1: do *not* add superclasses.  If we have
1000         --      df::Floating a
1001         --      dn::Num a
1002         -- but a is not bound here, then we *don't* want to derive 
1003         -- dn from df here lest we lose sharing.
1004         --
1005         -- NB2: do *not* add the Inst to avails at all if it's a method.
1006         -- The following situation shows why this is bad:
1007         --      truncate :: forall a. RealFrac a => forall b. Integral b => a -> b
1008         -- From an application (truncate f i) we get
1009         --      t1 = truncate at f 
1010         --      t2 = t1 at i
1011         -- If we have also have a second occurrence of truncate, we get
1012         --      t3 = truncate at f
1013         --      t4 = t3 at i
1014         -- When simplifying with i,f free, we might still notice that
1015         --   t1=t3; but alas, the binding for t2 (which mentions t1)
1016         --   will continue to float out!
1017         -- Solution: never put methods in avail till they are captured
1018         -- in which case addFree isn't used
1019         --
1020         -- NB3: make sure that CCallable/CReturnable use NoRhs rather
1021         --      than BoundTo, else we end up with bogus bindings.
1022         --      c.f. instBindingRequired in addWanted
1023 addFree (avails, frees) free
1024   | isDict free = returnNF_Tc (addToFM avails free avail, free:frees)
1025   | otherwise   = returnNF_Tc (avails,                    free:frees)
1026   where
1027     avail | instBindingRequired free = BoundTo (instToId free)
1028           | otherwise                = NoRhs
1029
1030 addGiven :: RedState -> Inst -> NF_TcM RedState
1031 addGiven state given = add_avail state given (BoundTo (instToId given))
1032
1033 addIrred :: RedState -> Inst -> NF_TcM RedState
1034 addIrred state irred = add_avail state irred Irred
1035
1036 addWanted :: RedState -> Inst -> TcExpr -> [Inst] -> NF_TcM RedState
1037 addWanted state wanted rhs_expr wanteds
1038   = ASSERT( not (isAvailable state wanted) )
1039     add_avail state wanted avail
1040   where 
1041     avail | instBindingRequired wanted = Rhs rhs_expr wanteds
1042           | otherwise                  = ASSERT( null wanteds ) NoRhs
1043
1044 add_avail :: RedState -> Inst -> Avail -> NF_TcM RedState
1045 add_avail (avails, frees) wanted avail
1046   = addAvail avails wanted avail        `thenNF_Tc` \ avails' ->
1047     returnNF_Tc (avails', frees)
1048
1049 ---------------------
1050 addAvail :: Avails -> Inst -> Avail -> NF_TcM Avails
1051 addAvail avails wanted avail
1052   = addSuperClasses (addToFM avails wanted avail) wanted
1053
1054 addSuperClasses :: Avails -> Inst -> NF_TcM Avails
1055         -- Add all the superclasses of the Inst to Avails
1056         -- Invariant: the Inst is already in Avails.
1057
1058 addSuperClasses avails dict
1059   | not (isClassDict dict)
1060   = returnNF_Tc avails
1061
1062   | otherwise   -- It is a dictionary
1063   = newDictsFromOld dict sc_theta'      `thenNF_Tc` \ sc_dicts ->
1064     foldlNF_Tc add_sc avails (zipEqual "addSuperClasses" sc_dicts sc_sels)
1065   where
1066     (clas, tys) = getDictClassTys dict
1067     (tyvars, sc_theta, sc_sels, _) = classBigSig clas
1068     sc_theta' = substClasses (mkTopTyVarSubst tyvars tys) sc_theta
1069
1070     add_sc avails (sc_dict, sc_sel)     -- Add it, and its superclasses
1071       = case lookupFM avails sc_dict of
1072           Just (BoundTo _) -> returnNF_Tc avails        -- See Note [SUPER] below
1073           other            -> addAvail avails sc_dict avail
1074       where
1075         sc_sel_rhs = DictApp (TyApp (HsVar sc_sel) tys) [instToId dict]
1076         avail      = Rhs sc_sel_rhs [dict]
1077 \end{code}
1078
1079 Note [SUPER].  We have to be careful here.  If we are *given* d1:Ord a,
1080 and want to deduce (d2:C [a]) where
1081
1082         class Ord a => C a where
1083         instance Ord a => C [a] where ...
1084
1085 Then we'll use the instance decl to deduce C [a] and then add the 
1086 superclasses of C [a] to avails.  But we must not overwrite the binding
1087 for d1:Ord a (which is given) with a superclass selection or we'll just
1088 build a loop!  Hence looking for BoundTo.  Crudely, BoundTo is cheaper
1089 than a selection.
1090
1091
1092 %************************************************************************
1093 %*                                                                      *
1094 \section{tcSimplifyTop: defaulting}
1095 %*                                                                      *
1096 %************************************************************************
1097
1098
1099 If a dictionary constrains a type variable which is
1100         * not mentioned in the environment
1101         * and not mentioned in the type of the expression
1102 then it is ambiguous. No further information will arise to instantiate
1103 the type variable; nor will it be generalised and turned into an extra
1104 parameter to a function.
1105
1106 It is an error for this to occur, except that Haskell provided for
1107 certain rules to be applied in the special case of numeric types.
1108 Specifically, if
1109         * at least one of its classes is a numeric class, and
1110         * all of its classes are numeric or standard
1111 then the type variable can be defaulted to the first type in the
1112 default-type list which is an instance of all the offending classes.
1113
1114 So here is the function which does the work.  It takes the ambiguous
1115 dictionaries and either resolves them (producing bindings) or
1116 complains.  It works by splitting the dictionary list by type
1117 variable, and using @disambigOne@ to do the real business.
1118
1119 @tcSimplifyTop@ is called once per module to simplify all the constant
1120 and ambiguous Insts.
1121
1122 We need to be careful of one case.  Suppose we have
1123
1124         instance Num a => Num (Foo a b) where ...
1125
1126 and @tcSimplifyTop@ is given a constraint (Num (Foo x y)).  Then it'll simplify
1127 to (Num x), and default x to Int.  But what about y??  
1128
1129 It's OK: the final zonking stage should zap y to (), which is fine.
1130
1131
1132 \begin{code}
1133 tcSimplifyTop :: LIE -> TcM TcDictBinds
1134 tcSimplifyTop wanted_lie
1135   = simpleReduceLoop (text "tcSimplTop") try_me wanteds `thenTc` \ (frees, binds, irreds) ->
1136     ASSERT( null frees )
1137
1138     let
1139                 -- All the non-std ones are definite errors
1140         (stds, non_stds) = partition isStdClassTyVarDict irreds
1141         
1142                 -- Group by type variable
1143         std_groups = equivClasses cmp_by_tyvar stds
1144
1145                 -- Pick the ones which its worth trying to disambiguate
1146         (std_oks, std_bads) = partition worth_a_try std_groups
1147
1148                 -- Have a try at disambiguation 
1149                 -- if the type variable isn't bound
1150                 -- up with one of the non-standard classes
1151         worth_a_try group@(d:_) = not (non_std_tyvars `intersectsVarSet` tyVarsOfInst d)
1152         non_std_tyvars          = unionVarSets (map tyVarsOfInst non_stds)
1153
1154                 -- Collect together all the bad guys
1155         bad_guys = non_stds ++ concat std_bads
1156     in
1157         -- Disambiguate the ones that look feasible
1158     mapTc disambigGroup std_oks         `thenTc` \ binds_ambig ->
1159
1160         -- And complain about the ones that don't
1161     addTopAmbigErrs bad_guys            `thenNF_Tc_`
1162
1163     returnTc (binds `andMonoBinds` andMonoBindList binds_ambig)
1164   where
1165     wanteds     = lieToList wanted_lie
1166     try_me inst = ReduceMe AddToIrreds
1167
1168     d1 `cmp_by_tyvar` d2 = get_tv d1 `compare` get_tv d2
1169
1170 get_tv d   = case getDictClassTys d of
1171                    (clas, [ty]) -> getTyVar "tcSimplifyTop" ty
1172 get_clas d = case getDictClassTys d of
1173                    (clas, [ty]) -> clas
1174 \end{code}
1175
1176 @disambigOne@ assumes that its arguments dictionaries constrain all
1177 the same type variable.
1178
1179 ADR Comment 20/6/94: I've changed the @CReturnable@ case to default to
1180 @()@ instead of @Int@.  I reckon this is the Right Thing to do since
1181 the most common use of defaulting is code like:
1182 \begin{verbatim}
1183         _ccall_ foo     `seqPrimIO` bar
1184 \end{verbatim}
1185 Since we're not using the result of @foo@, the result if (presumably)
1186 @void@.
1187
1188 \begin{code}
1189 disambigGroup :: [Inst] -- All standard classes of form (C a)
1190               -> TcM TcDictBinds
1191
1192 disambigGroup dicts
1193   |   any isNumericClass classes        -- Guaranteed all standard classes
1194           -- see comment at the end of function for reasons as to 
1195           -- why the defaulting mechanism doesn't apply to groups that
1196           -- include CCallable or CReturnable dicts.
1197    && not (any isCcallishClass classes)
1198   =     -- THE DICTS OBEY THE DEFAULTABLE CONSTRAINT
1199         -- SO, TRY DEFAULT TYPES IN ORDER
1200
1201         -- Failure here is caused by there being no type in the
1202         -- default list which can satisfy all the ambiguous classes.
1203         -- For example, if Real a is reqd, but the only type in the
1204         -- default list is Int.
1205     tcGetDefaultTys                     `thenNF_Tc` \ default_tys ->
1206     let
1207       try_default []    -- No defaults work, so fail
1208         = failTc
1209
1210       try_default (default_ty : default_tys)
1211         = tryTc_ (try_default default_tys) $    -- If default_ty fails, we try
1212                                                 -- default_tys instead
1213           tcSimplifyCheckThetas [] thetas       `thenTc` \ _ ->
1214           returnTc default_ty
1215         where
1216           thetas = classes `zip` repeat [default_ty]
1217     in
1218         -- See if any default works, and if so bind the type variable to it
1219         -- If not, add an AmbigErr
1220     recoverTc (addAmbigErrs dicts `thenNF_Tc_` returnTc EmptyMonoBinds) $
1221
1222     try_default default_tys                     `thenTc` \ chosen_default_ty ->
1223
1224         -- Bind the type variable and reduce the context, for real this time
1225     unifyTauTy chosen_default_ty (mkTyVarTy tyvar)      `thenTc_`
1226     simpleReduceLoop (text "disambig" <+> ppr dicts)
1227                      try_me dicts                       `thenTc` \ (frees, binds, ambigs) ->
1228     WARN( not (null frees && null ambigs), ppr frees $$ ppr ambigs )
1229     warnDefault dicts chosen_default_ty                 `thenTc_`
1230     returnTc binds
1231
1232   | all isCreturnableClass classes
1233   =     -- Default CCall stuff to (); we don't even both to check that () is an 
1234         -- instance of CReturnable, because we know it is.
1235     unifyTauTy (mkTyVarTy tyvar) unitTy    `thenTc_`
1236     returnTc EmptyMonoBinds
1237     
1238   | otherwise -- No defaults
1239   = addAmbigErrs dicts  `thenNF_Tc_`
1240     returnTc EmptyMonoBinds
1241
1242   where
1243     try_me inst = ReduceMe AddToIrreds          -- This reduce should not fail
1244     tyvar       = get_tv (head dicts)           -- Should be non-empty
1245     classes     = map get_clas dicts
1246 \end{code}
1247
1248 [Aside - why the defaulting mechanism is turned off when
1249  dealing with arguments and results to ccalls.
1250
1251 When typechecking _ccall_s, TcExpr ensures that the external
1252 function is only passed arguments (and in the other direction,
1253 results) of a restricted set of 'native' types. This is
1254 implemented via the help of the pseudo-type classes,
1255 @CReturnable@ (CR) and @CCallable@ (CC.)
1256  
1257 The interaction between the defaulting mechanism for numeric
1258 values and CC & CR can be a bit puzzling to the user at times.
1259 For example,
1260
1261     x <- _ccall_ f
1262     if (x /= 0) then
1263        _ccall_ g x
1264      else
1265        return ()
1266
1267 What type has 'x' got here? That depends on the default list
1268 in operation, if it is equal to Haskell 98's default-default
1269 of (Integer, Double), 'x' has type Double, since Integer
1270 is not an instance of CR. If the default list is equal to
1271 Haskell 1.4's default-default of (Int, Double), 'x' has type
1272 Int. 
1273
1274 To try to minimise the potential for surprises here, the
1275 defaulting mechanism is turned off in the presence of
1276 CCallable and CReturnable.
1277
1278 ]
1279
1280
1281 %************************************************************************
1282 %*                                                                      *
1283 \subsection[simple]{@Simple@ versions}
1284 %*                                                                      *
1285 %************************************************************************
1286
1287 Much simpler versions when there are no bindings to make!
1288
1289 @tcSimplifyThetas@ simplifies class-type constraints formed by
1290 @deriving@ declarations and when specialising instances.  We are
1291 only interested in the simplified bunch of class/type constraints.
1292
1293 It simplifies to constraints of the form (C a b c) where
1294 a,b,c are type variables.  This is required for the context of
1295 instance declarations.
1296
1297 \begin{code}
1298 tcSimplifyThetas :: ClassContext                -- Wanted
1299                  -> TcM ClassContext            -- Needed
1300
1301 tcSimplifyThetas wanteds
1302   = doptsTc Opt_GlasgowExts             `thenNF_Tc` \ glaExts ->
1303     reduceSimple [] wanteds             `thenNF_Tc` \ irreds ->
1304     let
1305         -- For multi-param Haskell, check that the returned dictionaries
1306         -- don't have any of the form (C Int Bool) for which
1307         -- we expect an instance here
1308         -- For Haskell 98, check that all the constraints are of the form C a,
1309         -- where a is a type variable
1310         bad_guys | glaExts   = [ct | ct@(clas,tys) <- irreds, 
1311                                      isEmptyVarSet (tyVarsOfTypes tys)]
1312                  | otherwise = [ct | ct@(clas,tys) <- irreds, 
1313                                      not (all isTyVarTy tys)]
1314     in
1315     if null bad_guys then
1316         returnTc irreds
1317     else
1318        mapNF_Tc addNoInstErr bad_guys           `thenNF_Tc_`
1319        failTc
1320 \end{code}
1321
1322 @tcSimplifyCheckThetas@ just checks class-type constraints, essentially;
1323 used with \tr{default} declarations.  We are only interested in
1324 whether it worked or not.
1325
1326 \begin{code}
1327 tcSimplifyCheckThetas :: ClassContext   -- Given
1328                       -> ClassContext   -- Wanted
1329                       -> TcM ()
1330
1331 tcSimplifyCheckThetas givens wanteds
1332   = reduceSimple givens wanteds    `thenNF_Tc`  \ irreds ->
1333     if null irreds then
1334        returnTc ()
1335     else
1336        mapNF_Tc addNoInstErr irreds             `thenNF_Tc_`
1337        failTc
1338 \end{code}
1339
1340
1341 \begin{code}
1342 type AvailsSimple = FiniteMap (Class,[Type]) Bool
1343                     -- True  => irreducible 
1344                     -- False => given, or can be derived from a given or from an irreducible
1345
1346 reduceSimple :: ClassContext                    -- Given
1347              -> ClassContext                    -- Wanted
1348              -> NF_TcM ClassContext             -- Irreducible
1349
1350 reduceSimple givens wanteds
1351   = reduce_simple (0,[]) givens_fm wanteds      `thenNF_Tc` \ givens_fm' ->
1352     returnNF_Tc [ct | (ct,True) <- fmToList givens_fm']
1353   where
1354     givens_fm     = foldl addNonIrred emptyFM givens
1355
1356 reduce_simple :: (Int,ClassContext)             -- Stack
1357               -> AvailsSimple
1358               -> ClassContext
1359               -> NF_TcM AvailsSimple
1360
1361 reduce_simple (n,stack) avails wanteds
1362   = go avails wanteds
1363   where
1364     go avails []     = returnNF_Tc avails
1365     go avails (w:ws) = reduce_simple_help (n+1,w:stack) avails w        `thenNF_Tc` \ avails' ->
1366                        go avails' ws
1367
1368 reduce_simple_help stack givens wanted@(clas,tys)
1369   | wanted `elemFM` givens
1370   = returnNF_Tc givens
1371
1372   | otherwise
1373   = lookupSimpleInst clas tys   `thenNF_Tc` \ maybe_theta ->
1374
1375     case maybe_theta of
1376       Nothing ->    returnNF_Tc (addSimpleIrred givens wanted)
1377       Just theta -> reduce_simple stack (addNonIrred givens wanted) theta
1378
1379 addSimpleIrred :: AvailsSimple -> (Class,[Type]) -> AvailsSimple
1380 addSimpleIrred givens ct@(clas,tys)
1381   = addSCs (addToFM givens ct True) ct
1382
1383 addNonIrred :: AvailsSimple -> (Class,[Type]) -> AvailsSimple
1384 addNonIrred givens ct@(clas,tys)
1385   = addSCs (addToFM givens ct False) ct
1386
1387 addSCs givens ct@(clas,tys)
1388  = foldl add givens sc_theta
1389  where
1390    (tyvars, sc_theta_tmpl, _, _) = classBigSig clas
1391    sc_theta = substClasses (mkTopTyVarSubst tyvars tys) sc_theta_tmpl
1392
1393    add givens ct@(clas, tys)
1394      = case lookupFM givens ct of
1395        Nothing    -> -- Add it and its superclasses
1396                      addSCs (addToFM givens ct False) ct
1397
1398        Just True  -> -- Set its flag to False; superclasses already done
1399                      addToFM givens ct False
1400
1401        Just False -> -- Already done
1402                      givens
1403                            
1404 \end{code}
1405
1406
1407 %************************************************************************
1408 %*                                                                      *
1409 \section{Errors and contexts}
1410 %*                                                                      *
1411 %************************************************************************
1412
1413 ToDo: for these error messages, should we note the location as coming
1414 from the insts, or just whatever seems to be around in the monad just
1415 now?
1416
1417 \begin{code}
1418 addTopAmbigErrs dicts
1419   = mapNF_Tc complain tidy_dicts
1420   where
1421     fixed_tvs = oclose (predsOfInsts tidy_dicts) emptyVarSet
1422     (tidy_env, tidy_dicts) = tidyInsts emptyTidyEnv dicts
1423     complain d | not (null (getIPs d))                = addTopIPErr tidy_env d
1424                | tyVarsOfInst d `subVarSet` fixed_tvs = addTopInstanceErr tidy_env d
1425                | otherwise                            = addAmbigErr tidy_env d
1426
1427 addTopIPErr tidy_env tidy_dict
1428   = addInstErrTcM (instLoc tidy_dict) 
1429         (tidy_env, 
1430          ptext SLIT("Unbound implicit parameter") <+> quotes (pprInst tidy_dict))
1431
1432 -- Used for top-level irreducibles
1433 addTopInstanceErr tidy_env tidy_dict
1434   = addInstErrTcM (instLoc tidy_dict) 
1435         (tidy_env, 
1436          ptext SLIT("No instance for") <+> quotes (pprInst tidy_dict))
1437
1438 addAmbigErrs dicts
1439   = mapNF_Tc (addAmbigErr tidy_env) tidy_dicts
1440   where
1441     (tidy_env, tidy_dicts) = tidyInsts emptyTidyEnv dicts
1442
1443 addAmbigErr tidy_env tidy_dict
1444   = addInstErrTcM (instLoc tidy_dict)
1445         (tidy_env,
1446          sep [text "Ambiguous type variable(s)" <+> pprQuotedList ambig_tvs,
1447               nest 4 (text "in the constraint" <+> quotes (pprInst tidy_dict))])
1448   where
1449     ambig_tvs = varSetElems (tyVarsOfInst tidy_dict)
1450
1451 warnDefault dicts default_ty
1452   = doptsTc Opt_WarnTypeDefaults  `thenTc` \ warn_flag ->
1453     if warn_flag 
1454         then mapNF_Tc warn groups  `thenNF_Tc_`  returnNF_Tc ()
1455         else returnNF_Tc ()
1456
1457   where
1458         -- Tidy them first
1459     (_, tidy_dicts) = mapAccumL tidyInst emptyTidyEnv dicts
1460
1461         -- Group the dictionaries by source location
1462     groups      = equivClasses cmp tidy_dicts
1463     i1 `cmp` i2 = get_loc i1 `compare` get_loc i2
1464     get_loc i   = case instLoc i of { (_,loc,_) -> loc }
1465
1466     warn [dict] = tcAddSrcLoc (get_loc dict) $
1467                   warnTc True (ptext SLIT("Defaulting") <+> quotes (pprInst dict) <+> 
1468                                ptext SLIT("to type") <+> quotes (ppr default_ty))
1469
1470     warn dicts  = tcAddSrcLoc (get_loc (head dicts)) $
1471                   warnTc True (vcat [ptext SLIT("Defaulting the following constraint(s) to type") <+> quotes (ppr default_ty),
1472                                      pprInstsInFull dicts])
1473
1474 -- The error message when we don't find a suitable instance
1475 -- is complicated by the fact that sometimes this is because
1476 -- there is no instance, and sometimes it's because there are
1477 -- too many instances (overlap).  See the comments in TcEnv.lhs
1478 -- with the InstEnv stuff.
1479 addNoInstanceErr what_doc givens dict
1480   = tcGetInstEnv        `thenNF_Tc` \ inst_env ->
1481     let
1482         doc = vcat [sep [herald <+> quotes (pprInst tidy_dict),
1483                          nest 4 $ ptext SLIT("from the context") <+> pprInsts tidy_givens],
1484                     ambig_doc,
1485                     ptext SLIT("Probable fix:"),
1486                     nest 4 fix1,
1487                     nest 4 fix2]
1488     
1489         herald = ptext SLIT("Could not") <+> unambig_doc <+> ptext SLIT("deduce")
1490         unambig_doc | ambig_overlap = ptext SLIT("unambiguously")       
1491                     | otherwise     = empty
1492     
1493         ambig_doc 
1494             | not ambig_overlap = empty
1495             | otherwise             
1496             = vcat [ptext SLIT("The choice of (overlapping) instance declaration"),
1497                     nest 4 (ptext SLIT("depends on the instantiation of") <+> 
1498                             quotes (pprWithCommas ppr (varSetElems (tyVarsOfInst tidy_dict))))]
1499     
1500         fix1 = sep [ptext SLIT("Add") <+> quotes (pprInst tidy_dict),
1501                     ptext SLIT("to the") <+> what_doc]
1502     
1503         fix2 | isTyVarDict dict || ambig_overlap
1504              = empty
1505              | otherwise
1506              = ptext SLIT("Or add an instance declaration for") <+> quotes (pprInst tidy_dict)
1507     
1508         (tidy_env, tidy_dict:tidy_givens) = tidyInsts emptyTidyEnv (dict:givens)
1509     
1510             -- Checks for the ambiguous case when we have overlapping instances
1511         ambig_overlap | isClassDict dict
1512                       = case lookupInstEnv inst_env clas tys of
1513                             NoMatch ambig -> ambig
1514                             other         -> False
1515                       | otherwise = False
1516                       where
1517                         (clas,tys) = getDictClassTys dict
1518     in
1519     addInstErrTcM (instLoc dict) (tidy_env, doc)
1520
1521 -- Used for the ...Thetas variants; all top level
1522 addNoInstErr (c,ts)
1523   = addErrTc (ptext SLIT("No instance for") <+> quotes (pprClassPred c ts))
1524
1525 reduceDepthErr n stack
1526   = vcat [ptext SLIT("Context reduction stack overflow; size =") <+> int n,
1527           ptext SLIT("Use -fcontext-stack20 to increase stack size to (e.g.) 20"),
1528           nest 4 (pprInstsInFull stack)]
1529
1530 reduceDepthMsg n stack = nest 4 (pprInstsInFull stack)
1531
1532 -----------------------------------------------
1533 addCantGenErr inst
1534   = addErrTc (sep [ptext SLIT("Cannot generalise these overloadings (in a _ccall_):"), 
1535                    nest 4 (ppr inst <+> pprInstLoc (instLoc inst))])
1536 \end{code}