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