Re-jig simplifySuperClass (again)
[ghc-hetmet.git] / compiler / typecheck / TcSimplify.lhs
1 \begin{code}
2 module TcSimplify( 
3        simplifyInfer, simplifySuperClass,
4        simplifyDefault, simplifyDeriv, simplifyBracket,
5        simplifyRule, simplifyTop, simplifyInteractive
6   ) where
7
8 #include "HsVersions.h"
9
10 import HsSyn           
11 import TcRnMonad
12 import TcErrors
13 import TcCanonical
14 import TcMType
15 import TcType 
16 import TcSMonad 
17 import TcInteract
18 import Inst
19 import Var
20 import VarSet
21 import VarEnv 
22 import TypeRep
23
24 import Name
25 import NameEnv  ( emptyNameEnv )
26 import Bag
27 import ListSetOps
28 import Util
29 import PrelInfo
30 import PrelNames
31 import Class            ( classKey )
32 import BasicTypes       ( RuleName )
33 import Data.List        ( partition )
34 import Outputable
35 import FastString
36 import Control.Monad    ( unless )
37 \end{code}
38
39
40 *********************************************************************************
41 *                                                                               * 
42 *                           External interface                                  *
43 *                                                                               *
44 *********************************************************************************
45
46 \begin{code}
47 simplifyTop :: WantedConstraints -> TcM (Bag EvBind)
48 -- Simplify top-level constraints
49 -- Usually these will be implications, when there is
50 --   nothing to quanitfy we don't wrap in a degenerate implication,
51 --   so we do that here instead
52 simplifyTop wanteds 
53   = simplifyCheck SimplCheck wanteds
54
55 ------------------
56 simplifyInteractive :: WantedConstraints -> TcM (Bag EvBind)
57 simplifyInteractive wanteds 
58   = simplifyCheck SimplInteractive wanteds
59
60 ------------------
61 simplifyDefault :: ThetaType    -- Wanted; has no type variables in it
62                 -> TcM ()       -- Succeeds iff the constraint is soluble
63 simplifyDefault theta
64   = do { loc <- getCtLoc DefaultOrigin
65        ; wanted <- newWantedEvVars theta
66        ; let wanted_bag = listToBag [WcEvVar (WantedEvVar w loc) | w <- wanted]
67        ; _ignored_ev_binds <- simplifyCheck SimplCheck wanted_bag
68        ; return () }
69 \end{code}
70
71 simplifyBracket is used when simplifying the constraints arising from
72 a Template Haskell bracket [| ... |].  We want to check that there aren't
73 any constraints that can't be satisfied (e.g. Show Foo, where Foo has no
74 Show instance), but we aren't otherwise interested in the results.
75 Nor do we care about ambiguous dictionaries etc.  We will type check
76 this bracket again at its usage site.
77
78 \begin{code}
79 simplifyBracket :: WantedConstraints -> TcM ()
80 simplifyBracket wanteds
81   = do  { zonked_wanteds <- mapBagM zonkWanted wanteds 
82         ; _ <- simplifyAsMuchAsPossible SimplInfer zonked_wanteds
83         ; return () }
84 \end{code}
85
86
87 *********************************************************************************
88 *                                                                                 * 
89 *                            Deriving
90 *                                                                                 *
91 ***********************************************************************************
92
93 \begin{code}
94 simplifyDeriv :: CtOrigin
95                 -> [TyVar]      
96                 -> ThetaType            -- Wanted
97                 -> TcM ThetaType        -- Needed
98 -- Given  instance (wanted) => C inst_ty 
99 -- Simplify 'wanted' as much as possibles
100 simplifyDeriv orig tvs theta 
101   = do { tvs_skols <- tcInstSkolTyVars InstSkol tvs -- Skolemize 
102                    -- One reason is that the constraint solving machinery
103                    -- expects *TcTyVars* not TyVars.  Another is that
104                    -- when looking up instances we don't want overlap
105                    -- of type variables
106
107        ; let skol_subst = zipTopTvSubst tvs $ map mkTyVarTy tvs_skols
108              
109        ; loc    <- getCtLoc orig
110        ; wanted <- newWantedEvVars (substTheta skol_subst theta)
111        ; let wanted_bag = listToBag [WcEvVar (WantedEvVar w loc) | w <- wanted]
112
113        ; traceTc "simlifyDeriv" (ppr tvs $$ ppr theta $$ ppr wanted)
114        ; (unsolved, _binds) <- simplifyAsMuchAsPossible SimplInfer wanted_bag
115
116        ; let (good, bad) = partition validDerivPred $
117                            foldrBag ((:) . wantedEvVarPred) [] unsolved
118                 -- See Note [Exotic derived instance contexts]
119              subst_skol = zipTopTvSubst tvs_skols $ map mkTyVarTy tvs 
120
121        ; reportUnsolvedDeriv bad loc
122        ; return $ substTheta subst_skol good }
123 \end{code}
124
125 Note [Exotic derived instance contexts]
126 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
127 In a 'derived' instance declaration, we *infer* the context.  It's a
128 bit unclear what rules we should apply for this; the Haskell report is
129 silent.  Obviously, constraints like (Eq a) are fine, but what about
130         data T f a = MkT (f a) deriving( Eq )
131 where we'd get an Eq (f a) constraint.  That's probably fine too.
132
133 One could go further: consider
134         data T a b c = MkT (Foo a b c) deriving( Eq )
135         instance (C Int a, Eq b, Eq c) => Eq (Foo a b c)
136
137 Notice that this instance (just) satisfies the Paterson termination 
138 conditions.  Then we *could* derive an instance decl like this:
139
140         instance (C Int a, Eq b, Eq c) => Eq (T a b c) 
141 even though there is no instance for (C Int a), because there just
142 *might* be an instance for, say, (C Int Bool) at a site where we
143 need the equality instance for T's.  
144
145 However, this seems pretty exotic, and it's quite tricky to allow
146 this, and yet give sensible error messages in the (much more common)
147 case where we really want that instance decl for C.
148
149 So for now we simply require that the derived instance context
150 should have only type-variable constraints.
151
152 Here is another example:
153         data Fix f = In (f (Fix f)) deriving( Eq )
154 Here, if we are prepared to allow -XUndecidableInstances we
155 could derive the instance
156         instance Eq (f (Fix f)) => Eq (Fix f)
157 but this is so delicate that I don't think it should happen inside
158 'deriving'. If you want this, write it yourself!
159
160 NB: if you want to lift this condition, make sure you still meet the
161 termination conditions!  If not, the deriving mechanism generates
162 larger and larger constraints.  Example:
163   data Succ a = S a
164   data Seq a = Cons a (Seq (Succ a)) | Nil deriving Show
165
166 Note the lack of a Show instance for Succ.  First we'll generate
167   instance (Show (Succ a), Show a) => Show (Seq a)
168 and then
169   instance (Show (Succ (Succ a)), Show (Succ a), Show a) => Show (Seq a)
170 and so on.  Instead we want to complain of no instance for (Show (Succ a)).
171
172 The bottom line
173 ~~~~~~~~~~~~~~~
174 Allow constraints which consist only of type variables, with no repeats.
175
176 *********************************************************************************
177 *                                                                                 * 
178 *                            Inference
179 *                                                                                 *
180 ***********************************************************************************
181
182 \begin{code}
183 simplifyInfer :: Bool               -- Apply monomorphism restriction
184               -> TcTyVarSet         -- These type variables are free in the
185                                     -- types to be generalised
186               -> WantedConstraints
187               -> TcM ([TcTyVar],    -- Quantify over these type variables
188                       [EvVar],      -- ... and these constraints
189                       TcEvBinds)    -- ... binding these evidence variables
190 simplifyInfer apply_mr tau_tvs wanted
191   | isEmptyBag wanted     -- Trivial case is quite common
192   = do { zonked_tau_tvs <- zonkTcTyVarsAndFV tau_tvs
193        ; gbl_tvs        <- tcGetGlobalTyVars         -- Already zonked
194        ; qtvs <- zonkQuantifiedTyVars (varSetElems (zonked_tau_tvs `minusVarSet` gbl_tvs))
195        ; return (qtvs, [], emptyTcEvBinds) }
196
197   | otherwise
198   = do { zonked_wanted <- mapBagM zonkWanted wanted 
199        ; traceTc "simplifyInfer {"  $ vcat
200              [ ptext (sLit "apply_mr =") <+> ppr apply_mr
201              , ptext (sLit "wanted =") <+> ppr zonked_wanted
202              , ptext (sLit "tau_tvs =") <+> ppr tau_tvs
203              ]
204
205              -- Make a guess at the quantified type variables
206              -- Then split the constraints on the baisis of those tyvars
207              -- to avoid unnecessarily simplifying a class constraint
208              -- See Note [Avoid unecessary constraint simplification]
209        ; gbl_tvs <- tcGetGlobalTyVars
210        ; zonked_tau_tvs <- zonkTcTyVarsAndFV tau_tvs
211        ; let proto_qtvs = growWanteds gbl_tvs zonked_wanted $
212                           zonked_tau_tvs `minusVarSet` gbl_tvs
213              (perhaps_bound, surely_free) 
214                   = partitionBag (quantifyMeWC proto_qtvs) zonked_wanted
215       
216        ; emitConstraints surely_free
217        ; traceTc "sinf"  $ vcat
218              [ ptext (sLit "perhaps_bound =") <+> ppr perhaps_bound
219              , ptext (sLit "surely_free   =") <+> ppr surely_free
220              ]
221
222               -- Now simplify the possibly-bound constraints
223        ; (simplified_perhaps_bound, tc_binds) 
224               <- simplifyAsMuchAsPossible SimplInfer perhaps_bound
225
226               -- Sigh: must re-zonk because because simplifyAsMuchAsPossible
227               --       may have done some unification
228        ; gbl_tvs <- tcGetGlobalTyVars
229        ; zonked_tau_tvs <- zonkTcTyVarsAndFV tau_tvs
230        ; zonked_simples <- mapBagM zonkWantedEvVar simplified_perhaps_bound
231        ; let init_tvs        = zonked_tau_tvs `minusVarSet` gbl_tvs
232              mr_qtvs         = init_tvs `minusVarSet` constrained_tvs
233              constrained_tvs = tyVarsOfWantedEvVars zonked_simples
234              qtvs            = growWantedEVs gbl_tvs zonked_simples init_tvs
235              (final_qtvs, (bound, free))
236                 | apply_mr  = (mr_qtvs, (emptyBag, zonked_simples))
237                 | otherwise = (qtvs,    partitionBag (quantifyMe qtvs) zonked_simples)
238
239        ; traceTc "end simplifyInfer }" $
240               vcat [ ptext (sLit "apply_mr =") <+> ppr apply_mr
241                    , text "wanted = " <+> ppr zonked_wanted
242                    , text "qtvs =   " <+> ppr final_qtvs
243                    , text "free =   " <+> ppr free
244                    , text "bound =  " <+> ppr bound ]
245
246        -- Turn the quantified meta-type variables into real type variables 
247        ; emitConstraints (mapBag WcEvVar free)
248        ; qtvs_to_return <- zonkQuantifiedTyVars (varSetElems final_qtvs) 
249        ; let bound_evvars = bagToList $ mapBag wantedEvVarToVar bound
250        ; return (qtvs_to_return, bound_evvars, EvBinds tc_binds) }
251
252 ------------------------
253 simplifyAsMuchAsPossible :: SimplContext -> WantedConstraints
254                          -> TcM (Bag WantedEvVar, Bag EvBind) 
255 -- We use this function when inferring the type of a function
256 -- The wanted constraints are already zonked
257 simplifyAsMuchAsPossible ctxt wanteds
258   = do { let untch = NoUntouchables
259                  -- We allow ourselves to unify environment 
260                  -- variables; hence *no untouchables*
261
262        ; ((unsolved_flats, unsolved_implics), frozen_errors, ev_binds) 
263            <- runTcS ctxt untch $
264               simplifyApproxLoop 0 wanteds
265
266               -- Report any errors
267        ; reportUnsolved (emptyBag, unsolved_implics) frozen_errors
268
269        ; return (unsolved_flats, ev_binds) }
270
271   where 
272     simplifyApproxLoop :: Int -> WantedConstraints
273                        -> TcS (Bag WantedEvVar, Bag Implication)
274     simplifyApproxLoop n wanteds
275      | n > 10 
276      = pprPanic "simplifyApproxLoop loops!" (ppr n <+> text "iterations") 
277      | otherwise 
278      = do { traceTcS "simplifyApproxLoop" (vcat 
279                [ ptext (sLit "Wanted = ") <+> ppr wanteds ])
280           ; (unsolved_flats, unsolved_implics) <- solveWanteds emptyInert wanteds
281
282           ; let (extra_flats, thiner_unsolved_implics) 
283                     = approximateImplications unsolved_implics
284                 unsolved 
285                     = Bag.mapBag WcEvVar unsolved_flats `unionBags` 
286                                     Bag.mapBag WcImplic thiner_unsolved_implics
287
288           ; -- If no new work was produced then we are done with simplifyApproxLoop
289             if isEmptyBag extra_flats
290             then do { traceTcS "simplifyApproxLoopRes" (vcat 
291                               [ ptext (sLit "Wanted = ") <+> ppr wanteds
292                               , ptext (sLit "Result = ") <+> ppr unsolved_flats ])
293                     ; return (unsolved_flats, unsolved_implics) }
294
295             else -- Produced new flat work wanteds, go round the loop
296                 simplifyApproxLoop (n+1) (extra_flats `unionBags` unsolved)
297           }     
298
299 approximateImplications :: Bag Implication -> (WantedConstraints, Bag Implication) 
300 -- (wc1, impls2) <- approximateImplications impls 
301 -- splits 'impls' into two parts
302 --    wc1:    a bag of constraints that do not mention any skolems 
303 --    impls2: a bag of *thiner* implication constraints
304 approximateImplications impls 
305   = splitBag (do_implic emptyVarSet) impls
306   where 
307     ------------------
308     do_wanted :: TcTyVarSet -> WantedConstraint
309               -> (WantedConstraints, WantedConstraints) 
310     do_wanted skols (WcImplic impl) 
311         = let (fl_w, mb_impl) = do_implic skols impl 
312           in (fl_w, mapBag WcImplic mb_impl)
313     do_wanted skols wc@(WcEvVar wev) 
314       | tyVarsOfWantedEvVar wev `disjointVarSet` skols = (unitBag wc, emptyBag) 
315       | otherwise                                      = (emptyBag, unitBag wc) 
316      
317     ------------------
318     do_implic :: TcTyVarSet -> Implication
319               -> (WantedConstraints, Bag Implication)
320     do_implic skols impl@(Implic { ic_skols = skols', ic_wanted = wanted })
321      = (floatable_wanted, if isEmptyBag rest_wanted then emptyBag
322                           else unitBag impl{ ic_wanted = rest_wanted } ) 
323      where
324         (floatable_wanted, rest_wanted) 
325             = splitBag (do_wanted (skols `unionVarSet` skols')) wanted
326
327     ------------------
328     splitBag :: (a -> (WantedConstraints, Bag a))
329              -> Bag a -> (WantedConstraints, Bag a)
330     splitBag f bag = foldrBag do_one (emptyBag,emptyBag) bag
331        where
332          do_one x (b1,b2) 
333            = (wcs `unionBags` b1, imps `unionBags` b2)
334            where
335               (wcs, imps) = f x 
336 \end{code}
337
338 \begin{code}
339 growWantedEVs :: TyVarSet -> Bag WantedEvVar      -> TyVarSet -> TyVarSet
340 growWanteds   :: TyVarSet -> Bag WantedConstraint -> TyVarSet -> TyVarSet
341 growWanteds   gbl_tvs ws tvs
342   | isEmptyBag ws = tvs
343   | otherwise     = fixVarSet (\tvs -> foldrBag (growWanted   gbl_tvs) tvs ws) tvs
344 growWantedEVs gbl_tvs ws tvs 
345   | isEmptyBag ws = tvs
346   | otherwise     = fixVarSet (\tvs -> foldrBag (growWantedEV gbl_tvs) tvs ws) tvs
347
348 growEvVar    :: TyVarSet -> EvVar            -> TyVarSet -> TyVarSet
349 growWantedEV :: TyVarSet -> WantedEvVar      -> TyVarSet -> TyVarSet
350 growWanted   :: TyVarSet -> WantedConstraint -> TyVarSet -> TyVarSet
351 -- (growX gbls wanted tvs) grows a seed 'tvs' against the 
352 -- X-constraint 'wanted', nuking the 'gbls' at each stage
353
354 growEvVar gbl_tvs ev tvs
355   = tvs `unionVarSet` (ev_tvs `minusVarSet` gbl_tvs)
356   where
357     ev_tvs = growPredTyVars (evVarPred ev) tvs
358
359 growWantedEV gbl_tvs wev tvs = growEvVar gbl_tvs (wantedEvVarToVar wev) tvs
360
361 growWanted gbl_tvs (WcEvVar wev) tvs
362   = growWantedEV gbl_tvs wev tvs
363 growWanted gbl_tvs (WcImplic implic) tvs
364   = foldrBag (growWanted inner_gbl_tvs) 
365              (foldr (growEvVar inner_gbl_tvs) tvs (ic_given implic))
366                     -- Must grow over inner givens too
367              (ic_wanted implic)
368   where
369     inner_gbl_tvs = gbl_tvs `unionVarSet` ic_skols implic
370
371 --------------------
372 quantifyMe :: TyVarSet      -- Quantifying over these
373            -> WantedEvVar
374            -> Bool          -- True <=> quantify over this wanted
375 quantifyMe qtvs wev
376   | isIPPred pred = True  -- Note [Inheriting implicit parameters]
377   | otherwise     = tyVarsOfPred pred `intersectsVarSet` qtvs
378   where
379     pred = wantedEvVarPred wev
380
381 quantifyMeWC :: TyVarSet -> WantedConstraint -> Bool
382 -- False => we can *definitely* float the WantedConstraint out
383 quantifyMeWC qtvs (WcImplic implic)
384   =  (tyVarsOfEvVars (ic_given implic) `intersectsVarSet` inner_qtvs)
385   || anyBag (quantifyMeWC inner_qtvs) (ic_wanted implic)
386   where
387     inner_qtvs = qtvs `minusVarSet` ic_skols implic
388
389 quantifyMeWC qtvs (WcEvVar wev)
390   = quantifyMe qtvs wev
391 \end{code}
392
393 Note [Avoid unecessary constraint simplification]
394 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
395 When inferring the type of a let-binding, with simplifyInfer,
396 try to avoid unnecessariliy simplifying class constraints.
397 Doing so aids sharing, but it also helps with delicate 
398 situations like
399    instance C t => C [t] where ..
400    f :: C [t] => ....
401    f x = let g y = ...(constraint C [t])... 
402          in ...
403 When inferring a type for 'g', we don't want to apply the
404 instance decl, because then we can't satisfy (C t).  So we
405 just notice that g isn't quantified over 't' and partition
406 the contraints before simplifying.
407
408 This only half-works, but then let-generalisation only half-works.
409
410
411 Note [Inheriting implicit parameters]
412 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
413 Consider this:
414
415         f x = (x::Int) + ?y
416
417 where f is *not* a top-level binding.
418 From the RHS of f we'll get the constraint (?y::Int).
419 There are two types we might infer for f:
420
421         f :: Int -> Int
422
423 (so we get ?y from the context of f's definition), or
424
425         f :: (?y::Int) => Int -> Int
426
427 At first you might think the first was better, becuase then
428 ?y behaves like a free variable of the definition, rather than
429 having to be passed at each call site.  But of course, the WHOLE
430 IDEA is that ?y should be passed at each call site (that's what
431 dynamic binding means) so we'd better infer the second.
432
433 BOTTOM LINE: when *inferring types* you *must* quantify 
434 over implicit parameters. See the predicate isFreeWhenInferring.
435
436
437 *********************************************************************************
438 *                                                                                 * 
439 *                             Superclasses                                        *
440 *                                                                                 *
441 ***********************************************************************************
442
443 When constructing evidence for superclasses in an instance declaration, 
444   * we MUST have the "self" dictionary available
445
446 Moreover, we must *completely* solve the constraints right now,
447 not wrap them in an implication constraint to solve later.  Why?
448 Because when that implication constraint is solved there may
449 be some unrelated other solved top-level constraints that
450 recursively depend on the superclass we are building. Consider
451    class Ord a => C a where
452    instance C [Int] where ...
453 Then we get
454    dCListInt :: C [Int]
455    dCListInt = MkC $cNum ...
456
457    $cNum :: Ord [Int] -- The superclass
458    $cNum = let self = dCListInt in <solve Ord [Int]>
459
460 Now, if there is some *other* top-level constraint solved
461 looking like
462         foo :: Ord [Int]
463         foo = scsel dCInt
464 we must not solve the (Ord [Int]) wanted from foo!
465
466 Note [Dependencies in self dictionaries] 
467 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
468
469 Moreover, notice that when solving for a superclass, we record the dependency of 
470 self on the superclass. This is because this dependency is not evident in the 
471 EvBind of the self dictionary, which only involves a call to a DFun. Example: 
472
473 class A a => C a 
474 instance B a => C a 
475
476 When we check the instance declaration, we pass in a self dictionary that is merely
477      self = dfun b
478 But we will be asked to solve that from: 
479    [Given] d : B a 
480    [Derived] self : C a 
481 We can show: 
482    [Wanted] sc : A a
483 The problem is that self *depends* on the sc variable, but that is not apparent in 
484 the binding self = dfun b. So we record the extra dependency, using the evidence bind: 
485    EvBind self (EvDFunApp dfun [b] [b,sc])
486 It is these dependencies that are the ''true'' dependencies in an EvDFunApp, and those 
487 that we must chase in function isGoodRecEv (in TcSMonad) 
488
489 \begin{code}
490 simplifySuperClass :: [TyVar]
491                    -> [EvVar]          -- givens
492                    -> EvVar            -- the superclass we must solve for
493                    -> EvBind           -- the 'self' evidence bind 
494                    -> TcM TcEvBinds
495 -- Post:  
496 --   ev_binds <- simplifySuperClasses tvs inst_givens sc_dict self_ev_bind
497 -- Then: 
498 --    1) ev_binds already contains self_ev_bind
499 --    2) if successful then ev_binds contains binding for
500 --       the wanted superclass, sc_dict
501 simplifySuperClass tvs inst_givens sc_dict (EvBind self_dict self_ev)
502   = do { giv_loc      <- getCtLoc InstSkol  -- For the inst_givens
503        ; want_loc     <- getCtLoc ScOrigin  -- As wanted/derived (for the superclass and self)
504        ; lcl_env      <- getLclTypeEnv
505
506        -- Record the dependency of self_dict to sc_dict, see Note [Dependencies in self dictionaries]
507        ; let wanted = unitBag $ WcEvVar $ WantedEvVar sc_dict want_loc
508              self_ev_with_dep
509                = case self_ev of 
510                    EvDFunApp df tys insts deps -> EvDFunApp df tys insts (sc_dict:deps)
511                    _ -> panic "Self-dictionary not EvDFunApp!"
512
513        -- And solve for it
514        ; ((unsolved_flats, unsolved_implics), frozen_errors, ev_binds)
515              <- runTcS SimplCheck NoUntouchables $
516                 do {   -- Record a binding for self_dict that *depends on sc_dict*
517                        -- And canonicalise self_dict (which adds its superclasses)
518                        -- with a Derived origin, which in turn triggers the
519                        -- goodRecEv recursive-evidence check
520                    ; setEvBind self_dict self_ev_with_dep
521                    ; can_selfs <- mkCanonical  (Derived want_loc DerSelf) self_dict
522
523                        -- The rest is just like solveImplication
524                    ; can_inst_givens <- mkCanonicals (Given giv_loc) inst_givens
525                    ; inert           <- solveInteract emptyInert $
526                                         can_inst_givens `andCCan` can_selfs
527                    ; solveWanteds inert wanted }
528
529        -- For error reporting, conjure up a fake implication,
530        -- so that we get decent error messages
531        ; let implic = Implic { ic_untch  = NoUntouchables
532                              , ic_env    = lcl_env
533                              , ic_skols  = mkVarSet tvs
534                              , ic_given  = inst_givens
535                              , ic_wanted = mapBag WcEvVar unsolved_flats
536                              , ic_scoped = panic "super1"
537                              , ic_binds  = panic "super2"
538                              , ic_loc    = giv_loc }
539         ; ASSERT (isEmptyBag unsolved_implics) -- Impossible to have any implications!
540           unless (isEmptyBag unsolved_flats) $
541           reportUnsolved (emptyBag, unitBag implic) frozen_errors
542
543         ; return (EvBinds ev_binds) }
544 \end{code}
545
546
547 *********************************************************************************
548 *                                                                                 * 
549 *                             RULES                                               *
550 *                                                                                 *
551 ***********************************************************************************
552
553 Note [Simplifying RULE lhs constraints]
554 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
555 On the LHS of transformation rules we only simplify only equalitis,
556 but not dictionaries.  We want to keep dictionaries unsimplified, to
557 serve as the available stuff for the RHS of the rule.  We *do* want to
558 simplify equalities, however, to detect ill-typed rules that cannot be
559 applied.
560
561 Implementation: the TcSFlags carried by the TcSMonad controls the
562 amount of simplification, so simplifyRuleLhs just sets the flag
563 appropriately.
564
565 Example.  Consider the following left-hand side of a rule
566         f (x == y) (y > z) = ...
567 If we typecheck this expression we get constraints
568         d1 :: Ord a, d2 :: Eq a
569 We do NOT want to "simplify" to the LHS
570         forall x::a, y::a, z::a, d1::Ord a.
571           f ((==) (eqFromOrd d1) x y) ((>) d1 y z) = ...
572 Instead we want 
573         forall x::a, y::a, z::a, d1::Ord a, d2::Eq a.
574           f ((==) d2 x y) ((>) d1 y z) = ...
575
576 Here is another example:
577         fromIntegral :: (Integral a, Num b) => a -> b
578         {-# RULES "foo"  fromIntegral = id :: Int -> Int #-}
579 In the rule, a=b=Int, and Num Int is a superclass of Integral Int. But
580 we *dont* want to get
581         forall dIntegralInt.
582            fromIntegral Int Int dIntegralInt (scsel dIntegralInt) = id Int
583 because the scsel will mess up RULE matching.  Instead we want
584         forall dIntegralInt, dNumInt.
585           fromIntegral Int Int dIntegralInt dNumInt = id Int
586
587 Even if we have 
588         g (x == y) (y == z) = ..
589 where the two dictionaries are *identical*, we do NOT WANT
590         forall x::a, y::a, z::a, d1::Eq a
591           f ((==) d1 x y) ((>) d1 y z) = ...
592 because that will only match if the dict args are (visibly) equal.
593 Instead we want to quantify over the dictionaries separately.
594
595 In short, simplifyRuleLhs must *only* squash equalities, leaving
596 all dicts unchanged, with absolutely no sharing.  
597
598 HOWEVER, under a nested implication things are different
599 Consider
600   f :: (forall a. Eq a => a->a) -> Bool -> ...
601   {-# RULES "foo" forall (v::forall b. Eq b => b->b).
602        f b True = ...
603     #=}
604 Here we *must* solve the wanted (Eq a) from the given (Eq a)
605 resulting from skolemising the agument type of g.  So we 
606 revert to SimplCheck when going under an implication.  
607
608 \begin{code}
609 simplifyRule :: RuleName 
610              -> [TcTyVar]               -- Explicit skolems
611              -> WantedConstraints       -- Constraints from LHS
612              -> WantedConstraints       -- Constraints from RHS
613              -> TcM ([EvVar],           -- LHS dicts
614                      TcEvBinds,         -- Evidence for LHS
615                      TcEvBinds)         -- Evidence for RHS
616 -- See Note [Simplifying RULE lhs constraints]
617 simplifyRule name tv_bndrs lhs_wanted rhs_wanted
618   = do { zonked_lhs <- mapBagM zonkWanted lhs_wanted
619        ; (lhs_residual, lhs_binds) <- simplifyAsMuchAsPossible SimplRuleLhs zonked_lhs
620
621        -- Don't quantify over equalities (judgement call here)
622        ; let (eqs, dicts) = partitionBag (isEqPred . wantedEvVarPred) lhs_residual
623              lhs_dicts    = map wantedEvVarToVar (bagToList dicts)  
624                                  -- Dicts and implicit parameters
625        ; reportUnsolvedWantedEvVars eqs
626
627              -- Notice that we simplify the RHS with only the explicitly
628              -- introduced skolems, allowing the RHS to constrain any 
629              -- unification variables.
630              -- Then, and only then, we call zonkQuantifiedTypeVariables
631              -- Example   foo :: Ord a => a -> a
632              --           foo_spec :: Int -> Int
633              --           {-# RULE "foo"  foo = foo_spec #-}
634              --     Here, it's the RHS that fixes the type variable
635
636              -- So we don't want to make untouchable the type
637              -- variables in the envt of the RHS, because they include
638              -- the template variables of the RULE
639
640              -- Hence the rather painful ad-hoc treatement here
641        ; rhs_binds_var@(EvBindsVar evb_ref _)  <- newTcEvBinds
642        ; loc        <- getCtLoc (RuleSkol name)
643        ; rhs_binds1 <- simplifyCheck SimplCheck $ unitBag $ WcImplic $ 
644              Implic { ic_untch = NoUntouchables
645                     , ic_env = emptyNameEnv
646                     , ic_skols = mkVarSet tv_bndrs
647                     , ic_scoped = panic "emitImplication"
648                     , ic_given = lhs_dicts
649                     , ic_wanted = rhs_wanted
650                     , ic_binds = rhs_binds_var
651                     , ic_loc = loc }
652        ; rhs_binds2 <- readTcRef evb_ref
653
654        ; return ( lhs_dicts
655                 , EvBinds lhs_binds 
656                 , EvBinds (rhs_binds1 `unionBags` evBindMapBinds rhs_binds2)) }
657 \end{code}
658
659
660 *********************************************************************************
661 *                                                                                 * 
662 *                                 Main Simplifier                                 *
663 *                                                                                 *
664 ***********************************************************************************
665
666 \begin{code}
667 simplifyCheck :: SimplContext
668               -> WantedConstraints      -- Wanted
669               -> TcM (Bag EvBind)
670 -- Solve a single, top-level implication constraint
671 -- e.g. typically one created from a top-level type signature
672 --          f :: forall a. [a] -> [a]
673 --          f x = rhs
674 -- We do this even if the function has no polymorphism:
675 --          g :: Int -> Int
676
677 --          g y = rhs
678 -- (whereas for *nested* bindings we would not create
679 --  an implication constraint for g at all.)
680 --
681 -- Fails if can't solve something in the input wanteds
682 simplifyCheck ctxt wanteds
683   = do { wanteds <- mapBagM zonkWanted wanteds
684
685        ; traceTc "simplifyCheck {" (vcat
686              [ ptext (sLit "wanted =") <+> ppr wanteds ])
687
688        ; (unsolved, frozen_errors, ev_binds) 
689            <- runTcS ctxt NoUntouchables $ solveWanteds emptyInert wanteds
690
691        ; traceTc "simplifyCheck }" $
692              ptext (sLit "unsolved =") <+> ppr unsolved
693
694        ; reportUnsolved unsolved frozen_errors
695
696        ; return ev_binds }
697
698 ----------------
699 solveWanteds :: InertSet              -- Given 
700              -> WantedConstraints     -- Wanted
701              -> TcS (Bag WantedEvVar, -- Unsolved constraints, but unflattened, this is why 
702                                       -- they are WantedConstraints and not CanonicalCts
703                      Bag Implication) -- Unsolved implications
704 -- solveWanteds iterates when it is able to float equalities
705 -- out of one or more of the implications 
706 solveWanteds inert wanteds
707   = do { let (flat_wanteds, implic_wanteds) = splitWanteds wanteds
708        ; can_flats <- canWanteds $ bagToList flat_wanteds
709        ; traceTcS "solveWanteds {" $
710                  vcat [ text "wanteds =" <+> ppr wanteds
711                       , text "inert =" <+> ppr inert ]
712        ; (unsolved_flats, unsolved_implics) 
713                <- simpl_loop 1 inert can_flats implic_wanteds
714        ; bb <- getTcEvBindsBag
715        ; tb <- getTcSTyBindsMap
716        ; traceTcS "solveWanteds }" $
717                  vcat [ text "unsolved_flats   =" <+> ppr unsolved_flats
718                       , text "unsolved_implics =" <+> ppr unsolved_implics 
719                       , text "current evbinds  =" <+> vcat (map ppr (varEnvElts bb))
720                       , text "current tybinds  =" <+> vcat (map ppr (varEnvElts tb))
721                       ]
722
723        ; solveCTyFunEqs unsolved_flats unsolved_implics
724                 -- See Note [Solving Family Equations]
725        }
726   where
727     simpl_loop :: Int 
728                -> InertSet 
729                -> CanonicalCts  -- May inlude givens (in the recursive call)
730                -> Bag Implication
731                -> TcS (CanonicalCts, Bag Implication)
732     simpl_loop n inert can_ws implics
733       | n>10
734       = trace "solveWanteds: loop" $    -- Always bleat
735         do { traceTcS "solveWanteds: loop" (ppr inert)  -- Bleat more informatively
736            ; return (can_ws, implics) }
737
738       | otherwise
739       = do { traceTcS "solveWanteds: simpl_loop start {" $
740                  vcat [ text "n =" <+> ppr n
741                       , text "can_ws =" <+> ppr can_ws
742                       , text "implics =" <+> ppr implics
743                       , text "inert =" <+> ppr inert ]
744            ; inert1 <- solveInteract inert can_ws
745            ; let (inert2, unsolved_flats) = extractUnsolved inert1
746
747            -- NB: Importantly, inerts2 may contain *more* givens than inert 
748            -- because of having solved equalities from can_ws 
749            ; traceTcS "solveWanteds: done flats"  $
750                  vcat [ text "inerts =" <+> ppr inert2
751                       , text "unsolved =" <+> ppr unsolved_flats ]
752
753                 -- Go inside each implication
754            ; (implic_eqs, unsolved_implics) 
755                <- solveNestedImplications inert2 unsolved_flats implics
756
757                 -- Apply defaulting rules if and only if there
758                 -- no floated equalities.  If there are, they may
759                 -- solve the remaining wanteds, so don't do defaulting.
760            ; final_eqs <- if not (isEmptyBag implic_eqs)
761                           then return implic_eqs
762                           else applyDefaultingRules inert2 unsolved_flats
763                                      
764                 -- default_eqs are *givens*, so simpl_loop may 
765                 -- recurse with givens in the argument
766
767            ; traceTcS "solveWanteds: simpl_loop end }" $
768                  vcat [ text "final_eqs =" <+> ppr final_eqs
769                       , text "unsolved_flats =" <+> ppr unsolved_flats
770                       , text "unsolved_implics =" <+> ppr unsolved_implics ]
771
772            ; if isEmptyBag final_eqs then
773                  return (unsolved_flats, unsolved_implics)
774              else 
775                  do { can_final_eqs <- canWanteds (Bag.bagToList final_eqs)
776                        -- final eqs is *just* a bunch of WantedEvVars
777                     ; simpl_loop (n+1) inert2 
778                           (can_final_eqs `andCCan` unsolved_flats) unsolved_implics 
779                        -- Important: reiterate with inert2, not plainly inert
780                        -- because inert2 may contain more givens, as the result of solving
781                        -- some wanteds in the incoming can_ws 
782                      }       
783            }
784
785 solveNestedImplications :: InertSet -> CanonicalCts -> Bag Implication
786                         -> TcS (Bag WantedEvVar, Bag Implication)
787 solveNestedImplications inerts unsolved implics
788   | isEmptyBag implics
789   = return (emptyBag, emptyBag)
790   | otherwise 
791   = do { -- See Note [Preparing inert set for implications]
792          traceTcS "solveWanteds: preparing inerts for implications {"  empty
793        ; inert_for_implics <- solveInteract inerts (makeGivens unsolved)
794        ; traceTcS "}" empty
795
796        ; traceTcS "solveWanteds: doing nested implications {" $
797          vcat [ text "inerts_for_implics =" <+> ppr inert_for_implics
798               , text "implics =" <+> ppr implics ]
799
800        ; let tcs_untouchables = filterVarSet isFlexiTcsTv $
801                                 tyVarsOfInert inert_for_implics
802              -- See Note [Extra TcsTv untouchables]
803        ; (implic_eqs, unsolved_implics)
804            <- flatMapBagPairM (solveImplication tcs_untouchables inert_for_implics) implics
805
806        ; traceTcS "solveWanteds: done nested implications }" $
807                   vcat [ text "implic_eqs ="       <+> ppr implic_eqs
808                        , text "unsolved_implics =" <+> ppr unsolved_implics ]
809
810        ; return (implic_eqs, unsolved_implics) }
811
812 solveImplication :: TcTyVarSet            -- Untouchable TcS unification variables
813                  -> InertSet              -- Given
814                  -> Implication           -- Wanted
815                  -> TcS (Bag WantedEvVar, -- Unsolved unification var = type
816                          Bag Implication) -- Unsolved rest (always empty or singleton)
817 -- Returns: 
818 --  1. A bag of floatable wanted constraints, not mentioning any skolems, 
819 --     that are of the form unification var = type
820 -- 
821 --  2. Maybe a unsolved implication, empty if entirely solved! 
822 -- 
823 -- Precondition: everything is zonked by now
824 solveImplication tcs_untouchables inert
825      imp@(Implic { ic_untch  = untch 
826                  , ic_binds  = ev_binds
827                  , ic_skols  = skols 
828                  , ic_given  = givens
829                  , ic_wanted = wanteds
830                  , ic_loc    = loc })
831   = nestImplicTcS ev_binds (untch, tcs_untouchables) $
832     recoverTcS (return (emptyBag, emptyBag)) $
833        -- Recover from nested failures.  Even the top level is
834        -- just a bunch of implications, so failing at the first
835        -- one is bad
836     do { traceTcS "solveImplication {" (ppr imp) 
837
838          -- Solve flat givens
839        ; can_givens  <- canGivens loc givens
840        ; given_inert <- solveInteract inert can_givens
841
842          -- Simplify the wanteds
843        ; (unsolved_flats, unsolved_implics) <- solveWanteds given_inert wanteds
844
845        ; let (res_flat_free, res_flat_bound) 
846                       = floatEqualities skols givens unsolved_flats
847              unsolved = Bag.mapBag WcEvVar res_flat_bound `unionBags`
848                               Bag.mapBag WcImplic unsolved_implics
849
850        ; traceTcS "solveImplication end }" $ vcat
851              [ text "res_flat_free =" <+> ppr res_flat_free
852              , text "res_flat_bound =" <+> ppr res_flat_bound
853              , text "unsolved_implics =" <+> ppr unsolved_implics ]
854
855        ; let res_bag | isEmptyBag unsolved = emptyBag
856                      | otherwise           = unitBag (imp { ic_wanted  = unsolved })
857
858        ; return (res_flat_free, res_bag) }
859
860 floatEqualities :: TcTyVarSet -> [EvVar] 
861                 -> Bag WantedEvVar -> (Bag WantedEvVar, Bag WantedEvVar)
862                    -- The CanonicalCts will be floated out to be used later, whereas
863                    -- the remaining WantedEvVars will remain inside the implication. 
864 floatEqualities skols can_given wanteds
865   | hasEqualities can_given = (emptyBag, wanteds)
866           -- Note [Float Equalities out of Implications]
867   | otherwise = partitionBag is_floatable wanteds 
868   where is_floatable :: WantedEvVar -> Bool 
869         is_floatable (WantedEvVar cv _) 
870           | isCoVar cv = skols `disjointVarSet` predTvs_under_fsks (coVarPred cv)
871         is_floatable _wv = False
872
873         tvs_under_fsks :: Type -> TyVarSet
874         -- ^ NB: for type synonyms tvs_under_fsks does /not/ expand the synonym
875         tvs_under_fsks (TyVarTy tv)     
876           | not (isTcTyVar tv)               = unitVarSet tv
877           | FlatSkol ty <- tcTyVarDetails tv = tvs_under_fsks ty
878           | otherwise                        = unitVarSet tv
879         tvs_under_fsks (TyConApp _ tys) = unionVarSets (map tvs_under_fsks tys)
880         tvs_under_fsks (PredTy sty)     = predTvs_under_fsks sty
881         tvs_under_fsks (FunTy arg res)  = tvs_under_fsks arg `unionVarSet` tvs_under_fsks res
882         tvs_under_fsks (AppTy fun arg)  = tvs_under_fsks fun `unionVarSet` tvs_under_fsks arg
883         tvs_under_fsks (ForAllTy tv ty) -- The kind of a coercion binder 
884                                       -- can mention type variables!
885           | isTyVar tv                = inner_tvs `delVarSet` tv
886           | otherwise  {- Coercion -} = -- ASSERT( not (tv `elemVarSet` inner_tvs) )
887                                         inner_tvs `unionVarSet` tvs_under_fsks (tyVarKind tv)
888           where
889             inner_tvs = tvs_under_fsks ty
890
891         predTvs_under_fsks :: PredType -> TyVarSet
892         predTvs_under_fsks (IParam _ ty)    = tvs_under_fsks ty
893         predTvs_under_fsks (ClassP _ tys)   = unionVarSets (map tvs_under_fsks tys)
894         predTvs_under_fsks (EqPred ty1 ty2) = tvs_under_fsks ty1 `unionVarSet` tvs_under_fsks ty2
895
896
897
898
899 \end{code}
900
901 Note [Float Equalities out of Implications]
902 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
903 We want to float equalities out of vanilla existentials, but *not* out 
904 of GADT pattern matches. 
905
906 Note [Preparing inert set for implications]
907 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
908 Before solving the nested implications, we convert any unsolved flat wanteds
909 to givens, and add them to the inert set.  Reasons:
910
911   a) In checking mode, suppresses unnecessary errors.  We already have
912      on unsolved-wanted error; adding it to the givens prevents any 
913      consequential errors from showing uop
914
915   b) More importantly, in inference mode, we are going to quantify over this
916      constraint, and we *don't* want to quantify over any constraints that
917      are deducible from it.
918
919 The unsolved wanteds are *canonical* but they may not be *inert*,
920 because when made into a given they might interact with other givens.
921 Hence the call to solveInteract.  Example:
922
923  Original inert set = (d :_g D a) /\ (co :_w  a ~ [beta]) 
924
925 We were not able to solve (a ~w [beta]) but we can't just assume it as
926 given because the resulting set is not inert. Hence we have to do a
927 'solveInteract' step first. 
928
929 Note [Extra TcsTv untouchables]
930 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
931 Furthemore, we record the inert set simplifier-generated unification variables of the TcsTv
932 kind (such as variables from instance that have been applied, or unification flattens). These
933 variables must be passed to the implications as extra untouchable variables. Otherwise
934 we have the danger of double unifications. Example (from trac ticket #4494):
935
936    (F Int ~ uf)  /\  (forall a. C a => F Int ~ beta) 
937
938 In this example, beta is touchable inside the implication. The first solveInteract step
939 leaves 'uf' ununified. Then we move inside the implication where a new constraint
940        uf  ~  beta  
941 emerges. We may spontaneously solve it to get uf := beta, so the whole implication disappears
942 but when we pop out again we are left with (F Int ~ uf) which will be unified by our final 
943 solveCTyFunEqs stage and uf will get unified *once more* to  (F Int). 
944
945 The solution is to record the TcsTvs (i.e. the simplifier-generated unification variables)
946 that are generated when solving the flats, and make them untouchables for the nested 
947 implication. In the example above uf would become untouchable, so beta would be forced to 
948 be unified as beta := uf.
949
950 NB: A consequence is that every simplifier-generated TcsTv variable that gets floated out 
951     of an implication becomes now untouchable next time we go inside that implication to 
952     solve any residual constraints. In effect, by floating an equality out of the implication 
953     we are committing to have it solved in the outside. 
954
955
956 \begin{code}
957
958 solveCTyFunEqs :: CanonicalCts -> Bag Implication -> TcS (Bag WantedEvVar, Bag Implication)
959 -- Default equalities (F xi ~ alpha) by setting (alpha := F xi), whenever possible
960 -- See Note [Solving Family Equations]
961 -- Returns: a bunch of unsolved constraints from the original CanonicalCts and implications
962 --          where the newly generated equalities (alpha := F xi) have been substituted through.
963 solveCTyFunEqs cts implics
964  = do { untch   <- getUntouchables 
965       ; let (unsolved_can_cts, funeq_bnds) = getSolvableCTyFunEqs untch cts
966       ; traceTcS "defaultCTyFunEqs" (vcat [text "Trying to default family equations:"
967                                           , ppr funeq_bnds
968                                           ])
969       ; mapM_ solve_one funeq_bnds
970
971              -- Apply the substitution through to eliminate the flatten 
972              -- unification variables we substituted both in the unsolved flats and implics
973       ; let final_unsolved 
974               = Bag.mapBag (subst_wevar funeq_bnds . deCanonicaliseWanted) unsolved_can_cts
975             final_implics 
976               = Bag.mapBag (subst_impl funeq_bnds) implics
977
978       ; return (final_unsolved, final_implics) }
979
980   where solve_one (tv,(ty,cv,fl)) 
981           | not (typeKind ty `isSubKind` tyVarKind tv) 
982           = addErrorTcS KindError fl (mkTyVarTy tv) ty
983              -- Must do a small kind check since TcCanonical invariants 
984              -- on family equations only impose compatibility, not subkinding
985           | otherwise = setWantedTyBind tv ty >> setWantedCoBind cv ty
986
987         subst_wanted :: FunEqBinds -> WantedConstraint -> WantedConstraint
988         subst_wanted funeq_bnds (WcEvVar wv)    = WcEvVar  (subst_wevar funeq_bnds wv)
989         subst_wanted funeq_bnds (WcImplic impl) = WcImplic (subst_impl funeq_bnds impl)
990
991         subst_wevar :: FunEqBinds -> WantedEvVar -> WantedEvVar        
992         subst_wevar funeq_bnds (WantedEvVar v loc)
993           = let orig_ty  = varType v
994                 new_ty   = substFunEqBnds funeq_bnds orig_ty
995             in WantedEvVar (setVarType v new_ty) loc
996                
997         subst_impl :: FunEqBinds -> Implication -> Implication
998         subst_impl funeq_bnds impl@(Implic { ic_wanted = ws })
999           = impl { ic_wanted = Bag.mapBag (subst_wanted funeq_bnds) ws }
1000
1001
1002 type FunEqBinds = [(TcTyVar,(TcType,CoVar,CtFlavor))]
1003 -- Invariant: if it contains:
1004 --       [... a -> (ta,...) ... b -> (tb,...) ... ] 
1005 -- then 'ta' cannot mention 'b'
1006
1007 getSolvableCTyFunEqs :: TcsUntouchables
1008                      -> CanonicalCts                -- Precondition: all wanteds 
1009                      -> (CanonicalCts, FunEqBinds)  -- Postcondition: returns the unsolvables
1010 getSolvableCTyFunEqs untch cts
1011   = Bag.foldlBag dflt_funeq (emptyCCan, []) cts
1012   where dflt_funeq (cts_in, extra_binds) ct@(CFunEqCan { cc_id = cv
1013                                                        , cc_flavor = fl
1014                                                        , cc_fun = tc
1015                                                        , cc_tyargs = xis
1016                                                        , cc_rhs = xi })
1017           | Just tv <- tcGetTyVar_maybe xi
1018           , isTouchableMetaTyVar_InRange untch tv -- If RHS is a touchable unif. variable
1019           , Nothing <- lookup tv extra_binds      -- or in extra_binds
1020                -- See Note [Solving Family Equations], Point 1
1021           = ASSERT ( isWanted fl )
1022             let ty_orig   = mkTyConApp tc xis 
1023                 ty_bind   = substFunEqBnds extra_binds ty_orig
1024             in if tv `elemVarSet` tyVarsOfType ty_bind 
1025                then (cts_in `extendCCans` ct, extra_binds)     
1026                       -- See Note [Solving Family Equations], Point 2
1027                else (cts_in, (tv,(ty_bind,cv,fl)):extra_binds) 
1028                       -- Postcondition met because extra_binds is already applied to ty_bind
1029
1030         dflt_funeq (cts_in, extra_binds) ct = (cts_in `extendCCans` ct, extra_binds)
1031
1032 substFunEqBnds :: FunEqBinds -> TcType -> TcType 
1033 substFunEqBnds bnds ty 
1034   = foldr (\(x,(t,_cv,_fl)) xy -> substTyWith [x] [t] xy) ty bnds
1035     -- foldr works because of the FunEqBinds invariant
1036
1037
1038 \end{code}
1039
1040 Note [Solving Family Equations] 
1041 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
1042 After we are done with simplification we may be left with constraints of the form:
1043      [Wanted] F xis ~ beta 
1044 If 'beta' is a touchable unification variable not already bound in the TyBinds 
1045 then we'd like to create a binding for it, effectively "defaulting" it to be 'F xis'.
1046
1047 When is it ok to do so? 
1048     1) 'beta' must not already be defaulted to something. Example: 
1049
1050            [Wanted] F Int  ~ beta   <~ Will default [beta := F Int]
1051            [Wanted] F Char ~ beta   <~ Already defaulted, can't default again. We 
1052                                        have to report this as unsolved.
1053
1054     2) However, we must still do an occurs check when defaulting (F xis ~ beta), to 
1055        set [beta := F xis] only if beta is not among the free variables of xis.
1056
1057     3) Notice that 'beta' can't be bound in ty binds already because we rewrite RHS 
1058        of type family equations. See Inert Set invariants in TcInteract. 
1059
1060
1061 *********************************************************************************
1062 *                                                                               * 
1063 *                          Defaulting and disamgiguation                        *
1064 *                                                                               *
1065 *********************************************************************************
1066
1067 Basic plan behind applyDefaulting rules: 
1068  
1069  Step 1:  
1070     Split wanteds into defaultable groups, `groups' and the rest `rest_wanted' 
1071     For each defaultable group, do: 
1072       For each possible substitution for [alpha |-> tau] where `alpha' is the 
1073       group's variable, do: 
1074         1) Make up new TcEvBinds
1075         2) Extend TcS with (groupVariable 
1076         3) given_inert <- solveOne inert (given : a ~ tau) 
1077         4) (final_inert,unsolved) <- solveWanted (given_inert) (group_constraints)
1078         5) if unsolved == empty then 
1079                  sneakyUnify a |-> tau 
1080                  write the evidence bins
1081                  return (final_inert ++ group_constraints,[]) 
1082                       -- will contain the info (alpha |-> tau)!!
1083                  goto next defaultable group 
1084            if unsolved <> empty then 
1085                  throw away evidence binds
1086                  try next substitution 
1087      If you've run out of substitutions for this group, too bad, you failed 
1088                  return (inert,group) 
1089                  goto next defaultable group
1090  
1091  Step 2: 
1092    Collect all the (canonical-cts, wanteds) gathered this way. 
1093    - Do a solveGiven over the canonical-cts to make sure they are inert 
1094 ------------------------------------------------------------------------------------------
1095
1096
1097 \begin{code}
1098 applyDefaultingRules :: InertSet
1099                      -> CanonicalCts           -- All wanteds
1100                      -> TcS (Bag WantedEvVar)  -- All wanteds again!  
1101 -- Return some *extra* givens, which express the 
1102 -- type-class-default choice
1103
1104 applyDefaultingRules inert wanteds
1105   | isEmptyBag wanteds 
1106   = return emptyBag
1107   | otherwise
1108   = do { untch <- getUntouchables
1109        ; tv_cts <- mapM (defaultTyVar untch) $
1110                    varSetElems (tyVarsOfCDicts wanteds) 
1111
1112        ; info@(_, default_tys, _) <- getDefaultInfo
1113        ; let groups = findDefaultableGroups info untch wanteds
1114        ; deflt_cts <- mapM (disambigGroup default_tys inert) groups
1115
1116        ; traceTcS "deflt2" (vcat [ text "Tyvar defaults =" <+> ppr tv_cts
1117                                  , text "Type defaults =" <+> ppr deflt_cts])
1118
1119        ; return (unionManyBags deflt_cts `unionBags` unionManyBags tv_cts) }
1120
1121 ------------------
1122 defaultTyVar :: TcsUntouchables -> TcTyVar -> TcS (Bag WantedEvVar)
1123 -- defaultTyVar is used on any un-instantiated meta type variables to
1124 -- default the kind of ? and ?? etc to *.  This is important to ensure
1125 -- that instance declarations match.  For example consider
1126 --      instance Show (a->b)
1127 --      foo x = show (\_ -> True)
1128 -- Then we'll get a constraint (Show (p ->q)) where p has argTypeKind (printed ??), 
1129 -- and that won't match the typeKind (*) in the instance decl.  
1130 -- See test tc217.
1131 --
1132 -- We look only at touchable type variables. No further constraints
1133 -- are going to affect these type variables, so it's time to do it by
1134 -- hand.  However we aren't ready to default them fully to () or
1135 -- whatever, because the type-class defaulting rules have yet to run.
1136
1137 defaultTyVar untch the_tv 
1138   | isTouchableMetaTyVar_InRange untch the_tv
1139   , not (k `eqKind` default_k)
1140   = do { ev <- TcSMonad.newKindConstraint the_tv default_k
1141        ; let loc = CtLoc DefaultOrigin (getSrcSpan the_tv) [] -- Yuk
1142        ; return (unitBag (WantedEvVar ev loc)) }
1143   | otherwise            
1144   = return emptyBag      -- The common case
1145   where
1146     k = tyVarKind the_tv
1147     default_k = defaultKind k
1148
1149
1150 ----------------
1151 findDefaultableGroups 
1152     :: ( SimplContext 
1153        , [Type]
1154        , (Bool,Bool) )  -- (Overloaded strings, extended default rules)
1155     -> TcsUntouchables  -- Untouchable
1156     -> CanonicalCts     -- Unsolved
1157     -> [[(CanonicalCt,TcTyVar)]]
1158 findDefaultableGroups (ctxt, default_tys, (ovl_strings, extended_defaults)) 
1159                       untch wanteds
1160   | not (performDefaulting ctxt) = []
1161   | null default_tys             = []
1162   | otherwise = filter is_defaultable_group (equivClasses cmp_tv unaries)
1163   where 
1164     unaries     :: [(CanonicalCt, TcTyVar)]  -- (C tv) constraints
1165     non_unaries :: [CanonicalCt]             -- and *other* constraints
1166     
1167     (unaries, non_unaries) = partitionWith find_unary (bagToList wanteds)
1168         -- Finds unary type-class constraints
1169     find_unary cc@(CDictCan { cc_tyargs = [ty] })
1170         | Just tv <- tcGetTyVar_maybe ty
1171         = Left (cc, tv)
1172     find_unary cc = Right cc  -- Non unary or non dictionary 
1173
1174     bad_tvs :: TcTyVarSet  -- TyVars mentioned by non-unaries 
1175     bad_tvs = foldr (unionVarSet . tyVarsOfCanonical) emptyVarSet non_unaries 
1176
1177     cmp_tv (_,tv1) (_,tv2) = tv1 `compare` tv2
1178
1179     is_defaultable_group ds@((_,tv):_)
1180         = isTyConableTyVar tv   -- Note [Avoiding spurious errors]
1181         && not (tv `elemVarSet` bad_tvs)
1182         && isTouchableMetaTyVar_InRange untch tv 
1183         && defaultable_classes [cc_class cc | (cc,_) <- ds]
1184     is_defaultable_group [] = panic "defaultable_group"
1185
1186     defaultable_classes clss 
1187         | extended_defaults = any isInteractiveClass clss
1188         | otherwise         = all is_std_class clss && (any is_num_class clss)
1189
1190     -- In interactive mode, or with -XExtendedDefaultRules,
1191     -- we default Show a to Show () to avoid graututious errors on "show []"
1192     isInteractiveClass cls 
1193         = is_num_class cls || (classKey cls `elem` [showClassKey, eqClassKey, ordClassKey])
1194
1195     is_num_class cls = isNumericClass cls || (ovl_strings && (cls `hasKey` isStringClassKey))
1196     -- is_num_class adds IsString to the standard numeric classes, 
1197     -- when -foverloaded-strings is enabled
1198
1199     is_std_class cls = isStandardClass cls || (ovl_strings && (cls `hasKey` isStringClassKey))
1200     -- Similarly is_std_class
1201
1202 ------------------------------
1203 disambigGroup :: [Type]                    -- The default types 
1204               -> InertSet                  -- Given inert 
1205               -> [(CanonicalCt, TcTyVar)]  -- All classes of the form (C a)
1206                                            --  sharing same type variable
1207               -> TcS (Bag WantedEvVar)
1208
1209 disambigGroup [] _inert _grp 
1210   = return emptyBag
1211 disambigGroup (default_ty:default_tys) inert group
1212   = do { traceTcS "disambigGroup" (ppr group $$ ppr default_ty)
1213        ; let ct_loc = get_ct_loc (cc_flavor the_ct) 
1214        ; ev <- TcSMonad.newWantedCoVar (mkTyVarTy the_tv) default_ty
1215        ; let wanted_eq = CTyEqCan { cc_id = ev
1216                                   , cc_flavor = Wanted ct_loc
1217                                   , cc_tyvar  = the_tv 
1218                                   , cc_rhs    = default_ty }
1219        ; success <- tryTcS $ 
1220                     do { final_inert <- solveInteract inert(listToBag $ wanted_eq:wanteds)
1221                        ; let (_, unsolved) = extractUnsolved final_inert                                    
1222                        ; errs <- getTcSErrorsBag 
1223                        ; return (isEmptyBag unsolved && isEmptyBag errs) }
1224
1225        ; case success of
1226            True  ->  -- Success: record the type variable binding, and return
1227                     do { wrapWarnTcS $ warnDefaulting wanted_ev_vars default_ty
1228                        ; traceTcS "disambigGroup succeeded" (ppr default_ty)
1229                        ; return (unitBag $ WantedEvVar ev ct_loc) }
1230            False ->    -- Failure: try with the next type
1231                     do { traceTcS "disambigGroup failed, will try other default types" (ppr default_ty)
1232                        ; disambigGroup default_tys inert group } }
1233   where
1234     ((the_ct,the_tv):_) = group
1235     wanteds = map fst group
1236     wanted_ev_vars = map deCanonicaliseWanted wanteds
1237
1238     get_ct_loc (Wanted l) = l
1239     get_ct_loc _ = panic "Asked  to disambiguate given or derived!"
1240
1241
1242 \end{code}
1243
1244 Note [Avoiding spurious errors]
1245 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1246 When doing the unification for defaulting, we check for skolem
1247 type variables, and simply don't default them.  For example:
1248    f = (*)      -- Monomorphic
1249    g :: Num a => a -> a
1250    g x = f x x
1251 Here, we get a complaint when checking the type signature for g,
1252 that g isn't polymorphic enough; but then we get another one when
1253 dealing with the (Num a) context arising from f's definition;
1254 we try to unify a with Int (to default it), but find that it's
1255 already been unified with the rigid variable from g's type sig