[project @ 2003-09-16 13:03:37 by simonmar]
[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,
11         tcSimplifyCheck, tcSimplifyRestricted,
12         tcSimplifyToDicts, tcSimplifyIPs, 
13         tcSimplifyTop, tcSimplifyInteractive,
14         tcSimplifyBracket,
15
16         tcSimplifyDeriv, tcSimplifyDefault,
17         bindInstsOfLocalFuns
18     ) where
19
20 #include "HsVersions.h"
21
22 import {-# SOURCE #-} TcUnify( unifyTauTy )
23 import TcEnv            -- temp
24 import HsSyn            ( MonoBinds(..), HsExpr(..), andMonoBinds, andMonoBindList )
25 import TcHsSyn          ( TcExpr, TcId,
26                           TcMonoBinds, TcDictBinds
27                         )
28
29 import TcRnMonad
30 import Inst             ( lookupInst, LookupInstResult(..),
31                           tyVarsOfInst, fdPredsOfInsts, fdPredsOfInst, newDicts,
32                           isDict, isClassDict, isLinearInst, linearInstType,
33                           isStdClassTyVarDict, isMethodFor, isMethod,
34                           instToId, tyVarsOfInsts,  cloneDict,
35                           ipNamesOfInsts, ipNamesOfInst, dictPred,
36                           instBindingRequired,
37                           newDictsFromOld, tcInstClassOp,
38                           getDictClassTys, isTyVarDict,
39                           instLoc, zonkInst, tidyInsts, tidyMoreInsts,
40                           Inst, pprInsts, pprInstsInFull,
41                           isIPDict, isInheritableInst
42                         )
43 import TcEnv            ( tcGetGlobalTyVars, tcGetInstEnv, tcLookupId, findGlobals )
44 import InstEnv          ( lookupInstEnv, classInstEnv, InstLookupResult(..) )
45 import TcMType          ( zonkTcTyVarsAndFV, tcInstTyVars, checkAmbiguity )
46 import TcType           ( TcTyVar, TcTyVarSet, ThetaType, TyVarDetails(VanillaTv),
47                           mkClassPred, isOverloadedTy, mkTyConApp,
48                           mkTyVarTy, tcGetTyVar, isTyVarClassPred, mkTyVarTys,
49                           tyVarsOfPred )
50 import Id               ( idType, mkUserLocal )
51 import Var              ( TyVar )
52 import Name             ( getOccName, getSrcLoc )
53 import NameSet          ( NameSet, mkNameSet, elemNameSet )
54 import Class            ( classBigSig, classKey )
55 import FunDeps          ( oclose, grow, improve, pprEquationDoc )
56 import PrelInfo         ( isNumericClass ) 
57 import PrelNames        ( splitName, fstName, sndName, showClassKey, eqClassKey, ordClassKey)
58 import HscTypes         ( GhciMode(Interactive) )
59
60 import Subst            ( mkTopTyVarSubst, substTheta, substTy )
61 import TysWiredIn       ( unitTy, pairTyCon )
62 import ErrUtils         ( Message )
63 import VarSet
64 import VarEnv           ( TidyEnv )
65 import FiniteMap
66 import Outputable
67 import ListSetOps       ( equivClasses )
68 import Unique           ( hasKey )
69 import Util             ( zipEqual, isSingleton )
70 import List             ( partition )
71 import CmdLineOpts
72 \end{code}
73
74
75 %************************************************************************
76 %*                                                                      *
77 \subsection{NOTES}
78 %*                                                                      *
79 %************************************************************************
80
81         --------------------------------------
82                 Notes on quantification
83         --------------------------------------
84
85 Suppose we are about to do a generalisation step.
86 We have in our hand
87
88         G       the environment
89         T       the type of the RHS
90         C       the constraints from that RHS
91
92 The game is to figure out
93
94         Q       the set of type variables over which to quantify
95         Ct      the constraints we will *not* quantify over
96         Cq      the constraints we will quantify over
97
98 So we're going to infer the type
99
100         forall Q. Cq => T
101
102 and float the constraints Ct further outwards.
103
104 Here are the things that *must* be true:
105
106  (A)    Q intersect fv(G) = EMPTY                       limits how big Q can be
107  (B)    Q superset fv(Cq union T) \ oclose(fv(G),C)     limits how small Q can be
108
109 (A) says we can't quantify over a variable that's free in the
110 environment.  (B) says we must quantify over all the truly free
111 variables in T, else we won't get a sufficiently general type.  We do
112 not *need* to quantify over any variable that is fixed by the free
113 vars of the environment G.
114
115         BETWEEN THESE TWO BOUNDS, ANY Q WILL DO!
116
117 Example:        class H x y | x->y where ...
118
119         fv(G) = {a}     C = {H a b, H c d}
120                         T = c -> b
121
122         (A)  Q intersect {a} is empty
123         (B)  Q superset {a,b,c,d} \ oclose({a}, C) = {a,b,c,d} \ {a,b} = {c,d}
124
125         So Q can be {c,d}, {b,c,d}
126
127 Other things being equal, however, we'd like to quantify over as few
128 variables as possible: smaller types, fewer type applications, more
129 constraints can get into Ct instead of Cq.
130
131
132 -----------------------------------------
133 We will make use of
134
135   fv(T)         the free type vars of T
136
137   oclose(vs,C)  The result of extending the set of tyvars vs
138                 using the functional dependencies from C
139
140   grow(vs,C)    The result of extend the set of tyvars vs
141                 using all conceivable links from C.
142
143                 E.g. vs = {a}, C = {H [a] b, K (b,Int) c, Eq e}
144                 Then grow(vs,C) = {a,b,c}
145
146                 Note that grow(vs,C) `superset` grow(vs,simplify(C))
147                 That is, simplfication can only shrink the result of grow.
148
149 Notice that
150    oclose is conservative one way:      v `elem` oclose(vs,C) => v is definitely fixed by vs
151    grow is conservative the other way:  if v might be fixed by vs => v `elem` grow(vs,C)
152
153
154 -----------------------------------------
155
156 Choosing Q
157 ~~~~~~~~~~
158 Here's a good way to choose Q:
159
160         Q = grow( fv(T), C ) \ oclose( fv(G), C )
161
162 That is, quantify over all variable that that MIGHT be fixed by the
163 call site (which influences T), but which aren't DEFINITELY fixed by
164 G.  This choice definitely quantifies over enough type variables,
165 albeit perhaps too many.
166
167 Why grow( fv(T), C ) rather than fv(T)?  Consider
168
169         class H x y | x->y where ...
170
171         T = c->c
172         C = (H c d)
173
174   If we used fv(T) = {c} we'd get the type
175
176         forall c. H c d => c -> b
177
178   And then if the fn was called at several different c's, each of
179   which fixed d differently, we'd get a unification error, because
180   d isn't quantified.  Solution: quantify d.  So we must quantify
181   everything that might be influenced by c.
182
183 Why not oclose( fv(T), C )?  Because we might not be able to see
184 all the functional dependencies yet:
185
186         class H x y | x->y where ...
187         instance H x y => Eq (T x y) where ...
188
189         T = c->c
190         C = (Eq (T c d))
191
192   Now oclose(fv(T),C) = {c}, because the functional dependency isn't
193   apparent yet, and that's wrong.  We must really quantify over d too.
194
195
196 There really isn't any point in quantifying over any more than
197 grow( fv(T), C ), because the call sites can't possibly influence
198 any other type variables.
199
200
201
202         --------------------------------------
203                 Notes on ambiguity
204         --------------------------------------
205
206 It's very hard to be certain when a type is ambiguous.  Consider
207
208         class K x
209         class H x y | x -> y
210         instance H x y => K (x,y)
211
212 Is this type ambiguous?
213         forall a b. (K (a,b), Eq b) => a -> a
214
215 Looks like it!  But if we simplify (K (a,b)) we get (H a b) and
216 now we see that a fixes b.  So we can't tell about ambiguity for sure
217 without doing a full simplification.  And even that isn't possible if
218 the context has some free vars that may get unified.  Urgle!
219
220 Here's another example: is this ambiguous?
221         forall a b. Eq (T b) => a -> a
222 Not if there's an insance decl (with no context)
223         instance Eq (T b) where ...
224
225 You may say of this example that we should use the instance decl right
226 away, but you can't always do that:
227
228         class J a b where ...
229         instance J Int b where ...
230
231         f :: forall a b. J a b => a -> a
232
233 (Notice: no functional dependency in J's class decl.)
234 Here f's type is perfectly fine, provided f is only called at Int.
235 It's premature to complain when meeting f's signature, or even
236 when inferring a type for f.
237
238
239
240 However, we don't *need* to report ambiguity right away.  It'll always
241 show up at the call site.... and eventually at main, which needs special
242 treatment.  Nevertheless, reporting ambiguity promptly is an excellent thing.
243
244 So here's the plan.  We WARN about probable ambiguity if
245
246         fv(Cq) is not a subset of  oclose(fv(T) union fv(G), C)
247
248 (all tested before quantification).
249 That is, all the type variables in Cq must be fixed by the the variables
250 in the environment, or by the variables in the type.
251
252 Notice that we union before calling oclose.  Here's an example:
253
254         class J a b c | a b -> c
255         fv(G) = {a}
256
257 Is this ambiguous?
258         forall b c. (J a b c) => b -> b
259
260 Only if we union {a} from G with {b} from T before using oclose,
261 do we see that c is fixed.
262
263 It's a bit vague exactly which C we should use for this oclose call.  If we
264 don't fix enough variables we might complain when we shouldn't (see
265 the above nasty example).  Nothing will be perfect.  That's why we can
266 only issue a warning.
267
268
269 Can we ever be *certain* about ambiguity?  Yes: if there's a constraint
270
271         c in C such that fv(c) intersect (fv(G) union fv(T)) = EMPTY
272
273 then c is a "bubble"; there's no way it can ever improve, and it's
274 certainly ambiguous.  UNLESS it is a constant (sigh).  And what about
275 the nasty example?
276
277         class K x
278         class H x y | x -> y
279         instance H x y => K (x,y)
280
281 Is this type ambiguous?
282         forall a b. (K (a,b), Eq b) => a -> a
283
284 Urk.  The (Eq b) looks "definitely ambiguous" but it isn't.  What we are after
285 is a "bubble" that's a set of constraints
286
287         Cq = Ca union Cq'  st  fv(Ca) intersect (fv(Cq') union fv(T) union fv(G)) = EMPTY
288
289 Hence another idea.  To decide Q start with fv(T) and grow it
290 by transitive closure in Cq (no functional dependencies involved).
291 Now partition Cq using Q, leaving the definitely-ambiguous and probably-ok.
292 The definitely-ambiguous can then float out, and get smashed at top level
293 (which squashes out the constants, like Eq (T a) above)
294
295
296         --------------------------------------
297                 Notes on principal types
298         --------------------------------------
299
300     class C a where
301       op :: a -> a
302
303     f x = let g y = op (y::Int) in True
304
305 Here the principal type of f is (forall a. a->a)
306 but we'll produce the non-principal type
307     f :: forall a. C Int => a -> a
308
309
310         --------------------------------------
311                 Notes on implicit parameters
312         --------------------------------------
313
314 Question 1: can we "inherit" implicit parameters
315 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
316 Consider this:
317
318         f x = (x::Int) + ?y
319
320 where f is *not* a top-level binding.
321 From the RHS of f we'll get the constraint (?y::Int).
322 There are two types we might infer for f:
323
324         f :: Int -> Int
325
326 (so we get ?y from the context of f's definition), or
327
328         f :: (?y::Int) => Int -> Int
329
330 At first you might think the first was better, becuase then
331 ?y behaves like a free variable of the definition, rather than
332 having to be passed at each call site.  But of course, the WHOLE
333 IDEA is that ?y should be passed at each call site (that's what
334 dynamic binding means) so we'd better infer the second.
335
336 BOTTOM LINE: when *inferring types* you *must* quantify 
337 over implicit parameters. See the predicate isFreeWhenInferring.
338
339
340 Question 2: type signatures
341 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
342 BUT WATCH OUT: When you supply a type signature, we can't force you
343 to quantify over implicit parameters.  For example:
344
345         (?x + 1) :: Int
346
347 This is perfectly reasonable.  We do not want to insist on
348
349         (?x + 1) :: (?x::Int => Int)
350
351 That would be silly.  Here, the definition site *is* the occurrence site,
352 so the above strictures don't apply.  Hence the difference between
353 tcSimplifyCheck (which *does* allow implicit paramters to be inherited)
354 and tcSimplifyCheckBind (which does not).
355
356 What about when you supply a type signature for a binding?
357 Is it legal to give the following explicit, user type 
358 signature to f, thus:
359
360         f :: Int -> Int
361         f x = (x::Int) + ?y
362
363 At first sight this seems reasonable, but it has the nasty property
364 that adding a type signature changes the dynamic semantics.
365 Consider this:
366
367         (let f x = (x::Int) + ?y
368          in (f 3, f 3 with ?y=5))  with ?y = 6
369
370                 returns (3+6, 3+5)
371 vs
372         (let f :: Int -> Int
373              f x = x + ?y
374          in (f 3, f 3 with ?y=5))  with ?y = 6
375
376                 returns (3+6, 3+6)
377
378 Indeed, simply inlining f (at the Haskell source level) would change the
379 dynamic semantics.
380
381 Nevertheless, as Launchbury says (email Oct 01) we can't really give the
382 semantics for a Haskell program without knowing its typing, so if you 
383 change the typing you may change the semantics.
384
385 To make things consistent in all cases where we are *checking* against
386 a supplied signature (as opposed to inferring a type), we adopt the
387 rule: 
388
389         a signature does not need to quantify over implicit params.
390
391 [This represents a (rather marginal) change of policy since GHC 5.02,
392 which *required* an explicit signature to quantify over all implicit
393 params for the reasons mentioned above.]
394
395 But that raises a new question.  Consider 
396
397         Given (signature)       ?x::Int
398         Wanted (inferred)       ?x::Int, ?y::Bool
399
400 Clearly we want to discharge the ?x and float the ?y out.  But
401 what is the criterion that distinguishes them?  Clearly it isn't
402 what free type variables they have.  The Right Thing seems to be
403 to float a constraint that
404         neither mentions any of the quantified type variables
405         nor any of the quantified implicit parameters
406
407 See the predicate isFreeWhenChecking.
408
409
410 Question 3: monomorphism
411 ~~~~~~~~~~~~~~~~~~~~~~~~
412 There's a nasty corner case when the monomorphism restriction bites:
413
414         z = (x::Int) + ?y
415
416 The argument above suggests that we *must* generalise
417 over the ?y parameter, to get
418         z :: (?y::Int) => Int,
419 but the monomorphism restriction says that we *must not*, giving
420         z :: Int.
421 Why does the momomorphism restriction say this?  Because if you have
422
423         let z = x + ?y in z+z
424
425 you might not expect the addition to be done twice --- but it will if
426 we follow the argument of Question 2 and generalise over ?y.
427
428
429
430 Possible choices
431 ~~~~~~~~~~~~~~~~
432 (A) Always generalise over implicit parameters
433     Bindings that fall under the monomorphism restriction can't
434         be generalised
435
436     Consequences:
437         * Inlining remains valid
438         * No unexpected loss of sharing
439         * But simple bindings like
440                 z = ?y + 1
441           will be rejected, unless you add an explicit type signature
442           (to avoid the monomorphism restriction)
443                 z :: (?y::Int) => Int
444                 z = ?y + 1
445           This seems unacceptable
446
447 (B) Monomorphism restriction "wins"
448     Bindings that fall under the monomorphism restriction can't
449         be generalised
450     Always generalise over implicit parameters *except* for bindings
451         that fall under the monomorphism restriction
452
453     Consequences
454         * Inlining isn't valid in general
455         * No unexpected loss of sharing
456         * Simple bindings like
457                 z = ?y + 1
458           accepted (get value of ?y from binding site)
459
460 (C) Always generalise over implicit parameters
461     Bindings that fall under the monomorphism restriction can't
462         be generalised, EXCEPT for implicit parameters
463     Consequences
464         * Inlining remains valid
465         * Unexpected loss of sharing (from the extra generalisation)
466         * Simple bindings like
467                 z = ?y + 1
468           accepted (get value of ?y from occurrence sites)
469
470
471 Discussion
472 ~~~~~~~~~~
473 None of these choices seems very satisfactory.  But at least we should
474 decide which we want to do.
475
476 It's really not clear what is the Right Thing To Do.  If you see
477
478         z = (x::Int) + ?y
479
480 would you expect the value of ?y to be got from the *occurrence sites*
481 of 'z', or from the valuue of ?y at the *definition* of 'z'?  In the
482 case of function definitions, the answer is clearly the former, but
483 less so in the case of non-fucntion definitions.   On the other hand,
484 if we say that we get the value of ?y from the definition site of 'z',
485 then inlining 'z' might change the semantics of the program.
486
487 Choice (C) really says "the monomorphism restriction doesn't apply
488 to implicit parameters".  Which is fine, but remember that every
489 innocent binding 'x = ...' that mentions an implicit parameter in
490 the RHS becomes a *function* of that parameter, called at each
491 use of 'x'.  Now, the chances are that there are no intervening 'with'
492 clauses that bind ?y, so a decent compiler should common up all
493 those function calls.  So I think I strongly favour (C).  Indeed,
494 one could make a similar argument for abolishing the monomorphism
495 restriction altogether.
496
497 BOTTOM LINE: we choose (B) at present.  See tcSimplifyRestricted
498
499
500
501 %************************************************************************
502 %*                                                                      *
503 \subsection{tcSimplifyInfer}
504 %*                                                                      *
505 %************************************************************************
506
507 tcSimplify is called when we *inferring* a type.  Here's the overall game plan:
508
509     1. Compute Q = grow( fvs(T), C )
510
511     2. Partition C based on Q into Ct and Cq.  Notice that ambiguous
512        predicates will end up in Ct; we deal with them at the top level
513
514     3. Try improvement, using functional dependencies
515
516     4. If Step 3 did any unification, repeat from step 1
517        (Unification can change the result of 'grow'.)
518
519 Note: we don't reduce dictionaries in step 2.  For example, if we have
520 Eq (a,b), we don't simplify to (Eq a, Eq b).  So Q won't be different
521 after step 2.  However note that we may therefore quantify over more
522 type variables than we absolutely have to.
523
524 For the guts, we need a loop, that alternates context reduction and
525 improvement with unification.  E.g. Suppose we have
526
527         class C x y | x->y where ...
528
529 and tcSimplify is called with:
530         (C Int a, C Int b)
531 Then improvement unifies a with b, giving
532         (C Int a, C Int a)
533
534 If we need to unify anything, we rattle round the whole thing all over
535 again.
536
537
538 \begin{code}
539 tcSimplifyInfer
540         :: SDoc
541         -> TcTyVarSet           -- fv(T); type vars
542         -> [Inst]               -- Wanted
543         -> TcM ([TcTyVar],      -- Tyvars to quantify (zonked)
544                 TcDictBinds,    -- Bindings
545                 [TcId])         -- Dict Ids that must be bound here (zonked)
546         -- Any free (escaping) Insts are tossed into the environment
547 \end{code}
548
549
550 \begin{code}
551 tcSimplifyInfer doc tau_tvs wanted_lie
552   = inferLoop doc (varSetElems tau_tvs)
553               wanted_lie                `thenM` \ (qtvs, frees, binds, irreds) ->
554
555     extendLIEs frees                                                    `thenM_`
556     returnM (qtvs, binds, map instToId irreds)
557
558 inferLoop doc tau_tvs wanteds
559   =     -- Step 1
560     zonkTcTyVarsAndFV tau_tvs           `thenM` \ tau_tvs' ->
561     mappM zonkInst wanteds              `thenM` \ wanteds' ->
562     tcGetGlobalTyVars                   `thenM` \ gbl_tvs ->
563     let
564         preds = fdPredsOfInsts wanteds'
565         qtvs  = grow preds tau_tvs' `minusVarSet` oclose preds gbl_tvs
566
567         try_me inst
568           | isFreeWhenInferring qtvs inst = Free
569           | isClassDict inst              = DontReduceUnlessConstant    -- Dicts
570           | otherwise                     = ReduceMe                    -- Lits and Methods
571     in
572     traceTc (text "infloop" <+> vcat [ppr tau_tvs', ppr wanteds', ppr preds, ppr (grow preds tau_tvs'), ppr qtvs])      `thenM_`
573                 -- Step 2
574     reduceContext doc try_me [] wanteds'    `thenM` \ (no_improvement, frees, binds, irreds) ->
575
576                 -- Step 3
577     if no_improvement then
578         returnM (varSetElems qtvs, frees, binds, irreds)
579     else
580         -- If improvement did some unification, we go round again.  There
581         -- are two subtleties:
582         --   a) We start again with irreds, not wanteds
583         --      Using an instance decl might have introduced a fresh type variable
584         --      which might have been unified, so we'd get an infinite loop
585         --      if we started again with wanteds!  See example [LOOP]
586         --
587         --   b) It's also essential to re-process frees, because unification
588         --      might mean that a type variable that looked free isn't now.
589         --
590         -- Hence the (irreds ++ frees)
591
592         -- However, NOTICE that when we are done, we might have some bindings, but
593         -- the final qtvs might be empty.  See [NO TYVARS] below.
594                                 
595         inferLoop doc tau_tvs (irreds ++ frees) `thenM` \ (qtvs1, frees1, binds1, irreds1) ->
596         returnM (qtvs1, frees1, binds `AndMonoBinds` binds1, irreds1)
597 \end{code}
598
599 Example [LOOP]
600
601         class If b t e r | b t e -> r
602         instance If T t e t
603         instance If F t e e
604         class Lte a b c | a b -> c where lte :: a -> b -> c
605         instance Lte Z b T
606         instance (Lte a b l,If l b a c) => Max a b c
607
608 Wanted: Max Z (S x) y
609
610 Then we'll reduce using the Max instance to:
611         (Lte Z (S x) l, If l (S x) Z y)
612 and improve by binding l->T, after which we can do some reduction
613 on both the Lte and If constraints.  What we *can't* do is start again
614 with (Max Z (S x) y)!
615
616 [NO TYVARS]
617
618         class Y a b | a -> b where
619             y :: a -> X b
620         
621         instance Y [[a]] a where
622             y ((x:_):_) = X x
623         
624         k :: X a -> X a -> X a
625
626         g :: Num a => [X a] -> [X a]
627         g xs = h xs
628             where
629             h ys = ys ++ map (k (y [[0]])) xs
630
631 The excitement comes when simplifying the bindings for h.  Initially
632 try to simplify {y @ [[t1]] t2, 0 @ t1}, with initial qtvs = {t2}.
633 From this we get t1:=:t2, but also various bindings.  We can't forget
634 the bindings (because of [LOOP]), but in fact t1 is what g is
635 polymorphic in.  
636
637 The net effect of [NO TYVARS] 
638
639 \begin{code}
640 isFreeWhenInferring :: TyVarSet -> Inst -> Bool
641 isFreeWhenInferring qtvs inst
642   =  isFreeWrtTyVars qtvs inst          -- Constrains no quantified vars
643   && isInheritableInst inst             -- And no implicit parameter involved
644                                         -- (see "Notes on implicit parameters")
645
646 isFreeWhenChecking :: TyVarSet  -- Quantified tyvars
647                    -> NameSet   -- Quantified implicit parameters
648                    -> Inst -> Bool
649 isFreeWhenChecking qtvs ips inst
650   =  isFreeWrtTyVars qtvs inst
651   && isFreeWrtIPs    ips inst
652
653 isFreeWrtTyVars qtvs inst = not (tyVarsOfInst inst `intersectsVarSet` qtvs)
654 isFreeWrtIPs     ips inst = not (any (`elemNameSet` ips) (ipNamesOfInst inst))
655 \end{code}
656
657
658 %************************************************************************
659 %*                                                                      *
660 \subsection{tcSimplifyCheck}
661 %*                                                                      *
662 %************************************************************************
663
664 @tcSimplifyCheck@ is used when we know exactly the set of variables
665 we are going to quantify over.  For example, a class or instance declaration.
666
667 \begin{code}
668 tcSimplifyCheck
669          :: SDoc
670          -> [TcTyVar]           -- Quantify over these
671          -> [Inst]              -- Given
672          -> [Inst]              -- Wanted
673          -> TcM TcDictBinds     -- Bindings
674
675 -- tcSimplifyCheck is used when checking expression type signatures,
676 -- class decls, instance decls etc.
677 --
678 -- NB: tcSimplifyCheck does not consult the
679 --      global type variables in the environment; so you don't
680 --      need to worry about setting them before calling tcSimplifyCheck
681 tcSimplifyCheck doc qtvs givens wanted_lie
682   = tcSimplCheck doc get_qtvs
683                  givens wanted_lie      `thenM` \ (qtvs', binds) ->
684     returnM binds
685   where
686     get_qtvs = zonkTcTyVarsAndFV qtvs
687
688
689 -- tcSimplifyInferCheck is used when we know the constraints we are to simplify
690 -- against, but we don't know the type variables over which we are going to quantify.
691 -- This happens when we have a type signature for a mutually recursive group
692 tcSimplifyInferCheck
693          :: SDoc
694          -> TcTyVarSet          -- fv(T)
695          -> [Inst]              -- Given
696          -> [Inst]              -- Wanted
697          -> TcM ([TcTyVar],     -- Variables over which to quantify
698                  TcDictBinds)   -- Bindings
699
700 tcSimplifyInferCheck doc tau_tvs givens wanted_lie
701   = tcSimplCheck doc get_qtvs givens wanted_lie
702   where
703         -- Figure out which type variables to quantify over
704         -- You might think it should just be the signature tyvars,
705         -- but in bizarre cases you can get extra ones
706         --      f :: forall a. Num a => a -> a
707         --      f x = fst (g (x, head [])) + 1
708         --      g a b = (b,a)
709         -- Here we infer g :: forall a b. a -> b -> (b,a)
710         -- We don't want g to be monomorphic in b just because
711         -- f isn't quantified over b.
712     all_tvs = varSetElems (tau_tvs `unionVarSet` tyVarsOfInsts givens)
713
714     get_qtvs = zonkTcTyVarsAndFV all_tvs        `thenM` \ all_tvs' ->
715                tcGetGlobalTyVars                `thenM` \ gbl_tvs ->
716                let
717                   qtvs = all_tvs' `minusVarSet` gbl_tvs
718                         -- We could close gbl_tvs, but its not necessary for
719                         -- soundness, and it'll only affect which tyvars, not which
720                         -- dictionaries, we quantify over
721                in
722                returnM qtvs
723 \end{code}
724
725 Here is the workhorse function for all three wrappers.
726
727 \begin{code}
728 tcSimplCheck doc get_qtvs givens wanted_lie
729   = check_loop givens wanted_lie        `thenM` \ (qtvs, frees, binds, irreds) ->
730
731         -- Complain about any irreducible ones
732     complainCheck doc givens irreds             `thenM_`
733
734         -- Done
735     extendLIEs frees                            `thenM_`
736     returnM (qtvs, binds)
737
738   where
739     ip_set = mkNameSet (ipNamesOfInsts givens)
740
741     check_loop givens wanteds
742       =         -- Step 1
743         mappM zonkInst givens   `thenM` \ givens' ->
744         mappM zonkInst wanteds  `thenM` \ wanteds' ->
745         get_qtvs                `thenM` \ qtvs' ->
746
747                     -- Step 2
748         let
749             -- When checking against a given signature we always reduce
750             -- until we find a match against something given, or can't reduce
751             try_me inst | isFreeWhenChecking qtvs' ip_set inst = Free
752                         | otherwise                            = ReduceMe
753         in
754         reduceContext doc try_me givens' wanteds'       `thenM` \ (no_improvement, frees, binds, irreds) ->
755
756                     -- Step 3
757         if no_improvement then
758             returnM (varSetElems qtvs', frees, binds, irreds)
759         else
760             check_loop givens' (irreds ++ frees)        `thenM` \ (qtvs', frees1, binds1, irreds1) ->
761             returnM (qtvs', frees1, binds `AndMonoBinds` binds1, irreds1)
762 \end{code}
763
764
765 %************************************************************************
766 %*                                                                      *
767 \subsection{tcSimplifyRestricted}
768 %*                                                                      *
769 %************************************************************************
770
771 \begin{code}
772 tcSimplifyRestricted    -- Used for restricted binding groups
773                         -- i.e. ones subject to the monomorphism restriction
774         :: SDoc
775         -> TcTyVarSet           -- Free in the type of the RHSs
776         -> [Inst]               -- Free in the RHSs
777         -> TcM ([TcTyVar],      -- Tyvars to quantify (zonked)
778                 TcDictBinds)    -- Bindings
779
780 tcSimplifyRestricted doc tau_tvs wanteds
781   =     -- First squash out all methods, to find the constrained tyvars
782         -- We can't just take the free vars of wanted_lie because that'll
783         -- have methods that may incidentally mention entirely unconstrained variables
784         --      e.g. a call to  f :: Eq a => a -> b -> b
785         -- Here, b is unconstrained.  A good example would be
786         --      foo = f (3::Int)
787         -- We want to infer the polymorphic type
788         --      foo :: forall b. b -> b
789
790         -- 'reduceMe': Reduce as far as we can.  Don't stop at
791         -- dicts; the idea is to get rid of as many type
792         -- variables as possible, and we don't want to stop
793         -- at (say) Monad (ST s), because that reduces
794         -- immediately, with no constraint on s.
795     simpleReduceLoop doc reduceMe wanteds       `thenM` \ (foo_frees, foo_binds, constrained_dicts) ->
796
797         -- Next, figure out the tyvars we will quantify over
798     zonkTcTyVarsAndFV (varSetElems tau_tvs)     `thenM` \ tau_tvs' ->
799     tcGetGlobalTyVars                           `thenM` \ gbl_tvs ->
800     let
801         constrained_tvs = tyVarsOfInsts constrained_dicts
802         qtvs = (tau_tvs' `minusVarSet` oclose (fdPredsOfInsts constrained_dicts) gbl_tvs)
803                          `minusVarSet` constrained_tvs
804     in
805     traceTc (text "tcSimplifyRestricted" <+> vcat [
806                 pprInsts wanteds, pprInsts foo_frees, pprInsts constrained_dicts,
807                 ppr foo_binds,
808                 ppr constrained_tvs, ppr tau_tvs', ppr qtvs ])  `thenM_`
809
810         -- The first step may have squashed more methods than
811         -- necessary, so try again, this time knowing the exact
812         -- set of type variables to quantify over.
813         --
814         -- We quantify only over constraints that are captured by qtvs;
815         -- these will just be a subset of non-dicts.  This in contrast
816         -- to normal inference (using isFreeWhenInferring) in which we quantify over
817         -- all *non-inheritable* constraints too.  This implements choice
818         -- (B) under "implicit parameter and monomorphism" above.
819         --
820         -- Remember that we may need to do *some* simplification, to
821         -- (for example) squash {Monad (ST s)} into {}.  It's not enough
822         -- just to float all constraints
823     restrict_loop doc qtvs wanteds
824         -- We still need a loop because improvement can take place
825         -- E.g. if we have (C (T a)) and the instance decl
826         --      instance D Int b => C (T a) where ...
827         -- and there's a functional dependency for D.   Then we may improve
828         -- the tyep variable 'b'.
829
830 restrict_loop doc qtvs wanteds
831   = mappM zonkInst wanteds                      `thenM` \ wanteds' ->
832     zonkTcTyVarsAndFV (varSetElems qtvs)        `thenM` \ qtvs' ->
833     let
834         try_me inst | isFreeWrtTyVars qtvs' inst = Free
835                     | otherwise                  = ReduceMe
836     in
837     reduceContext doc try_me [] wanteds'        `thenM` \ (no_improvement, frees, binds, irreds) ->
838     if no_improvement then
839         ASSERT( null irreds )
840         extendLIEs frees                        `thenM_`
841         returnM (varSetElems qtvs', binds)
842     else
843         restrict_loop doc qtvs' (irreds ++ frees)       `thenM` \ (qtvs1, binds1) ->
844         returnM (qtvs1, binds `AndMonoBinds` binds1)
845 \end{code}
846
847
848 %************************************************************************
849 %*                                                                      *
850 \subsection{tcSimplifyToDicts}
851 %*                                                                      *
852 %************************************************************************
853
854 On the LHS of transformation rules we only simplify methods and constants,
855 getting dictionaries.  We want to keep all of them unsimplified, to serve
856 as the available stuff for the RHS of the rule.
857
858 The same thing is used for specialise pragmas. Consider
859
860         f :: Num a => a -> a
861         {-# SPECIALISE f :: Int -> Int #-}
862         f = ...
863
864 The type checker generates a binding like:
865
866         f_spec = (f :: Int -> Int)
867
868 and we want to end up with
869
870         f_spec = _inline_me_ (f Int dNumInt)
871
872 But that means that we must simplify the Method for f to (f Int dNumInt)!
873 So tcSimplifyToDicts squeezes out all Methods.
874
875 IMPORTANT NOTE:  we *don't* want to do superclass commoning up.  Consider
876
877         fromIntegral :: (Integral a, Num b) => a -> b
878         {-# RULES "foo"  fromIntegral = id :: Int -> Int #-}
879
880 Here, a=b=Int, and Num Int is a superclass of Integral Int. But we *dont*
881 want to get
882
883         forall dIntegralInt.
884         fromIntegral Int Int dIntegralInt (scsel dIntegralInt) = id Int
885
886 because the scsel will mess up matching.  Instead we want
887
888         forall dIntegralInt, dNumInt.
889         fromIntegral Int Int dIntegralInt dNumInt = id Int
890
891 Hence "DontReduce NoSCs"
892
893 \begin{code}
894 tcSimplifyToDicts :: [Inst] -> TcM (TcDictBinds)
895 tcSimplifyToDicts wanteds
896   = simpleReduceLoop doc try_me wanteds         `thenM` \ (frees, binds, irreds) ->
897         -- Since try_me doesn't look at types, we don't need to
898         -- do any zonking, so it's safe to call reduceContext directly
899     ASSERT( null frees )
900     extendLIEs irreds           `thenM_`
901     returnM binds
902
903   where
904     doc = text "tcSimplifyToDicts"
905
906         -- Reduce methods and lits only; stop as soon as we get a dictionary
907     try_me inst | isDict inst = DontReduce NoSCs
908                 | otherwise   = ReduceMe
909 \end{code}
910
911
912
913 tcSimplifyBracket is used when simplifying the constraints arising from
914 a Template Haskell bracket [| ... |].  We want to check that there aren't
915 any constraints that can't be satisfied (e.g. Show Foo, where Foo has no
916 Show instance), but we aren't otherwise interested in the results.
917 Nor do we care about ambiguous dictionaries etc.  We will type check
918 this bracket again at its usage site.
919
920 \begin{code}
921 tcSimplifyBracket :: [Inst] -> TcM ()
922 tcSimplifyBracket wanteds
923   = simpleReduceLoop doc reduceMe wanteds       `thenM_`
924     returnM ()
925   where
926     doc = text "tcSimplifyBracket"
927 \end{code}
928
929
930 %************************************************************************
931 %*                                                                      *
932 \subsection{Filtering at a dynamic binding}
933 %*                                                                      *
934 %************************************************************************
935
936 When we have
937         let ?x = R in B
938
939 we must discharge all the ?x constraints from B.  We also do an improvement
940 step; if we have ?x::t1 and ?x::t2 we must unify t1, t2.
941
942 Actually, the constraints from B might improve the types in ?x. For example
943
944         f :: (?x::Int) => Char -> Char
945         let ?x = 3 in f 'c'
946
947 then the constraint (?x::Int) arising from the call to f will
948 force the binding for ?x to be of type Int.
949
950 \begin{code}
951 tcSimplifyIPs :: [Inst]         -- The implicit parameters bound here
952               -> [Inst]         -- Wanted
953               -> TcM TcDictBinds
954 tcSimplifyIPs given_ips wanteds
955   = simpl_loop given_ips wanteds        `thenM` \ (frees, binds) ->
956     extendLIEs frees                    `thenM_`
957     returnM binds
958   where
959     doc      = text "tcSimplifyIPs" <+> ppr given_ips
960     ip_set   = mkNameSet (ipNamesOfInsts given_ips)
961
962         -- Simplify any methods that mention the implicit parameter
963     try_me inst | isFreeWrtIPs ip_set inst = Free
964                 | otherwise                = ReduceMe
965
966     simpl_loop givens wanteds
967       = mappM zonkInst givens           `thenM` \ givens' ->
968         mappM zonkInst wanteds          `thenM` \ wanteds' ->
969
970         reduceContext doc try_me givens' wanteds'    `thenM` \ (no_improvement, frees, binds, irreds) ->
971
972         if no_improvement then
973             ASSERT( null irreds )
974             returnM (frees, binds)
975         else
976             simpl_loop givens' (irreds ++ frees)        `thenM` \ (frees1, binds1) ->
977             returnM (frees1, binds `AndMonoBinds` binds1)
978 \end{code}
979
980
981 %************************************************************************
982 %*                                                                      *
983 \subsection[binds-for-local-funs]{@bindInstsOfLocalFuns@}
984 %*                                                                      *
985 %************************************************************************
986
987 When doing a binding group, we may have @Insts@ of local functions.
988 For example, we might have...
989 \begin{verbatim}
990 let f x = x + 1     -- orig local function (overloaded)
991     f.1 = f Int     -- two instances of f
992     f.2 = f Float
993  in
994     (f.1 5, f.2 6.7)
995 \end{verbatim}
996 The point is: we must drop the bindings for @f.1@ and @f.2@ here,
997 where @f@ is in scope; those @Insts@ must certainly not be passed
998 upwards towards the top-level.  If the @Insts@ were binding-ified up
999 there, they would have unresolvable references to @f@.
1000
1001 We pass in an @init_lie@ of @Insts@ and a list of locally-bound @Ids@.
1002 For each method @Inst@ in the @init_lie@ that mentions one of the
1003 @Ids@, we create a binding.  We return the remaining @Insts@ (in an
1004 @LIE@), as well as the @HsBinds@ generated.
1005
1006 \begin{code}
1007 bindInstsOfLocalFuns :: [Inst] -> [TcId] -> TcM TcMonoBinds
1008
1009 bindInstsOfLocalFuns wanteds local_ids
1010   | null overloaded_ids
1011         -- Common case
1012   = extendLIEs wanteds          `thenM_`
1013     returnM EmptyMonoBinds
1014
1015   | otherwise
1016   = simpleReduceLoop doc try_me wanteds         `thenM` \ (frees, binds, irreds) ->
1017     ASSERT( null irreds )
1018     extendLIEs frees            `thenM_`
1019     returnM binds
1020   where
1021     doc              = text "bindInsts" <+> ppr local_ids
1022     overloaded_ids   = filter is_overloaded local_ids
1023     is_overloaded id = isOverloadedTy (idType id)
1024
1025     overloaded_set = mkVarSet overloaded_ids    -- There can occasionally be a lot of them
1026                                                 -- so it's worth building a set, so that
1027                                                 -- lookup (in isMethodFor) is faster
1028
1029     try_me inst | isMethodFor overloaded_set inst = ReduceMe
1030                 | otherwise                       = Free
1031 \end{code}
1032
1033
1034 %************************************************************************
1035 %*                                                                      *
1036 \subsection{Data types for the reduction mechanism}
1037 %*                                                                      *
1038 %************************************************************************
1039
1040 The main control over context reduction is here
1041
1042 \begin{code}
1043 data WhatToDo
1044  = ReduceMe             -- Try to reduce this
1045                         -- If there's no instance, behave exactly like
1046                         -- DontReduce: add the inst to
1047                         -- the irreductible ones, but don't
1048                         -- produce an error message of any kind.
1049                         -- It might be quite legitimate such as (Eq a)!
1050
1051  | DontReduce WantSCs           -- Return as irreducible
1052
1053  | DontReduceUnlessConstant     -- Return as irreducible unless it can
1054                                 -- be reduced to a constant in one step
1055
1056  | Free                   -- Return as free
1057
1058 reduceMe :: Inst -> WhatToDo
1059 reduceMe inst = ReduceMe
1060
1061 data WantSCs = NoSCs | AddSCs   -- Tells whether we should add the superclasses
1062                                 -- of a predicate when adding it to the avails
1063 \end{code}
1064
1065
1066
1067 \begin{code}
1068 type Avails = FiniteMap Inst Avail
1069
1070 data Avail
1071   = IsFree              -- Used for free Insts
1072   | Irred               -- Used for irreducible dictionaries,
1073                         -- which are going to be lambda bound
1074
1075   | Given TcId          -- Used for dictionaries for which we have a binding
1076                         -- e.g. those "given" in a signature
1077           Bool          -- True <=> actually consumed (splittable IPs only)
1078
1079   | NoRhs               -- Used for Insts like (CCallable f)
1080                         -- where no witness is required.
1081                         -- ToDo: remove?
1082
1083   | Rhs                 -- Used when there is a RHS
1084         TcExpr          -- The RHS
1085         [Inst]          -- Insts free in the RHS; we need these too
1086
1087   | Linear              -- Splittable Insts only.
1088         Int             -- The Int is always 2 or more; indicates how
1089                         -- many copies are required
1090         Inst            -- The splitter
1091         Avail           -- Where the "master copy" is
1092
1093   | LinRhss             -- Splittable Insts only; this is used only internally
1094                         --      by extractResults, where a Linear 
1095                         --      is turned into an LinRhss
1096         [TcExpr]        -- A supply of suitable RHSs
1097
1098 pprAvails avails = vcat [sep [ppr inst, nest 2 (equals <+> pprAvail avail)]
1099                         | (inst,avail) <- fmToList avails ]
1100
1101 instance Outputable Avail where
1102     ppr = pprAvail
1103
1104 pprAvail NoRhs          = text "<no rhs>"
1105 pprAvail IsFree         = text "Free"
1106 pprAvail Irred          = text "Irred"
1107 pprAvail (Given x b)    = text "Given" <+> ppr x <+> 
1108                           if b then text "(used)" else empty
1109 pprAvail (Rhs rhs bs)   = text "Rhs" <+> ppr rhs <+> braces (ppr bs)
1110 pprAvail (Linear n i a) = text "Linear" <+> ppr n <+> braces (ppr i) <+> ppr a
1111 pprAvail (LinRhss rhss) = text "LinRhss" <+> ppr rhss
1112 \end{code}
1113
1114 Extracting the bindings from a bunch of Avails.
1115 The bindings do *not* come back sorted in dependency order.
1116 We assume that they'll be wrapped in a big Rec, so that the
1117 dependency analyser can sort them out later
1118
1119 The loop startes
1120 \begin{code}
1121 extractResults :: Avails
1122                -> [Inst]                -- Wanted
1123                -> TcM (TcDictBinds,     -- Bindings
1124                           [Inst],       -- Irreducible ones
1125                           [Inst])       -- Free ones
1126
1127 extractResults avails wanteds
1128   = go avails EmptyMonoBinds [] [] wanteds
1129   where
1130     go avails binds irreds frees [] 
1131       = returnM (binds, irreds, frees)
1132
1133     go avails binds irreds frees (w:ws)
1134       = case lookupFM avails w of
1135           Nothing    -> pprTrace "Urk: extractResults" (ppr w) $
1136                         go avails binds irreds frees ws
1137
1138           Just NoRhs  -> go avails               binds irreds     frees     ws
1139           Just IsFree -> go (add_free avails w)  binds irreds     (w:frees) ws
1140           Just Irred  -> go (add_given avails w) binds (w:irreds) frees     ws
1141
1142           Just (Given id _) -> go avails new_binds irreds frees ws
1143                             where
1144                                new_binds | id == instToId w = binds
1145                                          | otherwise        = addBind binds w (HsVar id)
1146                 -- The sought Id can be one of the givens, via a superclass chain
1147                 -- and then we definitely don't want to generate an x=x binding!
1148
1149           Just (Rhs rhs ws') -> go (add_given avails w) new_binds irreds frees (ws' ++ ws)
1150                              where
1151                                 new_binds = addBind binds w rhs
1152
1153           Just (Linear n split_inst avail)      -- Transform Linear --> LinRhss
1154             -> get_root irreds frees avail w            `thenM` \ (irreds', frees', root_id) ->
1155                split n (instToId split_inst) root_id w  `thenM` \ (binds', rhss) ->
1156                go (addToFM avails w (LinRhss rhss))
1157                   (binds `AndMonoBinds` binds')
1158                   irreds' frees' (split_inst : w : ws)
1159
1160           Just (LinRhss (rhs:rhss))             -- Consume one of the Rhss
1161                 -> go new_avails new_binds irreds frees ws
1162                 where           
1163                    new_binds  = addBind binds w rhs
1164                    new_avails = addToFM avails w (LinRhss rhss)
1165
1166     get_root irreds frees (Given id _) w = returnM (irreds, frees, id)
1167     get_root irreds frees Irred        w = cloneDict w  `thenM` \ w' ->
1168                                            returnM (w':irreds, frees, instToId w')
1169     get_root irreds frees IsFree       w = cloneDict w  `thenM` \ w' ->
1170                                            returnM (irreds, w':frees, instToId w')
1171
1172     add_given avails w 
1173         | instBindingRequired w = addToFM avails w (Given (instToId w) True)
1174         | otherwise             = addToFM avails w NoRhs
1175         -- NB: make sure that CCallable/CReturnable use NoRhs rather
1176         --      than Given, else we end up with bogus bindings.
1177
1178     add_free avails w | isMethod w = avails
1179                       | otherwise  = add_given avails w
1180         -- NB: Hack alert!  
1181         -- Do *not* replace Free by Given if it's a method.
1182         -- The following situation shows why this is bad:
1183         --      truncate :: forall a. RealFrac a => forall b. Integral b => a -> b
1184         -- From an application (truncate f i) we get
1185         --      t1 = truncate at f
1186         --      t2 = t1 at i
1187         -- If we have also have a second occurrence of truncate, we get
1188         --      t3 = truncate at f
1189         --      t4 = t3 at i
1190         -- When simplifying with i,f free, we might still notice that
1191         --   t1=t3; but alas, the binding for t2 (which mentions t1)
1192         --   will continue to float out!
1193         -- (split n i a) returns: n rhss
1194         --                        auxiliary bindings
1195         --                        1 or 0 insts to add to irreds
1196
1197
1198 split :: Int -> TcId -> TcId -> Inst 
1199       -> TcM (TcDictBinds, [TcExpr])
1200 -- (split n split_id root_id wanted) returns
1201 --      * a list of 'n' expressions, all of which witness 'avail'
1202 --      * a bunch of auxiliary bindings to support these expressions
1203 --      * one or zero insts needed to witness the whole lot
1204 --        (maybe be zero if the initial Inst is a Given)
1205 --
1206 -- NB: 'wanted' is just a template
1207
1208 split n split_id root_id wanted
1209   = go n
1210   where
1211     ty      = linearInstType wanted
1212     pair_ty = mkTyConApp pairTyCon [ty,ty]
1213     id      = instToId wanted
1214     occ     = getOccName id
1215     loc     = getSrcLoc id
1216
1217     go 1 = returnM (EmptyMonoBinds, [HsVar root_id])
1218
1219     go n = go ((n+1) `div` 2)           `thenM` \ (binds1, rhss) ->
1220            expand n rhss                `thenM` \ (binds2, rhss') ->
1221            returnM (binds1 `AndMonoBinds` binds2, rhss')
1222
1223         -- (expand n rhss) 
1224         -- Given ((n+1)/2) rhss, make n rhss, using auxiliary bindings
1225         --  e.g.  expand 3 [rhs1, rhs2]
1226         --        = ( { x = split rhs1 },
1227         --            [fst x, snd x, rhs2] )
1228     expand n rhss
1229         | n `rem` 2 == 0 = go rhss      -- n is even
1230         | otherwise      = go (tail rhss)       `thenM` \ (binds', rhss') ->
1231                            returnM (binds', head rhss : rhss')
1232         where
1233           go rhss = mapAndUnzipM do_one rhss    `thenM` \ (binds', rhss') ->
1234                     returnM (andMonoBindList binds', concat rhss')
1235
1236           do_one rhs = newUnique                        `thenM` \ uniq -> 
1237                        tcLookupId fstName               `thenM` \ fst_id ->
1238                        tcLookupId sndName               `thenM` \ snd_id ->
1239                        let 
1240                           x = mkUserLocal occ uniq pair_ty loc
1241                        in
1242                        returnM (VarMonoBind x (mk_app split_id rhs),
1243                                     [mk_fs_app fst_id ty x, mk_fs_app snd_id ty x])
1244
1245 mk_fs_app id ty var = HsVar id `TyApp` [ty,ty] `HsApp` HsVar var
1246
1247 mk_app id rhs = HsApp (HsVar id) rhs
1248
1249 addBind binds inst rhs = binds `AndMonoBinds` VarMonoBind (instToId inst) rhs
1250 \end{code}
1251
1252
1253 %************************************************************************
1254 %*                                                                      *
1255 \subsection[reduce]{@reduce@}
1256 %*                                                                      *
1257 %************************************************************************
1258
1259 When the "what to do" predicate doesn't depend on the quantified type variables,
1260 matters are easier.  We don't need to do any zonking, unless the improvement step
1261 does something, in which case we zonk before iterating.
1262
1263 The "given" set is always empty.
1264
1265 \begin{code}
1266 simpleReduceLoop :: SDoc
1267                  -> (Inst -> WhatToDo)          -- What to do, *not* based on the quantified type variables
1268                  -> [Inst]                      -- Wanted
1269                  -> TcM ([Inst],                -- Free
1270                          TcDictBinds,
1271                          [Inst])                -- Irreducible
1272
1273 simpleReduceLoop doc try_me wanteds
1274   = mappM zonkInst wanteds                      `thenM` \ wanteds' ->
1275     reduceContext doc try_me [] wanteds'        `thenM` \ (no_improvement, frees, binds, irreds) ->
1276     if no_improvement then
1277         returnM (frees, binds, irreds)
1278     else
1279         simpleReduceLoop doc try_me (irreds ++ frees)   `thenM` \ (frees1, binds1, irreds1) ->
1280         returnM (frees1, binds `AndMonoBinds` binds1, irreds1)
1281 \end{code}
1282
1283
1284
1285 \begin{code}
1286 reduceContext :: SDoc
1287               -> (Inst -> WhatToDo)
1288               -> [Inst]                 -- Given
1289               -> [Inst]                 -- Wanted
1290               -> TcM (Bool,             -- True <=> improve step did no unification
1291                          [Inst],        -- Free
1292                          TcDictBinds,   -- Dictionary bindings
1293                          [Inst])        -- Irreducible
1294
1295 reduceContext doc try_me givens wanteds
1296   =
1297     traceTc (text "reduceContext" <+> (vcat [
1298              text "----------------------",
1299              doc,
1300              text "given" <+> ppr givens,
1301              text "wanted" <+> ppr wanteds,
1302              text "----------------------"
1303              ]))                                        `thenM_`
1304
1305         -- Build the Avail mapping from "givens"
1306     foldlM addGiven emptyFM givens                      `thenM` \ init_state ->
1307
1308         -- Do the real work
1309     reduceList (0,[]) try_me wanteds init_state         `thenM` \ avails ->
1310
1311         -- Do improvement, using everything in avails
1312         -- In particular, avails includes all superclasses of everything
1313     tcImprove avails                                    `thenM` \ no_improvement ->
1314
1315     extractResults avails wanteds                       `thenM` \ (binds, irreds, frees) ->
1316
1317     traceTc (text "reduceContext end" <+> (vcat [
1318              text "----------------------",
1319              doc,
1320              text "given" <+> ppr givens,
1321              text "wanted" <+> ppr wanteds,
1322              text "----",
1323              text "avails" <+> pprAvails avails,
1324              text "frees" <+> ppr frees,
1325              text "no_improvement =" <+> ppr no_improvement,
1326              text "----------------------"
1327              ]))                                        `thenM_`
1328
1329     returnM (no_improvement, frees, binds, irreds)
1330
1331 tcImprove avails
1332  =  tcGetInstEnv                                `thenM` \ inst_env ->
1333     let
1334         preds = [ (pred, pp_loc)
1335                 | inst <- keysFM avails,
1336                   let pp_loc = pprInstLoc (instLoc inst),
1337                   pred <- fdPredsOfInst inst
1338                 ]
1339                 -- Avails has all the superclasses etc (good)
1340                 -- It also has all the intermediates of the deduction (good)
1341                 -- It does not have duplicates (good)
1342                 -- NB that (?x::t1) and (?x::t2) will be held separately in avails
1343                 --    so that improve will see them separate
1344         eqns  = improve (classInstEnv inst_env) preds
1345      in
1346      if null eqns then
1347         returnM True
1348      else
1349         traceTc (ptext SLIT("Improve:") <+> vcat (map pprEquationDoc eqns))     `thenM_`
1350         mappM_ unify eqns       `thenM_`
1351         returnM False
1352   where
1353     unify ((qtvs, t1, t2), doc)
1354          = addErrCtxt doc                               $
1355            tcInstTyVars VanillaTv (varSetElems qtvs)    `thenM` \ (_, _, tenv) ->
1356            unifyTauTy (substTy tenv t1) (substTy tenv t2)
1357 \end{code}
1358
1359 The main context-reduction function is @reduce@.  Here's its game plan.
1360
1361 \begin{code}
1362 reduceList :: (Int,[Inst])              -- Stack (for err msgs)
1363                                         -- along with its depth
1364            -> (Inst -> WhatToDo)
1365            -> [Inst]
1366            -> Avails
1367            -> TcM Avails
1368 \end{code}
1369
1370 @reduce@ is passed
1371      try_me:    given an inst, this function returns
1372                   Reduce       reduce this
1373                   DontReduce   return this in "irreds"
1374                   Free         return this in "frees"
1375
1376      wanteds:   The list of insts to reduce
1377      state:     An accumulating parameter of type Avails
1378                 that contains the state of the algorithm
1379
1380   It returns a Avails.
1381
1382 The (n,stack) pair is just used for error reporting.
1383 n is always the depth of the stack.
1384 The stack is the stack of Insts being reduced: to produce X
1385 I had to produce Y, to produce Y I had to produce Z, and so on.
1386
1387 \begin{code}
1388 reduceList (n,stack) try_me wanteds state
1389   | n > opt_MaxContextReductionDepth
1390   = failWithTc (reduceDepthErr n stack)
1391
1392   | otherwise
1393   =
1394 #ifdef DEBUG
1395    (if n > 8 then
1396         pprTrace "Jeepers! ReduceContext:" (reduceDepthMsg n stack)
1397     else (\x->x))
1398 #endif
1399     go wanteds state
1400   where
1401     go []     state = returnM state
1402     go (w:ws) state = reduce (n+1, w:stack) try_me w state      `thenM` \ state' ->
1403                       go ws state'
1404
1405     -- Base case: we're done!
1406 reduce stack try_me wanted state
1407     -- It's the same as an existing inst, or a superclass thereof
1408   | Just avail <- isAvailable state wanted
1409   = if isLinearInst wanted then
1410         addLinearAvailable state avail wanted   `thenM` \ (state', wanteds') ->
1411         reduceList stack try_me wanteds' state'
1412     else
1413         returnM state           -- No op for non-linear things
1414
1415   | otherwise
1416   = case try_me wanted of {
1417
1418       DontReduce want_scs -> addIrred want_scs state wanted
1419
1420     ; DontReduceUnlessConstant ->    -- It's irreducible (or at least should not be reduced)
1421                                      -- First, see if the inst can be reduced to a constant in one step
1422         try_simple (addIrred AddSCs)    -- Assume want superclasses
1423
1424     ; Free ->   -- It's free so just chuck it upstairs
1425                 -- First, see if the inst can be reduced to a constant in one step
1426         try_simple addFree
1427
1428     ; ReduceMe ->               -- It should be reduced
1429         lookupInst wanted             `thenM` \ lookup_result ->
1430         case lookup_result of
1431             GenInst wanteds' rhs -> addWanted state wanted rhs wanteds'         `thenM` \ state' ->
1432                                     reduceList stack try_me wanteds' state'
1433                 -- Experiment with doing addWanted *before* the reduceList, 
1434                 -- which has the effect of adding the thing we are trying
1435                 -- to prove to the database before trying to prove the things it
1436                 -- needs.  See note [RECURSIVE DICTIONARIES]
1437
1438             SimpleInst rhs       -> addWanted state wanted rhs []
1439
1440             NoInstance ->    -- No such instance!
1441                              -- Add it and its superclasses
1442                              addIrred AddSCs state wanted
1443
1444     }
1445   where
1446     try_simple do_this_otherwise
1447       = lookupInst wanted         `thenM` \ lookup_result ->
1448         case lookup_result of
1449             SimpleInst rhs -> addWanted state wanted rhs []
1450             other          -> do_this_otherwise state wanted
1451 \end{code}
1452
1453
1454 \begin{code}
1455 -------------------------
1456 isAvailable :: Avails -> Inst -> Maybe Avail
1457 isAvailable avails wanted = lookupFM avails wanted
1458         -- NB 1: the Ord instance of Inst compares by the class/type info
1459         -- *not* by unique.  So
1460         --      d1::C Int ==  d2::C Int
1461
1462 addLinearAvailable :: Avails -> Avail -> Inst -> TcM (Avails, [Inst])
1463 addLinearAvailable avails avail wanted
1464         -- avails currently maps [wanted -> avail]
1465         -- Extend avails to reflect a neeed for an extra copy of avail
1466
1467   | Just avail' <- split_avail avail
1468   = returnM (addToFM avails wanted avail', [])
1469
1470   | otherwise
1471   = tcLookupId splitName                        `thenM` \ split_id ->
1472     tcInstClassOp (instLoc wanted) split_id 
1473                   [linearInstType wanted]       `thenM` \ split_inst ->
1474     returnM (addToFM avails wanted (Linear 2 split_inst avail), [split_inst])
1475
1476   where
1477     split_avail :: Avail -> Maybe Avail
1478         -- (Just av) if there's a modified version of avail that
1479         --           we can use to replace avail in avails
1480         -- Nothing   if there isn't, so we need to create a Linear
1481     split_avail (Linear n i a)              = Just (Linear (n+1) i a)
1482     split_avail (Given id used) | not used  = Just (Given id True)
1483                                 | otherwise = Nothing
1484     split_avail Irred                       = Nothing
1485     split_avail IsFree                      = Nothing
1486     split_avail other = pprPanic "addLinearAvailable" (ppr avail $$ ppr wanted $$ ppr avails)
1487                   
1488 -------------------------
1489 addFree :: Avails -> Inst -> TcM Avails
1490         -- When an Inst is tossed upstairs as 'free' we nevertheless add it
1491         -- to avails, so that any other equal Insts will be commoned up right
1492         -- here rather than also being tossed upstairs.  This is really just
1493         -- an optimisation, and perhaps it is more trouble that it is worth,
1494         -- as the following comments show!
1495         --
1496         -- NB: do *not* add superclasses.  If we have
1497         --      df::Floating a
1498         --      dn::Num a
1499         -- but a is not bound here, then we *don't* want to derive
1500         -- dn from df here lest we lose sharing.
1501         --
1502 addFree avails free = returnM (addToFM avails free IsFree)
1503
1504 addWanted :: Avails -> Inst -> TcExpr -> [Inst] -> TcM Avails
1505 addWanted avails wanted rhs_expr wanteds
1506   = ASSERT2( not (wanted `elemFM` avails), ppr wanted $$ ppr avails )
1507     addAvailAndSCs avails wanted avail
1508   where
1509     avail | instBindingRequired wanted = Rhs rhs_expr wanteds
1510           | otherwise                  = ASSERT( null wanteds ) NoRhs
1511
1512 addGiven :: Avails -> Inst -> TcM Avails
1513 addGiven state given = addAvailAndSCs state given (Given (instToId given) False)
1514         -- No ASSERT( not (given `elemFM` avails) ) because in an instance
1515         -- decl for Ord t we can add both Ord t and Eq t as 'givens', 
1516         -- so the assert isn't true
1517
1518 addIrred :: WantSCs -> Avails -> Inst -> TcM Avails
1519 addIrred NoSCs  avails irred = returnM (addToFM avails irred Irred)
1520 addIrred AddSCs avails irred = ASSERT2( not (irred `elemFM` avails), ppr irred $$ ppr avails )
1521                                addAvailAndSCs avails irred Irred
1522
1523 addAvailAndSCs :: Avails -> Inst -> Avail -> TcM Avails
1524 addAvailAndSCs avails inst avail
1525   | not (isClassDict inst) = returnM avails1
1526   | otherwise              = addSCs is_loop avails1 inst 
1527   where
1528     avails1 = addToFM avails inst avail
1529     is_loop inst = inst `elem` deps     -- Note: this compares by *type*, not by Unique
1530     deps         = findAllDeps avails avail
1531
1532 findAllDeps :: Avails -> Avail -> [Inst]
1533 -- Find all the Insts that this one depends on
1534 -- See Note [SUPERCLASS-LOOP]
1535 findAllDeps avails (Rhs _ kids) = kids ++ concat (map (find_all_deps_help avails) kids)
1536 findAllDeps avails other        = []
1537
1538 find_all_deps_help :: Avails -> Inst -> [Inst]
1539 find_all_deps_help avails inst
1540   = case lookupFM avails inst of
1541         Just avail -> findAllDeps avails avail
1542         Nothing    -> []
1543
1544 addSCs :: (Inst -> Bool) -> Avails -> Inst -> TcM Avails
1545         -- Add all the superclasses of the Inst to Avails
1546         -- The first param says "dont do this because the original thing
1547         --      depends on this one, so you'd build a loop"
1548         -- Invariant: the Inst is already in Avails.
1549
1550 addSCs is_loop avails dict
1551   = newDictsFromOld dict sc_theta'      `thenM` \ sc_dicts ->
1552     foldlM add_sc avails (zipEqual "add_scs" sc_dicts sc_sels)
1553   where
1554     (clas, tys) = getDictClassTys dict
1555     (tyvars, sc_theta, sc_sels, _) = classBigSig clas
1556     sc_theta' = substTheta (mkTopTyVarSubst tyvars tys) sc_theta
1557
1558     add_sc avails (sc_dict, sc_sel)     -- Add it, and its superclasses
1559       = case lookupFM avails sc_dict of
1560           Just (Given _ _) -> returnM avails    -- Given is cheaper than
1561                                                         --   a superclass selection
1562           Just other | is_loop sc_dict -> returnM avails        -- See Note [SUPERCLASS-LOOP]
1563                      | otherwise       -> returnM avails'       -- SCs already added
1564
1565           Nothing -> addSCs is_loop avails' sc_dict
1566       where
1567         sc_sel_rhs = DictApp (TyApp (HsVar sc_sel) tys) [instToId dict]
1568         avail      = Rhs sc_sel_rhs [dict]
1569         avails'    = addToFM avails sc_dict avail
1570 \end{code}
1571
1572 Note [SUPERCLASS-LOOP]: Checking for loops
1573 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1574 We have to be careful here.  If we are *given* d1:Ord a,
1575 and want to deduce (d2:C [a]) where
1576
1577         class Ord a => C a where
1578         instance Ord a => C [a] where ...
1579
1580 Then we'll use the instance decl to deduce C [a] and then add the
1581 superclasses of C [a] to avails.  But we must not overwrite the binding
1582 for d1:Ord a (which is given) with a superclass selection or we'll just
1583 build a loop! 
1584
1585 Here's another example 
1586         class Eq b => Foo a b
1587         instance Eq a => Foo [a] a
1588 If we are reducing
1589         (Foo [t] t)
1590
1591 we'll first deduce that it holds (via the instance decl).  We must not
1592 then overwrite the Eq t constraint with a superclass selection!
1593
1594 At first I had a gross hack, whereby I simply did not add superclass constraints
1595 in addWanted, though I did for addGiven and addIrred.  This was sub-optimal,
1596 becuase it lost legitimate superclass sharing, and it still didn't do the job:
1597 I found a very obscure program (now tcrun021) in which improvement meant the
1598 simplifier got two bites a the cherry... so something seemed to be an Irred
1599 first time, but reducible next time.
1600
1601 Now we implement the Right Solution, which is to check for loops directly 
1602 when adding superclasses.  It's a bit like the occurs check in unification.
1603
1604
1605 Note [RECURSIVE DICTIONARIES]
1606 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1607 Consider 
1608     data D r = ZeroD | SuccD (r (D r));
1609     
1610     instance (Eq (r (D r))) => Eq (D r) where
1611         ZeroD     == ZeroD     = True
1612         (SuccD a) == (SuccD b) = a == b
1613         _         == _         = False;
1614     
1615     equalDC :: D [] -> D [] -> Bool;
1616     equalDC = (==);
1617
1618 We need to prove (Eq (D [])).  Here's how we go:
1619
1620         d1 : Eq (D [])
1621
1622 by instance decl, holds if
1623         d2 : Eq [D []]
1624         where   d1 = dfEqD d2
1625
1626 by instance decl of Eq, holds if
1627         d3 : D []
1628         where   d2 = dfEqList d2
1629                 d1 = dfEqD d2
1630
1631 But now we can "tie the knot" to give
1632
1633         d3 = d1
1634         d2 = dfEqList d2
1635         d1 = dfEqD d2
1636
1637 and it'll even run!  The trick is to put the thing we are trying to prove
1638 (in this case Eq (D []) into the database before trying to prove its
1639 contributing clauses.
1640         
1641
1642 %************************************************************************
1643 %*                                                                      *
1644 \section{tcSimplifyTop: defaulting}
1645 %*                                                                      *
1646 %************************************************************************
1647
1648
1649 @tcSimplifyTop@ is called once per module to simplify all the constant
1650 and ambiguous Insts.
1651
1652 We need to be careful of one case.  Suppose we have
1653
1654         instance Num a => Num (Foo a b) where ...
1655
1656 and @tcSimplifyTop@ is given a constraint (Num (Foo x y)).  Then it'll simplify
1657 to (Num x), and default x to Int.  But what about y??
1658
1659 It's OK: the final zonking stage should zap y to (), which is fine.
1660
1661
1662 \begin{code}
1663 tcSimplifyTop, tcSimplifyInteractive :: [Inst] -> TcM TcDictBinds
1664 tcSimplifyTop         wanteds = tc_simplify_top False {- Not interactive loop -} wanteds
1665 tcSimplifyInteractive wanteds = tc_simplify_top True  {- Interactive loop -}     wanteds
1666
1667
1668 -- The TcLclEnv should be valid here, solely to improve
1669 -- error message generation for the monomorphism restriction
1670 tc_simplify_top is_interactive wanteds
1671   = getLclEnv                                                   `thenM` \ lcl_env ->
1672     traceTc (text "tcSimplifyTop" <+> ppr (lclEnvElts lcl_env)) `thenM_`
1673     simpleReduceLoop (text "tcSimplTop") reduceMe wanteds       `thenM` \ (frees, binds, irreds) ->
1674     ASSERT( null frees )
1675
1676     let
1677                 -- All the non-std ones are definite errors
1678         (stds, non_stds) = partition isStdClassTyVarDict irreds
1679
1680                 -- Group by type variable
1681         std_groups = equivClasses cmp_by_tyvar stds
1682
1683                 -- Pick the ones which its worth trying to disambiguate
1684                 -- namely, the onese whose type variable isn't bound
1685                 -- up with one of the non-standard classes
1686         (std_oks, std_bads)     = partition worth_a_try std_groups
1687         worth_a_try group@(d:_) = not (non_std_tyvars `intersectsVarSet` tyVarsOfInst d)
1688         non_std_tyvars          = unionVarSets (map tyVarsOfInst non_stds)
1689
1690                 -- Collect together all the bad guys
1691         bad_guys               = non_stds ++ concat std_bads
1692         (tidy_env, tidy_dicts) = tidyInsts bad_guys
1693         (bad_ips, non_ips)     = partition isIPDict tidy_dicts
1694         (no_insts, ambigs)     = partition no_inst non_ips
1695         no_inst d              = not (isTyVarDict d) 
1696         -- Previously, there was a more elaborate no_inst definition:
1697         --      no_inst d = not (isTyVarDict d) || tyVarsOfInst d `subVarSet` fixed_tvs
1698         --      fixed_tvs = oclose (fdPredsOfInsts tidy_dicts) emptyVarSet
1699         -- But that seems over-elaborate to me; it only bites for class decls with
1700         -- fundeps like this:           class C a b | -> b where ...
1701     in
1702
1703         -- Report definite errors
1704     addTopInstanceErrs tidy_env no_insts        `thenM_`
1705     addTopIPErrs tidy_env bad_ips               `thenM_`
1706
1707         -- Deal with ambiguity errors, but only if
1708         -- if there has not been an error so far; errors often
1709         -- give rise to spurious ambiguous Insts
1710     ifErrsM (returnM []) (
1711         
1712         -- Complain about the ones that don't fall under
1713         -- the Haskell rules for disambiguation
1714         -- This group includes both non-existent instances
1715         --      e.g. Num (IO a) and Eq (Int -> Int)
1716         -- and ambiguous dictionaries
1717         --      e.g. Num a
1718         addTopAmbigErrs (tidy_env, ambigs)      `thenM_`
1719
1720         -- Disambiguate the ones that look feasible
1721         mappM (disambigGroup is_interactive) std_oks
1722     )                                   `thenM` \ binds_ambig ->
1723
1724     returnM (binds `andMonoBinds` andMonoBindList binds_ambig)
1725
1726 ----------------------------------
1727 d1 `cmp_by_tyvar` d2 = get_tv d1 `compare` get_tv d2
1728
1729 get_tv d   = case getDictClassTys d of
1730                    (clas, [ty]) -> tcGetTyVar "tcSimplify" ty
1731 get_clas d = case getDictClassTys d of
1732                    (clas, [ty]) -> clas
1733 \end{code}
1734
1735 If a dictionary constrains a type variable which is
1736         * not mentioned in the environment
1737         * and not mentioned in the type of the expression
1738 then it is ambiguous. No further information will arise to instantiate
1739 the type variable; nor will it be generalised and turned into an extra
1740 parameter to a function.
1741
1742 It is an error for this to occur, except that Haskell provided for
1743 certain rules to be applied in the special case of numeric types.
1744 Specifically, if
1745         * at least one of its classes is a numeric class, and
1746         * all of its classes are numeric or standard
1747 then the type variable can be defaulted to the first type in the
1748 default-type list which is an instance of all the offending classes.
1749
1750 So here is the function which does the work.  It takes the ambiguous
1751 dictionaries and either resolves them (producing bindings) or
1752 complains.  It works by splitting the dictionary list by type
1753 variable, and using @disambigOne@ to do the real business.
1754
1755 @disambigOne@ assumes that its arguments dictionaries constrain all
1756 the same type variable.
1757
1758 ADR Comment 20/6/94: I've changed the @CReturnable@ case to default to
1759 @()@ instead of @Int@.  I reckon this is the Right Thing to do since
1760 the most common use of defaulting is code like:
1761 \begin{verbatim}
1762         _ccall_ foo     `seqPrimIO` bar
1763 \end{verbatim}
1764 Since we're not using the result of @foo@, the result if (presumably)
1765 @void@.
1766
1767 \begin{code}
1768 disambigGroup :: Bool   -- True <=> simplifying at top-level interactive loop
1769               -> [Inst] -- All standard classes of form (C a)
1770               -> TcM TcDictBinds
1771
1772 disambigGroup is_interactive dicts
1773   |   any std_default_class classes     -- Guaranteed all standard classes
1774   =     -- THE DICTS OBEY THE DEFAULTABLE CONSTRAINT
1775         -- SO, TRY DEFAULT TYPES IN ORDER
1776
1777         -- Failure here is caused by there being no type in the
1778         -- default list which can satisfy all the ambiguous classes.
1779         -- For example, if Real a is reqd, but the only type in the
1780         -- default list is Int.
1781     getDefaultTys                       `thenM` \ default_tys ->
1782     let
1783       try_default []    -- No defaults work, so fail
1784         = failM
1785
1786       try_default (default_ty : default_tys)
1787         = tryTcLIE_ (try_default default_tys) $ -- If default_ty fails, we try
1788                                                 -- default_tys instead
1789           tcSimplifyDefault theta               `thenM` \ _ ->
1790           returnM default_ty
1791         where
1792           theta = [mkClassPred clas [default_ty] | clas <- classes]
1793     in
1794         -- See if any default works
1795     tryM (try_default default_tys)      `thenM` \ mb_ty ->
1796     case mb_ty of
1797         Left  _                 -> bomb_out
1798         Right chosen_default_ty -> choose_default chosen_default_ty
1799
1800   | otherwise                           -- No defaults
1801   = bomb_out
1802
1803   where
1804     tyvar   = get_tv (head dicts)       -- Should be non-empty
1805     classes = map get_clas dicts
1806
1807     std_default_class cls
1808       =  isNumericClass cls
1809       || (is_interactive && 
1810           classKey cls `elem` [showClassKey, eqClassKey, ordClassKey])
1811                 -- In interactive mode, we default Show a to Show ()
1812                 -- to avoid graututious errors on "show []"
1813
1814     choose_default default_ty   -- Commit to tyvar = default_ty
1815       = -- Bind the type variable 
1816         unifyTauTy default_ty (mkTyVarTy tyvar) `thenM_`
1817         -- and reduce the context, for real this time
1818         simpleReduceLoop (text "disambig" <+> ppr dicts)
1819                      reduceMe dicts                     `thenM` \ (frees, binds, ambigs) ->
1820         WARN( not (null frees && null ambigs), ppr frees $$ ppr ambigs )
1821         warnDefault dicts default_ty                    `thenM_`
1822         returnM binds
1823
1824     bomb_out = addTopAmbigErrs (tidyInsts dicts)        `thenM_`
1825                returnM EmptyMonoBinds
1826 \end{code}
1827
1828 [Aside - why the defaulting mechanism is turned off when
1829  dealing with arguments and results to ccalls.
1830
1831 When typechecking _ccall_s, TcExpr ensures that the external
1832 function is only passed arguments (and in the other direction,
1833 results) of a restricted set of 'native' types. This is
1834 implemented via the help of the pseudo-type classes,
1835 @CReturnable@ (CR) and @CCallable@ (CC.)
1836
1837 The interaction between the defaulting mechanism for numeric
1838 values and CC & CR can be a bit puzzling to the user at times.
1839 For example,
1840
1841     x <- _ccall_ f
1842     if (x /= 0) then
1843        _ccall_ g x
1844      else
1845        return ()
1846
1847 What type has 'x' got here? That depends on the default list
1848 in operation, if it is equal to Haskell 98's default-default
1849 of (Integer, Double), 'x' has type Double, since Integer
1850 is not an instance of CR. If the default list is equal to
1851 Haskell 1.4's default-default of (Int, Double), 'x' has type
1852 Int.
1853
1854 To try to minimise the potential for surprises here, the
1855 defaulting mechanism is turned off in the presence of
1856 CCallable and CReturnable.
1857
1858 End of aside]
1859
1860
1861 %************************************************************************
1862 %*                                                                      *
1863 \subsection[simple]{@Simple@ versions}
1864 %*                                                                      *
1865 %************************************************************************
1866
1867 Much simpler versions when there are no bindings to make!
1868
1869 @tcSimplifyThetas@ simplifies class-type constraints formed by
1870 @deriving@ declarations and when specialising instances.  We are
1871 only interested in the simplified bunch of class/type constraints.
1872
1873 It simplifies to constraints of the form (C a b c) where
1874 a,b,c are type variables.  This is required for the context of
1875 instance declarations.
1876
1877 \begin{code}
1878 tcSimplifyDeriv :: [TyVar]      
1879                 -> ThetaType            -- Wanted
1880                 -> TcM ThetaType        -- Needed
1881
1882 tcSimplifyDeriv tyvars theta
1883   = tcInstTyVars VanillaTv tyvars                       `thenM` \ (tvs, _, tenv) ->
1884         -- The main loop may do unification, and that may crash if 
1885         -- it doesn't see a TcTyVar, so we have to instantiate. Sigh
1886         -- ToDo: what if two of them do get unified?
1887     newDicts DataDeclOrigin (substTheta tenv theta)     `thenM` \ wanteds ->
1888     simpleReduceLoop doc reduceMe wanteds               `thenM` \ (frees, _, irreds) ->
1889     ASSERT( null frees )                        -- reduceMe never returns Free
1890
1891     doptM Opt_AllowUndecidableInstances         `thenM` \ undecidable_ok ->
1892     let
1893         tv_set      = mkVarSet tvs
1894         simpl_theta = map dictPred irreds       -- reduceMe squashes all non-dicts
1895
1896         check_pred pred
1897           | isEmptyVarSet pred_tyvars   -- Things like (Eq T) should be rejected
1898           = addErrTc (noInstErr pred)
1899
1900           | not undecidable_ok && not (isTyVarClassPred pred)
1901           -- Check that the returned dictionaries are all of form (C a b)
1902           --    (where a, b are type variables).  
1903           -- We allow this if we had -fallow-undecidable-instances,
1904           -- but note that risks non-termination in the 'deriving' context-inference
1905           -- fixpoint loop.   It is useful for situations like
1906           --    data Min h a = E | M a (h a)
1907           -- which gives the instance decl
1908           --    instance (Eq a, Eq (h a)) => Eq (Min h a)
1909           = addErrTc (noInstErr pred)
1910   
1911           | not (pred_tyvars `subVarSet` tv_set) 
1912           -- Check for a bizarre corner case, when the derived instance decl should
1913           -- have form  instance C a b => D (T a) where ...
1914           -- Note that 'b' isn't a parameter of T.  This gives rise to all sorts
1915           -- of problems; in particular, it's hard to compare solutions for
1916           -- equality when finding the fixpoint.  So I just rule it out for now.
1917           = addErrTc (badDerivedPred pred)
1918   
1919           | otherwise
1920           = returnM ()
1921           where
1922             pred_tyvars = tyVarsOfPred pred
1923
1924         rev_env = mkTopTyVarSubst tvs (mkTyVarTys tyvars)
1925                 -- This reverse-mapping is a Royal Pain, 
1926                 -- but the result should mention TyVars not TcTyVars
1927     in
1928    
1929     mappM check_pred simpl_theta                `thenM_`
1930     checkAmbiguity tvs simpl_theta tv_set       `thenM_`
1931     returnM (substTheta rev_env simpl_theta)
1932   where
1933     doc    = ptext SLIT("deriving classes for a data type")
1934 \end{code}
1935
1936 @tcSimplifyDefault@ just checks class-type constraints, essentially;
1937 used with \tr{default} declarations.  We are only interested in
1938 whether it worked or not.
1939
1940 \begin{code}
1941 tcSimplifyDefault :: ThetaType  -- Wanted; has no type variables in it
1942                   -> TcM ()
1943
1944 tcSimplifyDefault theta
1945   = newDicts DataDeclOrigin theta               `thenM` \ wanteds ->
1946     simpleReduceLoop doc reduceMe wanteds       `thenM` \ (frees, _, irreds) ->
1947     ASSERT( null frees )        -- try_me never returns Free
1948     mappM (addErrTc . noInstErr) irreds         `thenM_`
1949     if null irreds then
1950         returnM ()
1951     else
1952         failM
1953   where
1954     doc = ptext SLIT("default declaration")
1955 \end{code}
1956
1957
1958 %************************************************************************
1959 %*                                                                      *
1960 \section{Errors and contexts}
1961 %*                                                                      *
1962 %************************************************************************
1963
1964 ToDo: for these error messages, should we note the location as coming
1965 from the insts, or just whatever seems to be around in the monad just
1966 now?
1967
1968 \begin{code}
1969 groupErrs :: ([Inst] -> TcM ()) -- Deal with one group
1970           -> [Inst]             -- The offending Insts
1971           -> TcM ()
1972 -- Group together insts with the same origin
1973 -- We want to report them together in error messages
1974
1975 groupErrs report_err [] 
1976   = returnM ()
1977 groupErrs report_err (inst:insts) 
1978   = do_one (inst:friends)               `thenM_`
1979     groupErrs report_err others
1980
1981   where
1982         -- (It may seem a bit crude to compare the error messages,
1983         --  but it makes sure that we combine just what the user sees,
1984         --  and it avoids need equality on InstLocs.)
1985    (friends, others) = partition is_friend insts
1986    loc_msg           = showSDoc (pprInstLoc (instLoc inst))
1987    is_friend friend  = showSDoc (pprInstLoc (instLoc friend)) == loc_msg
1988    do_one insts = addInstCtxt (instLoc (head insts)) (report_err insts)
1989                 -- Add location and context information derived from the Insts
1990
1991 -- Add the "arising from..." part to a message about bunch of dicts
1992 addInstLoc :: [Inst] -> Message -> Message
1993 addInstLoc insts msg = msg $$ nest 2 (pprInstLoc (instLoc (head insts)))
1994
1995 plural [x] = empty
1996 plural xs  = char 's'
1997
1998
1999 addTopIPErrs tidy_env tidy_dicts
2000   = groupErrs report tidy_dicts
2001   where
2002     report dicts = addErrTcM (tidy_env, mk_msg dicts)
2003     mk_msg dicts = addInstLoc dicts (ptext SLIT("Unbound implicit parameter") <> 
2004                                      plural tidy_dicts <+> pprInsts tidy_dicts)
2005
2006 -- Used for top-level irreducibles
2007 addTopInstanceErrs tidy_env tidy_dicts
2008   = groupErrs report tidy_dicts
2009   where
2010     report dicts = mkMonomorphismMsg tidy_env dicts     `thenM` \ (tidy_env, mono_msg) ->
2011                    addErrTcM (tidy_env, mk_msg dicts $$ mono_msg)
2012     mk_msg dicts = addInstLoc dicts (ptext SLIT("No instance") <> plural tidy_dicts <+> 
2013                                      ptext SLIT("for") <+> pprInsts tidy_dicts)
2014                    
2015
2016 addTopAmbigErrs (tidy_env, tidy_dicts)
2017 -- Divide into groups that share a common set of ambiguous tyvars
2018   = mapM report (equivClasses cmp [(d, tvs_of d) | d <- tidy_dicts])
2019   where
2020     tvs_of :: Inst -> [TcTyVar]
2021     tvs_of d = varSetElems (tyVarsOfInst d)
2022     cmp (_,tvs1) (_,tvs2) = tvs1 `compare` tvs2
2023     
2024     report :: [(Inst,[TcTyVar])] -> TcM ()
2025     report pairs@((_,tvs) : _)  -- The pairs share a common set of ambiguous tyvars
2026         = mkMonomorphismMsg tidy_env dicts      `thenM` \ (tidy_env, mono_msg) ->
2027           addErrTcM (tidy_env, msg $$ mono_msg)
2028         where
2029           dicts = map fst pairs
2030           msg = sep [text "Ambiguous type variable" <> plural tvs <+> 
2031                              pprQuotedList tvs <+> in_msg,
2032                      nest 2 (pprInstsInFull dicts)]
2033           in_msg | isSingleton dicts = text "in the top-level constraint:"
2034                  | otherwise         = text "in these top-level constraints:"
2035
2036
2037 mkMonomorphismMsg :: TidyEnv -> [Inst] -> TcM (TidyEnv, Message)
2038 -- There's an error with these Insts; if they have free type variables
2039 -- it's probably caused by the monomorphism restriction. 
2040 -- Try to identify the offending variable
2041 -- ASSUMPTION: the Insts are fully zonked
2042 mkMonomorphismMsg tidy_env insts
2043   | isEmptyVarSet inst_tvs
2044   = returnM (tidy_env, empty)
2045   | otherwise
2046   = findGlobals inst_tvs tidy_env       `thenM` \ (tidy_env, docs) ->
2047     returnM (tidy_env, mk_msg docs)
2048
2049   where
2050     inst_tvs = tyVarsOfInsts insts
2051
2052     mk_msg []   = empty         -- This happens in things like
2053                                 --      f x = show (read "foo")
2054                                 -- whre monomorphism doesn't play any role
2055     mk_msg docs = vcat [ptext SLIT("Possible cause: the monomorphism restriction applied to the following:"),
2056                         nest 2 (vcat docs),
2057                         ptext SLIT("Probable fix: give these definition(s) an explicit type signature")]
2058     
2059 warnDefault dicts default_ty
2060   = doptM Opt_WarnTypeDefaults  `thenM` \ warn_flag ->
2061     addInstCtxt (instLoc (head dicts)) (warnTc warn_flag warn_msg)
2062   where
2063         -- Tidy them first
2064     (_, tidy_dicts) = tidyInsts dicts
2065     warn_msg  = vcat [ptext SLIT("Defaulting the following constraint(s) to type") <+>
2066                                 quotes (ppr default_ty),
2067                       pprInstsInFull tidy_dicts]
2068
2069 complainCheck doc givens irreds
2070   = mappM zonkInst given_dicts_and_ips                  `thenM` \ givens' ->
2071     groupErrs (addNoInstanceErrs doc givens') irreds    `thenM_`
2072     returnM ()
2073   where
2074     given_dicts_and_ips = filter (not . isMethod) givens
2075         -- Filter out methods, which are only added to
2076         -- the given set as an optimisation
2077
2078 addNoInstanceErrs what_doc givens dicts
2079   = getDOpts            `thenM` \ dflags ->
2080     tcGetInstEnv        `thenM` \ inst_env ->
2081     let
2082         (tidy_env1, tidy_givens) = tidyInsts givens
2083         (tidy_env2, tidy_dicts)  = tidyMoreInsts tidy_env1 dicts
2084
2085         doc = vcat [addInstLoc dicts $
2086                     sep [herald <+> pprInsts tidy_dicts,
2087                          nest 4 $ ptext SLIT("from the context") <+> pprInsts tidy_givens],
2088                     ambig_doc,
2089                     ptext SLIT("Probable fix:"),
2090                     nest 4 fix1,
2091                     nest 4 fix2]
2092
2093         herald = ptext SLIT("Could not") <+> unambig_doc <+> ptext SLIT("deduce")
2094         unambig_doc | ambig_overlap = ptext SLIT("unambiguously")
2095                     | otherwise     = empty
2096
2097                 -- The error message when we don't find a suitable instance
2098                 -- is complicated by the fact that sometimes this is because
2099                 -- there is no instance, and sometimes it's because there are
2100                 -- too many instances (overlap).  See the comments in TcEnv.lhs
2101                 -- with the InstEnv stuff.
2102
2103         ambig_doc
2104             | not ambig_overlap = empty
2105             | otherwise
2106             = vcat [ptext SLIT("The choice of (overlapping) instance declaration"),
2107                     nest 4 (ptext SLIT("depends on the instantiation of") <+>
2108                             quotes (pprWithCommas ppr (varSetElems (tyVarsOfInsts tidy_dicts))))]
2109
2110         fix1 = sep [ptext SLIT("Add") <+> pprInsts tidy_dicts,
2111                     ptext SLIT("to the") <+> what_doc]
2112
2113         fix2 | null instance_dicts 
2114              = empty
2115              | otherwise
2116              = ptext SLIT("Or add an instance declaration for") <+> pprInsts instance_dicts
2117
2118         instance_dicts = [d | d <- tidy_dicts, isClassDict d, not (isTyVarDict d)]
2119                 -- Insts for which it is worth suggesting an adding an instance declaration
2120                 -- Exclude implicit parameters, and tyvar dicts
2121
2122             -- Checks for the ambiguous case when we have overlapping instances
2123         ambig_overlap = any ambig_overlap1 dicts
2124         ambig_overlap1 dict 
2125                 | isClassDict dict
2126                 = case lookupInstEnv dflags inst_env clas tys of
2127                             NoMatch ambig -> ambig
2128                             other         -> False
2129                 | otherwise = False
2130                 where
2131                   (clas,tys) = getDictClassTys dict
2132     in
2133     addErrTcM (tidy_env2, doc)
2134
2135 -- Used for the ...Thetas variants; all top level
2136 noInstErr pred = ptext SLIT("No instance for") <+> quotes (ppr pred)
2137
2138 badDerivedPred pred
2139   = vcat [ptext SLIT("Can't derive instances where the instance context mentions"),
2140           ptext SLIT("type variables that are not data type parameters"),
2141           nest 2 (ptext SLIT("Offending constraint:") <+> ppr pred)]
2142
2143 reduceDepthErr n stack
2144   = vcat [ptext SLIT("Context reduction stack overflow; size =") <+> int n,
2145           ptext SLIT("Use -fcontext-stack20 to increase stack size to (e.g.) 20"),
2146           nest 4 (pprInstsInFull stack)]
2147
2148 reduceDepthMsg n stack = nest 4 (pprInstsInFull stack)
2149 \end{code}