Introducing:
[ghc-hetmet.git] / compiler / typecheck / TcInteract.lhs
1 \begin{code}
2 module TcInteract ( 
3      solveInteract, solveInteractGiven, solveInteractWanted,
4      AtomicInert, tyVarsOfInert, 
5      InertSet, emptyInert, updInertSet, extractUnsolved, solveOne,
6   ) where  
7
8 #include "HsVersions.h"
9
10
11 import BasicTypes 
12 import TcCanonical
13 import VarSet
14 import Type
15 import Unify
16
17 import Id 
18 import Var
19
20 import TcType
21 import HsBinds
22
23 import Inst( tyVarsOfEvVar )
24 import Class
25 import TyCon
26 import Name
27
28 import FunDeps
29
30 import Coercion
31 import Outputable
32
33 import TcRnTypes
34 import TcMType ( isSilentEvVar )
35 import TcErrors
36 import TcSMonad
37 import Bag
38 import qualified Data.Map as Map
39
40 import Control.Monad( when )
41
42 import FastString ( sLit ) 
43 import DynFlags
44 \end{code}
45
46 Note [InertSet invariants]
47 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
48 An InertSet is a bag of canonical constraints, with the following invariants:
49
50   1 No two constraints react with each other. 
51     
52     A tricky case is when there exists a given (solved) dictionary 
53     constraint and a wanted identical constraint in the inert set, but do 
54     not react because reaction would create loopy dictionary evidence for 
55     the wanted. See note [Recursive dictionaries]
56
57   2 Given equalities form an idempotent substitution [none of the
58     given LHS's occur in any of the given RHS's or reactant parts]
59
60   3 Wanted equalities also form an idempotent substitution
61
62   4 The entire set of equalities is acyclic.
63
64   5 Wanted dictionaries are inert with the top-level axiom set 
65
66   6 Equalities of the form tv1 ~ tv2 always have a touchable variable
67     on the left (if possible).
68
69   7 No wanted constraints tv1 ~ tv2 with tv1 touchable. Such constraints
70     will be marked as solved right before being pushed into the inert set. 
71     See note [Touchables and givens].
72
73   8 No Given constraint mentions a touchable unification variable, but 
74     Given/Solved may do so. 
75
76   9 Given constraints will also have their superclasses in the inert set, 
77     but Given/Solved will not. 
78  
79 Note that 6 and 7 are /not/ enforced by canonicalization but rather by 
80 insertion in the inert list, ie by TcInteract. 
81
82 During the process of solving, the inert set will contain some
83 previously given constraints, some wanted constraints, and some given
84 constraints which have arisen from solving wanted constraints. For
85 now we do not distinguish between given and solved constraints.
86
87 Note that we must switch wanted inert items to given when going under an
88 implication constraint (when in top-level inference mode).
89
90 \begin{code}
91
92 data CCanMap a = CCanMap { cts_given   :: Map.Map a CanonicalCts
93                                           -- Invariant: all Given
94                          , cts_derived :: Map.Map a CanonicalCts 
95                                           -- Invariant: all Derived
96                          , cts_wanted  :: Map.Map a CanonicalCts } 
97                                           -- Invariant: all Wanted
98
99 cCanMapToBag :: Ord a => CCanMap a -> CanonicalCts 
100 cCanMapToBag cmap = Map.fold unionBags rest_wder (cts_given cmap)
101   where rest_wder = Map.fold unionBags rest_der  (cts_wanted cmap) 
102         rest_der  = Map.fold unionBags emptyCCan (cts_derived cmap)
103
104 emptyCCanMap :: CCanMap a 
105 emptyCCanMap = CCanMap { cts_given = Map.empty
106                        , cts_derived = Map.empty, cts_wanted = Map.empty } 
107
108 updCCanMap:: Ord a => (a,CanonicalCt) -> CCanMap a -> CCanMap a 
109 updCCanMap (a,ct) cmap 
110   = case cc_flavor ct of 
111       Wanted {} 
112           -> cmap { cts_wanted = Map.insertWith unionBags a this_ct (cts_wanted cmap) } 
113       Given {} 
114           -> cmap { cts_given = Map.insertWith unionBags a this_ct (cts_given cmap) }
115       Derived {}
116           -> cmap { cts_derived = Map.insertWith unionBags a this_ct (cts_derived cmap) }
117   where this_ct = singleCCan ct 
118
119 getRelevantCts :: Ord a => a -> CCanMap a -> (CanonicalCts, CCanMap a) 
120 -- Gets the relevant constraints and returns the rest of the CCanMap
121 getRelevantCts a cmap 
122     = let relevant = unionManyBags [ Map.findWithDefault emptyCCan a (cts_wanted cmap)
123                                    , Map.findWithDefault emptyCCan a (cts_given cmap)
124                                    , Map.findWithDefault emptyCCan a (cts_derived cmap) ]
125           residual_map = cmap { cts_wanted = Map.delete a (cts_wanted cmap) 
126                               , cts_given = Map.delete a (cts_given cmap) 
127                               , cts_derived = Map.delete a (cts_derived cmap) }
128       in (relevant, residual_map) 
129
130 extractUnsolvedCMap :: Ord a => CCanMap a -> (CanonicalCts, CCanMap a)
131 -- Gets the wanted or derived constraints and returns a residual
132 -- CCanMap with only givens.
133 extractUnsolvedCMap cmap =
134   let wntd = Map.fold unionBags emptyCCan (cts_wanted cmap)
135       derd = Map.fold unionBags emptyCCan (cts_derived cmap)
136   in (wntd `unionBags` derd, 
137            cmap { cts_wanted = Map.empty, cts_derived = Map.empty })
138
139
140 -- See Note [InertSet invariants]
141 data InertSet 
142   = IS { inert_eqs          :: CanonicalCts               -- Equalities only (CTyEqCan)
143        , inert_dicts        :: CCanMap Class              -- Dictionaries only
144        , inert_ips          :: CCanMap (IPName Name)      -- Implicit parameters 
145        , inert_frozen       :: CanonicalCts
146        , inert_funeqs       :: CCanMap TyCon              -- Type family equalities only
147                -- This representation allows us to quickly get to the relevant 
148                -- inert constraints when interacting a work item with the inert set.
149        }
150
151 tyVarsOfInert :: InertSet -> TcTyVarSet 
152 tyVarsOfInert (IS { inert_eqs    = eqs
153                   , inert_dicts  = dictmap
154                   , inert_ips    = ipmap
155                   , inert_frozen = frozen
156                   , inert_funeqs = funeqmap }) = tyVarsOfCanonicals cts
157   where
158     cts = eqs `andCCan` frozen `andCCan` cCanMapToBag dictmap
159               `andCCan` cCanMapToBag ipmap `andCCan` cCanMapToBag funeqmap
160
161 instance Outputable InertSet where
162   ppr is = vcat [ vcat (map ppr (Bag.bagToList $ inert_eqs is))
163                 , vcat (map ppr (Bag.bagToList $ cCanMapToBag (inert_dicts is)))
164                 , vcat (map ppr (Bag.bagToList $ cCanMapToBag (inert_ips is))) 
165                 , vcat (map ppr (Bag.bagToList $ cCanMapToBag (inert_funeqs is)))
166                 , vcat (map ppr (Bag.bagToList $ inert_frozen is))
167                 ]
168                        
169 emptyInert :: InertSet
170 emptyInert = IS { inert_eqs    = Bag.emptyBag
171                 , inert_frozen = Bag.emptyBag
172                 , inert_dicts  = emptyCCanMap
173                 , inert_ips    = emptyCCanMap
174                 , inert_funeqs = emptyCCanMap }
175
176 updInertSet :: InertSet -> AtomicInert -> InertSet 
177 updInertSet is item 
178   | isCTyEqCan item                     -- Other equality 
179   = let eqs' = inert_eqs is `Bag.snocBag` item 
180     in is { inert_eqs = eqs' } 
181   | Just cls <- isCDictCan_Maybe item   -- Dictionary 
182   = is { inert_dicts = updCCanMap (cls,item) (inert_dicts is) } 
183   | Just x  <- isCIPCan_Maybe item      -- IP 
184   = is { inert_ips   = updCCanMap (x,item) (inert_ips is) }  
185   | Just tc <- isCFunEqCan_Maybe item   -- Function equality 
186   = is { inert_funeqs = updCCanMap (tc,item) (inert_funeqs is) }
187   | otherwise 
188   = is { inert_frozen = inert_frozen is `Bag.snocBag` item }
189
190 extractUnsolved :: InertSet -> (InertSet, CanonicalCts)
191 -- Postcondition: the returned canonical cts are either Derived, or Wanted.
192 extractUnsolved is@(IS {inert_eqs = eqs}) 
193   = let is_solved  = is { inert_eqs    = solved_eqs
194                         , inert_dicts  = solved_dicts
195                         , inert_ips    = solved_ips
196                         , inert_frozen = emptyCCan
197                         , inert_funeqs = solved_funeqs }
198     in (is_solved, unsolved)
199
200   where (unsolved_eqs, solved_eqs)       = Bag.partitionBag (not.isGivenOrSolvedCt) eqs
201         (unsolved_ips, solved_ips)       = extractUnsolvedCMap (inert_ips is) 
202         (unsolved_dicts, solved_dicts)   = extractUnsolvedCMap (inert_dicts is) 
203         (unsolved_funeqs, solved_funeqs) = extractUnsolvedCMap (inert_funeqs is) 
204
205         unsolved = unsolved_eqs `unionBags` inert_frozen is `unionBags`
206                    unsolved_ips `unionBags` unsolved_dicts `unionBags` unsolved_funeqs
207 \end{code}
208
209 %*********************************************************************
210 %*                                                                   * 
211 *                      Main Interaction Solver                       *
212 *                                                                    *
213 **********************************************************************
214
215 Note [Basic plan] 
216 ~~~~~~~~~~~~~~~~~
217 1. Canonicalise (unary)
218 2. Pairwise interaction (binary)
219     * Take one from work list 
220     * Try all pair-wise interactions with each constraint in inert
221    
222    As an optimisation, we prioritize the equalities both in the 
223    worklist and in the inerts. 
224
225 3. Try to solve spontaneously for equalities involving touchables 
226 4. Top-level interaction (binary wrt top-level)
227    Superclass decomposition belongs in (4), see note [Superclasses]
228
229 \begin{code}
230 type AtomicInert = CanonicalCt     -- constraint pulled from InertSet
231 type WorkItem    = CanonicalCt     -- constraint pulled from WorkList
232
233 ------------------------
234 data StopOrContinue 
235   = Stop                        -- Work item is consumed
236   | ContinueWith WorkItem       -- Not consumed
237
238 instance Outputable StopOrContinue where
239   ppr Stop             = ptext (sLit "Stop")
240   ppr (ContinueWith w) = ptext (sLit "ContinueWith") <+> ppr w
241
242 -- Results after interacting a WorkItem as far as possible with an InertSet
243 data StageResult
244   = SR { sr_inerts     :: InertSet
245            -- The new InertSet to use (REPLACES the old InertSet)
246        , sr_new_work   :: WorkList
247            -- Any new work items generated (should be ADDED to the old WorkList)
248            -- Invariant: 
249            --    sr_stop = Just workitem => workitem is *not* in sr_inerts and
250            --                               workitem is inert wrt to sr_inerts
251        , sr_stop       :: StopOrContinue
252        }
253
254 instance Outputable StageResult where
255   ppr (SR { sr_inerts = inerts, sr_new_work = work, sr_stop = stop })
256     = ptext (sLit "SR") <+> 
257       braces (sep [ ptext (sLit "inerts =") <+> ppr inerts <> comma
258                   , ptext (sLit "new work =") <+> ppr work <> comma
259                   , ptext (sLit "stop =") <+> ppr stop])
260
261 type SubGoalDepth = Int   -- Starts at zero; used to limit infinite
262                           -- recursion of sub-goals
263 type SimplifierStage = SubGoalDepth -> WorkItem -> InertSet -> TcS StageResult 
264
265 -- Combine a sequence of simplifier 'stages' to create a pipeline 
266 runSolverPipeline :: SubGoalDepth
267                   -> [(String, SimplifierStage)]
268                   -> InertSet -> WorkItem 
269                   -> TcS (InertSet, WorkList)
270 -- Precondition: non-empty list of stages 
271 runSolverPipeline depth pipeline inerts workItem
272   = do { traceTcS "Start solver pipeline" $ 
273             vcat [ ptext (sLit "work item =") <+> ppr workItem
274                  , ptext (sLit "inerts    =") <+> ppr inerts]
275
276        ; let itr_in = SR { sr_inerts = inerts
277                          , sr_new_work = emptyWorkList
278                          , sr_stop = ContinueWith workItem }
279        ; itr_out <- run_pipeline pipeline itr_in
280        ; let new_inert 
281               = case sr_stop itr_out of 
282                   Stop              -> sr_inerts itr_out
283                   ContinueWith item -> sr_inerts itr_out `updInertSet` item
284        ; return (new_inert, sr_new_work itr_out) }
285   where 
286     run_pipeline :: [(String, SimplifierStage)]
287                  -> StageResult -> TcS StageResult
288     run_pipeline [] itr                         = return itr
289     run_pipeline _  itr@(SR { sr_stop = Stop }) = return itr
290
291     run_pipeline ((name,stage):stages) 
292                  (SR { sr_new_work = accum_work
293                      , sr_inerts   = inerts
294                      , sr_stop     = ContinueWith work_item })
295       = do { itr <- stage depth work_item inerts 
296            ; traceTcS ("Stage result (" ++ name ++ ")") (ppr itr)
297            ; let itr' = itr { sr_new_work = accum_work `unionWorkList` sr_new_work itr }
298            ; run_pipeline stages itr' }
299 \end{code}
300
301 Example 1:
302   Inert:   {c ~ d, F a ~ t, b ~ Int, a ~ ty} (all given)
303   Reagent: a ~ [b] (given)
304
305 React with (c~d)     ==> IR (ContinueWith (a~[b]))  True    []
306 React with (F a ~ t) ==> IR (ContinueWith (a~[b]))  False   [F [b] ~ t]
307 React with (b ~ Int) ==> IR (ContinueWith (a~[Int]) True    []
308
309 Example 2:
310   Inert:  {c ~w d, F a ~g t, b ~w Int, a ~w ty}
311   Reagent: a ~w [b]
312
313 React with (c ~w d)   ==> IR (ContinueWith (a~[b]))  True    []
314 React with (F a ~g t) ==> IR (ContinueWith (a~[b]))  True    []    (can't rewrite given with wanted!)
315 etc.
316
317 Example 3:
318   Inert:  {a ~ Int, F Int ~ b} (given)
319   Reagent: F a ~ b (wanted)
320
321 React with (a ~ Int)   ==> IR (ContinueWith (F Int ~ b)) True []
322 React with (F Int ~ b) ==> IR Stop True []    -- after substituting we re-canonicalize and get nothing
323
324 \begin{code}
325 -- Main interaction solver: we fully solve the worklist 'in one go', 
326 -- returning an extended inert set.
327 --
328 -- See Note [Touchables and givens].
329 solveInteractGiven :: InertSet -> GivenLoc -> [EvVar] -> TcS InertSet
330 solveInteractGiven inert gloc evs
331   = do { (_, inert_ret) <- solveInteract inert $ listToBag $
332                            map mk_given evs
333        ; return inert_ret }
334   where
335     flav = Given gloc GivenOrig
336     mk_given ev = mkEvVarX ev flav
337
338 solveInteractWanted :: InertSet -> [WantedEvVar] -> TcS InertSet
339 solveInteractWanted inert wvs
340   = do { (_,inert_ret) <- solveInteract inert $ listToBag $
341                           map wantedToFlavored wvs
342        ; return inert_ret }
343
344 solveInteract :: InertSet -> Bag FlavoredEvVar -> TcS (Bool, InertSet)
345 -- Post: (True,  inert_set) means we managed to discharge all constraints
346 --                          without actually doing any interactions!
347 --       (False, inert_set) means some interactions occurred
348 solveInteract inert ws 
349   = do { dyn_flags <- getDynFlags
350        ; sctx <- getTcSContext
351
352        ; traceTcS "solveInteract, before clever canonicalization:" $
353          vcat [ text "ws = " <+>  ppr (mapBag (\(EvVarX ev ct)
354                                                    -> (ct,evVarPred ev)) ws)
355               , text "inert = " <+> ppr inert ]
356
357        ; can_ws <- mkCanonicalFEVs ws
358
359        ; (flag, inert_ret)
360            <- foldrWorkListM (tryPreSolveAndInteract sctx dyn_flags) (True,inert) can_ws
361
362        ; traceTcS "solveInteract, after clever canonicalization (and interaction):" $
363          vcat [ text "No interaction happened = " <+> ppr flag
364               , text "inert_ret = " <+> ppr inert_ret ]
365
366        ; return (flag, inert_ret) }
367
368 tryPreSolveAndInteract :: SimplContext
369                        -> DynFlags
370                        -> CanonicalCt
371                        -> (Bool, InertSet)
372                        -> TcS (Bool, InertSet)
373 -- Returns: True if it was able to discharge this constraint AND all previous ones
374 tryPreSolveAndInteract sctx dyn_flags ct (all_previous_discharged, inert)
375   = do { let inert_cts = get_inert_cts (evVarPred ev_var)
376
377        ; this_one_discharged <- 
378            if isCFrozenErr ct then 
379                return False
380            else
381                dischargeFromCCans inert_cts ev_var fl
382
383        ; if this_one_discharged
384          then return (all_previous_discharged, inert)
385
386          else do
387        { inert_ret <- solveOneWithDepth (ctxtStkDepth dyn_flags,0,[]) ct inert
388        ; return (False, inert_ret) } }
389
390   where
391     ev_var = cc_id ct
392     fl = cc_flavor ct 
393
394     get_inert_cts (ClassP clas _)
395       | simplEqsOnly sctx = emptyCCan
396       | otherwise         = fst (getRelevantCts clas (inert_dicts inert))
397     get_inert_cts (IParam {})
398       = emptyCCan -- We must not do the same thing for IParams, because (contrary
399                   -- to dictionaries), work items /must/ override inert items.
400                  -- See Note [Overriding implicit parameters] in TcInteract.
401     get_inert_cts (EqPred {})
402       = inert_eqs inert `unionBags` cCanMapToBag (inert_funeqs inert)
403
404 dischargeFromCCans :: CanonicalCts -> EvVar -> CtFlavor -> TcS Bool
405 -- See if this (pre-canonicalised) work-item is identical to a 
406 -- one already in the inert set. Reasons:
407 --    a) Avoid creating superclass constraints for millions of incoming (Num a) constraints
408 --    b) Termination for improve_eqs in TcSimplify.simpl_loop
409 dischargeFromCCans cans ev fl
410   = Bag.foldrBag discharge_ct (return False) cans
411   where 
412     the_pred = evVarPred ev
413
414     discharge_ct :: CanonicalCt -> TcS Bool -> TcS Bool
415     discharge_ct ct _rest
416       | evVarPred (cc_id ct) `tcEqPred` the_pred
417       , cc_flavor ct `canSolve` fl
418                -- DV: No special care should be taken for Given/Solveds, we will
419                -- never encounter a Given entering the constraint bag after a Given/Solved
420       = do { when (isWanted fl) $ set_ev_bind ev (cc_id ct) 
421                  -- Deriveds need no evidence
422                  -- For Givens, we already have evidence, and we don't need it twice 
423            ; return True }
424       where 
425          set_ev_bind x y
426             | EqPred {} <- evVarPred y = setEvBind x (EvCoercion (mkCoVarCoercion y))
427             | otherwise                = setEvBind x (EvId y)
428
429     discharge_ct _ct rest = rest
430 \end{code}
431
432 Note [Avoiding the superclass explosion] 
433 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
434 This note now is not as significant as it used to be because we no
435 longer add the superclasses of Wanted as Derived, except only if they
436 have equality superclasses or superclasses with functional
437 dependencies. The fear was that hundreds of identical wanteds would
438 give rise each to the same superclass or equality Derived's which
439 would lead to a blo-up in the number of interactions.
440
441 Instead, what we do with tryPreSolveAndCanon, is when we encounter a
442 new constraint, we very quickly see if it can be immediately
443 discharged by a class constraint in our inert set or the previous
444 canonicals. If so, we add nothing to the returned canonical
445 constraints.
446
447 \begin{code}
448 solveOne :: WorkItem -> InertSet -> TcS InertSet 
449 solveOne workItem inerts 
450   = do { dyn_flags <- getDynFlags
451        ; solveOneWithDepth (ctxtStkDepth dyn_flags,0,[]) workItem inerts
452        }
453
454 -----------------
455 solveInteractWithDepth :: (Int, Int, [WorkItem])
456                        -> WorkList -> InertSet -> TcS InertSet
457 solveInteractWithDepth ctxt@(max_depth,n,stack) ws inert
458   | isEmptyWorkList ws
459   = return inert
460
461   | n > max_depth 
462   = solverDepthErrorTcS n stack
463
464   | otherwise 
465   = do { traceTcS "solveInteractWithDepth" $ 
466               vcat [ text "Current depth =" <+> ppr n
467                    , text "Max depth =" <+> ppr max_depth
468                    , text "ws =" <+> ppr ws ]
469
470
471        ; foldrWorkListM (solveOneWithDepth ctxt) inert ws }
472               -- use foldr to preserve the order
473
474 ------------------
475 -- Fully interact the given work item with an inert set, and return a
476 -- new inert set which has assimilated the new information.
477 solveOneWithDepth :: (Int, Int, [WorkItem])
478                   -> WorkItem -> InertSet -> TcS InertSet
479 solveOneWithDepth (max_depth, depth, stack) work inert
480   = do { traceFireTcS depth (text "Solving {" <+> ppr work)
481        ; (new_inert, new_work) <- runSolverPipeline depth thePipeline inert work
482          
483          -- Recursively solve the new work generated 
484          -- from workItem, with a greater depth
485        ; res_inert <- solveInteractWithDepth (max_depth, depth+1, work:stack) new_work new_inert 
486
487        ; traceFireTcS depth (text "Done }" <+> ppr work) 
488
489        ; return res_inert }
490
491 thePipeline :: [(String,SimplifierStage)]
492 thePipeline = [ ("interact with inert eqs", interactWithInertEqsStage)
493               , ("interact with inerts",    interactWithInertsStage)
494               , ("spontaneous solve",       spontaneousSolveStage)
495               , ("top-level reactions",     topReactionsStage) ]
496 \end{code}
497
498 *********************************************************************************
499 *                                                                               * 
500                        The spontaneous-solve Stage
501 *                                                                               *
502 *********************************************************************************
503
504 Note [Efficient Orientation] 
505 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
506
507 There are two cases where we have to be careful about 
508 orienting equalities to get better efficiency. 
509
510 Case 1: In Rewriting Equalities (function rewriteEqLHS) 
511
512     When rewriting two equalities with the same LHS:
513           (a)  (tv ~ xi1) 
514           (b)  (tv ~ xi2) 
515     We have a choice of producing work (xi1 ~ xi2) (up-to the
516     canonicalization invariants) However, to prevent the inert items
517     from getting kicked out of the inerts first, we prefer to
518     canonicalize (xi1 ~ xi2) if (b) comes from the inert set, or (xi2
519     ~ xi1) if (a) comes from the inert set.
520     
521     This choice is implemented using the WhichComesFromInert flag. 
522
523 Case 2: Functional Dependencies 
524     Again, we should prefer, if possible, the inert variables on the RHS
525
526 Case 3: IP improvement work
527     We must always rewrite so that the inert type is on the right. 
528
529 \begin{code}
530 spontaneousSolveStage :: SimplifierStage 
531 spontaneousSolveStage depth workItem inerts 
532   = do { mSolve <- trySpontaneousSolve workItem
533
534        ; case mSolve of 
535            SPCantSolve -> -- No spontaneous solution for him, keep going
536                return $ SR { sr_new_work   = emptyWorkList
537                            , sr_inerts     = inerts
538                            , sr_stop       = ContinueWith workItem }
539
540            SPSolved workItem'
541                | not (isGivenOrSolvedCt workItem) 
542                  -- Original was wanted or derived but we have now made him 
543                  -- given so we have to interact him with the inerts due to
544                  -- its status change. This in turn may produce more work.
545                  -- We do this *right now* (rather than just putting workItem'
546                  -- back into the work-list) because we've solved 
547                -> do { bumpStepCountTcS
548                      ; traceFireTcS depth (ptext (sLit "Spontaneous (w/d)") <+> ppr workItem)
549                      ; (new_inert, new_work) <- runSolverPipeline depth
550                              [ ("recursive interact with inert eqs", interactWithInertEqsStage)
551                              , ("recursive interact with inerts", interactWithInertsStage)
552                              ] inerts workItem'
553                      ; return $ SR { sr_new_work = new_work 
554                                    , sr_inerts   = new_inert -- will include workItem' 
555                                    , sr_stop     = Stop }
556                      }
557                | otherwise 
558                    -> -- Original was given; he must then be inert all right, and
559                       -- workList' are all givens from flattening
560                       do { bumpStepCountTcS
561                          ; traceFireTcS depth (ptext (sLit "Spontaneous (g)") <+> ppr workItem)
562                          ; return $ SR { sr_new_work = emptyWorkList
563                                        , sr_inerts   = inerts `updInertSet` workItem' 
564                                        , sr_stop     = Stop } }
565            SPError -> -- Return with no new work
566                return $ SR { sr_new_work = emptyWorkList
567                            , sr_inerts   = inerts
568                            , sr_stop     = Stop }
569        }
570
571 data SPSolveResult = SPCantSolve | SPSolved WorkItem | SPError
572 -- SPCantSolve means that we can't do the unification because e.g. the variable is untouchable
573 -- SPSolved workItem' gives us a new *given* to go on 
574 -- SPError means that it's completely impossible to solve this equality, eg due to a kind error
575
576
577 -- @trySpontaneousSolve wi@ solves equalities where one side is a
578 -- touchable unification variable.
579 --          See Note [Touchables and givens] 
580 trySpontaneousSolve :: WorkItem -> TcS SPSolveResult
581 trySpontaneousSolve workItem@(CTyEqCan { cc_id = cv, cc_flavor = gw, cc_tyvar = tv1, cc_rhs = xi })
582   | isGivenOrSolved gw
583   = return SPCantSolve
584   | Just tv2 <- tcGetTyVar_maybe xi
585   = do { tch1 <- isTouchableMetaTyVar tv1
586        ; tch2 <- isTouchableMetaTyVar tv2
587        ; case (tch1, tch2) of
588            (True,  True)  -> trySpontaneousEqTwoWay cv gw tv1 tv2
589            (True,  False) -> trySpontaneousEqOneWay cv gw tv1 xi
590            (False, True)  -> trySpontaneousEqOneWay cv gw tv2 (mkTyVarTy tv1)
591            _ -> return SPCantSolve }
592   | otherwise
593   = do { tch1 <- isTouchableMetaTyVar tv1
594        ; if tch1 then trySpontaneousEqOneWay cv gw tv1 xi
595                  else do { traceTcS "Untouchable LHS, can't spontaneously solve workitem:" 
596                                     (ppr workItem) 
597                          ; return SPCantSolve }
598        }
599
600   -- No need for 
601   --      trySpontaneousSolve (CFunEqCan ...) = ...
602   -- See Note [No touchables as FunEq RHS] in TcSMonad
603 trySpontaneousSolve _ = return SPCantSolve
604
605 ----------------
606 trySpontaneousEqOneWay :: CoVar -> CtFlavor -> TcTyVar -> Xi -> TcS SPSolveResult
607 -- tv is a MetaTyVar, not untouchable
608 trySpontaneousEqOneWay cv gw tv xi      
609   | not (isSigTyVar tv) || isTyVarTy xi 
610   = do { let kxi = typeKind xi -- NB: 'xi' is fully rewritten according to the inerts 
611                                -- so we have its more specific kind in our hands
612        ; if kxi `isSubKind` tyVarKind tv then
613              solveWithIdentity cv gw tv xi
614          else return SPCantSolve
615 {-
616          else if tyVarKind tv `isSubKind` kxi then
617              return SPCantSolve -- kinds are compatible but we can't solveWithIdentity this way
618                                 -- This case covers the  a_touchable :: * ~ b_untouchable :: ?? 
619                                 -- which has to be deferred or floated out for someone else to solve 
620                                 -- it in a scope where 'b' is no longer untouchable.
621          else do { addErrorTcS KindError gw (mkTyVarTy tv) xi -- See Note [Kind errors]
622                  ; return SPError }
623 -}
624        }
625   | otherwise -- Still can't solve, sig tyvar and non-variable rhs
626   = return SPCantSolve
627
628 ----------------
629 trySpontaneousEqTwoWay :: CoVar -> CtFlavor -> TcTyVar -> TcTyVar -> TcS SPSolveResult
630 -- Both tyvars are *touchable* MetaTyvars so there is only a chance for kind error here
631 trySpontaneousEqTwoWay cv gw tv1 tv2
632   | k1 `isSubKind` k2
633   , nicer_to_update_tv2 = solveWithIdentity cv gw tv2 (mkTyVarTy tv1)
634   | k2 `isSubKind` k1 
635   = solveWithIdentity cv gw tv1 (mkTyVarTy tv2)
636   | otherwise -- None is a subkind of the other, but they are both touchable! 
637   = return SPCantSolve
638     -- do { addErrorTcS KindError gw (mkTyVarTy tv1) (mkTyVarTy tv2)
639     --   ; return SPError }
640   where
641     k1 = tyVarKind tv1
642     k2 = tyVarKind tv2
643     nicer_to_update_tv2 = isSigTyVar tv1 || isSystemName (Var.varName tv2)
644 \end{code}
645
646 Note [Kind errors] 
647 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
648 Consider the wanted problem: 
649       alpha ~ (# Int, Int #) 
650 where alpha :: ?? and (# Int, Int #) :: (#). We can't spontaneously solve this constraint, 
651 but we should rather reject the program that give rise to it. If 'trySpontaneousEqTwoWay' 
652 simply returns @CantSolve@ then that wanted constraint is going to propagate all the way and 
653 get quantified over in inference mode. That's bad because we do know at this point that the 
654 constraint is insoluble. Instead, we call 'recKindErrorTcS' here, which will fail later on.
655
656 The same applies in canonicalization code in case of kind errors in the givens. 
657
658 However, when we canonicalize givens we only check for compatibility (@compatKind@). 
659 If there were a kind error in the givens, this means some form of inconsistency or dead code.
660
661 You may think that when we spontaneously solve wanteds we may have to look through the 
662 bindings to determine the right kind of the RHS type. E.g one may be worried that xi is 
663 @alpha@ where alpha :: ? and a previous spontaneous solving has set (alpha := f) with (f :: *).
664 But we orient our constraints so that spontaneously solved ones can rewrite all other constraint
665 so this situation can't happen. 
666
667 Note [Spontaneous solving and kind compatibility] 
668 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
669 Note that our canonical constraints insist that *all* equalities (tv ~
670 xi) or (F xis ~ rhs) require the LHS and the RHS to have *compatible*
671 the same kinds.  ("compatible" means one is a subKind of the other.)
672
673   - It can't be *equal* kinds, because
674      b) wanted constraints don't necessarily have identical kinds
675                eg   alpha::? ~ Int
676      b) a solved wanted constraint becomes a given
677
678   - SPJ thinks that *given* constraints (tv ~ tau) always have that
679     tau has a sub-kind of tv; and when solving wanted constraints
680     in trySpontaneousEqTwoWay we re-orient to achieve this.
681
682   - Note that the kind invariant is maintained by rewriting.
683     Eg wanted1 rewrites wanted2; if both were compatible kinds before,
684        wanted2 will be afterwards.  Similarly givens.
685
686 Caveat:
687   - Givens from higher-rank, such as: 
688           type family T b :: * -> * -> * 
689           type instance T Bool = (->) 
690
691           f :: forall a. ((T a ~ (->)) => ...) -> a -> ... 
692           flop = f (...) True 
693      Whereas we would be able to apply the type instance, we would not be able to 
694      use the given (T Bool ~ (->)) in the body of 'flop' 
695
696
697 Note [Avoid double unifications] 
698 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
699 The spontaneous solver has to return a given which mentions the unified unification
700 variable *on the left* of the equality. Here is what happens if not: 
701   Original wanted:  (a ~ alpha),  (alpha ~ Int) 
702 We spontaneously solve the first wanted, without changing the order! 
703       given : a ~ alpha      [having unified alpha := a] 
704 Now the second wanted comes along, but he cannot rewrite the given, so we simply continue.
705 At the end we spontaneously solve that guy, *reunifying*  [alpha := Int] 
706
707 We avoid this problem by orienting the resulting given so that the unification
708 variable is on the left.  [Note that alternatively we could attempt to
709 enforce this at canonicalization]
710
711 See also Note [No touchables as FunEq RHS] in TcSMonad; avoiding
712 double unifications is the main reason we disallow touchable
713 unification variables as RHS of type family equations: F xis ~ alpha.
714
715 \begin{code}
716 ----------------
717
718 solveWithIdentity :: CoVar -> CtFlavor -> TcTyVar -> Xi -> TcS SPSolveResult
719 -- Solve with the identity coercion 
720 -- Precondition: kind(xi) is a sub-kind of kind(tv)
721 -- Precondition: CtFlavor is Wanted or Derived
722 -- See [New Wanted Superclass Work] to see why solveWithIdentity 
723 --     must work for Derived as well as Wanted
724 -- Returns: workItem where 
725 --        workItem = the new Given constraint
726 solveWithIdentity cv wd tv xi 
727   = do { traceTcS "Sneaky unification:" $ 
728                        vcat [text "Coercion variable:  " <+> ppr wd, 
729                              text "Coercion:           " <+> pprEq (mkTyVarTy tv) xi,
730                              text "Left  Kind is     : " <+> ppr (typeKind (mkTyVarTy tv)),
731                              text "Right Kind is     : " <+> ppr (typeKind xi)
732                   ]
733
734        ; setWantedTyBind tv xi
735        ; cv_given <- newGivenCoVar (mkTyVarTy tv) xi xi
736
737        ; when (isWanted wd) (setCoBind cv xi)
738            -- We don't want to do this for Derived, that's why we use 'when (isWanted wd)'
739        ; return $ SPSolved (CTyEqCan { cc_id = cv_given
740                                      , cc_flavor = mkSolvedFlavor wd UnkSkol
741                                      , cc_tyvar  = tv, cc_rhs = xi }) }
742 \end{code}
743
744
745 *********************************************************************************
746 *                                                                               * 
747                        The interact-with-inert Stage
748 *                                                                               *
749 *********************************************************************************
750
751 Note [The Solver Invariant]
752 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
753 We always add Givens first.  So you might think that the solver has
754 the invariant
755
756    If the work-item is Given, 
757    then the inert item must Given
758
759 But this isn't quite true.  Suppose we have, 
760     c1: [W] beta ~ [alpha], c2 : [W] blah, c3 :[W] alpha ~ Int
761 After processing the first two, we get
762      c1: [G] beta ~ [alpha], c2 : [W] blah
763 Now, c3 does not interact with the the given c1, so when we spontaneously
764 solve c3, we must re-react it with the inert set.  So we can attempt a 
765 reaction between inert c2 [W] and work-item c3 [G].
766
767 It *is* true that [Solver Invariant]
768    If the work-item is Given, 
769    AND there is a reaction
770    then the inert item must Given
771 or, equivalently,
772    If the work-item is Given, 
773    and the inert item is Wanted/Derived
774    then there is no reaction
775
776 \begin{code}
777 -- Interaction result of  WorkItem <~> AtomicInert
778 data InteractResult
779    = IR { ir_stop         :: StopOrContinue
780             -- Stop
781             --   => Reagent (work item) consumed.
782             -- ContinueWith new_reagent
783             --   => Reagent transformed but keep gathering interactions. 
784             --      The transformed item remains inert with respect 
785             --      to any previously encountered inerts.
786
787         , ir_inert_action :: InertAction
788             -- Whether the inert item should remain in the InertSet.
789
790         , ir_new_work     :: WorkList
791             -- new work items to add to the WorkList
792
793         , ir_fire :: Maybe String    -- Tells whether a rule fired, and if so what
794         }
795
796 -- What to do with the inert reactant.
797 data InertAction = KeepInert | DropInert 
798
799 mkIRContinue :: String -> WorkItem -> InertAction -> WorkList -> TcS InteractResult
800 mkIRContinue rule wi keep newWork 
801   = return $ IR { ir_stop = ContinueWith wi, ir_inert_action = keep
802                 , ir_new_work = newWork, ir_fire = Just rule }
803
804 mkIRStopK :: String -> WorkList -> TcS InteractResult
805 mkIRStopK rule newWork
806   = return $ IR { ir_stop = Stop, ir_inert_action = KeepInert
807                 , ir_new_work = newWork, ir_fire = Just rule }
808
809 mkIRStopD :: String -> WorkList -> TcS InteractResult
810 mkIRStopD rule newWork
811   = return $ IR { ir_stop = Stop, ir_inert_action = DropInert
812                 , ir_new_work = newWork, ir_fire = Just rule }
813
814 noInteraction :: Monad m => WorkItem -> m InteractResult
815 noInteraction wi
816   = return $ IR { ir_stop = ContinueWith wi, ir_inert_action = KeepInert
817                 , ir_new_work = emptyWorkList, ir_fire = Nothing }
818
819 data WhichComesFromInert = LeftComesFromInert | RightComesFromInert 
820      -- See Note [Efficient Orientation] 
821
822
823 ---------------------------------------------------
824 -- Interact a single WorkItem with the equalities of an inert set as
825 -- far as possible, i.e. until we get a Stop result from an individual
826 -- reaction (i.e. when the WorkItem is consumed), or until we've
827 -- interact the WorkItem with the entire equalities of the InertSet
828
829 interactWithInertEqsStage :: SimplifierStage 
830 interactWithInertEqsStage depth workItem inert
831   = Bag.foldrBagM (interactNext depth) initITR (inert_eqs inert)
832                         -- use foldr to preserve the order          
833   where
834     initITR = SR { sr_inerts   = inert { inert_eqs = emptyCCan }
835                  , sr_new_work = emptyWorkList
836                  , sr_stop     = ContinueWith workItem }
837
838 ---------------------------------------------------
839 -- Interact a single WorkItem with *non-equality* constraints in the inert set. 
840 -- Precondition: equality interactions must have already happened, hence we have 
841 -- to pick up some information from the incoming inert, before folding over the 
842 -- "Other" constraints it contains!
843
844 interactWithInertsStage :: SimplifierStage
845 interactWithInertsStage depth workItem inert
846   = let (relevant, inert_residual) = getISRelevant workItem inert 
847         initITR = SR { sr_inerts   = inert_residual
848                      , sr_new_work = emptyWorkList
849                      , sr_stop     = ContinueWith workItem } 
850     in Bag.foldrBagM (interactNext depth) initITR relevant 
851                         -- use foldr to preserve the order
852   where 
853     getISRelevant :: CanonicalCt -> InertSet -> (CanonicalCts, InertSet) 
854     getISRelevant (CFrozenErr {}) is = (emptyCCan, is)
855                   -- Nothing s relevant; we have alread interacted
856                   -- it with the equalities in the inert set
857
858     getISRelevant (CDictCan { cc_class = cls } ) is
859       = let (relevant, residual_map) = getRelevantCts cls (inert_dicts is)
860         in (relevant, is { inert_dicts = residual_map }) 
861     getISRelevant (CFunEqCan { cc_fun = tc } ) is 
862       = let (relevant, residual_map) = getRelevantCts tc (inert_funeqs is) 
863         in (relevant, is { inert_funeqs = residual_map })
864     getISRelevant (CIPCan { cc_ip_nm = nm }) is 
865       = let (relevant, residual_map) = getRelevantCts nm (inert_ips is)
866         in (relevant, is { inert_ips = residual_map }) 
867     -- An equality, finally, may kick everything except equalities out 
868     -- because we have already interacted the equalities in interactWithInertEqsStage
869     getISRelevant _eq_ct is  -- Equality, everything is relevant for this one 
870                              -- TODO: if we were caching variables, we'd know that only 
871                              --       some are relevant. Experiment with this for now. 
872       = let cts = cCanMapToBag (inert_ips is) `unionBags` 
873                     cCanMapToBag (inert_dicts is) `unionBags` cCanMapToBag (inert_funeqs is)
874         in (cts, is { inert_dicts  = emptyCCanMap
875                     , inert_ips    = emptyCCanMap
876                     , inert_funeqs = emptyCCanMap })
877
878 interactNext :: SubGoalDepth -> AtomicInert -> StageResult -> TcS StageResult 
879 interactNext depth inert it
880   | ContinueWith work_item <- sr_stop it
881   = do { let inerts = sr_inerts it 
882
883        ; IR { ir_new_work = new_work, ir_inert_action = inert_action
884             , ir_fire = fire_info, ir_stop = stop } 
885             <- interactWithInert inert work_item
886
887        ; let mk_msg rule 
888                = text rule <+> keep_doc
889                  <+> vcat [ ptext (sLit "Inert =") <+> ppr inert
890                           , ptext (sLit "Work =")  <+> ppr work_item
891                           , ppUnless (isEmptyWorkList new_work) $
892                             ptext (sLit "New =") <+> ppr new_work ]
893              keep_doc = case inert_action of
894                           KeepInert -> ptext (sLit "[keep]")
895                           DropInert -> ptext (sLit "[drop]")
896        ; case fire_info of
897            Just rule -> do { bumpStepCountTcS
898                            ; traceFireTcS depth (mk_msg rule) }
899            Nothing  -> return ()
900
901        -- New inerts depend on whether we KeepInert or not 
902        ; let inerts_new = case inert_action of
903                             KeepInert -> inerts `updInertSet` inert
904                             DropInert -> inerts
905
906        ; return $ SR { sr_inerts   = inerts_new
907                      , sr_new_work = sr_new_work it `unionWorkList` new_work
908                      , sr_stop     = stop } }
909   | otherwise 
910   = return $ it { sr_inerts = (sr_inerts it) `updInertSet` inert }
911
912 -- Do a single interaction of two constraints.
913 interactWithInert :: AtomicInert -> WorkItem -> TcS InteractResult
914 interactWithInert inert workItem 
915   = do { ctxt <- getTcSContext
916        ; let is_allowed  = allowedInteraction (simplEqsOnly ctxt) inert workItem 
917
918        ; if is_allowed then 
919               doInteractWithInert inert workItem 
920           else 
921               noInteraction workItem 
922        }
923
924 allowedInteraction :: Bool -> AtomicInert -> WorkItem -> Bool 
925 -- Allowed interactions 
926 allowedInteraction eqs_only (CDictCan {}) (CDictCan {}) = not eqs_only
927 allowedInteraction eqs_only (CIPCan {})   (CIPCan {})   = not eqs_only
928 allowedInteraction _ _ _ = True 
929
930 --------------------------------------------
931 doInteractWithInert :: CanonicalCt -> CanonicalCt -> TcS InteractResult
932 -- Identical class constraints.
933
934 doInteractWithInert
935   inertItem@(CDictCan { cc_id = d1, cc_flavor = fl1, cc_class = cls1, cc_tyargs = tys1 }) 
936    workItem@(CDictCan { cc_id = d2, cc_flavor = fl2, cc_class = cls2, cc_tyargs = tys2 })
937   | cls1 == cls2 && (and $ zipWith tcEqType tys1 tys2)
938   = solveOneFromTheOther "Cls/Cls" (EvId d1,fl1) workItem 
939
940   | cls1 == cls2 && (not (isGivenOrSolved fl1 && isGivenOrSolved fl2))
941   =      -- See Note [When improvement happens]
942     do { let pty1 = ClassP cls1 tys1
943              pty2 = ClassP cls2 tys2
944              inert_pred_loc     = (pty1, pprFlavorArising fl1)
945              work_item_pred_loc = (pty2, pprFlavorArising fl2)
946              fd_eqns = improveFromAnother 
947                                   inert_pred_loc     -- the template
948                                   work_item_pred_loc -- the one we aim to rewrite
949                                   -- See Note [Efficient Orientation]
950
951        ; m <- rewriteWithFunDeps fd_eqns tys2 fl2
952        ; case m of 
953            Nothing -> noInteraction workItem
954            Just (rewritten_tys2, cos2, fd_work)
955              | tcEqTypes tys1 rewritten_tys2
956              -> -- Solve him on the spot in this case
957                 case fl2 of
958                   Given   {} -> pprPanic "Unexpected given" (ppr inertItem $$ ppr workItem)
959                   Derived {} -> mkIRStopK "Cls/Cls fundep (solved)" fd_work
960                   Wanted  {} 
961                     | isDerived fl1 
962                    -> do { setDictBind d2 (EvCast d1 dict_co)
963                          ; let inert_w = inertItem { cc_flavor = fl2 }
964                            -- A bit naughty: we take the inert Derived, 
965                            -- turn it into a Wanted, use it to solve the work-item
966                            -- and put it back into the work-list
967                            -- Maybe rather than starting again, we could *replace* the
968                            -- inert item, but its safe and simple to restart
969                          ; mkIRStopD "Cls/Cls fundep (solved)" $ 
970                            workListFromNonEq inert_w `unionWorkList` fd_work }
971                     | otherwise 
972                     -> do { setDictBind d2 (EvCast d1 dict_co)
973                           ; mkIRStopK "Cls/Cls fundep (solved)" fd_work }
974
975              | otherwise
976              -> -- We could not quite solve him, but we still rewrite him
977                 -- Example: class C a b c | a -> b
978                 --          Given: C Int Bool x, Wanted: C Int beta y
979                 --          Then rewrite the wanted to C Int Bool y
980                 --          but note that is still not identical to the given
981                 -- The important thing is that the rewritten constraint is
982                 -- inert wrt the given.
983                 -- However it is not necessarily inert wrt previous inert-set items.
984                 --      class C a b c d |  a -> b, b c -> d
985                 --      Inert: c1: C b Q R S, c2: C P Q a b
986                 --      Work: C P alpha R beta
987                 --      Does not react with c1; reacts with c2, with alpha:=Q
988                 --      NOW it reacts with c1!
989                 -- So we must stop, and put the rewritten constraint back in the work list
990                 do { d2' <- newDictVar cls1 rewritten_tys2
991                    ; case fl2 of
992                        Given {}   -> pprPanic "Unexpected given" (ppr inertItem $$ ppr workItem)
993                        Wanted {}  -> setDictBind d2 (EvCast d2' dict_co)
994                        Derived {} -> return ()
995                    ; let workItem' = workItem { cc_id = d2', cc_tyargs = rewritten_tys2 }
996                    ; mkIRStopK "Cls/Cls fundep (partial)" $ 
997                      workListFromNonEq workItem' `unionWorkList` fd_work } 
998
999              where
1000                dict_co = mkTyConCoercion (classTyCon cls1) cos2
1001   }
1002
1003 -- Class constraint and given equality: use the equality to rewrite
1004 -- the class constraint. 
1005 doInteractWithInert (CTyEqCan { cc_id = cv, cc_flavor = ifl, cc_tyvar = tv, cc_rhs = xi }) 
1006                     (CDictCan { cc_id = dv, cc_flavor = wfl, cc_class = cl, cc_tyargs = xis }) 
1007   | ifl `canRewrite` wfl 
1008   , tv `elemVarSet` tyVarsOfTypes xis
1009   = do { rewritten_dict <- rewriteDict (cv,tv,xi) (dv,wfl,cl,xis)
1010             -- Continue with rewritten Dictionary because we can only be in the 
1011             -- interactWithEqsStage, so the dictionary is inert. 
1012        ; mkIRContinue "Eq/Cls" rewritten_dict KeepInert emptyWorkList }
1013     
1014 doInteractWithInert (CDictCan { cc_id = dv, cc_flavor = ifl, cc_class = cl, cc_tyargs = xis }) 
1015            workItem@(CTyEqCan { cc_id = cv, cc_flavor = wfl, cc_tyvar = tv, cc_rhs = xi })
1016   | wfl `canRewrite` ifl
1017   , tv `elemVarSet` tyVarsOfTypes xis
1018   = do { rewritten_dict <- rewriteDict (cv,tv,xi) (dv,ifl,cl,xis)
1019        ; mkIRContinue "Cls/Eq" workItem DropInert (workListFromNonEq rewritten_dict) }
1020
1021 -- Class constraint and given equality: use the equality to rewrite
1022 -- the class constraint.
1023 doInteractWithInert (CTyEqCan { cc_id = cv, cc_flavor = ifl, cc_tyvar = tv, cc_rhs = xi }) 
1024                     (CIPCan { cc_id = ipid, cc_flavor = wfl, cc_ip_nm = nm, cc_ip_ty = ty }) 
1025   | ifl `canRewrite` wfl
1026   , tv `elemVarSet` tyVarsOfType ty 
1027   = do { rewritten_ip <- rewriteIP (cv,tv,xi) (ipid,wfl,nm,ty) 
1028        ; mkIRContinue "Eq/IP" rewritten_ip KeepInert emptyWorkList } 
1029
1030 doInteractWithInert (CIPCan { cc_id = ipid, cc_flavor = ifl, cc_ip_nm = nm, cc_ip_ty = ty }) 
1031            workItem@(CTyEqCan { cc_id = cv, cc_flavor = wfl, cc_tyvar = tv, cc_rhs = xi })
1032   | wfl `canRewrite` ifl
1033   , tv `elemVarSet` tyVarsOfType ty
1034   = do { rewritten_ip <- rewriteIP (cv,tv,xi) (ipid,ifl,nm,ty) 
1035        ; mkIRContinue "IP/Eq" workItem DropInert (workListFromNonEq rewritten_ip) }
1036
1037 -- Two implicit parameter constraints.  If the names are the same,
1038 -- but their types are not, we generate a wanted type equality 
1039 -- that equates the type (this is "improvement").  
1040 -- However, we don't actually need the coercion evidence,
1041 -- so we just generate a fresh coercion variable that isn't used anywhere.
1042 doInteractWithInert (CIPCan { cc_id = id1, cc_flavor = ifl, cc_ip_nm = nm1, cc_ip_ty = ty1 }) 
1043            workItem@(CIPCan { cc_flavor = wfl, cc_ip_nm = nm2, cc_ip_ty = ty2 })
1044   | nm1 == nm2 && isGivenOrSolved wfl && isGivenOrSolved ifl
1045   =     -- See Note [Overriding implicit parameters]
1046         -- Dump the inert item, override totally with the new one
1047         -- Do not require type equality
1048         -- For example, given let ?x::Int = 3 in let ?x::Bool = True in ...
1049         --              we must *override* the outer one with the inner one
1050     mkIRContinue "IP/IP override" workItem DropInert emptyWorkList
1051
1052   | nm1 == nm2 && ty1 `tcEqType` ty2 
1053   = solveOneFromTheOther "IP/IP" (EvId id1,ifl) workItem 
1054
1055   | nm1 == nm2
1056   =     -- See Note [When improvement happens]
1057     do { co_var <- newCoVar ty2 ty1 -- See Note [Efficient Orientation]
1058        ; let flav = Wanted (combineCtLoc ifl wfl)
1059        ; cans <- mkCanonical flav co_var
1060        ; case wfl of
1061            Given   {} -> pprPanic "Unexpected given IP" (ppr workItem)
1062            Derived {} -> pprPanic "Unexpected derived IP" (ppr workItem)
1063            Wanted  {} ->
1064                do { setIPBind (cc_id workItem) $
1065                     EvCast id1 (mkSymCoercion (mkCoVarCoercion co_var))
1066                   ; mkIRStopK "IP/IP interaction (solved)" cans }
1067        }
1068
1069 -- Never rewrite a given with a wanted equality, and a type function
1070 -- equality can never rewrite an equality. We rewrite LHS *and* RHS 
1071 -- of function equalities so that our inert set exposes everything that 
1072 -- we know about equalities.
1073
1074 -- Inert: equality, work item: function equality
1075 doInteractWithInert (CTyEqCan { cc_id = cv1, cc_flavor = ifl, cc_tyvar = tv, cc_rhs = xi1 }) 
1076                     (CFunEqCan { cc_id = cv2, cc_flavor = wfl, cc_fun = tc
1077                                , cc_tyargs = args, cc_rhs = xi2 })
1078   | ifl `canRewrite` wfl 
1079   , tv `elemVarSet` tyVarsOfTypes (xi2:args) -- Rewrite RHS as well
1080   = do { rewritten_funeq <- rewriteFunEq (cv1,tv,xi1) (cv2,wfl,tc,args,xi2) 
1081        ; mkIRStopK "Eq/FunEq" (workListFromEq rewritten_funeq) } 
1082          -- Must Stop here, because we may no longer be inert after the rewritting.
1083
1084 -- Inert: function equality, work item: equality
1085 doInteractWithInert (CFunEqCan {cc_id = cv1, cc_flavor = ifl, cc_fun = tc
1086                               , cc_tyargs = args, cc_rhs = xi1 }) 
1087            workItem@(CTyEqCan { cc_id = cv2, cc_flavor = wfl, cc_tyvar = tv, cc_rhs = xi2 })
1088   | wfl `canRewrite` ifl
1089   , tv `elemVarSet` tyVarsOfTypes (xi1:args) -- Rewrite RHS as well
1090   = do { rewritten_funeq <- rewriteFunEq (cv2,tv,xi2) (cv1,ifl,tc,args,xi1) 
1091        ; mkIRContinue "FunEq/Eq" workItem DropInert (workListFromEq rewritten_funeq) } 
1092          -- One may think that we could (KeepTransformedInert rewritten_funeq) 
1093          -- but that is wrong, because it may end up not being inert with respect 
1094          -- to future inerts. Example: 
1095          -- Original inert = {    F xis ~  [a], b ~ Maybe Int } 
1096          -- Work item comes along = a ~ [b] 
1097          -- If we keep { F xis ~ [b] } in the inert set we will end up with: 
1098          --      { F xis ~ [b], b ~ Maybe Int, a ~ [Maybe Int] } 
1099          -- At the end, which is *not* inert. So we should unfortunately DropInert here.
1100
1101 doInteractWithInert (CFunEqCan { cc_id = cv1, cc_flavor = fl1, cc_fun = tc1
1102                                , cc_tyargs = args1, cc_rhs = xi1 }) 
1103            workItem@(CFunEqCan { cc_id = cv2, cc_flavor = fl2, cc_fun = tc2
1104                                , cc_tyargs = args2, cc_rhs = xi2 })
1105   | tc1 == tc2 && and (zipWith tcEqType args1 args2) 
1106   , Just GivenSolved <- isGiven_maybe fl1 
1107   = mkIRContinue "Funeq/Funeq" workItem DropInert emptyWorkList
1108   | tc1 == tc2 && and (zipWith tcEqType args1 args2) 
1109   , Just GivenSolved <- isGiven_maybe fl2 
1110   = mkIRStopK "Funeq/Funeq" emptyWorkList
1111
1112   | fl1 `canSolve` fl2 && lhss_match
1113   = do { cans <- rewriteEqLHS LeftComesFromInert  (mkCoVarCoercion cv1,xi1) (cv2,fl2,xi2) 
1114        ; mkIRStopK "FunEq/FunEq" cans } 
1115   | fl2 `canSolve` fl1 && lhss_match
1116   = do { cans <- rewriteEqLHS RightComesFromInert (mkCoVarCoercion cv2,xi2) (cv1,fl1,xi1) 
1117        ; mkIRContinue "FunEq/FunEq" workItem DropInert cans }
1118   where
1119     lhss_match = tc1 == tc2 && and (zipWith tcEqType args1 args2) 
1120
1121 doInteractWithInert (CTyEqCan { cc_id = cv1, cc_flavor = fl1, cc_tyvar = tv1, cc_rhs = xi1 }) 
1122            workItem@(CTyEqCan { cc_id = cv2, cc_flavor = fl2, cc_tyvar = tv2, cc_rhs = xi2 })
1123 -- Check for matching LHS 
1124   | fl1 `canSolve` fl2 && tv1 == tv2 
1125   = do { cans <- rewriteEqLHS LeftComesFromInert (mkCoVarCoercion cv1,xi1) (cv2,fl2,xi2) 
1126        ; mkIRStopK "Eq/Eq lhs" cans } 
1127
1128   | fl2 `canSolve` fl1 && tv1 == tv2 
1129   = do { cans <- rewriteEqLHS RightComesFromInert (mkCoVarCoercion cv2,xi2) (cv1,fl1,xi1) 
1130        ; mkIRContinue "Eq/Eq lhs" workItem DropInert cans }
1131
1132 -- Check for rewriting RHS 
1133   | fl1 `canRewrite` fl2 && tv1 `elemVarSet` tyVarsOfType xi2 
1134   = do { rewritten_eq <- rewriteEqRHS (cv1,tv1,xi1) (cv2,fl2,tv2,xi2) 
1135        ; mkIRStopK "Eq/Eq rhs" rewritten_eq }
1136
1137   | fl2 `canRewrite` fl1 && tv2 `elemVarSet` tyVarsOfType xi1
1138   = do { rewritten_eq <- rewriteEqRHS (cv2,tv2,xi2) (cv1,fl1,tv1,xi1) 
1139        ; mkIRContinue "Eq/Eq rhs" workItem DropInert rewritten_eq } 
1140
1141 doInteractWithInert (CTyEqCan   { cc_id = cv1, cc_flavor = fl1, cc_tyvar = tv1, cc_rhs = xi1 })
1142                     (CFrozenErr { cc_id = cv2, cc_flavor = fl2 })
1143   | fl1 `canRewrite` fl2 && tv1 `elemVarSet` tyVarsOfEvVar cv2
1144   = do { rewritten_frozen <- rewriteFrozen (cv1, tv1, xi1) (cv2, fl2)
1145        ; mkIRStopK "Frozen/Eq" rewritten_frozen }
1146
1147 doInteractWithInert (CFrozenErr { cc_id = cv2, cc_flavor = fl2 })
1148            workItem@(CTyEqCan   { cc_id = cv1, cc_flavor = fl1, cc_tyvar = tv1, cc_rhs = xi1 })
1149   | fl1 `canRewrite` fl2 && tv1 `elemVarSet` tyVarsOfEvVar cv2
1150   = do { rewritten_frozen <- rewriteFrozen (cv1, tv1, xi1) (cv2, fl2)
1151        ; mkIRContinue "Frozen/Eq" workItem DropInert rewritten_frozen }
1152
1153 -- Fall-through case for all other situations
1154 doInteractWithInert _ workItem = noInteraction workItem
1155
1156 -------------------------
1157 -- Equational Rewriting 
1158 rewriteDict  :: (CoVar, TcTyVar, Xi) -> (DictId, CtFlavor, Class, [Xi]) -> TcS CanonicalCt
1159 rewriteDict (cv,tv,xi) (dv,gw,cl,xis) 
1160   = do { let cos  = substTysWith [tv] [mkCoVarCoercion cv] xis -- xis[tv] ~ xis[xi]
1161              args = substTysWith [tv] [xi] xis
1162              con  = classTyCon cl 
1163              dict_co = mkTyConCoercion con cos 
1164        ; dv' <- newDictVar cl args 
1165        ; case gw of 
1166            Wanted {}         -> setDictBind dv (EvCast dv' (mkSymCoercion dict_co))
1167            Given {}          -> setDictBind dv' (EvCast dv dict_co) 
1168            Derived {}        -> return () -- Derived dicts we don't set any evidence
1169
1170        ; return (CDictCan { cc_id = dv'
1171                           , cc_flavor = gw 
1172                           , cc_class = cl 
1173                           , cc_tyargs = args }) } 
1174
1175 rewriteIP :: (CoVar,TcTyVar,Xi) -> (EvVar,CtFlavor, IPName Name, TcType) -> TcS CanonicalCt 
1176 rewriteIP (cv,tv,xi) (ipid,gw,nm,ty) 
1177   = do { let ip_co = substTyWith [tv] [mkCoVarCoercion cv] ty     -- ty[tv] ~ t[xi] 
1178              ty'   = substTyWith [tv] [xi] ty
1179        ; ipid' <- newIPVar nm ty' 
1180        ; case gw of 
1181            Wanted {}         -> setIPBind ipid  (EvCast ipid' (mkSymCoercion ip_co))
1182            Given {}          -> setIPBind ipid' (EvCast ipid ip_co) 
1183            Derived {}        -> return () -- Derived ips: we don't set any evidence
1184
1185        ; return (CIPCan { cc_id = ipid'
1186                         , cc_flavor = gw
1187                         , cc_ip_nm = nm
1188                         , cc_ip_ty = ty' }) }
1189    
1190 rewriteFunEq :: (CoVar,TcTyVar,Xi) -> (CoVar,CtFlavor,TyCon, [Xi], Xi) -> TcS CanonicalCt
1191 rewriteFunEq (cv1,tv,xi1) (cv2,gw, tc,args,xi2)                   -- cv2 :: F args ~ xi2
1192   = do { let arg_cos = substTysWith [tv] [mkCoVarCoercion cv1] args 
1193              args'   = substTysWith [tv] [xi1] args 
1194              fun_co  = mkTyConCoercion tc arg_cos                 -- fun_co :: F args ~ F args'
1195
1196              xi2'    = substTyWith [tv] [xi1] xi2
1197              xi2_co  = substTyWith [tv] [mkCoVarCoercion cv1] xi2 -- xi2_co :: xi2 ~ xi2' 
1198
1199        ; cv2' <- newCoVar (mkTyConApp tc args') xi2'
1200        ; case gw of 
1201            Wanted {} -> setCoBind cv2  (fun_co               `mkTransCoercion` 
1202                                         mkCoVarCoercion cv2' `mkTransCoercion` 
1203                                         mkSymCoercion xi2_co)
1204            Given {}  -> setCoBind cv2' (mkSymCoercion fun_co `mkTransCoercion` 
1205                                         mkCoVarCoercion cv2  `mkTransCoercion` 
1206                                         xi2_co)
1207            Derived {} -> return () 
1208
1209        ; return (CFunEqCan { cc_id = cv2'
1210                            , cc_flavor = gw
1211                            , cc_tyargs = args'
1212                            , cc_fun = tc 
1213                            , cc_rhs = xi2' }) }
1214
1215
1216 rewriteEqRHS :: (CoVar,TcTyVar,Xi) -> (CoVar,CtFlavor,TcTyVar,Xi) -> TcS WorkList
1217 -- Use the first equality to rewrite the second, flavors already checked. 
1218 -- E.g.          c1 : tv1 ~ xi1   c2 : tv2 ~ xi2
1219 -- rewrites c2 to give
1220 --               c2' : tv2 ~ xi2[xi1/tv1]
1221 -- We must do an occurs check to sure the new constraint is canonical
1222 -- So we might return an empty bag
1223 rewriteEqRHS (cv1,tv1,xi1) (cv2,gw,tv2,xi2) 
1224   | Just tv2' <- tcGetTyVar_maybe xi2'
1225   , tv2 == tv2'  -- In this case xi2[xi1/tv1] = tv2, so we have tv2~tv2
1226   = do { when (isWanted gw) (setCoBind cv2 (mkSymCoercion co2')) 
1227        ; return emptyWorkList } 
1228   | otherwise
1229   = do { cv2' <- newCoVar (mkTyVarTy tv2) xi2'
1230        ; case gw of
1231              Wanted {} -> setCoBind cv2 $ mkCoVarCoercion cv2' `mkTransCoercion` 
1232                                           mkSymCoercion co2'
1233              Given {}  -> setCoBind cv2' $ mkCoVarCoercion cv2 `mkTransCoercion` 
1234                                            co2'
1235              Derived {} -> return ()
1236        ; canEqToWorkList gw cv2' (mkTyVarTy tv2) xi2' }
1237   where 
1238     xi2' = substTyWith [tv1] [xi1] xi2 
1239     co2' = substTyWith [tv1] [mkCoVarCoercion cv1] xi2  -- xi2 ~ xi2[xi1/tv1]
1240
1241 rewriteEqLHS :: WhichComesFromInert -> (Coercion,Xi) -> (CoVar,CtFlavor,Xi) -> TcS WorkList
1242 -- Used to ineract two equalities of the following form: 
1243 -- First Equality:   co1: (XXX ~ xi1)  
1244 -- Second Equality:  cv2: (XXX ~ xi2) 
1245 -- Where the cv1 `canRewrite` cv2 equality 
1246 -- We have an option of creating new work (xi1 ~ xi2) OR (xi2 ~ xi1), 
1247 --    See Note [Efficient Orientation] for that 
1248 rewriteEqLHS LeftComesFromInert (co1,xi1) (cv2,gw,xi2) 
1249   = do { cv2' <- newCoVar xi2 xi1 
1250        ; case gw of 
1251            Wanted {} -> setCoBind cv2 $ 
1252                         co1 `mkTransCoercion` mkSymCoercion (mkCoVarCoercion cv2')
1253            Given {}  -> setCoBind cv2' $ 
1254                         mkSymCoercion (mkCoVarCoercion cv2) `mkTransCoercion` co1 
1255            Derived {} -> return ()
1256        ; mkCanonical gw cv2' }
1257
1258 rewriteEqLHS RightComesFromInert (co1,xi1) (cv2,gw,xi2) 
1259   = do { cv2' <- newCoVar xi1 xi2
1260        ; case gw of
1261            Wanted {} -> setCoBind cv2 $
1262                         co1 `mkTransCoercion` mkCoVarCoercion cv2'
1263            Given {}  -> setCoBind cv2' $
1264                         mkSymCoercion co1 `mkTransCoercion` mkCoVarCoercion cv2
1265            Derived {} -> return ()
1266        ; mkCanonical gw cv2' }
1267
1268 rewriteFrozen :: (CoVar,TcTyVar,Xi) -> (CoVar,CtFlavor) -> TcS WorkList
1269 rewriteFrozen (cv1, tv1, xi1) (cv2, fl2)
1270   = do { cv2' <- newCoVar ty2a' ty2b'  -- ty2a[xi1/tv1] ~ ty2b[xi1/tv1]
1271        ; case fl2 of
1272              Wanted {} -> setCoBind cv2 $ co2a'                `mkTransCoercion`
1273                                           mkCoVarCoercion cv2' `mkTransCoercion`
1274                                           mkSymCoercion co2b'
1275
1276              Given {} -> setCoBind cv2' $ mkSymCoercion co2a'  `mkTransCoercion`
1277                                           mkCoVarCoercion cv2  `mkTransCoercion`
1278                                           co2b'
1279
1280              Derived {} -> return ()
1281
1282       ; return (workListFromNonEq $ CFrozenErr { cc_id = cv2', cc_flavor = fl2 }) }
1283   where
1284     (ty2a, ty2b) = coVarKind cv2          -- cv2 : ty2a ~ ty2b
1285     ty2a' = substTyWith [tv1] [xi1] ty2a
1286     ty2b' = substTyWith [tv1] [xi1] ty2b
1287
1288     co2a' = substTyWith [tv1] [mkCoVarCoercion cv1] ty2a  -- ty2a ~ ty2a[xi1/tv1]
1289     co2b' = substTyWith [tv1] [mkCoVarCoercion cv1] ty2b  -- ty2b ~ ty2b[xi1/tv1]
1290
1291 solveOneFromTheOther :: String -> (EvTerm, CtFlavor) -> CanonicalCt -> TcS InteractResult
1292 -- First argument inert, second argument work-item. They both represent 
1293 -- wanted/given/derived evidence for the *same* predicate so 
1294 -- we can discharge one directly from the other. 
1295 --
1296 -- Precondition: value evidence only (implicit parameters, classes) 
1297 --               not coercion
1298 solveOneFromTheOther info (ev_term,ifl) workItem
1299   | isDerived wfl
1300   = mkIRStopK ("Solved[DW] " ++ info) emptyWorkList
1301
1302   | isDerived ifl -- The inert item is Derived, we can just throw it away, 
1303                   -- The workItem is inert wrt earlier inert-set items, 
1304                   -- so it's safe to continue on from this point
1305   = mkIRContinue ("Solved[DI] " ++ info) workItem DropInert emptyWorkList
1306   
1307   | Just GivenSolved <- isGiven_maybe ifl, isGivenOrSolved wfl
1308     -- Same if the inert is a GivenSolved -- just get rid of it
1309   = mkIRContinue ("Solved[SI] " ++ info) workItem DropInert emptyWorkList
1310
1311   | otherwise
1312   = ASSERT( ifl `canSolve` wfl )
1313       -- Because of Note [The Solver Invariant], plus Derived dealt with
1314     do { when (isWanted wfl) $ setEvBind wid ev_term
1315            -- Overwrite the binding, if one exists
1316            -- If both are Given, we already have evidence; no need to duplicate
1317        ; mkIRStopK ("Solved " ++ info) emptyWorkList }
1318   where 
1319      wfl = cc_flavor workItem
1320      wid = cc_id workItem
1321 \end{code}
1322
1323 Note [Superclasses and recursive dictionaries]
1324 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1325     Overlaps with Note [SUPERCLASS-LOOP 1]
1326                   Note [SUPERCLASS-LOOP 2]
1327                   Note [Recursive instances and superclases]
1328     ToDo: check overlap and delete redundant stuff
1329
1330 Right before adding a given into the inert set, we must
1331 produce some more work, that will bring the superclasses 
1332 of the given into scope. The superclass constraints go into 
1333 our worklist. 
1334
1335 When we simplify a wanted constraint, if we first see a matching
1336 instance, we may produce new wanted work. To (1) avoid doing this work 
1337 twice in the future and (2) to handle recursive dictionaries we may ``cache'' 
1338 this item as given into our inert set WITHOUT adding its superclass constraints, 
1339 otherwise we'd be in danger of creating a loop [In fact this was the exact reason
1340 for doing the isGoodRecEv check in an older version of the type checker]. 
1341
1342 But now we have added partially solved constraints to the worklist which may 
1343 interact with other wanteds. Consider the example: 
1344
1345 Example 1: 
1346
1347     class Eq b => Foo a b        --- 0-th selector
1348     instance Eq a => Foo [a] a   --- fooDFun
1349
1350 and wanted (Foo [t] t). We are first going to see that the instance matches 
1351 and create an inert set that includes the solved (Foo [t] t) but not its superclasses:
1352        d1 :_g Foo [t] t                 d1 := EvDFunApp fooDFun d3 
1353 Our work list is going to contain a new *wanted* goal
1354        d3 :_w Eq t 
1355
1356 Ok, so how do we get recursive dictionaries, at all: 
1357
1358 Example 2:
1359
1360     data D r = ZeroD | SuccD (r (D r));
1361     
1362     instance (Eq (r (D r))) => Eq (D r) where
1363         ZeroD     == ZeroD     = True
1364         (SuccD a) == (SuccD b) = a == b
1365         _         == _         = False;
1366     
1367     equalDC :: D [] -> D [] -> Bool;
1368     equalDC = (==);
1369
1370 We need to prove (Eq (D [])). Here's how we go:
1371
1372         d1 :_w Eq (D [])
1373
1374 by instance decl, holds if
1375         d2 :_w Eq [D []]
1376         where   d1 = dfEqD d2
1377
1378 *BUT* we have an inert set which gives us (no superclasses): 
1379         d1 :_g Eq (D []) 
1380 By the instance declaration of Eq we can show the 'd2' goal if 
1381         d3 :_w Eq (D [])
1382         where   d2 = dfEqList d3
1383                 d1 = dfEqD d2
1384 Now, however this wanted can interact with our inert d1 to set: 
1385         d3 := d1 
1386 and solve the goal. Why was this interaction OK? Because, if we chase the 
1387 evidence of d1 ~~> dfEqD d2 ~~-> dfEqList d3, so by setting d3 := d1 we 
1388 are really setting
1389         d3 := dfEqD2 (dfEqList d3) 
1390 which is FINE because the use of d3 is protected by the instance function 
1391 applications. 
1392
1393 So, our strategy is to try to put solved wanted dictionaries into the
1394 inert set along with their superclasses (when this is meaningful,
1395 i.e. when new wanted goals are generated) but solve a wanted dictionary
1396 from a given only in the case where the evidence variable of the
1397 wanted is mentioned in the evidence of the given (recursively through
1398 the evidence binds) in a protected way: more instance function applications 
1399 than superclass selectors.
1400
1401 Here are some more examples from GHC's previous type checker
1402
1403
1404 Example 3: 
1405 This code arises in the context of "Scrap Your Boilerplate with Class"
1406
1407     class Sat a
1408     class Data ctx a
1409     instance  Sat (ctx Char)             => Data ctx Char       -- dfunData1
1410     instance (Sat (ctx [a]), Data ctx a) => Data ctx [a]        -- dfunData2
1411
1412     class Data Maybe a => Foo a    
1413
1414     instance Foo t => Sat (Maybe t)                             -- dfunSat
1415
1416     instance Data Maybe a => Foo a                              -- dfunFoo1
1417     instance Foo a        => Foo [a]                            -- dfunFoo2
1418     instance                 Foo [Char]                         -- dfunFoo3
1419
1420 Consider generating the superclasses of the instance declaration
1421          instance Foo a => Foo [a]
1422
1423 So our problem is this
1424     d0 :_g Foo t
1425     d1 :_w Data Maybe [t] 
1426
1427 We may add the given in the inert set, along with its superclasses
1428 [assuming we don't fail because there is a matching instance, see 
1429  tryTopReact, given case ]
1430   Inert:
1431     d0 :_g Foo t 
1432   WorkList 
1433     d01 :_g Data Maybe t  -- d2 := EvDictSuperClass d0 0 
1434     d1 :_w Data Maybe [t] 
1435 Then d2 can readily enter the inert, and we also do solving of the wanted
1436   Inert: 
1437     d0 :_g Foo t 
1438     d1 :_s Data Maybe [t]           d1 := dfunData2 d2 d3 
1439   WorkList
1440     d2 :_w Sat (Maybe [t])          
1441     d3 :_w Data Maybe t
1442     d01 :_g Data Maybe t 
1443 Now, we may simplify d2 more: 
1444   Inert:
1445       d0 :_g Foo t 
1446       d1 :_s Data Maybe [t]           d1 := dfunData2 d2 d3 
1447       d1 :_g Data Maybe [t] 
1448       d2 :_g Sat (Maybe [t])          d2 := dfunSat d4 
1449   WorkList: 
1450       d3 :_w Data Maybe t 
1451       d4 :_w Foo [t] 
1452       d01 :_g Data Maybe t 
1453
1454 Now, we can just solve d3.
1455   Inert
1456       d0 :_g Foo t 
1457       d1 :_s Data Maybe [t]           d1 := dfunData2 d2 d3 
1458       d2 :_g Sat (Maybe [t])          d2 := dfunSat d4 
1459   WorkList
1460       d4 :_w Foo [t] 
1461       d01 :_g Data Maybe t 
1462 And now we can simplify d4 again, but since it has superclasses we *add* them to the worklist:
1463   Inert
1464       d0 :_g Foo t 
1465       d1 :_s Data Maybe [t]           d1 := dfunData2 d2 d3 
1466       d2 :_g Sat (Maybe [t])          d2 := dfunSat d4 
1467       d4 :_g Foo [t]                  d4 := dfunFoo2 d5 
1468   WorkList:
1469       d5 :_w Foo t 
1470       d6 :_g Data Maybe [t]           d6 := EvDictSuperClass d4 0
1471       d01 :_g Data Maybe t 
1472 Now, d5 can be solved! (and its superclass enter scope) 
1473   Inert
1474       d0 :_g Foo t 
1475       d1 :_s Data Maybe [t]           d1 := dfunData2 d2 d3 
1476       d2 :_g Sat (Maybe [t])          d2 := dfunSat d4 
1477       d4 :_g Foo [t]                  d4 := dfunFoo2 d5 
1478       d5 :_g Foo t                    d5 := dfunFoo1 d7
1479   WorkList:
1480       d7 :_w Data Maybe t
1481       d6 :_g Data Maybe [t]
1482       d8 :_g Data Maybe t            d8 := EvDictSuperClass d5 0
1483       d01 :_g Data Maybe t 
1484
1485 Now, two problems: 
1486    [1] Suppose we pick d8 and we react him with d01. Which of the two givens should 
1487        we keep? Well, we *MUST NOT* drop d01 because d8 contains recursive evidence 
1488        that must not be used (look at case interactInert where both inert and workitem
1489        are givens). So we have several options: 
1490        - Drop the workitem always (this will drop d8)
1491               This feels very unsafe -- what if the work item was the "good" one
1492               that should be used later to solve another wanted?
1493        - Don't drop anyone: the inert set may contain multiple givens! 
1494               [This is currently implemented] 
1495
1496 The "don't drop anyone" seems the most safe thing to do, so now we come to problem 2: 
1497   [2] We have added both d6 and d01 in the inert set, and we are interacting our wanted
1498       d7. Now the [isRecDictEv] function in the ineration solver 
1499       [case inert-given workitem-wanted] will prevent us from interacting d7 := d8 
1500       precisely because chasing the evidence of d8 leads us to an unguarded use of d7. 
1501
1502       So, no interaction happens there. Then we meet d01 and there is no recursion 
1503       problem there [isRectDictEv] gives us the OK to interact and we do solve d7 := d01! 
1504              
1505 Note [SUPERCLASS-LOOP 1]
1506 ~~~~~~~~~~~~~~~~~~~~~~~~
1507 We have to be very, very careful when generating superclasses, lest we
1508 accidentally build a loop. Here's an example:
1509
1510   class S a
1511
1512   class S a => C a where { opc :: a -> a }
1513   class S b => D b where { opd :: b -> b }
1514   
1515   instance C Int where
1516      opc = opd
1517   
1518   instance D Int where
1519      opd = opc
1520
1521 From (instance C Int) we get the constraint set {ds1:S Int, dd:D Int}
1522 Simplifying, we may well get:
1523         $dfCInt = :C ds1 (opd dd)
1524         dd  = $dfDInt
1525         ds1 = $p1 dd
1526 Notice that we spot that we can extract ds1 from dd.  
1527
1528 Alas!  Alack! We can do the same for (instance D Int):
1529
1530         $dfDInt = :D ds2 (opc dc)
1531         dc  = $dfCInt
1532         ds2 = $p1 dc
1533
1534 And now we've defined the superclass in terms of itself.
1535 Two more nasty cases are in
1536         tcrun021
1537         tcrun033
1538
1539 Solution: 
1540   - Satisfy the superclass context *all by itself* 
1541     (tcSimplifySuperClasses)
1542   - And do so completely; i.e. no left-over constraints
1543     to mix with the constraints arising from method declarations
1544
1545
1546 Note [SUPERCLASS-LOOP 2]
1547 ~~~~~~~~~~~~~~~~~~~~~~~~
1548 We need to be careful when adding "the constaint we are trying to prove".
1549 Suppose we are *given* d1:Ord a, and want to deduce (d2:C [a]) where
1550
1551         class Ord a => C a where
1552         instance Ord [a] => C [a] where ...
1553
1554 Then we'll use the instance decl to deduce C [a] from Ord [a], and then add the
1555 superclasses of C [a] to avails.  But we must not overwrite the binding
1556 for Ord [a] (which is obtained from Ord a) with a superclass selection or we'll just
1557 build a loop! 
1558
1559 Here's another variant, immortalised in tcrun020
1560         class Monad m => C1 m
1561         class C1 m => C2 m x
1562         instance C2 Maybe Bool
1563 For the instance decl we need to build (C1 Maybe), and it's no good if
1564 we run around and add (C2 Maybe Bool) and its superclasses to the avails 
1565 before we search for C1 Maybe.
1566
1567 Here's another example 
1568         class Eq b => Foo a b
1569         instance Eq a => Foo [a] a
1570 If we are reducing
1571         (Foo [t] t)
1572
1573 we'll first deduce that it holds (via the instance decl).  We must not
1574 then overwrite the Eq t constraint with a superclass selection!
1575
1576 At first I had a gross hack, whereby I simply did not add superclass constraints
1577 in addWanted, though I did for addGiven and addIrred.  This was sub-optimal,
1578 becuase it lost legitimate superclass sharing, and it still didn't do the job:
1579 I found a very obscure program (now tcrun021) in which improvement meant the
1580 simplifier got two bites a the cherry... so something seemed to be an Stop
1581 first time, but reducible next time.
1582
1583 Now we implement the Right Solution, which is to check for loops directly 
1584 when adding superclasses.  It's a bit like the occurs check in unification.
1585
1586 Note [Recursive instances and superclases]
1587 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1588 Consider this code, which arises in the context of "Scrap Your 
1589 Boilerplate with Class".  
1590
1591     class Sat a
1592     class Data ctx a
1593     instance  Sat (ctx Char)             => Data ctx Char
1594     instance (Sat (ctx [a]), Data ctx a) => Data ctx [a]
1595
1596     class Data Maybe a => Foo a
1597
1598     instance Foo t => Sat (Maybe t)
1599
1600     instance Data Maybe a => Foo a
1601     instance Foo a        => Foo [a]
1602     instance                 Foo [Char]
1603
1604 In the instance for Foo [a], when generating evidence for the superclasses
1605 (ie in tcSimplifySuperClasses) we need a superclass (Data Maybe [a]).
1606 Using the instance for Data, we therefore need
1607         (Sat (Maybe [a], Data Maybe a)
1608 But we are given (Foo a), and hence its superclass (Data Maybe a).
1609 So that leaves (Sat (Maybe [a])).  Using the instance for Sat means
1610 we need (Foo [a]).  And that is the very dictionary we are bulding
1611 an instance for!  So we must put that in the "givens".  So in this
1612 case we have
1613         Given:  Foo a, Foo [a]
1614         Wanted: Data Maybe [a]
1615
1616 BUT we must *not not not* put the *superclasses* of (Foo [a]) in
1617 the givens, which is what 'addGiven' would normally do. Why? Because
1618 (Data Maybe [a]) is the superclass, so we'd "satisfy" the wanted 
1619 by selecting a superclass from Foo [a], which simply makes a loop.
1620
1621 On the other hand we *must* put the superclasses of (Foo a) in
1622 the givens, as you can see from the derivation described above.
1623
1624 Conclusion: in the very special case of tcSimplifySuperClasses
1625 we have one 'given' (namely the "this" dictionary) whose superclasses
1626 must not be added to 'givens' by addGiven.  
1627
1628 There is a complication though.  Suppose there are equalities
1629       instance (Eq a, a~b) => Num (a,b)
1630 Then we normalise the 'givens' wrt the equalities, so the original
1631 given "this" dictionary is cast to one of a different type.  So it's a
1632 bit trickier than before to identify the "special" dictionary whose
1633 superclasses must not be added. See test
1634    indexed-types/should_run/EqInInstance
1635
1636 We need a persistent property of the dictionary to record this
1637 special-ness.  Current I'm using the InstLocOrigin (a bit of a hack,
1638 but cool), which is maintained by dictionary normalisation.
1639 Specifically, the InstLocOrigin is
1640              NoScOrigin
1641 then the no-superclass thing kicks in.  WATCH OUT if you fiddle
1642 with InstLocOrigin!
1643
1644 Note [MATCHING-SYNONYMS]
1645 ~~~~~~~~~~~~~~~~~~~~~~~~
1646 When trying to match a dictionary (D tau) to a top-level instance, or a 
1647 type family equation (F taus_1 ~ tau_2) to a top-level family instance, 
1648 we do *not* need to expand type synonyms because the matcher will do that for us.
1649
1650
1651 Note [RHS-FAMILY-SYNONYMS] 
1652 ~~~~~~~~~~~~~~~~~~~~~~~~~~
1653 The RHS of a family instance is represented as yet another constructor which is 
1654 like a type synonym for the real RHS the programmer declared. Eg: 
1655     type instance F (a,a) = [a] 
1656 Becomes: 
1657     :R32 a = [a]      -- internal type synonym introduced
1658     F (a,a) ~ :R32 a  -- instance 
1659
1660 When we react a family instance with a type family equation in the work list 
1661 we keep the synonym-using RHS without expansion. 
1662
1663
1664 *********************************************************************************
1665 *                                                                               * 
1666                        The top-reaction Stage
1667 *                                                                               *
1668 *********************************************************************************
1669
1670 \begin{code}
1671 -- If a work item has any form of interaction with top-level we get this 
1672 data TopInteractResult 
1673   = NoTopInt         -- No top-level interaction
1674                      -- Equivalent to (SomeTopInt emptyWorkList (ContinueWith work_item))
1675   | SomeTopInt 
1676       { tir_new_work  :: WorkList       -- Sub-goals or new work (could be given, 
1677                                         --                        for superclasses)
1678       , tir_new_inert :: StopOrContinue -- The input work item, ready to become *inert* now: 
1679       }                                 -- NB: in ``given'' (solved) form if the 
1680                                         -- original was wanted or given and instance match
1681                                         -- was found, but may also be in wanted form if we 
1682                                         -- only reacted with functional dependencies 
1683                                         -- arising from top-level instances.
1684
1685 topReactionsStage :: SimplifierStage
1686 topReactionsStage depth workItem inerts
1687   = do { tir <- tryTopReact inerts workItem
1688              -- NB: we pass the inerts as well. See Note [Instance and Given overlap]
1689        ; case tir of
1690            NoTopInt ->
1691                return $ SR { sr_inerts   = inerts
1692                            , sr_new_work = emptyWorkList
1693                            , sr_stop     = ContinueWith workItem }
1694            SomeTopInt tir_new_work tir_new_inert ->
1695                do { bumpStepCountTcS
1696                   ; traceFireTcS depth (ptext (sLit "Top react")
1697                        <+> vcat [ ptext (sLit "Work =") <+> ppr workItem
1698                                 , ptext (sLit "New =") <+> ppr tir_new_work ])
1699                   ; return $ SR { sr_inerts   = inerts
1700                                 , sr_new_work = tir_new_work
1701                                 , sr_stop     = tir_new_inert
1702                                 } }
1703        }
1704
1705 tryTopReact :: InertSet -> WorkItem -> TcS TopInteractResult 
1706 tryTopReact inerts workitem 
1707   = do {  -- A flag controls the amount of interaction allowed
1708           -- See Note [Simplifying RULE lhs constraints]
1709          ctxt <- getTcSContext
1710        ; if allowedTopReaction (simplEqsOnly ctxt) workitem 
1711          then do { traceTcS "tryTopReact / calling doTopReact" (ppr workitem)
1712                  ; doTopReact inerts workitem }
1713          else return NoTopInt 
1714        } 
1715
1716 allowedTopReaction :: Bool -> WorkItem -> Bool
1717 allowedTopReaction eqs_only (CDictCan {}) = not eqs_only
1718 allowedTopReaction _        _             = True
1719
1720 doTopReact :: InertSet -> WorkItem -> TcS TopInteractResult
1721 -- The work item does not react with the inert set, so try interaction with top-level instances
1722 -- NB: The place to add superclasses in *not* in doTopReact stage. Instead superclasses are 
1723 --     added in the worklist as part of the canonicalisation process. 
1724 -- See Note [Adding superclasses] in TcCanonical.
1725
1726 -- Given dictionary
1727 -- See Note [Given constraint that matches an instance declaration]
1728 doTopReact _inerts (CDictCan { cc_flavor = Given {} })
1729   = return NoTopInt -- NB: Superclasses already added since it's canonical
1730
1731 -- Derived dictionary: just look for functional dependencies
1732 doTopReact _inerts workItem@(CDictCan { cc_flavor = fl@(Derived loc)
1733                                       , cc_class = cls, cc_tyargs = xis })
1734   = do { instEnvs <- getInstEnvs
1735        ; let fd_eqns = improveFromInstEnv instEnvs
1736                                                 (ClassP cls xis, pprArisingAt loc)
1737        ; m <- rewriteWithFunDeps fd_eqns xis fl
1738        ; case m of
1739            Nothing -> return NoTopInt
1740            Just (xis',_,fd_work) ->
1741                let workItem' = workItem { cc_tyargs = xis' }
1742                    -- Deriveds are not supposed to have identity (cc_id is unused!)
1743                in return $ SomeTopInt { tir_new_work  = fd_work 
1744                                       , tir_new_inert = ContinueWith workItem' } }
1745
1746 -- Wanted dictionary
1747 doTopReact inerts workItem@(CDictCan { cc_id = dv, cc_flavor = fl@(Wanted loc)
1748                                      , cc_class = cls, cc_tyargs = xis })
1749   = do { -- See Note [MATCHING-SYNONYMS]
1750        ; lkp_inst_res <- matchClassInst inerts cls xis loc
1751        ; case lkp_inst_res of
1752            NoInstance ->
1753              do { traceTcS "doTopReact/ no class instance for" (ppr dv)
1754
1755                 ; instEnvs <- getInstEnvs
1756                 ; let fd_eqns = improveFromInstEnv instEnvs
1757                                                          (ClassP cls xis, pprArisingAt loc)
1758                 ; m <- rewriteWithFunDeps fd_eqns xis fl
1759                 ; case m of
1760                     Nothing -> return NoTopInt
1761                     Just (xis',cos,fd_work) ->
1762                         do { let dict_co = mkTyConCoercion (classTyCon cls) cos
1763                            ; dv'<- newDictVar cls xis'
1764                            ; setDictBind dv (EvCast dv' dict_co)
1765                            ; let workItem' = CDictCan { cc_id = dv', cc_flavor = fl, 
1766                                                         cc_class = cls, cc_tyargs = xis' }
1767                            ; return $ 
1768                              SomeTopInt { tir_new_work  = workListFromNonEq workItem' `unionWorkList` fd_work
1769                                         , tir_new_inert = Stop } } }
1770
1771            GenInst wtvs ev_term -- Solved 
1772                    -- No need to do fundeps stuff here; the instance 
1773                    -- matches already so we won't get any more info
1774                    -- from functional dependencies
1775              | null wtvs
1776              -> do { traceTcS "doTopReact/found nullary class instance for" (ppr dv) 
1777                    ; setDictBind dv ev_term 
1778                     -- Solved in one step and no new wanted work produced. 
1779                     -- i.e we directly matched a top-level instance
1780                     -- No point in caching this in 'inert'; hence Stop
1781                    ; return $ SomeTopInt { tir_new_work  = emptyWorkList 
1782                                          , tir_new_inert = Stop } }
1783
1784              | otherwise
1785              -> do { traceTcS "doTopReact/found non-nullary class instance for" (ppr dv) 
1786                    ; setDictBind dv ev_term 
1787                         -- Solved and new wanted work produced, you may cache the 
1788                         -- (tentatively solved) dictionary as Solved given.
1789                    ; let solved    = workItem { cc_flavor = solved_fl }
1790                          solved_fl = mkSolvedFlavor fl UnkSkol  
1791                    ; inst_work <- canWanteds wtvs
1792                    ; return $ SomeTopInt { tir_new_work  = inst_work
1793                                          , tir_new_inert = ContinueWith solved } }
1794        }          
1795
1796 -- Type functions
1797 doTopReact _inerts (CFunEqCan { cc_flavor = fl })
1798   | Just GivenSolved <- isGiven_maybe fl
1799   = return NoTopInt -- If Solved, no more interactions should happen
1800
1801 -- Otherwise, it's a Given, Derived, or Wanted
1802 doTopReact _inerts workItem@(CFunEqCan { cc_id = cv, cc_flavor = fl
1803                                        , cc_fun = tc, cc_tyargs = args, cc_rhs = xi })
1804   = ASSERT (isSynFamilyTyCon tc)   -- No associated data families have reached that far 
1805     do { match_res <- matchFam tc args -- See Note [MATCHING-SYNONYMS]
1806        ; case match_res of 
1807            MatchInstNo -> return NoTopInt 
1808            MatchInstSingle (rep_tc, rep_tys)
1809              -> do { let Just coe_tc = tyConFamilyCoercion_maybe rep_tc
1810                          Just rhs_ty = tcView (mkTyConApp rep_tc rep_tys)
1811                             -- Eagerly expand away the type synonym on the
1812                             -- RHS of a type function, so that it never
1813                             -- appears in an error message
1814                             -- See Note [Type synonym families] in TyCon
1815                          coe = mkTyConApp coe_tc rep_tys 
1816                    ; case fl of
1817                        Wanted {} -> do { cv' <- newCoVar rhs_ty xi
1818                                        ; setCoBind cv $ 
1819                                          coe `mkTransCoercion` mkCoVarCoercion cv'
1820                                        ; can_cts <- mkCanonical fl cv'
1821                                        ; let solved = workItem { cc_flavor = solved_fl }
1822                                              solved_fl = mkSolvedFlavor fl UnkSkol
1823                                        ; if isEmptyWorkList can_cts then 
1824                                               return (SomeTopInt can_cts Stop) -- No point in caching
1825                                          else return $ 
1826                                               SomeTopInt { tir_new_work = can_cts
1827                                                          , tir_new_inert = ContinueWith solved }
1828                                        }
1829                        Given {} -> do { cv' <- newGivenCoVar xi rhs_ty $ 
1830                                                mkSymCoercion (mkCoVarCoercion cv) `mkTransCoercion` coe 
1831                                       ; can_cts <- mkCanonical fl cv'
1832                                       ; return $ 
1833                                         SomeTopInt { tir_new_work = can_cts
1834                                                    , tir_new_inert = Stop }
1835                                       }
1836                        Derived {} -> do { cv' <- newDerivedId (EqPred xi rhs_ty)
1837                                         ; can_cts <- mkCanonical fl cv'
1838                                         ; return $ 
1839                                           SomeTopInt { tir_new_work = can_cts
1840                                                      , tir_new_inert = Stop }
1841                                         }
1842                    }
1843            _ 
1844              -> panicTcS $ text "TcSMonad.matchFam returned multiple instances!"
1845        }
1846
1847
1848 -- Any other work item does not react with any top-level equations
1849 doTopReact _inerts _workItem = return NoTopInt 
1850 \end{code}
1851
1852
1853 Note [FunDep and implicit parameter reactions] 
1854 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1855 Currently, our story of interacting two dictionaries (or a dictionary
1856 and top-level instances) for functional dependencies, and implicit
1857 paramters, is that we simply produce new wanted equalities.  So for example
1858
1859         class D a b | a -> b where ... 
1860     Inert: 
1861         d1 :g D Int Bool
1862     WorkItem: 
1863         d2 :w D Int alpha
1864
1865     We generate the extra work item
1866         cv :w alpha ~ Bool
1867     where 'cv' is currently unused.  However, this new item reacts with d2,
1868     discharging it in favour of a new constraint d2' thus:
1869         d2' :w D Int Bool
1870         d2 := d2' |> D Int cv
1871     Now d2' can be discharged from d1
1872
1873 We could be more aggressive and try to *immediately* solve the dictionary 
1874 using those extra equalities. With the same inert set and work item we
1875 might dischard d2 directly:
1876
1877         cv :w alpha ~ Bool
1878         d2 := d1 |> D Int cv
1879
1880 But in general it's a bit painful to figure out the necessary coercion,
1881 so we just take the first approach. Here is a better example. Consider:
1882     class C a b c | a -> b 
1883 And: 
1884      [Given]  d1 : C T Int Char 
1885      [Wanted] d2 : C T beta Int 
1886 In this case, it's *not even possible* to solve the wanted immediately. 
1887 So we should simply output the functional dependency and add this guy
1888 [but NOT its superclasses] back in the worklist. Even worse: 
1889      [Given] d1 : C T Int beta 
1890      [Wanted] d2: C T beta Int 
1891 Then it is solvable, but its very hard to detect this on the spot. 
1892
1893 It's exactly the same with implicit parameters, except that the
1894 "aggressive" approach would be much easier to implement.
1895
1896 Note [When improvement happens]
1897 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1898 We fire an improvement rule when
1899
1900   * Two constraints match (modulo the fundep)
1901       e.g. C t1 t2, C t1 t3    where C a b | a->b
1902     The two match because the first arg is identical
1903
1904   * At least one is not Given.  If they are both given, we don't fire
1905     the reaction because we have no way of constructing evidence for a
1906     new equality nor does it seem right to create a new wanted goal
1907     (because the goal will most likely contain untouchables, which
1908     can't be solved anyway)!
1909    
1910 Note that we *do* fire the improvement if one is Given and one is Derived.
1911 The latter can be a superclass of a wanted goal. Example (tcfail138)
1912     class L a b | a -> b
1913     class (G a, L a b) => C a b
1914
1915     instance C a b' => G (Maybe a)
1916     instance C a b  => C (Maybe a) a
1917     instance L (Maybe a) a
1918
1919 When solving the superclasses of the (C (Maybe a) a) instance, we get
1920   Given:  C a b  ... and hance by superclasses, (G a, L a b)
1921   Wanted: G (Maybe a)
1922 Use the instance decl to get
1923   Wanted: C a b'
1924 The (C a b') is inert, so we generate its Derived superclasses (L a b'),
1925 and now we need improvement between that derived superclass an the Given (L a b)
1926
1927 Note [Overriding implicit parameters]
1928 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1929 Consider
1930    f :: (?x::a) -> Bool -> a
1931   
1932    g v = let ?x::Int = 3 
1933          in (f v, let ?x::Bool = True in f v)
1934
1935 This should probably be well typed, with
1936    g :: Bool -> (Int, Bool)
1937
1938 So the inner binding for ?x::Bool *overrides* the outer one.
1939 Hence a work-item Given overrides an inert-item Given.
1940
1941 Note [Given constraint that matches an instance declaration]
1942 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1943 What should we do when we discover that one (or more) top-level 
1944 instances match a given (or solved) class constraint? We have 
1945 two possibilities:
1946
1947   1. Reject the program. The reason is that there may not be a unique
1948      best strategy for the solver. Example, from the OutsideIn(X) paper:
1949        instance P x => Q [x] 
1950        instance (x ~ y) => R [x] y 
1951      
1952        wob :: forall a b. (Q [b], R b a) => a -> Int 
1953
1954        g :: forall a. Q [a] => [a] -> Int 
1955        g x = wob x 
1956
1957        will generate the impliation constraint: 
1958             Q [a] => (Q [beta], R beta [a]) 
1959        If we react (Q [beta]) with its top-level axiom, we end up with a 
1960        (P beta), which we have no way of discharging. On the other hand, 
1961        if we react R beta [a] with the top-level we get  (beta ~ a), which 
1962        is solvable and can help us rewrite (Q [beta]) to (Q [a]) which is 
1963        now solvable by the given Q [a]. 
1964  
1965      However, this option is restrictive, for instance [Example 3] from 
1966      Note [Recursive dictionaries] will fail to work. 
1967
1968   2. Ignore the problem, hoping that the situations where there exist indeed
1969      such multiple strategies are rare: Indeed the cause of the previous 
1970      problem is that (R [x] y) yields the new work (x ~ y) which can be 
1971      *spontaneously* solved, not using the givens. 
1972
1973 We are choosing option 2 below but we might consider having a flag as well.
1974
1975
1976 Note [New Wanted Superclass Work] 
1977 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1978 Even in the case of wanted constraints, we may add some superclasses 
1979 as new given work. The reason is: 
1980
1981         To allow FD-like improvement for type families. Assume that 
1982         we have a class 
1983              class C a b | a -> b 
1984         and we have to solve the implication constraint: 
1985              C a b => C a beta 
1986         Then, FD improvement can help us to produce a new wanted (beta ~ b) 
1987
1988         We want to have the same effect with the type family encoding of 
1989         functional dependencies. Namely, consider: 
1990              class (F a ~ b) => C a b 
1991         Now suppose that we have: 
1992                given: C a b 
1993                wanted: C a beta 
1994         By interacting the given we will get given (F a ~ b) which is not 
1995         enough by itself to make us discharge (C a beta). However, we 
1996         may create a new derived equality from the super-class of the
1997         wanted constraint (C a beta), namely derived (F a ~ beta). 
1998         Now we may interact this with given (F a ~ b) to get: 
1999                   derived :  beta ~ b 
2000         But 'beta' is a touchable unification variable, and hence OK to 
2001         unify it with 'b', replacing the derived evidence with the identity. 
2002
2003         This requires trySpontaneousSolve to solve *derived*
2004         equalities that have a touchable in their RHS, *in addition*
2005         to solving wanted equalities.
2006
2007 We also need to somehow use the superclasses to quantify over a minimal, 
2008 constraint see note [Minimize by Superclasses] in TcSimplify.
2009
2010
2011 Finally, here is another example where this is useful. 
2012
2013 Example 1:
2014 ----------
2015    class (F a ~ b) => C a b 
2016 And we are given the wanteds:
2017       w1 : C a b 
2018       w2 : C a c 
2019       w3 : b ~ c 
2020 We surely do *not* want to quantify over (b ~ c), since if someone provides
2021 dictionaries for (C a b) and (C a c), these dictionaries can provide a proof 
2022 of (b ~ c), hence no extra evidence is necessary. Here is what will happen: 
2023
2024      Step 1: We will get new *given* superclass work, 
2025              provisionally to our solving of w1 and w2
2026              
2027                g1: F a ~ b, g2 : F a ~ c, 
2028                w1 : C a b, w2 : C a c, w3 : b ~ c
2029
2030              The evidence for g1 and g2 is a superclass evidence term: 
2031
2032                g1 := sc w1, g2 := sc w2
2033
2034      Step 2: The givens will solve the wanted w3, so that 
2035                w3 := sym (sc w1) ; sc w2 
2036                   
2037      Step 3: Now, one may naively assume that then w2 can be solve from w1
2038              after rewriting with the (now solved equality) (b ~ c). 
2039              
2040              But this rewriting is ruled out by the isGoodRectDict! 
2041
2042 Conclusion, we will (correctly) end up with the unsolved goals 
2043     (C a b, C a c)   
2044
2045 NB: The desugarer needs be more clever to deal with equalities 
2046     that participate in recursive dictionary bindings. 
2047
2048 \begin{code}
2049 data LookupInstResult
2050   = NoInstance
2051   | GenInst [WantedEvVar] EvTerm 
2052
2053 matchClassInst :: InertSet -> Class -> [Type] -> WantedLoc -> TcS LookupInstResult
2054 matchClassInst inerts clas tys loc
2055    = do { let pred = mkClassPred clas tys 
2056         ; mb_result <- matchClass clas tys
2057         ; untch <- getUntouchables
2058         ; case mb_result of
2059             MatchInstNo   -> return NoInstance
2060             MatchInstMany -> return NoInstance -- defer any reactions of a multitude until
2061                                                -- we learn more about the reagent 
2062             MatchInstSingle (_,_)
2063               | given_overlap untch -> 
2064                   do { traceTcS "Delaying instance application" $ 
2065                        vcat [ text "Workitem=" <+> pprPred (ClassP clas tys) 
2066                             , text "Silents and their superclasses=" <+> ppr silents_and_their_scs
2067                             , text "All given dictionaries=" <+> ppr all_given_dicts ]
2068                      ; return NoInstance -- see Note [Instance and Given overlap]
2069                      }
2070
2071             MatchInstSingle (dfun_id, mb_inst_tys) ->
2072               do { checkWellStagedDFun pred dfun_id loc
2073
2074         -- It's possible that not all the tyvars are in
2075         -- the substitution, tenv. For example:
2076         --      instance C X a => D X where ...
2077         -- (presumably there's a functional dependency in class C)
2078         -- Hence mb_inst_tys :: Either TyVar TcType 
2079
2080                  ; tys <- instDFunTypes mb_inst_tys
2081                  ; let (theta, _) = tcSplitPhiTy (applyTys (idType dfun_id) tys)
2082                  ; if null theta then
2083                        return (GenInst [] (EvDFunApp dfun_id tys []))
2084                    else do
2085                      { ev_vars <- instDFunConstraints theta
2086                      ; let wevs = [EvVarX w loc | w <- ev_vars]
2087                      ; return $ GenInst wevs (EvDFunApp dfun_id tys ev_vars) }
2088                  }
2089         }
2090    where given_overlap :: TcsUntouchables -> Bool
2091          given_overlap untch
2092            = foldlBag (\r d -> r || matchable untch d) False all_given_dicts
2093
2094          matchable untch (CDictCan { cc_class = clas', cc_tyargs = sys, cc_flavor = fl })
2095            | Just GivenOrig <- isGiven_maybe fl
2096            , clas' == clas
2097            , does_not_originate_in_a_silent clas' sys
2098            = case tcUnifyTys (\tv -> if isTouchableMetaTyVar_InRange untch tv && 
2099                                         tv `elemVarSet` tyVarsOfTypes tys
2100                                      then BindMe else Skolem) tys sys of
2101            -- We can't learn anything more about any variable at this point, so the only
2102            -- cause of overlap can be by an instantiation of a touchable unification
2103            -- variable. Hence we only bind touchable unification variables. In addition,
2104            -- we use tcUnifyTys instead of tcMatchTys to rule out cyclic substitutions.
2105                 Nothing -> False
2106                 Just _  -> True
2107            | otherwise = False -- No overlap with a solved, already been taken care of 
2108                                -- by the overlap check with the instance environment.
2109          matchable _tys ct = pprPanic "Expecting dictionary!" (ppr ct)
2110
2111          does_not_originate_in_a_silent clas sys
2112              -- UGLY: See Note [Silent parameters overlapping]
2113            = null $ filter (tcEqPred (ClassP clas sys)) silents_and_their_scs
2114
2115          silents_and_their_scs 
2116            = foldlBag (\acc rvnt -> case rvnt of
2117                         CDictCan { cc_id = d, cc_class = c, cc_tyargs = s }
2118                          | isSilentEvVar d -> (ClassP c s) : (transSuperClasses c s) ++ acc 
2119                         _ -> acc) [] all_given_dicts
2120
2121          -- TODO:
2122          -- When silent parameters will go away we should simply select from 
2123          -- the given map of the inert set. 
2124          all_given_dicts = Map.fold unionBags emptyCCan (cts_given $ inert_dicts inerts)
2125
2126 \end{code}
2127
2128 Note [Silent parameters overlapping]
2129 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2130 DV 12/05/2011:
2131 The long-term goal is to completely remove silent superclass
2132 parameters when checking instance declarations. But until then we must
2133 make sure that we never prevent the application of an instance
2134 declaration because of a potential match from a silent parameter --
2135 after all we are supposed to have solved that silent parameter from
2136 some instance, anyway! In effect silent parameters behave more like
2137 Solved than like Given.
2138
2139 A concrete example appears in typecheck/SilentParametersOverlapping.hs
2140
2141 Note [Instance and Given overlap]
2142 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2143 Assume that we have an inert set that looks as follows:
2144        [Given] D [Int]
2145 And an instance declaration: 
2146        instance C a => D [a]
2147 A new wanted comes along of the form: 
2148        [Wanted] D [alpha]
2149
2150 One possibility is to apply the instance declaration which will leave us 
2151 with an unsolvable goal (C alpha). However, later on a new constraint may 
2152 arise (for instance due to a functional dependency between two later dictionaries), 
2153 that will add the equality (alpha ~ Int), in which case our ([Wanted] D [alpha]) 
2154 will be transformed to [Wanted] D [Int], which could have been discharged by the given. 
2155
2156 The solution is that in matchClassInst and eventually in topReact, we get back with 
2157 a matching instance, only when there is no Given in the inerts which is unifiable to
2158 this particular dictionary.
2159
2160 The end effect is that, much as we do for overlapping instances, we delay choosing a 
2161 class instance if there is a possibility of another instance OR a given to match our 
2162 constraint later on. This fixes bugs #4981 and #5002.
2163
2164 This is arguably not easy to appear in practice due to our aggressive prioritization 
2165 of equality solving over other constraints, but it is possible. I've added a test case 
2166 in typecheck/should-compile/GivenOverlapping.hs
2167
2168 Moreover notice that our goals here are different than the goals of the top-level 
2169 overlapping checks. There we are interested in validating the following principle:
2170  
2171     If we inline a function f at a site where the same global instance environment
2172     is available as the instance environment at the definition site of f then we 
2173     should get the same behaviour. 
2174
2175 But for the Given Overlap check our goal is just related to completeness of 
2176 constraint solving. 
2177
2178
2179
2180