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