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