Fix Trac #4360: omitted case in combineCtLoc
[ghc-hetmet.git] / compiler / typecheck / TcInteract.lhs
1 \begin{code}
2 module TcInteract ( 
3      solveInteract, AtomicInert, 
4      InertSet, emptyInert, updInertSet, extractUnsolved, solveOne,
5      listToWorkList
6   ) where  
7
8 #include "HsVersions.h"
9
10
11 import BasicTypes 
12 import TcCanonical
13 import VarSet
14 import Type
15 import TypeRep 
16
17 import Id 
18 import VarEnv
19 import Var
20
21 import TcType
22 import HsBinds 
23
24 import InstEnv 
25 import Class 
26 import TyCon 
27 import Name
28
29 import FunDeps
30
31 import Control.Monad ( when ) 
32
33 import Coercion
34 import Outputable
35
36 import TcRnTypes 
37 import TcErrors
38 import TcSMonad 
39 import Bag
40 import qualified Data.Map as Map 
41 import Maybes 
42
43 import Control.Monad( zipWithM, unless )
44 import FastString ( sLit ) 
45 import DynFlags
46 \end{code}
47
48 Note [InertSet invariants]
49 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
50
51 An InertSet is a bag of canonical constraints, with the following invariants:
52
53   1 No two constraints react with each other. 
54     
55     A tricky case is when there exists a given (solved) dictionary 
56     constraint and a wanted identical constraint in the inert set, but do 
57     not react because reaction would create loopy dictionary evidence for 
58     the wanted. See note [Recursive dictionaries]
59
60   2 Given equalities form an idempotent substitution [none of the
61     given LHS's occur in any of the given RHS's or reactant parts]
62
63   3 Wanted equalities also form an idempotent substitution
64   4 The entire set of equalities is acyclic.
65
66   5 Wanted dictionaries are inert with the top-level axiom set 
67
68   6 Equalities of the form tv1 ~ tv2 always have a touchable variable
69     on the left (if possible).
70   7 No wanted constraints tv1 ~ tv2 with tv1 touchable. Such constraints 
71     will be marked as solved right before being pushed into the inert set. 
72     See note [Touchables and givens].
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 Note [InertSet FlattenSkolemEqClass] 
86 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
87 The inert_fsks field of the inert set contains an "inverse map" of all the 
88 flatten skolem equalities in the inert set. For instance, if inert_cts looks
89 like this: 
90  
91     fsk1 ~ fsk2 
92     fsk3 ~ fsk2 
93     fsk4 ~ fsk5 
94
95 Then, the inert_fsks fields holds the following map: 
96     fsk2 |-> { fsk1, fsk3 } 
97     fsk5 |-> { fsk4 } 
98 Along with the necessary coercions to convert fsk1 and fsk3 back to fsk2 
99 and fsk4 back to fsk5. Hence, the invariants of the inert_fsks field are: 
100   
101    (a) All TcTyVars in the domain and range of inert_fsks are flatten skolems
102    (b) All TcTyVars in the domain of inert_fsk occur naked as rhs in some 
103        equalities of inert_cts 
104    (c) For every mapping  fsk1 |-> { (fsk2,co), ... } it must be: 
105          co : fsk2 ~ fsk1 
106
107 The role of the inert_fsks is to make it easy to maintain the equivalence
108 class of each flatten skolem, which is much needed to correctly do spontaneous
109 solving. See Note [Loopy Spontaneous Solving] 
110 \begin{code}
111
112 -- See Note [InertSet invariants]
113 data InertSet 
114   = IS { inert_cts  :: Bag.Bag CanonicalCt 
115        , inert_fsks :: Map.Map TcTyVar [(TcTyVar,Coercion)] }
116        -- See Note [InertSet FlattenSkolemEqClass] 
117
118 instance Outputable InertSet where
119   ppr is = vcat [ vcat (map ppr (Bag.bagToList $ inert_cts is))
120                 , vcat (map (\(v,rest) -> ppr v <+> text "|->" <+> hsep (map (ppr.fst) rest)) 
121                        (Map.toList $ inert_fsks is)
122                        )
123                 ]
124                        
125 emptyInert :: InertSet
126 emptyInert = IS { inert_cts = Bag.emptyBag, inert_fsks = Map.empty } 
127
128 updInertSet :: InertSet -> AtomicInert -> InertSet 
129 -- Introduces an element in the inert set for the first time 
130 updInertSet (IS { inert_cts = cts, inert_fsks = fsks })  
131             item@(CTyEqCan { cc_id    = cv
132                            , cc_tyvar = tv1 
133                            , cc_rhs   = xi })
134   | Just tv2 <- tcGetTyVar_maybe xi,
135     FlatSkol {} <- tcTyVarDetails tv1, 
136     FlatSkol {} <- tcTyVarDetails tv2 
137   = let cts'  = cts `Bag.snocBag` item 
138         fsks' = Map.insertWith (++) tv2 [(tv1, mkCoVarCoercion cv)] fsks
139         -- See Note [InertSet FlattenSkolemEqClass] 
140     in IS { inert_cts = cts', inert_fsks = fsks' }
141 updInertSet (IS { inert_cts = cts
142                 , inert_fsks = fsks }) item 
143   = let cts' = cts `Bag.snocBag` item
144     in IS { inert_cts = cts', inert_fsks = fsks } 
145
146 foldlInertSetM :: (Monad m) => (a -> AtomicInert -> m a) -> a -> InertSet -> m a 
147 foldlInertSetM k z (IS { inert_cts = cts }) 
148   = Bag.foldlBagM k z cts
149
150 extractUnsolved :: InertSet -> (InertSet, CanonicalCts)
151 extractUnsolved is@(IS {inert_cts = cts}) 
152   = (is { inert_cts = cts'}, unsolved)
153   where (unsolved, cts') = Bag.partitionBag isWantedCt cts
154
155
156 getFskEqClass :: InertSet -> TcTyVar -> [(TcTyVar,Coercion)] 
157 -- Precondition: tv is a FlatSkol. See Note [InertSet FlattenSkolemEqClass] 
158 getFskEqClass (IS { inert_cts = cts, inert_fsks = fsks }) tv 
159   = case lkpTyEqCanByLhs of
160       Nothing  -> fromMaybe [] (Map.lookup tv fsks)  
161       Just ceq -> 
162         case tcGetTyVar_maybe (cc_rhs ceq) of 
163           Just tv_rhs | FlatSkol {} <- tcTyVarDetails tv_rhs
164             -> let ceq_co = mkSymCoercion $ mkCoVarCoercion (cc_id ceq)
165                    mk_co (v,c) = (v, mkTransCoercion c ceq_co)
166                in (tv_rhs, ceq_co): map mk_co (fromMaybe [] $ Map.lookup tv fsks) 
167           _ -> []
168   where lkpTyEqCanByLhs = Bag.foldlBag lkp Nothing cts 
169         lkp :: Maybe CanonicalCt -> CanonicalCt -> Maybe CanonicalCt 
170         lkp Nothing ct@(CTyEqCan {cc_tyvar = tv'}) | tv' == tv = Just ct 
171         lkp other _ct = other 
172
173
174 isWantedCt :: CanonicalCt -> Bool 
175 isWantedCt ct = isWanted (cc_flavor ct)
176
177 {- TODO: Later ...
178 data Inert = IS { class_inerts :: FiniteMap Class Atomics
179                   ip_inerts    :: FiniteMap Class Atomics
180                   tyfun_inerts :: FiniteMap TyCon Atomics
181                   tyvar_inerts :: FiniteMap TyVar Atomics
182                 }
183
184 Later should we also separate out givens and wanteds?
185 -}
186
187 \end{code}
188
189 Note [Touchables and givens]
190 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
191 Touchable variables will never show up in givens which are inputs to
192 the solver.  However, touchables may show up in givens generated by the flattener.  
193 For example,
194
195   axioms:
196     G Int ~ Char
197     F Char ~ Int
198
199   wanted:
200     F (G alpha) ~w Int
201   
202 canonicalises to
203
204   G alpha ~g b
205   F b ~w Int
206
207 which can be put in the inert set.  Suppose we also have a wanted
208
209   alpha ~w Int
210
211 We cannot rewrite the given G alpha ~g b using the wanted alpha ~w
212 Int.  Instead, after reacting alpha ~w Int with the whole inert set,
213 we observe that we can solve it by unifying alpha with Int, so we mark
214 it as solved and put it back in the *work list*. [We also immediately unify
215 alpha := Int, without telling anyone, see trySpontaneousSolve function, to 
216 avoid doing this in the end.]
217
218 Later, because it is solved (given, in effect), we can use it to rewrite 
219 G alpha ~g b to G Int ~g b, which gets put back in the work list. Eventually, 
220 we will dispatch the remaining wanted constraints using the top-level axioms.
221
222 Finally, note that after reacting a wanted equality with the entire inert set
223 we may end up with something like
224
225   b ~w alpha
226
227 which we should flip around to generate the solved constraint alpha ~s b.
228
229 %*********************************************************************
230 %*                                                                   * 
231 *                      Main Interaction Solver                       *
232 *                                                                    *
233 **********************************************************************
234
235 Note [Basic plan] 
236 ~~~~~~~~~~~~~~~~~
237 1. Canonicalise (unary)
238 2. Pairwise interaction (binary)
239     * Take one from work list 
240     * Try all pair-wise interactions with each constraint in inert
241 3. Try to solve spontaneously for equalities involving touchables 
242 4. Top-level interaction (binary wrt top-level)
243    Superclass decomposition belongs in (4), see note [Superclasses]
244
245 \begin{code}
246
247 type AtomicInert = CanonicalCt     -- constraint pulled from InertSet
248 type WorkItem    = CanonicalCt     -- constraint pulled from WorkList
249
250 type WorkList    = CanonicalCts    -- A mixture of Given, Wanted, and Solved
251 type SWorkList   = WorkList        -- A worklist of solved 
252                    
253
254 listToWorkList :: [WorkItem] -> WorkList
255 listToWorkList = Bag.listToBag
256
257 unionWorkLists :: WorkList -> WorkList -> WorkList 
258 unionWorkLists = Bag.unionBags 
259
260 foldlWorkListM :: (Monad m) => (a -> WorkItem -> m a) -> a -> WorkList -> m a 
261 foldlWorkListM = Bag.foldlBagM 
262
263 isEmptyWorkList :: WorkList -> Bool 
264 isEmptyWorkList = Bag.isEmptyBag
265
266 emptyWorkList :: WorkList
267 emptyWorkList = Bag.emptyBag
268
269 singletonWorkList :: CanonicalCt -> WorkList 
270 singletonWorkList ct = singleCCan ct 
271
272 data StopOrContinue 
273   = Stop                        -- Work item is consumed
274   | ContinueWith WorkItem       -- Not consumed
275
276 instance Outputable StopOrContinue where
277   ppr Stop             = ptext (sLit "Stop")
278   ppr (ContinueWith w) = ptext (sLit "ContinueWith") <+> ppr w
279
280 -- Results after interacting a WorkItem as far as possible with an InertSet
281 data StageResult
282   = SR { sr_inerts     :: InertSet
283            -- The new InertSet to use (REPLACES the old InertSet)
284        , sr_new_work   :: WorkList
285            -- Any new work items generated (should be ADDED to the old WorkList)
286            -- Invariant: 
287            --    sr_stop = Just workitem => workitem is *not* in sr_inerts and
288            --                               workitem is inert wrt to sr_inerts
289        , sr_stop       :: StopOrContinue
290        }
291
292 instance Outputable StageResult where
293   ppr (SR { sr_inerts = inerts, sr_new_work = work, sr_stop = stop })
294     = ptext (sLit "SR") <+> 
295       braces (sep [ ptext (sLit "inerts =") <+> ppr inerts <> comma
296                   , ptext (sLit "new work =") <+> ppr work <> comma
297                   , ptext (sLit "stop =") <+> ppr stop])
298
299 type SimplifierStage = WorkItem -> InertSet -> TcS StageResult 
300
301 -- Combine a sequence of simplifier 'stages' to create a pipeline 
302 runSolverPipeline :: [(String, SimplifierStage)]
303                   -> InertSet -> WorkItem 
304                   -> TcS (InertSet, WorkList)
305 -- Precondition: non-empty list of stages 
306 runSolverPipeline pipeline inerts workItem
307   = do { traceTcS "Start solver pipeline" $ 
308             vcat [ ptext (sLit "work item =") <+> ppr workItem
309                  , ptext (sLit "inerts    =") <+> ppr inerts]
310
311        ; let itr_in = SR { sr_inerts = inerts
312                         , sr_new_work = emptyWorkList
313                         , sr_stop = ContinueWith workItem }
314        ; itr_out <- run_pipeline pipeline itr_in
315        ; let new_inert 
316               = case sr_stop itr_out of 
317                   Stop              -> sr_inerts itr_out
318                   ContinueWith item -> sr_inerts itr_out `updInertSet` item
319        ; return (new_inert, sr_new_work itr_out) }
320   where 
321     run_pipeline :: [(String, SimplifierStage)]
322                  -> StageResult -> TcS StageResult
323     run_pipeline [] itr                         = return itr
324     run_pipeline _  itr@(SR { sr_stop = Stop }) = return itr
325
326     run_pipeline ((name,stage):stages) 
327                  (SR { sr_new_work = accum_work
328                      , sr_inerts   = inerts
329                      , sr_stop     = ContinueWith work_item })
330       = do { itr <- stage work_item inerts 
331            ; traceTcS ("Stage result (" ++ name ++ ")") (ppr itr)
332            ; let itr' = itr { sr_new_work = sr_new_work itr 
333                                             `unionWorkLists` accum_work }
334            ; run_pipeline stages itr' }
335 \end{code}
336
337 Example 1:
338   Inert:   {c ~ d, F a ~ t, b ~ Int, a ~ ty} (all given)
339   Reagent: a ~ [b] (given)
340
341 React with (c~d)     ==> IR (ContinueWith (a~[b]))  True    []
342 React with (F a ~ t) ==> IR (ContinueWith (a~[b]))  False   [F [b] ~ t]
343 React with (b ~ Int) ==> IR (ContinueWith (a~[Int]) True    []
344
345 Example 2:
346   Inert:  {c ~w d, F a ~g t, b ~w Int, a ~w ty}
347   Reagent: a ~w [b]
348
349 React with (c ~w d)   ==> IR (ContinueWith (a~[b]))  True    []
350 React with (F a ~g t) ==> IR (ContinueWith (a~[b]))  True    []    (can't rewrite given with wanted!)
351 etc.
352
353 Example 3:
354   Inert:  {a ~ Int, F Int ~ b} (given)
355   Reagent: F a ~ b (wanted)
356
357 React with (a ~ Int)   ==> IR (ContinueWith (F Int ~ b)) True []
358 React with (F Int ~ b) ==> IR Stop True []    -- after substituting we re-canonicalize and get nothing
359
360 \begin{code}
361 -- Main interaction solver: we fully solve the worklist 'in one go', 
362 -- returning an extended inert set.
363 --
364 -- See Note [Touchables and givens].
365 solveInteract :: InertSet -> WorkList -> TcS InertSet
366 solveInteract inert ws 
367   = do { dyn_flags <- getDynFlags
368        ; solveInteractWithDepth (ctxtStkDepth dyn_flags,0,[]) inert ws 
369        }
370 solveOne :: InertSet -> WorkItem -> TcS InertSet 
371 solveOne inerts workItem 
372   = do { dyn_flags <- getDynFlags
373        ; solveOneWithDepth (ctxtStkDepth dyn_flags,0,[]) inerts workItem
374        }
375
376 -----------------
377 solveInteractWithDepth :: (Int, Int, [WorkItem])
378                        -> InertSet -> WorkList -> TcS InertSet
379 solveInteractWithDepth ctxt@(max_depth,n,stack) inert ws 
380   | isEmptyWorkList ws
381   = return inert
382
383   | n > max_depth 
384   = solverDepthErrorTcS n stack
385
386   | otherwise 
387   = do { traceTcS "solveInteractWithDepth" $ 
388          vcat [ text "Current depth =" <+> ppr n
389               , text "Max depth =" <+> ppr max_depth
390               ]
391        ; foldlWorkListM (solveOneWithDepth ctxt) inert ws }
392
393 ------------------
394 -- Fully interact the given work item with an inert set, and return a
395 -- new inert set which has assimilated the new information.
396 solveOneWithDepth :: (Int, Int, [WorkItem])
397                   -> InertSet -> WorkItem -> TcS InertSet
398 solveOneWithDepth (max_depth, n, stack) inert work
399   = do { traceTcS0 (indent ++ "Solving {") (ppr work)
400        ; (new_inert, new_work) <- runSolverPipeline thePipeline inert work
401          
402        ; traceTcS0 (indent ++ "Subgoals:") (ppr new_work)
403
404          -- Recursively solve the new work generated 
405          -- from workItem, with a greater depth
406        ; res_inert <- solveInteractWithDepth (max_depth, n+1, work:stack)
407                                 new_inert new_work 
408
409        ; traceTcS0 (indent ++ "Done }") (ppr work) 
410        ; return res_inert }
411   where
412     indent = replicate (2*n) ' '
413
414 thePipeline :: [(String,SimplifierStage)]
415 thePipeline = [ ("interact with inerts", interactWithInertsStage)
416               , ("spontaneous solve",    spontaneousSolveStage)
417               , ("top-level reactions",  topReactionsStage) ]
418 \end{code}
419
420 *********************************************************************************
421 *                                                                               * 
422                        The spontaneous-solve Stage
423 *                                                                               *
424 *********************************************************************************
425
426 \begin{code}
427 spontaneousSolveStage :: SimplifierStage 
428 spontaneousSolveStage workItem inerts 
429   = do { mSolve <- trySpontaneousSolve workItem inerts 
430        ; case mSolve of 
431            Nothing -> -- no spontaneous solution for him, keep going
432                return $ SR { sr_new_work   = emptyWorkList 
433                            , sr_inerts     = inerts 
434                            , sr_stop       = ContinueWith workItem }
435
436            Just workList' -> -- He has been solved; workList' are all givens 
437                return $ SR { sr_new_work = workList'
438                            , sr_inerts   = inerts 
439                            , sr_stop     = Stop } 
440        }
441
442 {-- This is all old code, but does not quite work now. The problem is that due to 
443     Note [Loopy Spontaneous Solving] we may have unflattened a type, to be able to 
444     perform a sneaky unification. This unflattening means that we may have to recanonicalize
445     a given (solved) equality, this is why the result of trySpontaneousSolve is now a list
446     of constraints (instead of an atomic solved constraint). We would have to react all of 
447     them once again with the worklist but that is very tiresome. Instead we throw them back
448     in the worklist. 
449
450                | isWantedCt workItem 
451                            -- Original was wanted we have now made him given so 
452                            -- we have to ineract him with the inerts again because 
453                            -- of the change in his status. This may produce some work. 
454                    -> do { traceTcS "recursive interact with inerts {" $ vcat
455                                [ text "work = " <+> ppr workItem'
456                                , text "inerts = " <+> ppr inerts ]
457                          ; itr_again <- interactWithInertsStage workItem' inerts 
458                          ; case sr_stop itr_again of 
459                             Stop -> pprPanic "BUG: Impossible to happen" $ 
460                                     vcat [ text "Original workitem:" <+> ppr workItem
461                                          , text "Spontaneously solved:" <+> ppr workItem'
462                                          , text "Solved was consumed, when reacting with inerts:"
463                                          , nest 2 (ppr inerts) ]
464                             ContinueWith workItem'' -- Now *this* guy is inert wrt to inerts
465                                 ->  do { traceTcS "end recursive interact }" $ ppr workItem''
466                                        ; return $ SR { sr_new_work = sr_new_work itr_again
467                                                      , sr_inerts   = sr_inerts itr_again 
468                                                                      `extendInertSet` workItem'' 
469                                                      , sr_stop     = Stop } }
470                          }
471                | otherwise
472                    -> return $ SR { sr_new_work   = emptyWorkList 
473                                   , sr_inerts     = inerts `extendInertSet` workItem' 
474                                   , sr_stop       = Stop } }
475 --} 
476
477 -- @trySpontaneousSolve wi@ solves equalities where one side is a
478 -- touchable unification variable. Returns:
479 --   * Nothing if we were not able to solve it
480 --   * Just wi' if we solved it, wi' (now a "given") should be put in the work list.
481 --          See Note [Touchables and givens] 
482 -- Note, just passing the inerts through for the skolem equivalence classes
483 trySpontaneousSolve :: WorkItem -> InertSet -> TcS (Maybe SWorkList)
484 trySpontaneousSolve (CTyEqCan { cc_id = cv, cc_flavor = gw, cc_tyvar = tv1, cc_rhs = xi }) inerts 
485   | isGiven gw
486   = return Nothing
487   | Just tv2 <- tcGetTyVar_maybe xi
488   = do { tch1 <- isTouchableMetaTyVar tv1
489        ; tch2 <- isTouchableMetaTyVar tv2
490        ; case (tch1, tch2) of
491            (True,  True)  -> trySpontaneousEqTwoWay inerts cv gw tv1 tv2
492            (True,  False) -> trySpontaneousEqOneWay inerts cv gw tv1 xi
493            (False, True)  | tyVarKind tv1 `isSubKind` tyVarKind tv2
494                           -> trySpontaneousEqOneWay inerts cv gw tv2 (mkTyVarTy tv1)
495            _ -> return Nothing }
496   | otherwise
497   = do { tch1 <- isTouchableMetaTyVar tv1
498        ; if tch1 then trySpontaneousEqOneWay inerts cv gw tv1 xi
499                  else return Nothing }
500
501   -- No need for 
502   --      trySpontaneousSolve (CFunEqCan ...) = ...
503   -- See Note [No touchables as FunEq RHS] in TcSMonad
504 trySpontaneousSolve _ _ = return Nothing 
505
506 ----------------
507 trySpontaneousEqOneWay :: InertSet -> CoVar -> CtFlavor -> TcTyVar -> Xi
508                        -> TcS (Maybe SWorkList)
509 -- tv is a MetaTyVar, not untouchable
510 -- Precondition: kind(xi) is a sub-kind of kind(tv)
511 trySpontaneousEqOneWay inerts cv gw tv xi       
512   | not (isSigTyVar tv) || isTyVarTy xi
513   = solveWithIdentity inerts cv gw tv xi
514   | otherwise
515   = return Nothing
516
517 ----------------
518 trySpontaneousEqTwoWay :: InertSet -> CoVar -> CtFlavor -> TcTyVar -> TcTyVar
519                        -> TcS (Maybe SWorkList)
520 -- Both tyvars are *touchable* MetaTyvars
521 -- By the CTyEqCan invariant, k2 `isSubKind` k1
522 trySpontaneousEqTwoWay inerts cv gw tv1 tv2
523   | k1 `eqKind` k2
524   , nicer_to_update_tv2 = solveWithIdentity inerts cv gw tv2 (mkTyVarTy tv1)
525   | otherwise           = ASSERT( k2 `isSubKind` k1 )
526                           solveWithIdentity inerts cv gw tv1 (mkTyVarTy tv2)
527   where
528     k1 = tyVarKind tv1
529     k2 = tyVarKind tv2
530     nicer_to_update_tv2 = isSigTyVar tv1 || isSystemName (Var.varName tv2)
531 \end{code}
532
533 Note [Loopy spontaneous solving] 
534 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
535 Consider the original wanted: 
536    wanted :  Maybe (E alpha) ~ alpha 
537 where E is a type family, such that E (T x) = x. After canonicalization, 
538 as a result of flattening, we will get: 
539    given  : E alpha ~ fsk 
540    wanted : alpha ~ Maybe fsk
541 where (fsk := E alpha, on the side). Now, if we spontaneously *solve* 
542 (alpha := Maybe fsk) we are in trouble! Instead, we should refrain from solving 
543 it and keep it as wanted.  In inference mode we'll end up quantifying over
544    (alpha ~ Maybe (E alpha))
545 Hence, 'solveWithIdentity' performs a small occurs check before
546 actually solving. But this occurs check *must look through* flatten skolems.
547
548 However, it may be the case that the flatten skolem in hand is equal to some other 
549 flatten skolem whith *does not* mention our unification variable. Here's a typical example:
550
551 Original wanteds: 
552    g: F alpha ~ F beta 
553    w: alpha ~ F alpha 
554 After canonicalization: 
555    g: F beta ~ f1 
556    g: F alpha ~ f1 
557    w: alpha ~ f2 
558    g: F alpha ~ f2 
559 After some reactions: 
560    g: f1 ~ f2 
561    g: F beta ~ f1 
562    w: alpha ~ f2 
563    g: F alpha ~ f2 
564 At this point, we will try to spontaneously solve (alpha ~ f2) which remains as yet unsolved.
565 We will look inside f2, which immediately mentions (F alpha), so it's not good to unify! However
566 by looking at the equivalence class of the flatten skolems, we can see that it is fine to 
567 unify (alpha ~ f1) which solves our goals! 
568
569 A similar problem happens because of other spontaneous solving. Suppose we have the 
570 following wanteds, arriving in this exact order:
571   (first)  w: beta ~ alpha 
572   (second) w: alpha ~ fsk 
573   (third)  g: F beta ~ fsk
574 Then, we first spontaneously solve the first constraint, making (beta := alpha), and having
575 (beta ~ alpha) as given. *Then* we encounter the second wanted (alpha ~ fsk). "fsk" does not 
576 obviously mention alpha, so naively we can also spontaneously solve (alpha := fsk). But 
577 that is wrong since fsk mentions beta, which has already secretly been unified to alpha! 
578
579 To avoid this problem, the same occurs check must unveil rewritings that can happen because 
580 of spontaneously having solved other constraints. 
581
582
583 Note [Avoid double unifications] 
584 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
585 The spontaneous solver has to return a given which mentions the unified unification
586 variable *on the left* of the equality. Here is what happens if not: 
587   Original wanted:  (a ~ alpha),  (alpha ~ Int) 
588 We spontaneously solve the first wanted, without changing the order! 
589       given : a ~ alpha      [having unified alpha := a] 
590 Now the second wanted comes along, but he cannot rewrite the given, so we simply continue.
591 At the end we spontaneously solve that guy, *reunifying*  [alpha := Int] 
592
593 We avoid this problem by orienting the given so that the unification
594 variable is on the left.  [Note that alternatively we could attempt to
595 enforce this at canonicalization]
596
597 See also Note [No touchables as FunEq RHS] in TcSMonad; avoiding
598 double unifications is the main reason we disallow touchable
599 unification variables as RHS of type family equations: F xis ~ alpha.
600
601 \begin{code}
602 ----------------
603 solveWithIdentity :: InertSet 
604                   -> CoVar -> CtFlavor -> TcTyVar -> Xi 
605                   -> TcS (Maybe SWorkList)
606 -- Solve with the identity coercion 
607 -- Precondition: kind(xi) is a sub-kind of kind(tv)
608 -- Precondition: CtFlavor is Wanted or Derived
609 -- See [New Wanted Superclass Work] to see why solveWithIdentity 
610 --     must work for Derived as well as Wanted
611 solveWithIdentity inerts cv gw tv xi 
612   = do { tybnds <- getTcSTyBindsMap
613        ; case occurCheck tybnds inerts tv xi of 
614            Nothing              -> return Nothing 
615            Just (xi_unflat,coi) -> solve_with xi_unflat coi }
616   where
617     solve_with xi_unflat coi  -- coi : xi_unflat ~ xi  
618       = do { traceTcS "Sneaky unification:" $ 
619                        vcat [text "Coercion variable:  " <+> ppr gw, 
620                              text "Coercion:           " <+> pprEq (mkTyVarTy tv) xi,
621                              text "Left  Kind is     : " <+> ppr (typeKind (mkTyVarTy tv)),
622                              text "Right Kind is     : " <+> ppr (typeKind xi)
623                   ]
624            ; setWantedTyBind tv xi_unflat        -- Set tv := xi_unflat
625            ; cv_given <- newGivOrDerCoVar (mkTyVarTy tv) xi_unflat xi_unflat
626            ; let flav = mkGivenFlavor gw UnkSkol 
627            ; (cts, co) <- case coi of 
628                ACo co  -> do { can_eqs <- canEq flav cv_given (mkTyVarTy tv) xi_unflat
629                              ; return (can_eqs, co) }
630                IdCo co -> return $ 
631                           (singleCCan (CTyEqCan { cc_id = cv_given 
632                                                 , cc_flavor = mkGivenFlavor gw UnkSkol
633                                                 , cc_tyvar = tv, cc_rhs = xi }
634                                                 -- xi, *not* xi_unflat because 
635                                                 -- xi_unflat may require flattening!
636                                       ), co)
637            ; case gw of 
638                Wanted  {} -> setWantedCoBind  cv co
639                Derived {} -> setDerivedCoBind cv co 
640                _          -> pprPanic "Can't spontaneously solve *given*" empty 
641                       -- See Note [Avoid double unifications] 
642            ; return (Just cts) }
643
644 occurCheck :: VarEnv (TcTyVar, TcType) -> InertSet
645            -> TcTyVar -> TcType -> Maybe (TcType,CoercionI) 
646 -- Traverse @ty@ to make sure that @tv@ does not appear under some flatten skolem. 
647 -- If it appears under some flatten skolem look in that flatten skolem equivalence class 
648 -- (see Note [InertSet FlattenSkolemEqClass], [Loopy Spontaneous Solving]) to see if you 
649 -- can find a different flatten skolem to use, that is, one that does not mention @tv@.
650 -- 
651 -- Postcondition: Just (ty', coi) = occurCheck binds inerts tv ty 
652 --       coi :: ty' ~ ty 
653 -- NB: The returned type ty' may not be flat!
654
655 occurCheck ty_binds inerts the_tv the_ty
656   = ok emptyVarSet the_ty 
657   where 
658     -- If (fsk `elem` bad) then tv occurs in any rendering
659     -- of the type under the expansion of fsk
660     ok bad this_ty@(TyConApp tc tys) 
661       | Just tys_cois <- allMaybes (map (ok bad) tys) 
662       , (tys',cois') <- unzip tys_cois
663       = Just (TyConApp tc tys', mkTyConAppCoI tc cois') 
664       | isSynTyCon tc, Just ty_expanded <- tcView this_ty
665       = ok bad ty_expanded   -- See Note [Type synonyms and the occur check] in TcUnify
666     ok bad (PredTy sty) 
667       | Just (sty',coi) <- ok_pred bad sty 
668       = Just (PredTy sty', coi) 
669     ok bad (FunTy arg res) 
670       | Just (arg', coiarg) <- ok bad arg, Just (res', coires) <- ok bad res
671       = Just (FunTy arg' res', mkFunTyCoI coiarg coires) 
672     ok bad (AppTy fun arg) 
673       | Just (fun', coifun) <- ok bad fun, Just (arg', coiarg) <- ok bad arg 
674       = Just (AppTy fun' arg', mkAppTyCoI coifun coiarg) 
675     ok bad (ForAllTy tv1 ty1) 
676     -- WARNING: What if it is a (t1 ~ t2) => t3? It's not handled properly at the moment. 
677       | Just (ty1', coi) <- ok bad ty1 
678       = Just (ForAllTy tv1 ty1', mkForAllTyCoI tv1 coi) 
679
680     -- Variable cases 
681     ok bad this_ty@(TyVarTy tv) 
682       | tv == the_tv                            = Nothing             -- Occurs check error
683       | not (isTcTyVar tv)                      = Just (this_ty, IdCo this_ty) -- Bound var
684       | FlatSkol zty <- tcTyVarDetails tv       = ok_fsk bad tv zty
685       | Just (_,ty) <- lookupVarEnv ty_binds tv = ok bad ty 
686       | otherwise                               = Just (this_ty, IdCo this_ty)
687
688     -- Check if there exists a ty bind already, as a result of sneaky unification. 
689     -- Fall through
690     ok _bad _ty = Nothing 
691
692     -----------
693     ok_pred bad (ClassP cn tys)
694       | Just tys_cois <- allMaybes $ map (ok bad) tys 
695       = let (tys', cois') = unzip tys_cois 
696         in Just (ClassP cn tys', mkClassPPredCoI cn cois')
697     ok_pred bad (IParam nm ty)   
698       | Just (ty',co') <- ok bad ty 
699       = Just (IParam nm ty', mkIParamPredCoI nm co') 
700     ok_pred bad (EqPred ty1 ty2) 
701       | Just (ty1',coi1) <- ok bad ty1, Just (ty2',coi2) <- ok bad ty2
702       = Just (EqPred ty1' ty2', mkEqPredCoI coi1 coi2) 
703     ok_pred _ _ = Nothing 
704
705     -----------
706     ok_fsk bad fsk zty
707       | fsk `elemVarSet` bad 
708             -- We are already trying to find a rendering of fsk, 
709             -- and to do that it seems we need a rendering, so fail
710       = Nothing
711       | otherwise 
712       = firstJusts (ok new_bad zty : map (go_under_fsk new_bad) fsk_equivs)
713       where
714         fsk_equivs = getFskEqClass inerts fsk 
715         new_bad    = bad `extendVarSetList` (fsk : map fst fsk_equivs)
716
717     -----------
718     go_under_fsk bad_tvs (fsk,co)
719       | FlatSkol zty <- tcTyVarDetails fsk
720       = case ok bad_tvs zty of
721            Nothing        -> Nothing
722            Just (ty,coi') -> Just (ty, mkTransCoI coi' (ACo co)) 
723       | otherwise = pprPanic "go_down_equiv" (ppr fsk)
724 \end{code}
725
726
727 *********************************************************************************
728 *                                                                               * 
729                        The interact-with-inert Stage
730 *                                                                               *
731 *********************************************************************************
732
733 \begin{code}
734 -- Interaction result of  WorkItem <~> AtomicInert
735 data InteractResult
736    = IR { ir_stop         :: StopOrContinue
737             -- Stop
738             --   => Reagent (work item) consumed.
739             -- ContinueWith new_reagent
740             --   => Reagent transformed but keep gathering interactions. 
741             --      The transformed item remains inert with respect 
742             --      to any previously encountered inerts.
743
744         , ir_inert_action :: InertAction
745             -- Whether the inert item should remain in the InertSet.
746
747         , ir_new_work     :: WorkList
748             -- new work items to add to the WorkList
749         }
750
751 -- What to do with the inert reactant.
752 data InertAction = KeepInert | DropInert
753   deriving Eq
754
755 mkIRContinue :: Monad m => WorkItem -> InertAction -> WorkList -> m InteractResult
756 mkIRContinue wi keep newWork = return $ IR (ContinueWith wi) keep newWork
757
758 mkIRStop :: Monad m => InertAction -> WorkList -> m InteractResult
759 mkIRStop keep newWork = return $ IR Stop keep newWork
760
761 dischargeWorkItem :: Monad m => m InteractResult
762 dischargeWorkItem = mkIRStop KeepInert emptyCCan
763
764 noInteraction :: Monad m => WorkItem -> m InteractResult
765 noInteraction workItem = mkIRContinue workItem KeepInert emptyCCan
766
767 data WhichComesFromInert = LeftComesFromInert | RightComesFromInert 
768
769 ---------------------------------------------------
770 -- Interact a single WorkItem with an InertSet as far as possible, i.e. until we get a Stop 
771 -- result from an individual interaction (i.e. when the WorkItem is consumed), or until we've 
772 -- interacted the WorkItem with the entire InertSet.
773 --
774 -- Postcondition: the new InertSet in the resulting StageResult is subset 
775 -- of the input InertSet.
776
777 interactWithInertsStage :: SimplifierStage
778 interactWithInertsStage workItem inert
779   = foldlInertSetM interactNext initITR inert
780   where 
781     initITR = SR { sr_inerts   = emptyInert
782                  , sr_new_work = emptyCCan
783                  , sr_stop     = ContinueWith workItem }
784
785
786     interactNext :: StageResult -> AtomicInert -> TcS StageResult 
787     interactNext it inert  
788       | ContinueWith workItem <- sr_stop it
789         = do { ir <- interactWithInert inert workItem 
790              ; let inerts = sr_inerts it 
791              ; return $ SR { sr_inerts   = if ir_inert_action ir == KeepInert
792                                            then inerts `updInertSet` inert
793                                            else inerts
794                            , sr_new_work = sr_new_work it `unionWorkLists` ir_new_work ir
795                            , sr_stop     = ir_stop ir } }
796       | otherwise = return $ itrAddInert inert it
797     
798                              
799     itrAddInert :: AtomicInert -> StageResult -> StageResult
800     itrAddInert inert itr = itr { sr_inerts = (sr_inerts itr) `updInertSet` inert }
801
802 -- Do a single interaction of two constraints.
803 interactWithInert :: AtomicInert -> WorkItem -> TcS InteractResult
804 interactWithInert inert workitem 
805   =  do { ctxt <- getTcSContext
806         ; let is_allowed  = allowedInteraction (simplEqsOnly ctxt) inert workitem 
807               inert_ev    = cc_id inert 
808               work_ev     = cc_id workitem 
809
810         -- Never interact a wanted and a derived where the derived's evidence 
811         -- mentions the wanted evidence in an unguarded way. 
812         -- See Note [Superclasses and recursive dictionaries] 
813         -- and Note [New Wanted Superclass Work] 
814         -- We don't have to do this for givens, as we fully know the evidence for them. 
815         ; rec_ev_ok <- 
816             case (cc_flavor inert, cc_flavor workitem) of 
817               (Wanted loc, Derived _) -> isGoodRecEv work_ev  (WantedEvVar inert_ev loc)
818               (Derived _, Wanted loc) -> isGoodRecEv inert_ev (WantedEvVar work_ev loc)
819               _                       -> return True 
820
821         ; if is_allowed && rec_ev_ok then 
822               doInteractWithInert inert workitem 
823           else 
824               noInteraction workitem 
825         }
826
827 allowedInteraction :: Bool -> AtomicInert -> WorkItem -> Bool 
828 -- Allowed interactions 
829 allowedInteraction eqs_only (CDictCan {}) (CDictCan {}) = not eqs_only
830 allowedInteraction eqs_only (CIPCan {})   (CIPCan {})   = not eqs_only
831 allowedInteraction _ _ _ = True 
832
833 --------------------------------------------
834 doInteractWithInert :: CanonicalCt -> CanonicalCt -> TcS InteractResult
835 -- Identical class constraints.
836
837 doInteractWithInert 
838            (CDictCan { cc_id = d1, cc_flavor = fl1, cc_class = cls1, cc_tyargs = tys1 }) 
839   workItem@(CDictCan { cc_id = d2, cc_flavor = fl2, cc_class = cls2, cc_tyargs = tys2 })
840   | cls1 == cls2 && (and $ zipWith tcEqType tys1 tys2)
841   = solveOneFromTheOther (d1,fl1) workItem 
842
843   | cls1 == cls2 && (not (isGiven fl1 && isGiven fl2))
844   =      -- See Note [When improvement happens]
845     do { let work_item_pred_loc = (ClassP cls2 tys2, ppr d2)
846              inert_pred_loc     = (ClassP cls1 tys1, ppr d1)
847              loc                = combineCtLoc fl1 fl2
848              eqn_pred_locs = improveFromAnother work_item_pred_loc inert_pred_loc         
849        ; wevvars <- mkWantedFunDepEqns loc eqn_pred_locs 
850                  -- See Note [Generating extra equalities]
851        ; workList <- canWanteds wevvars 
852        ; mkIRContinue workItem KeepInert workList -- Keep the inert there so we avoid 
853                                                   -- re-introducing the fundep equalities
854          -- See Note [FunDep Reactions] 
855        }
856
857 -- Class constraint and given equality: use the equality to rewrite
858 -- the class constraint. 
859 doInteractWithInert (CTyEqCan { cc_id = cv, cc_flavor = ifl, cc_tyvar = tv, cc_rhs = xi }) 
860                     (CDictCan { cc_id = dv, cc_flavor = wfl, cc_class = cl, cc_tyargs = xis }) 
861   | ifl `canRewrite` wfl 
862   , tv `elemVarSet` tyVarsOfTypes xis
863     -- substitute for tv in xis.  Note that the resulting class
864     -- constraint is still canonical, since substituting xi-types in
865     -- xi-types generates xi-types.  However, it may no longer be
866     -- inert with respect to the inert set items we've already seen.
867     -- For example, consider the inert set
868     --
869     --   D Int (g)
870     --   a ~g Int
871     --
872     -- and the work item D a (w). D a does not interact with D Int.
873     -- Next, it does interact with a ~g Int, getting rewritten to D
874     -- Int (w).  But now we must go back through the rest of the inert
875     -- set again, to find that it can now be discharged by the given D
876     -- Int instance.
877   = do { rewritten_dict <- rewriteDict (cv,tv,xi) (dv,wfl,cl,xis)
878        ; mkIRStop KeepInert (singleCCan rewritten_dict) }
879     
880 doInteractWithInert (CDictCan { cc_id = dv, cc_flavor = ifl, cc_class = cl, cc_tyargs = xis }) 
881            workItem@(CTyEqCan { cc_id = cv, cc_flavor = wfl, cc_tyvar = tv, cc_rhs = xi })
882   | wfl `canRewrite` ifl
883   , tv `elemVarSet` tyVarsOfTypes xis
884   = do { rewritten_dict <- rewriteDict (cv,tv,xi) (dv,ifl,cl,xis) 
885        ; mkIRContinue workItem DropInert (singleCCan rewritten_dict) }
886
887 -- Class constraint and given equality: use the equality to rewrite
888 -- the class constraint.
889 doInteractWithInert (CTyEqCan { cc_id = cv, cc_flavor = ifl, cc_tyvar = tv, cc_rhs = xi }) 
890                     (CIPCan { cc_id = ipid, cc_flavor = wfl, cc_ip_nm = nm, cc_ip_ty = ty }) 
891   | ifl `canRewrite` wfl
892   , tv `elemVarSet` tyVarsOfType ty 
893   = do { rewritten_ip <- rewriteIP (cv,tv,xi) (ipid,wfl,nm,ty) 
894        ; mkIRStop KeepInert (singleCCan rewritten_ip) }
895
896 doInteractWithInert (CIPCan { cc_id = ipid, cc_flavor = ifl, cc_ip_nm = nm, cc_ip_ty = ty }) 
897            workItem@(CTyEqCan { cc_id = cv, cc_flavor = wfl, cc_tyvar = tv, cc_rhs = xi })
898   | wfl `canRewrite` ifl
899   , tv `elemVarSet` tyVarsOfType ty
900   = do { rewritten_ip <- rewriteIP (cv,tv,xi) (ipid,ifl,nm,ty) 
901        ; mkIRContinue workItem DropInert (singleCCan rewritten_ip) } 
902
903 -- Two implicit parameter constraints.  If the names are the same,
904 -- but their types are not, we generate a wanted type equality 
905 -- that equates the type (this is "improvement").  
906 -- However, we don't actually need the coercion evidence,
907 -- so we just generate a fresh coercion variable that isn't used anywhere.
908 doInteractWithInert (CIPCan { cc_id = id1, cc_flavor = ifl, cc_ip_nm = nm1, cc_ip_ty = ty1 }) 
909            workItem@(CIPCan { cc_flavor = wfl, cc_ip_nm = nm2, cc_ip_ty = ty2 })
910   | nm1 == nm2 && isGiven wfl && isGiven ifl
911   =     -- See Note [Overriding implicit parameters]
912         -- Dump the inert item, override totally with the new one
913         -- Do not require type equality
914     mkIRContinue workItem DropInert emptyCCan
915
916   | nm1 == nm2 && ty1 `tcEqType` ty2 
917   = solveOneFromTheOther (id1,ifl) workItem 
918
919   | nm1 == nm2
920   =     -- See Note [When improvement happens]
921     do { co_var <- newWantedCoVar ty1 ty2 
922        ; let flav = Wanted (combineCtLoc ifl wfl) 
923        ; mkCanonical flav co_var >>= mkIRContinue workItem KeepInert } 
924
925
926 -- Inert: equality, work item: function equality
927
928 -- Never rewrite a given with a wanted equality, and a type function
929 -- equality can never rewrite an equality.  Note also that if we have
930 -- F x1 ~ x2 and a ~ x3, and a occurs in x2, we don't rewrite it.  We
931 -- can wait until F x1 ~ x2 matches another F x1 ~ x4, and only then
932 -- we will ``expose'' x2 and x4 to rewriting.
933
934 -- Otherwise, we can try rewriting the type function equality with the equality.
935 doInteractWithInert (CTyEqCan { cc_id = cv1, cc_flavor = ifl, cc_tyvar = tv, cc_rhs = xi1 }) 
936                     (CFunEqCan { cc_id = cv2, cc_flavor = wfl, cc_fun = tc
937                                , cc_tyargs = args, cc_rhs = xi2 })
938   | ifl `canRewrite` wfl 
939   , tv `elemVarSet` tyVarsOfTypes args
940   = do { rewritten_funeq <- rewriteFunEq (cv1,tv,xi1) (cv2,wfl,tc,args,xi2) 
941        ; mkIRStop KeepInert (singleCCan rewritten_funeq) }
942
943 -- Inert: function equality, work item: equality
944
945 doInteractWithInert (CFunEqCan {cc_id = cv1, cc_flavor = ifl, cc_fun = tc
946                               , cc_tyargs = args, cc_rhs = xi1 }) 
947            workItem@(CTyEqCan { cc_id = cv2, cc_flavor = wfl, cc_tyvar = tv, cc_rhs = xi2 })
948   | wfl `canRewrite` ifl
949   , tv `elemVarSet` tyVarsOfTypes args
950   = do { rewritten_funeq <- rewriteFunEq (cv2,tv,xi2) (cv1,ifl,tc,args,xi1) 
951        ; mkIRContinue workItem DropInert (singleCCan rewritten_funeq) } 
952
953 doInteractWithInert (CFunEqCan { cc_id = cv1, cc_flavor = fl1, cc_fun = tc1
954                                , cc_tyargs = args1, cc_rhs = xi1 }) 
955            workItem@(CFunEqCan { cc_id = cv2, cc_flavor = fl2, cc_fun = tc2
956                                , cc_tyargs = args2, cc_rhs = xi2 })
957   | fl1 `canRewrite` fl2 && lhss_match
958   = do { cans <- rewriteEqLHS LeftComesFromInert  (mkCoVarCoercion cv1,xi1) (cv2,fl2,xi2) 
959        ; mkIRStop KeepInert cans } 
960   | fl2 `canRewrite` fl1 && lhss_match
961   = do { cans <- rewriteEqLHS RightComesFromInert (mkCoVarCoercion cv2,xi2) (cv1,fl1,xi1) 
962        ; mkIRContinue workItem DropInert cans }
963   where
964     lhss_match = tc1 == tc2 && and (zipWith tcEqType args1 args2) 
965
966 doInteractWithInert 
967            inert@(CTyEqCan { cc_id = cv1, cc_flavor = fl1, cc_tyvar = tv1, cc_rhs = xi1 }) 
968            workItem@(CTyEqCan { cc_id = cv2, cc_flavor = fl2, cc_tyvar = tv2, cc_rhs = xi2 })
969 -- Check for matching LHS 
970   | fl1 `canRewrite` fl2 && tv1 == tv2 
971   = do { cans <- rewriteEqLHS LeftComesFromInert (mkCoVarCoercion cv1,xi1) (cv2,fl2,xi2) 
972        ; mkIRStop KeepInert cans } 
973
974   | fl2 `canRewrite` fl1 && tv1 == tv2 
975   = do { cans <- rewriteEqLHS RightComesFromInert (mkCoVarCoercion cv2,xi2) (cv1,fl1,xi1) 
976        ; mkIRContinue workItem DropInert cans } 
977
978 -- Check for rewriting RHS 
979   | fl1 `canRewrite` fl2 && tv1 `elemVarSet` tyVarsOfType xi2 
980   = do { rewritten_eq <- rewriteEqRHS (cv1,tv1,xi1) (cv2,fl2,tv2,xi2) 
981        ; mkIRStop KeepInert rewritten_eq }
982   | fl2 `canRewrite` fl1 && tv2 `elemVarSet` tyVarsOfType xi1
983   = do { rewritten_eq <- rewriteEqRHS (cv2,tv2,xi2) (cv1,fl1,tv1,xi1) 
984        ; mkIRContinue workItem DropInert rewritten_eq } 
985
986 -- Finally, if workitem is a Flatten Equivalence Class constraint and the 
987 -- inert is a wanted constraint, even when the workitem cannot rewrite the 
988 -- inert, drop the inert out because you may have to reconsider solving the 
989 -- inert *using* the equivalence class you created. See note [Loopy Spontaneous Solving]
990 -- and [InertSet FlattenSkolemEqClass] 
991
992   | not $ isGiven fl1,                  -- The inert is wanted or derived
993     isMetaTyVar tv1,                    -- and has a unification variable lhs
994     FlatSkol {} <- tcTyVarDetails tv2,  -- And workitem is a flatten skolem equality
995     Just tv2'   <- tcGetTyVar_maybe xi2, FlatSkol {} <- tcTyVarDetails tv2' 
996   = mkIRContinue workItem DropInert (singletonWorkList inert)
997
998
999 -- Fall-through case for all other situations
1000 doInteractWithInert _ workItem = noInteraction workItem
1001
1002 -------------------------
1003 -- Equational Rewriting 
1004 rewriteDict  :: (CoVar, TcTyVar, Xi) -> (DictId, CtFlavor, Class, [Xi]) -> TcS CanonicalCt
1005 rewriteDict (cv,tv,xi) (dv,gw,cl,xis) 
1006   = do { let cos  = substTysWith [tv] [mkCoVarCoercion cv] xis -- xis[tv] ~ xis[xi]
1007              args = substTysWith [tv] [xi] xis
1008              con  = classTyCon cl 
1009              dict_co = mkTyConCoercion con cos 
1010        ; dv' <- newDictVar cl args 
1011        ; case gw of 
1012            Wanted {}         -> setDictBind dv (EvCast dv' (mkSymCoercion dict_co))
1013            _given_or_derived -> setDictBind dv' (EvCast dv dict_co) 
1014        ; return (CDictCan { cc_id = dv'
1015                           , cc_flavor = gw 
1016                           , cc_class = cl 
1017                           , cc_tyargs = args }) } 
1018
1019 rewriteIP :: (CoVar,TcTyVar,Xi) -> (EvVar,CtFlavor, IPName Name, TcType) -> TcS CanonicalCt 
1020 rewriteIP (cv,tv,xi) (ipid,gw,nm,ty) 
1021   = do { let ip_co = substTyWith [tv] [mkCoVarCoercion cv] ty     -- ty[tv] ~ t[xi] 
1022              ty'   = substTyWith [tv] [xi] ty
1023        ; ipid' <- newIPVar nm ty' 
1024        ; case gw of 
1025            Wanted {}         -> setIPBind ipid  (EvCast ipid' (mkSymCoercion ip_co))
1026            _given_or_derived -> setIPBind ipid' (EvCast ipid ip_co) 
1027        ; return (CIPCan { cc_id = ipid'
1028                         , cc_flavor = gw
1029                         , cc_ip_nm = nm
1030                         , cc_ip_ty = ty' }) }
1031    
1032 rewriteFunEq :: (CoVar,TcTyVar,Xi) -> (CoVar,CtFlavor,TyCon, [Xi], Xi) -> TcS CanonicalCt
1033 rewriteFunEq (cv1,tv,xi1) (cv2,gw, tc,args,xi2) 
1034   = do { let arg_cos = substTysWith [tv] [mkCoVarCoercion cv1] args 
1035              args'   = substTysWith [tv] [xi1] args 
1036              fun_co  = mkTyConCoercion tc arg_cos 
1037        ; cv2' <- case gw of 
1038                    Wanted {} -> do { cv2' <- newWantedCoVar (mkTyConApp tc args') xi2 
1039                                    ; setWantedCoBind cv2 $ 
1040                                      mkTransCoercion fun_co (mkCoVarCoercion cv2') 
1041                                    ; return cv2' } 
1042                    _giv_or_der -> newGivOrDerCoVar (mkTyConApp tc args') xi2 $
1043                                   mkTransCoercion (mkSymCoercion fun_co) (mkCoVarCoercion cv2) 
1044        ; return (CFunEqCan { cc_id = cv2'
1045                            , cc_flavor = gw
1046                            , cc_tyargs = args'
1047                            , cc_fun = tc 
1048                            , cc_rhs = xi2 }) }
1049
1050
1051 rewriteEqRHS :: (CoVar,TcTyVar,Xi) -> (CoVar,CtFlavor,TcTyVar,Xi) -> TcS CanonicalCts
1052 -- Use the first equality to rewrite the second, flavors already checked. 
1053 -- E.g.          c1 : tv1 ~ xi1   c2 : tv2 ~ xi2
1054 -- rewrites c2 to give
1055 --               c2' : tv2 ~ xi2[xi1/tv1]
1056 -- We must do an occurs check to sure the new constraint is canonical
1057 -- So we might return an empty bag
1058 rewriteEqRHS (cv1,tv1,xi1) (cv2,gw,tv2,xi2) 
1059   | Just tv2' <- tcGetTyVar_maybe xi2'
1060   , tv2 == tv2'  -- In this case xi2[xi1/tv1] = tv2, so we have tv2~tv2
1061   = do { when (isWanted gw) (setWantedCoBind cv2 (mkSymCoercion co2')) 
1062        ; return emptyCCan } 
1063   | otherwise 
1064   = do { cv2' <- 
1065            case gw of 
1066              Wanted {} 
1067                  -> do { cv2' <- newWantedCoVar (mkTyVarTy tv2) xi2' 
1068                        ; setWantedCoBind cv2 $ 
1069                          mkCoVarCoercion cv2' `mkTransCoercion` mkSymCoercion co2'
1070                        ; return cv2' } 
1071              _giv_or_der 
1072                  -> newGivOrDerCoVar (mkTyVarTy tv2) xi2' $ 
1073                     mkCoVarCoercion cv2 `mkTransCoercion` co2'
1074
1075        ; xi2'' <- canOccursCheck gw tv2 xi2' -- we know xi2' is *not* tv2 
1076        ; return (singleCCan $ CTyEqCan { cc_id = cv2' 
1077                                        , cc_flavor = gw 
1078                                        , cc_tyvar = tv2 
1079                                        , cc_rhs   = xi2'' }) 
1080        }
1081   where 
1082     xi2' = substTyWith [tv1] [xi1] xi2 
1083     co2' = substTyWith [tv1] [mkCoVarCoercion cv1] xi2  -- xi2 ~ xi2[xi1/tv1]
1084
1085
1086 rewriteEqLHS :: WhichComesFromInert -> (Coercion,Xi) -> (CoVar,CtFlavor,Xi) -> TcS CanonicalCts
1087 -- Used to ineratct two equalities of the following form: 
1088 -- First Equality:   co1: (XXX ~ xi1)  
1089 -- Second Equality:  cv2: (XXX ~ xi2) 
1090 -- Where the cv1 `canRewrite` cv2 equality 
1091 -- We have an option of creating new work (xi1 ~ xi2) OR (xi2 ~ xi1). This 
1092 -- depends on whether the left or the right equality comes from the inert set. 
1093 -- We must:  
1094 --     prefer to create (xi2 ~ xi1) if the first comes from the inert 
1095 --     prefer to create (xi1 ~ xi2) if the second comes from the inert 
1096 rewriteEqLHS which (co1,xi1) (cv2,gw,xi2) 
1097   = do { cv2' <- case (isWanted gw, which) of 
1098                    (True,LeftComesFromInert) ->
1099                        do { cv2' <- newWantedCoVar xi2 xi1 
1100                           ; setWantedCoBind cv2 $ 
1101                             co1 `mkTransCoercion` mkSymCoercion (mkCoVarCoercion cv2')
1102                           ; return cv2' } 
1103                    (True,RightComesFromInert) -> 
1104                        do { cv2' <- newWantedCoVar xi1 xi2 
1105                           ; setWantedCoBind cv2 $ 
1106                             co1 `mkTransCoercion` mkCoVarCoercion cv2'
1107                           ; return cv2' } 
1108                    (False,LeftComesFromInert) ->
1109                        newGivOrDerCoVar xi2 xi1 $ 
1110                        mkSymCoercion (mkCoVarCoercion cv2) `mkTransCoercion` co1 
1111                    (False,RightComesFromInert) -> 
1112                         newGivOrDerCoVar xi1 xi2 $ 
1113                         mkSymCoercion co1 `mkTransCoercion` mkCoVarCoercion cv2
1114        ; mkCanonical gw cv2' }
1115
1116
1117
1118 solveOneFromTheOther :: (EvVar, CtFlavor) -> CanonicalCt -> TcS InteractResult 
1119 -- First argument inert, second argument workitem. They both represent 
1120 -- wanted/given/derived evidence for the *same* predicate so we try here to 
1121 -- discharge one directly from the other. 
1122 --
1123 -- Precondition: value evidence only (implicit parameters, classes) 
1124 --               not coercion
1125 solveOneFromTheOther (iid,ifl) workItem 
1126       -- Both derived needs a special case. You might think that we do not need
1127       -- two evidence terms for the same claim. But, since the evidence is partial, 
1128       -- either evidence may do in some cases; see TcSMonad.isGoodRecEv.
1129       -- See also Example 3 in Note [Superclasses and recursive dictionaries] 
1130   | isDerived ifl && isDerived wfl 
1131   = noInteraction workItem 
1132
1133   | ifl `canRewrite` wfl
1134   = do { unless (isGiven wfl) $ setEvBind wid (EvId iid) 
1135            -- Overwrite the binding, if one exists
1136            -- For Givens, which are lambda-bound, nothing to overwrite,
1137        ; dischargeWorkItem }
1138
1139   | otherwise  -- wfl `canRewrite` ifl 
1140   = do { unless (isGiven ifl) $ setEvBind iid (EvId wid)
1141        ; mkIRContinue workItem DropInert emptyCCan }
1142
1143   where 
1144      wfl = cc_flavor workItem
1145      wid = cc_id workItem
1146 \end{code}
1147
1148 Note [Superclasses and recursive dictionaries]
1149 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1150     Overlaps with Note [SUPERCLASS-LOOP 1]
1151                   Note [SUPERCLASS-LOOP 2]
1152                   Note [Recursive instances and superclases]
1153     ToDo: check overlap and delete redundant stuff
1154
1155 Right before adding a given into the inert set, we must
1156 produce some more work, that will bring the superclasses 
1157 of the given into scope. The superclass constraints go into 
1158 our worklist. 
1159
1160 When we simplify a wanted constraint, if we first see a matching
1161 instance, we may produce new wanted work. To (1) avoid doing this work 
1162 twice in the future and (2) to handle recursive dictionaries we may ``cache'' 
1163 this item as solved (in effect, given) into our inert set and with that add 
1164 its superclass constraints (as given) in our worklist. 
1165
1166 But now we have added partially solved constraints to the worklist which may 
1167 interact with other wanteds. Consider the example: 
1168
1169 Example 1: 
1170
1171     class Eq b => Foo a b        --- 0-th selector
1172     instance Eq a => Foo [a] a   --- fooDFun
1173
1174 and wanted (Foo [t] t). We are first going to see that the instance matches 
1175 and create an inert set that includes the solved (Foo [t] t) and its 
1176 superclasses. 
1177        d1 :_g Foo [t] t                 d1 := EvDFunApp fooDFun d3 
1178        d2 :_g Eq t                      d2 := EvSuperClass d1 0 
1179 Our work list is going to contain a new *wanted* goal
1180        d3 :_w Eq t 
1181 It is wrong to react the wanted (Eq t) with the given (Eq t) because that would 
1182 construct loopy evidence. Hence the check isGoodRecEv in doInteractWithInert. 
1183
1184 OK, so we have ruled out bad behaviour, but how do we ge recursive dictionaries, 
1185 at all? Consider
1186
1187 Example 2:
1188
1189     data D r = ZeroD | SuccD (r (D r));
1190     
1191     instance (Eq (r (D r))) => Eq (D r) where
1192         ZeroD     == ZeroD     = True
1193         (SuccD a) == (SuccD b) = a == b
1194         _         == _         = False;
1195     
1196     equalDC :: D [] -> D [] -> Bool;
1197     equalDC = (==);
1198
1199 We need to prove (Eq (D [])). Here's how we go:
1200
1201         d1 :_w Eq (D [])
1202
1203 by instance decl, holds if
1204         d2 :_w Eq [D []]
1205         where   d1 = dfEqD d2
1206
1207 *BUT* we have an inert set which gives us (no superclasses): 
1208         d1 :_g Eq (D []) 
1209 By the instance declaration of Eq we can show the 'd2' goal if 
1210         d3 :_w Eq (D [])
1211         where   d2 = dfEqList d3
1212                 d1 = dfEqD d2
1213 Now, however this wanted can interact with our inert d1 to set: 
1214         d3 := d1 
1215 and solve the goal. Why was this interaction OK? Because, if we chase the 
1216 evidence of d1 ~~> dfEqD d2 ~~-> dfEqList d3, so by setting d3 := d1 we 
1217 are really setting
1218         d3 := dfEqD2 (dfEqList d3) 
1219 which is FINE because the use of d3 is protected by the instance function 
1220 applications. 
1221
1222 So, our strategy is to try to put solved wanted dictionaries into the
1223 inert set along with their superclasses (when this is meaningful,
1224 i.e. when new wanted goals are generated) but solve a wanted dictionary
1225 from a given only in the case where the evidence variable of the
1226 wanted is mentioned in the evidence of the given (recursively through
1227 the evidence binds) in a protected way: more instance function applications 
1228 than superclass selectors.
1229
1230 Here are some more examples from GHC's previous type checker
1231
1232
1233 Example 3: 
1234 This code arises in the context of "Scrap Your Boilerplate with Class"
1235
1236     class Sat a
1237     class Data ctx a
1238     instance  Sat (ctx Char)             => Data ctx Char       -- dfunData1
1239     instance (Sat (ctx [a]), Data ctx a) => Data ctx [a]        -- dfunData2
1240
1241     class Data Maybe a => Foo a    
1242
1243     instance Foo t => Sat (Maybe t)                             -- dfunSat
1244
1245     instance Data Maybe a => Foo a                              -- dfunFoo1
1246     instance Foo a        => Foo [a]                            -- dfunFoo2
1247     instance                 Foo [Char]                         -- dfunFoo3
1248
1249 Consider generating the superclasses of the instance declaration
1250          instance Foo a => Foo [a]
1251
1252 So our problem is this
1253     d0 :_g Foo t
1254     d1 :_w Data Maybe [t] 
1255
1256 We may add the given in the inert set, along with its superclasses
1257 [assuming we don't fail because there is a matching instance, see 
1258  tryTopReact, given case ]
1259   Inert:
1260     d0 :_g Foo t 
1261   WorkList 
1262     d01 :_g Data Maybe t  -- d2 := EvDictSuperClass d0 0 
1263     d1 :_w Data Maybe [t] 
1264 Then d2 can readily enter the inert, and we also do solving of the wanted
1265   Inert: 
1266     d0 :_g Foo t 
1267     d1 :_s Data Maybe [t]           d1 := dfunData2 d2 d3 
1268   WorkList
1269     d2 :_w Sat (Maybe [t])          
1270     d3 :_w Data Maybe t
1271     d01 :_g Data Maybe t 
1272 Now, we may simplify d2 more: 
1273   Inert:
1274       d0 :_g Foo t 
1275       d1 :_s Data Maybe [t]           d1 := dfunData2 d2 d3 
1276       d1 :_g Data Maybe [t] 
1277       d2 :_g Sat (Maybe [t])          d2 := dfunSat d4 
1278   WorkList: 
1279       d3 :_w Data Maybe t 
1280       d4 :_w Foo [t] 
1281       d01 :_g Data Maybe t 
1282
1283 Now, we can just solve d3.
1284   Inert
1285       d0 :_g Foo t 
1286       d1 :_s Data Maybe [t]           d1 := dfunData2 d2 d3 
1287       d2 :_g Sat (Maybe [t])          d2 := dfunSat d4 
1288   WorkList
1289       d4 :_w Foo [t] 
1290       d01 :_g Data Maybe t 
1291 And now we can simplify d4 again, but since it has superclasses we *add* them to the worklist:
1292   Inert
1293       d0 :_g Foo t 
1294       d1 :_s Data Maybe [t]           d1 := dfunData2 d2 d3 
1295       d2 :_g Sat (Maybe [t])          d2 := dfunSat d4 
1296       d4 :_g Foo [t]                  d4 := dfunFoo2 d5 
1297   WorkList:
1298       d5 :_w Foo t 
1299       d6 :_g Data Maybe [t]           d6 := EvDictSuperClass d4 0
1300       d01 :_g Data Maybe t 
1301 Now, d5 can be solved! (and its superclass enter scope) 
1302   Inert
1303       d0 :_g Foo t 
1304       d1 :_s Data Maybe [t]           d1 := dfunData2 d2 d3 
1305       d2 :_g Sat (Maybe [t])          d2 := dfunSat d4 
1306       d4 :_g Foo [t]                  d4 := dfunFoo2 d5 
1307       d5 :_g Foo t                    d5 := dfunFoo1 d7
1308   WorkList:
1309       d7 :_w Data Maybe t
1310       d6 :_g Data Maybe [t]
1311       d8 :_g Data Maybe t            d8 := EvDictSuperClass d5 0
1312       d01 :_g Data Maybe t 
1313
1314 Now, two problems: 
1315    [1] Suppose we pick d8 and we react him with d01. Which of the two givens should 
1316        we keep? Well, we *MUST NOT* drop d01 because d8 contains recursive evidence 
1317        that must not be used (look at case interactInert where both inert and workitem
1318        are givens). So we have several options: 
1319        - Drop the workitem always (this will drop d8)
1320               This feels very unsafe -- what if the work item was the "good" one
1321               that should be used later to solve another wanted?
1322        - Don't drop anyone: the inert set may contain multiple givens! 
1323               [This is currently implemented] 
1324
1325 The "don't drop anyone" seems the most safe thing to do, so now we come to problem 2: 
1326   [2] We have added both d6 and d01 in the inert set, and we are interacting our wanted
1327       d7. Now the [isRecDictEv] function in the ineration solver 
1328       [case inert-given workitem-wanted] will prevent us from interacting d7 := d8 
1329       precisely because chasing the evidence of d8 leads us to an unguarded use of d7. 
1330
1331       So, no interaction happens there. Then we meet d01 and there is no recursion 
1332       problem there [isRectDictEv] gives us the OK to interact and we do solve d7 := d01! 
1333              
1334 Note [SUPERCLASS-LOOP 1]
1335 ~~~~~~~~~~~~~~~~~~~~~~~~
1336 We have to be very, very careful when generating superclasses, lest we
1337 accidentally build a loop. Here's an example:
1338
1339   class S a
1340
1341   class S a => C a where { opc :: a -> a }
1342   class S b => D b where { opd :: b -> b }
1343   
1344   instance C Int where
1345      opc = opd
1346   
1347   instance D Int where
1348      opd = opc
1349
1350 From (instance C Int) we get the constraint set {ds1:S Int, dd:D Int}
1351 Simplifying, we may well get:
1352         $dfCInt = :C ds1 (opd dd)
1353         dd  = $dfDInt
1354         ds1 = $p1 dd
1355 Notice that we spot that we can extract ds1 from dd.  
1356
1357 Alas!  Alack! We can do the same for (instance D Int):
1358
1359         $dfDInt = :D ds2 (opc dc)
1360         dc  = $dfCInt
1361         ds2 = $p1 dc
1362
1363 And now we've defined the superclass in terms of itself.
1364 Two more nasty cases are in
1365         tcrun021
1366         tcrun033
1367
1368 Solution: 
1369   - Satisfy the superclass context *all by itself* 
1370     (tcSimplifySuperClasses)
1371   - And do so completely; i.e. no left-over constraints
1372     to mix with the constraints arising from method declarations
1373
1374
1375 Note [SUPERCLASS-LOOP 2]
1376 ~~~~~~~~~~~~~~~~~~~~~~~~
1377 We need to be careful when adding "the constaint we are trying to prove".
1378 Suppose we are *given* d1:Ord a, and want to deduce (d2:C [a]) where
1379
1380         class Ord a => C a where
1381         instance Ord [a] => C [a] where ...
1382
1383 Then we'll use the instance decl to deduce C [a] from Ord [a], and then add the
1384 superclasses of C [a] to avails.  But we must not overwrite the binding
1385 for Ord [a] (which is obtained from Ord a) with a superclass selection or we'll just
1386 build a loop! 
1387
1388 Here's another variant, immortalised in tcrun020
1389         class Monad m => C1 m
1390         class C1 m => C2 m x
1391         instance C2 Maybe Bool
1392 For the instance decl we need to build (C1 Maybe), and it's no good if
1393 we run around and add (C2 Maybe Bool) and its superclasses to the avails 
1394 before we search for C1 Maybe.
1395
1396 Here's another example 
1397         class Eq b => Foo a b
1398         instance Eq a => Foo [a] a
1399 If we are reducing
1400         (Foo [t] t)
1401
1402 we'll first deduce that it holds (via the instance decl).  We must not
1403 then overwrite the Eq t constraint with a superclass selection!
1404
1405 At first I had a gross hack, whereby I simply did not add superclass constraints
1406 in addWanted, though I did for addGiven and addIrred.  This was sub-optimal,
1407 becuase it lost legitimate superclass sharing, and it still didn't do the job:
1408 I found a very obscure program (now tcrun021) in which improvement meant the
1409 simplifier got two bites a the cherry... so something seemed to be an Stop
1410 first time, but reducible next time.
1411
1412 Now we implement the Right Solution, which is to check for loops directly 
1413 when adding superclasses.  It's a bit like the occurs check in unification.
1414
1415 Note [Recursive instances and superclases]
1416 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1417 Consider this code, which arises in the context of "Scrap Your 
1418 Boilerplate with Class".  
1419
1420     class Sat a
1421     class Data ctx a
1422     instance  Sat (ctx Char)             => Data ctx Char
1423     instance (Sat (ctx [a]), Data ctx a) => Data ctx [a]
1424
1425     class Data Maybe a => Foo a
1426
1427     instance Foo t => Sat (Maybe t)
1428
1429     instance Data Maybe a => Foo a
1430     instance Foo a        => Foo [a]
1431     instance                 Foo [Char]
1432
1433 In the instance for Foo [a], when generating evidence for the superclasses
1434 (ie in tcSimplifySuperClasses) we need a superclass (Data Maybe [a]).
1435 Using the instance for Data, we therefore need
1436         (Sat (Maybe [a], Data Maybe a)
1437 But we are given (Foo a), and hence its superclass (Data Maybe a).
1438 So that leaves (Sat (Maybe [a])).  Using the instance for Sat means
1439 we need (Foo [a]).  And that is the very dictionary we are bulding
1440 an instance for!  So we must put that in the "givens".  So in this
1441 case we have
1442         Given:  Foo a, Foo [a]
1443         Wanted: Data Maybe [a]
1444
1445 BUT we must *not not not* put the *superclasses* of (Foo [a]) in
1446 the givens, which is what 'addGiven' would normally do. Why? Because
1447 (Data Maybe [a]) is the superclass, so we'd "satisfy" the wanted 
1448 by selecting a superclass from Foo [a], which simply makes a loop.
1449
1450 On the other hand we *must* put the superclasses of (Foo a) in
1451 the givens, as you can see from the derivation described above.
1452
1453 Conclusion: in the very special case of tcSimplifySuperClasses
1454 we have one 'given' (namely the "this" dictionary) whose superclasses
1455 must not be added to 'givens' by addGiven.  
1456
1457 There is a complication though.  Suppose there are equalities
1458       instance (Eq a, a~b) => Num (a,b)
1459 Then we normalise the 'givens' wrt the equalities, so the original
1460 given "this" dictionary is cast to one of a different type.  So it's a
1461 bit trickier than before to identify the "special" dictionary whose
1462 superclasses must not be added. See test
1463    indexed-types/should_run/EqInInstance
1464
1465 We need a persistent property of the dictionary to record this
1466 special-ness.  Current I'm using the InstLocOrigin (a bit of a hack,
1467 but cool), which is maintained by dictionary normalisation.
1468 Specifically, the InstLocOrigin is
1469              NoScOrigin
1470 then the no-superclass thing kicks in.  WATCH OUT if you fiddle
1471 with InstLocOrigin!
1472
1473 Note [MATCHING-SYNONYMS]
1474 ~~~~~~~~~~~~~~~~~~~~~~~~
1475 When trying to match a dictionary (D tau) to a top-level instance, or a 
1476 type family equation (F taus_1 ~ tau_2) to a top-level family instance, 
1477 we do *not* need to expand type synonyms because the matcher will do that for us.
1478
1479
1480 Note [RHS-FAMILY-SYNONYMS] 
1481 ~~~~~~~~~~~~~~~~~~~~~~~~~~
1482 The RHS of a family instance is represented as yet another constructor which is 
1483 like a type synonym for the real RHS the programmer declared. Eg: 
1484     type instance F (a,a) = [a] 
1485 Becomes: 
1486     :R32 a = [a]      -- internal type synonym introduced
1487     F (a,a) ~ :R32 a  -- instance 
1488
1489 When we react a family instance with a type family equation in the work list 
1490 we keep the synonym-using RHS without expansion. 
1491
1492
1493 *********************************************************************************
1494 *                                                                               * 
1495                        The top-reaction Stage
1496 *                                                                               *
1497 *********************************************************************************
1498
1499 \begin{code}
1500 -- If a work item has any form of interaction with top-level we get this 
1501 data TopInteractResult 
1502   = NoTopInt               -- No top-level interaction
1503   | SomeTopInt 
1504       { tir_new_work  :: WorkList       -- Sub-goals or new work (could be given, 
1505                                         --                        for superclasses)
1506       , tir_new_inert :: StopOrContinue -- The input work item, ready to become *inert* now: 
1507       }                                 -- NB: in ``given'' (solved) form if the 
1508                                         -- original was wanted or given and instance match
1509                                         -- was found, but may also be in wanted form if we 
1510                                         -- only reacted with functional dependencies 
1511                                         -- arising from top-level instances.
1512
1513 topReactionsStage :: SimplifierStage 
1514 topReactionsStage workItem inerts 
1515   = do { tir <- tryTopReact workItem 
1516        ; case tir of 
1517            NoTopInt -> 
1518                return $ SR { sr_inerts   = inerts 
1519                            , sr_new_work = emptyWorkList 
1520                            , sr_stop     = ContinueWith workItem } 
1521            SomeTopInt tir_new_work tir_new_inert -> 
1522                return $ SR { sr_inerts   = inerts 
1523                            , sr_new_work = tir_new_work
1524                            , sr_stop     = tir_new_inert
1525                            }
1526        }
1527
1528 tryTopReact :: WorkItem -> TcS TopInteractResult 
1529 tryTopReact workitem 
1530   = do {  -- A flag controls the amount of interaction allowed
1531           -- See Note [Simplifying RULE lhs constraints]
1532          ctxt <- getTcSContext
1533        ; if allowedTopReaction (simplEqsOnly ctxt) workitem 
1534          then do { traceTcS "tryTopReact / calling doTopReact" (ppr workitem)
1535                  ; doTopReact workitem }
1536          else return NoTopInt 
1537        } 
1538
1539 allowedTopReaction :: Bool -> WorkItem -> Bool 
1540 allowedTopReaction eqs_only (CDictCan {}) = not eqs_only
1541 allowedTopReaction _        _             = True 
1542
1543
1544 doTopReact :: WorkItem -> TcS TopInteractResult 
1545 -- The work item does not react with the inert set, 
1546 -- so try interaction with top-level instances
1547 doTopReact workItem@(CDictCan { cc_id = dv, cc_flavor = Wanted loc
1548                               , cc_class = cls, cc_tyargs = xis }) 
1549   = do { -- See Note [MATCHING-SYNONYMS]
1550        ; lkp_inst_res <- matchClassInst cls xis loc
1551        ; case lkp_inst_res of 
1552            NoInstance -> do { traceTcS "doTopReact/ no class instance for" (ppr dv) 
1553                             ; funDepReact }
1554            GenInst wtvs ev_term ->  -- Solved 
1555                    -- No need to do fundeps stuff here; the instance 
1556                    -- matches already so we won't get any more info
1557                    -- from functional dependencies
1558                do { traceTcS "doTopReact/ found class instance for" (ppr dv) 
1559                   ; setDictBind dv ev_term 
1560                   ; workList <- canWanteds wtvs
1561                   ; if null wtvs
1562                     -- Solved in one step and no new wanted work produced. 
1563                     -- i.e we directly matched a top-level instance
1564                     -- No point in caching this in 'inert', nor in adding superclasses
1565                     then return $ SomeTopInt { tir_new_work  = emptyCCan 
1566                                              , tir_new_inert = Stop }
1567
1568                     -- Solved and new wanted work produced, you may cache the 
1569                     -- (tentatively solved) dictionary as Derived and its superclasses
1570                     else do { let solved = makeSolved workItem
1571                             ; sc_work <- newSCWorkFromFlavored dv (Derived loc) cls xis 
1572                             ; return $ SomeTopInt 
1573                                   { tir_new_work = workList `unionWorkLists` sc_work 
1574                                   , tir_new_inert = ContinueWith solved } }
1575                   }
1576        }
1577   where 
1578     -- Try for a fundep reaction beween the wanted item 
1579     -- and a top-level instance declaration
1580     funDepReact 
1581       = do { instEnvs <- getInstEnvs
1582            ; let eqn_pred_locs = improveFromInstEnv (classInstances instEnvs)
1583                                                     (ClassP cls xis, ppr dv)
1584            ; wevvars <- mkWantedFunDepEqns loc eqn_pred_locs 
1585                       -- NB: fundeps generate some wanted equalities, but 
1586                       --     we don't use their evidence for anything
1587            ; fd_work <- canWanteds wevvars 
1588            ; sc_work <- newSCWorkFromFlavored dv (Derived loc) cls xis
1589            ; return $ SomeTopInt { tir_new_work = fd_work `unionWorkLists` sc_work
1590                                  , tir_new_inert = ContinueWith workItem }
1591            -- NB: workItem is inert, but it isn't solved
1592            -- keep it as inert, although it's not solved because we
1593            -- have now reacted all its top-level fundep-induced equalities!
1594                     
1595            -- See Note [FunDep Reactions]
1596            }
1597
1598 -- Otherwise, we have a given or derived 
1599 doTopReact workItem@(CDictCan { cc_id = dv, cc_flavor = fl
1600                               , cc_class = cls, cc_tyargs = xis }) 
1601   = do { sc_work <- newSCWorkFromFlavored dv fl cls xis 
1602        ; return $ SomeTopInt sc_work (ContinueWith workItem) }
1603     -- See Note [Given constraint that matches an instance declaration]
1604
1605 -- Type functions
1606 doTopReact (CFunEqCan { cc_id = cv, cc_flavor = fl
1607                       , cc_fun = tc, cc_tyargs = args, cc_rhs = xi })
1608   = ASSERT (isSynFamilyTyCon tc)   -- No associated data families have reached that far 
1609     do { match_res <- matchFam tc args -- See Note [MATCHING-SYNONYMS]
1610        ; case match_res of 
1611            MatchInstNo 
1612              -> return NoTopInt 
1613            MatchInstSingle (rep_tc, rep_tys)
1614              -> do { let Just coe_tc = tyConFamilyCoercion_maybe rep_tc
1615                          Just rhs_ty = tcView (mkTyConApp rep_tc rep_tys)
1616                             -- Eagerly expand away the type synonym on the
1617                             -- RHS of a type function, so that it never
1618                             -- appears in an error message
1619                             -- See Note [Type synonym families] in TyCon
1620                          coe = mkTyConApp coe_tc rep_tys 
1621                    ; cv' <- case fl of
1622                               Wanted {} -> do { cv' <- newWantedCoVar rhs_ty xi
1623                                               ; setWantedCoBind cv $ 
1624                                                     coe `mkTransCoercion`
1625                                                       mkCoVarCoercion cv'
1626                                               ; return cv' }
1627                               _ -> newGivOrDerCoVar xi rhs_ty $ 
1628                                    mkSymCoercion (mkCoVarCoercion cv) `mkTransCoercion` coe 
1629
1630                    ; workList <- mkCanonical fl cv'
1631                    ; return $ SomeTopInt workList Stop }
1632            _ 
1633              -> panicTcS $ text "TcSMonad.matchFam returned multiple instances!"
1634        }
1635
1636
1637 -- Any other work item does not react with any top-level equations
1638 doTopReact _workItem = return NoTopInt 
1639 \end{code}
1640
1641 Note [FunDep and implicit parameter reactions] 
1642 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1643 Currently, our story of interacting two dictionaries (or a dictionary
1644 and top-level instances) for functional dependencies, and implicit
1645 paramters, is that we simply produce new wanted equalities.  So for example
1646
1647         class D a b | a -> b where ... 
1648     Inert: 
1649         d1 :g D Int Bool
1650     WorkItem: 
1651         d2 :w D Int alpha
1652
1653     We generate the extra work item
1654         cv :w alpha ~ Bool
1655     where 'cv' is currently unused.  However, this new item reacts with d2,
1656     discharging it in favour of a new constraint d2' thus:
1657         d2' :w D Int Bool
1658         d2 := d2' |> D Int cv
1659     Now d2' can be discharged from d1
1660
1661 We could be more aggressive and try to *immediately* solve the dictionary 
1662 using those extra equalities. With the same inert set and work item we
1663 might dischard d2 directly:
1664
1665         cv :w alpha ~ Bool
1666         d2 := d1 |> D Int cv
1667
1668 But in general it's a bit painful to figure out the necessary coercion,
1669 so we just take the first approach.
1670
1671 It's exactly the same with implicit parameters, except that the
1672 "aggressive" approach would be much easier to implement.
1673
1674 Note [When improvement happens]
1675 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1676 We fire an improvement rule when
1677
1678   * Two constraints match (modulo the fundep)
1679       e.g. C t1 t2, C t1 t3    where C a b | a->b
1680     The two match because the first arg is identical
1681
1682   * At least one is not Given.  If they are both given, we don't fire
1683     the reaction because we have no way of constructing evidence for a
1684     new equality nor does it seem right to create a new wanted goal
1685     (because the goal will most likely contain untouchables, which
1686     can't be solved anyway)!
1687    
1688 Note that we *do* fire the improvement if one is Given and one is Derived.
1689 The latter can be a superclass of a wanted goal. Example (tcfail138)
1690     class L a b | a -> b
1691     class (G a, L a b) => C a b
1692
1693     instance C a b' => G (Maybe a)
1694     instance C a b  => C (Maybe a) a
1695     instance L (Maybe a) a
1696
1697 When solving the superclasses of the (C (Maybe a) a) instance, we get
1698   Given:  C a b  ... and hance by superclasses, (G a, L a b)
1699   Wanted: G (Maybe a)
1700 Use the instance decl to get
1701   Wanted: C a b'
1702 The (C a b') is inert, so we generate its Derived superclasses (L a b'),
1703 and now we need improvement between that derived superclass an the Given (L a b)
1704
1705 Note [Overriding implicit parameters]
1706 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1707 Consider
1708    f :: (?x::a) -> Bool -> a
1709   
1710    g v = let ?x::Int = 3 
1711          in (f v, let ?x::Bool = True in f v)
1712
1713 This should probably be well typed, with
1714    g :: Bool -> (Int, Bool)
1715
1716 So the inner binding for ?x::Bool *overrides* the outer one.
1717 Hence a work-item Given overrides an inert-item Given.
1718
1719 Note [Given constraint that matches an instance declaration]
1720 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1721 What should we do when we discover that one (or more) top-level 
1722 instances match a given (or solved) class constraint? We have 
1723 two possibilities:
1724
1725   1. Reject the program. The reason is that there may not be a unique
1726      best strategy for the solver. Example, from the OutsideIn(X) paper:
1727        instance P x => Q [x] 
1728        instance (x ~ y) => R [x] y 
1729      
1730        wob :: forall a b. (Q [b], R b a) => a -> Int 
1731
1732        g :: forall a. Q [a] => [a] -> Int 
1733        g x = wob x 
1734
1735        will generate the impliation constraint: 
1736             Q [a] => (Q [beta], R beta [a]) 
1737        If we react (Q [beta]) with its top-level axiom, we end up with a 
1738        (P beta), which we have no way of discharging. On the other hand, 
1739        if we react R beta [a] with the top-level we get  (beta ~ a), which 
1740        is solvable and can help us rewrite (Q [beta]) to (Q [a]) which is 
1741        now solvable by the given Q [a]. 
1742  
1743      However, this option is restrictive, for instance [Example 3] from 
1744      Note [Recursive dictionaries] will fail to work. 
1745
1746   2. Ignore the problem, hoping that the situations where there exist indeed
1747      such multiple strategies are rare: Indeed the cause of the previous 
1748      problem is that (R [x] y) yields the new work (x ~ y) which can be 
1749      *spontaneously* solved, not using the givens. 
1750
1751 We are choosing option 2 below but we might consider having a flag as well.
1752
1753
1754 Note [New Wanted Superclass Work] 
1755 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1756 Even in the case of wanted constraints, we add all of its superclasses as 
1757 new given work. There are several reasons for this: 
1758      a) to minimise error messages; 
1759         eg suppose we have wanted (Eq a, Ord a)
1760              then we report only (Ord a) unsoluble
1761
1762      b) to make the smallest number of constraints when *inferring* a type
1763         (same Eq/Ord example)
1764
1765      c) for recursive dictionaries we *must* add the superclasses
1766         so that we can use them when solving a sub-problem
1767
1768      d) To allow FD-like improvement for type families. Assume that 
1769         we have a class 
1770              class C a b | a -> b 
1771         and we have to solve the implication constraint: 
1772              C a b => C a beta 
1773         Then, FD improvement can help us to produce a new wanted (beta ~ b) 
1774
1775         We want to have the same effect with the type family encoding of 
1776         functional dependencies. Namely, consider: 
1777              class (F a ~ b) => C a b 
1778         Now suppose that we have: 
1779                given: C a b 
1780                wanted: C a beta 
1781         By interacting the given we will get given (F a ~ b) which is not 
1782         enough by itself to make us discharge (C a beta). However, we 
1783         may create a new derived equality from the super-class of the
1784         wanted constraint (C a beta), namely derived (F a ~ beta). 
1785         Now we may interact this with given (F a ~ b) to get: 
1786                   derived :  beta ~ b 
1787         But 'beta' is a touchable unification variable, and hence OK to 
1788         unify it with 'b', replacing the derived evidence with the identity. 
1789
1790         This requires trySpontaneousSolve to solve *derived*
1791         equalities that have a touchable in their RHS, *in addition*
1792         to solving wanted equalities.
1793
1794 Here is another example where this is useful. 
1795
1796 Example 1:
1797 ----------
1798    class (F a ~ b) => C a b 
1799 And we are given the wanteds:
1800       w1 : C a b 
1801       w2 : C a c 
1802       w3 : b ~ c 
1803 We surely do *not* want to quantify over (b ~ c), since if someone provides
1804 dictionaries for (C a b) and (C a c), these dictionaries can provide a proof 
1805 of (b ~ c), hence no extra evidence is necessary. Here is what will happen: 
1806
1807      Step 1: We will get new *given* superclass work, 
1808              provisionally to our solving of w1 and w2
1809              
1810                g1: F a ~ b, g2 : F a ~ c, 
1811                w1 : C a b, w2 : C a c, w3 : b ~ c
1812
1813              The evidence for g1 and g2 is a superclass evidence term: 
1814
1815                g1 := sc w1, g2 := sc w2
1816
1817      Step 2: The givens will solve the wanted w3, so that 
1818                w3 := sym (sc w1) ; sc w2 
1819                   
1820      Step 3: Now, one may naively assume that then w2 can be solve from w1
1821              after rewriting with the (now solved equality) (b ~ c). 
1822              
1823              But this rewriting is ruled out by the isGoodRectDict! 
1824
1825 Conclusion, we will (correctly) end up with the unsolved goals 
1826     (C a b, C a c)   
1827
1828 NB: The desugarer needs be more clever to deal with equalities 
1829     that participate in recursive dictionary bindings. 
1830
1831 \begin{code}
1832 newSCWorkFromFlavored :: EvVar -> CtFlavor -> Class -> [Xi]
1833                       -> TcS WorkList
1834 newSCWorkFromFlavored ev flavor cls xis
1835   | Given loc <- flavor          -- The NoScSkol says "don't add superclasses"
1836   , NoScSkol <- ctLocOrigin loc  -- Very important!
1837   = return emptyWorkList
1838     
1839   | otherwise
1840   = do { let (tyvars, sc_theta, _, _) = classBigSig cls 
1841              sc_theta1 = substTheta (zipTopTvSubst tyvars xis) sc_theta
1842              -- Add *all* its superclasses (equalities or not) as new given work 
1843              -- See Note [New Wanted Superclass Work] 
1844        ; sc_vars <- zipWithM inst_one sc_theta1 [0..]
1845        ; mkCanonicals flavor sc_vars } 
1846   where
1847     inst_one pred n = newGivOrDerEvVar pred (EvSuperClass ev n)
1848
1849 data LookupInstResult
1850   = NoInstance
1851   | GenInst [WantedEvVar] EvTerm 
1852
1853 matchClassInst :: Class -> [Type] -> WantedLoc -> TcS LookupInstResult
1854 matchClassInst clas tys loc
1855    = do { let pred = mkClassPred clas tys 
1856         ; mb_result <- matchClass clas tys
1857         ; case mb_result of
1858             MatchInstNo   -> return NoInstance
1859             MatchInstMany -> return NoInstance -- defer any reactions of a multitude until 
1860                                                -- we learn more about the reagent 
1861             MatchInstSingle (dfun_id, mb_inst_tys) -> 
1862               do { checkWellStagedDFun pred dfun_id loc
1863
1864         -- It's possible that not all the tyvars are in
1865         -- the substitution, tenv. For example:
1866         --      instance C X a => D X where ...
1867         -- (presumably there's a functional dependency in class C)
1868         -- Hence mb_inst_tys :: Either TyVar TcType 
1869
1870                  ; tys <- instDFunTypes mb_inst_tys 
1871                  ; let (theta, _) = tcSplitPhiTy (applyTys (idType dfun_id) tys)
1872                  ; if null theta then
1873                        return (GenInst [] (EvDFunApp dfun_id tys [])) 
1874                    else do
1875                      { ev_vars <- instDFunConstraints theta
1876                      ; let wevs = [WantedEvVar w loc | w <- ev_vars]
1877                      ; return $ GenInst wevs (EvDFunApp dfun_id tys ev_vars) }
1878                  }
1879         }
1880 \end{code}