TcInteract.lhs 72 KB
Newer Older
1
\begin{code}
Ian Lynagh's avatar
Ian Lynagh committed
2 3 4 5 6 7 8
{-# OPTIONS -fno-warn-tabs #-}
-- The above warning supression flag is a temporary kludge.
-- While working on this module you are encouraged to remove it and
-- detab the module (please do the detabbing in a separate patch). See
--     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#TabsvsSpaces
-- for details

9
module TcInteract ( 
10 11 12
     solveInteractWanted, -- Solves [WantedEvVar]
     solveInteractGiven,  -- Solves [EvVar],GivenLoc
     solveInteractCts,    -- Solves [Cts]
13 14 15 16
  ) where  

#include "HsVersions.h"

17

18
import BasicTypes ()
19 20 21
import TcCanonical
import VarSet
import Type
dimitris's avatar
dimitris committed
22
import Unify
23 24 25

import Id 
import Var
26
import VarEnv ( ) -- unitVarEnv, mkInScopeSet
27 28

import TcType
29
import HsBinds
30

31 32
import Class
import TyCon
33
import Name
34
import IParam
35 36 37 38 39 40

import FunDeps

import Coercion
import Outputable

41
import TcRnTypes
42
import TcErrors
43
import TcSMonad
44
import Maybes( orElse )
45
import Bag
46

47 48 49
import Control.Monad ( foldM )
import TrieMap

50
import Control.Monad( when )
51
import UniqFM
52 53 54
import FastString ( sLit ) 
import DynFlags
\end{code}
55 56
**********************************************************************
*                                                                    * 
57 58 59 60
*                      Main Interaction Solver                       *
*                                                                    *
**********************************************************************

61 62
Note [Basic Simplifier Plan] 
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
63

64 65
1. Pick an element from the WorkList if there exists one with depth 
   less thanour context-stack depth. 
66

67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
2. Run it down the 'stage' pipeline. Stages are: 
      - canonicalization
      - inert reactions
      - spontaneous reactions
      - top-level intreactions
   Each stage returns a StopOrContinue and may have sideffected 
   the inerts or worklist.
  
   The threading of the stages is as follows: 
      - If (Stop) is returned by a stage then we start again from Step 1. 
      - If (ContinueWith ct) is returned by a stage, we feed 'ct' on to 
        the next stage in the pipeline. 
4. If the element has survived (i.e. ContinueWith x) the last stage 
   then we add him in the inerts and jump back to Step 1.

If in Step 1 no such element exists, we have exceeded our context-stack 
depth and will simply fail.
84 85
\begin{code}

86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
solveInteractCts :: [Ct] -> TcS ()
solveInteractCts cts 
  = do { evvar_cache <- getTcSEvVarCacheMap
       ; (cts_thinner, new_evvar_cache) <- add_cts_in_cache evvar_cache cts
       ; traceTcS "solveInteractCts" (vcat [ text "cts_original =" <+> ppr cts, 
                                             text "cts_thinner  =" <+> ppr cts_thinner
                                           ])
       ; setTcSEvVarCacheMap new_evvar_cache 
       ; updWorkListTcS (appendWorkListCt cts_thinner) >> solveInteract }
 
  where add_cts_in_cache evvar_cache = foldM solve_or_cache ([],evvar_cache)
        solve_or_cache :: ([Ct],TypeMap (EvVar,CtFlavor)) 
                       -> Ct
                       -> TcS ([Ct],TypeMap (EvVar,CtFlavor))
        solve_or_cache (acc_cts,acc_cache) ct
          | isIPPred pty
          = return (ct:acc_cts,acc_cache) -- Do not use the cache, 
                                          -- nor update it for IPPreds due to subtle shadowing
          | Just (ev',fl') <- lookupTM pty acc_cache
          , fl' `canSolve` fl
          , isWanted fl
          = do { setEvBind ev (EvId ev')
               ; return (acc_cts,acc_cache) }
          | otherwise -- If it's a given keep it in the work list, even if it exists in the cache!
          = return (ct:acc_cts, alterTM pty (\_ -> Just (ev,fl)) acc_cache)
          where fl = cc_flavor ct
                ev = cc_id ct
                pty = evVarPred ev


solveInteractGiven :: GivenLoc -> [EvVar] -> TcS () 
solveInteractGiven gloc evs
  = solveInteractCts (map mk_noncan evs)
  where mk_noncan ev = CNonCanonical { cc_id = ev
                                     , cc_flavor = Given gloc GivenOrig 
                                     , cc_depth = 0 }

solveInteractWanted :: [WantedEvVar] -> TcS ()
-- Solve these wanteds along with current inerts and wanteds!
solveInteractWanted wevs
  = solveInteractCts (map mk_noncan wevs) 
  where mk_noncan (EvVarX v w) 
          = CNonCanonical { cc_id = v, cc_flavor = Wanted w, cc_depth = 0 }


-- The main solver loop implements Note [Basic Simplifier Plan]
---------------------------------------------------------------
solveInteract :: TcS ()
-- Returns the final InertSet in TcS, WorkList will be eventually empty.
solveInteract
  = do { dyn_flags <- getDynFlags
       ; let max_depth = ctxtStkDepth dyn_flags
             solve_loop
              = do { sel <- selectNextWorkItem max_depth
                   ; case sel of 
                      NoWorkRemaining     -- Done, successfuly (modulo frozen)
                        -> return ()
                      MaxDepthExceeded ct -- Failure, depth exceeded
                        -> solverDepthErrorTcS (cc_depth ct) [ct]
                      NextWorkItem ct     -- More work, loop around!
                        -> runSolverPipeline thePipeline ct >> solve_loop }
       ; solve_loop }

type WorkItem = Ct
type SimplifierStage = WorkItem -> TcS StopOrContinue

continueWith :: WorkItem -> TcS StopOrContinue
continueWith work_item = return (ContinueWith work_item) 

data SelectWorkItem 
       = NoWorkRemaining      -- No more work left (effectively we're done!)
       | MaxDepthExceeded Ct  -- More work left to do but this constraint has exceeded
                              -- the max subgoal depth and we must stop 
       | NextWorkItem Ct      -- More work left, here's the next item to look at 

selectNextWorkItem :: SubGoalDepth -- Max depth allowed
                   -> TcS SelectWorkItem
selectNextWorkItem max_depth
  = updWorkListTcS_return pick_next
165
  where 
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
    pick_next :: WorkList -> (SelectWorkItem, WorkList)
    -- A simple priorititization of equalities (for now)
    -- --------------------------------------------------------
    pick_next wl@(WorkList { wl_eqs = eqs, wl_rest = rest })
      = case (eqs,rest) of
          ([],[])                        -- No more work
              -> (NoWorkRemaining,wl)
          ((ct:cts),_)
            | cc_depth ct > max_depth  -- Depth exceeded
            -> (MaxDepthExceeded ct,wl)
            | otherwise                -- Equality work 
            -> (NextWorkItem ct, wl { wl_eqs = cts })
          ([],(ct:cts))
            | cc_depth ct > max_depth  -- Depth exceeded
            -> (MaxDepthExceeded ct,wl)
            | otherwise                -- Non-equality work
           -> (NextWorkItem ct, wl {wl_rest = cts})

runSolverPipeline :: [(String,SimplifierStage)] -- The pipeline 
                  -> WorkItem                   -- The work item 
                  -> TcS () 
-- Run this item down the pipeline, leaving behind new work and inerts
runSolverPipeline pipeline workItem 
  = do { initial_is <- getTcSInerts 
       ; traceTcS "Start solver pipeline {" $ 
                  vcat [ ptext (sLit "work item = ") <+> ppr workItem 
                       , ptext (sLit "inerts    = ") <+> ppr initial_is]

       ; final_res  <- run_pipeline pipeline (ContinueWith workItem)

       ; final_is <- getTcSInerts
       ; case final_res of 
           Stop            -> do { traceTcS "End solver pipeline (discharged) }" 
                                       (ptext (sLit "inerts    = ") <+> ppr final_is)
                                 ; return () }
           ContinueWith ct -> do { traceTcS "End solver pipeline (not discharged) }" $
                                       vcat [ ptext (sLit "final_item = ") <+> ppr ct
                                            , ptext (sLit "inerts     = ") <+> ppr final_is]
                                 ; updInertSetTcS ct }
       }
  where run_pipeline :: [(String,SimplifierStage)] -> StopOrContinue -> TcS StopOrContinue
        run_pipeline [] res = return res 
        run_pipeline _ Stop = return Stop 
        run_pipeline ((stg_name,stg):stgs) (ContinueWith ct)
          = do { traceTcS ("runStage " ++ stg_name ++ " {")
                          (text "workitem   = " <+> ppr ct) 
               ; res <- stg ct 
               ; traceTcS ("end stage " ++ stg_name ++ " }") empty
               ; run_pipeline stgs res 
               }
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
\end{code}

Example 1:
  Inert:   {c ~ d, F a ~ t, b ~ Int, a ~ ty} (all given)
  Reagent: a ~ [b] (given)

React with (c~d)     ==> IR (ContinueWith (a~[b]))  True    []
React with (F a ~ t) ==> IR (ContinueWith (a~[b]))  False   [F [b] ~ t]
React with (b ~ Int) ==> IR (ContinueWith (a~[Int]) True    []

Example 2:
  Inert:  {c ~w d, F a ~g t, b ~w Int, a ~w ty}
  Reagent: a ~w [b]

React with (c ~w d)   ==> IR (ContinueWith (a~[b]))  True    []
React with (F a ~g t) ==> IR (ContinueWith (a~[b]))  True    []    (can't rewrite given with wanted!)
etc.

Example 3:
  Inert:  {a ~ Int, F Int ~ b} (given)
  Reagent: F a ~ b (wanted)

React with (a ~ Int)   ==> IR (ContinueWith (F Int ~ b)) True []
React with (F Int ~ b) ==> IR Stop True []    -- after substituting we re-canonicalize and get nothing

\begin{code}
242 243 244 245 246 247 248 249 250 251
thePipeline :: [(String,SimplifierStage)]
thePipeline = [ ("canonicalization",        canonicalizationStage)
                -- If ContinueWith, will be canonical and fully rewritten wrt inert eqs
              , ("interact the inert eqs", interactWithInertEqsStage)
                -- If ContinueWith, will be wanted/derived eq or non-eq
                -- but can't rewrite not can be rewritten by the inerts
              , ("spontaneous solve",       spontaneousSolveStage)
                -- If ContinueWith its not spontaneously solved equality
              , ("interact with inerts",    interactWithInertsStage)
              , ("top-level reactions",     topReactionsStage) ]
252 253 254 255
\end{code}


\begin{code}
256

257 258 259 260
-- The canonicalization stage, see TcCanonical for details
----------------------------------------------------------
canonicalizationStage :: SimplifierStage
canonicalizationStage = TcCanonical.canonicalize 
261

262 263 264 265 266 267 268 269
\end{code}

*********************************************************************************
*                                                                               * 
                       The spontaneous-solve Stage
*                                                                               *
*********************************************************************************

270 271 272 273 274 275
Note [Efficient Orientation] 
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

There are two cases where we have to be careful about 
orienting equalities to get better efficiency. 

276
Case 1: In Rewriting Equalities (function rewriteEqLHS) 
277

278 279 280 281 282 283 284 285 286 287
    When rewriting two equalities with the same LHS:
          (a)  (tv ~ xi1) 
          (b)  (tv ~ xi2) 
    We have a choice of producing work (xi1 ~ xi2) (up-to the
    canonicalization invariants) However, to prevent the inert items
    from getting kicked out of the inerts first, we prefer to
    canonicalize (xi1 ~ xi2) if (b) comes from the inert set, or (xi2
    ~ xi1) if (a) comes from the inert set.
    
    This choice is implemented using the WhichComesFromInert flag. 
288

289 290 291 292 293
Case 2: Functional Dependencies 
    Again, we should prefer, if possible, the inert variables on the RHS

Case 3: IP improvement work
    We must always rewrite so that the inert type is on the right. 
294

295 296
\begin{code}
spontaneousSolveStage :: SimplifierStage 
297
spontaneousSolveStage workItem
298
  = do { mSolve <- trySpontaneousSolve workItem
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
       ; spont_solve mSolve } 
  where spont_solve SPCantSolve = continueWith workItem 
        spont_solve (SPSolved workItem')
          = do { bumpStepCountTcS
               ; traceFireTcS (cc_depth workItem) $
                 ptext (sLit "Spontaneous") 
                           <+> parens (ppr (cc_flavor workItem)) <+> ppr workItem
               -- If original was /not/ given we may have to kick out now-rewritable inerts
               ; when (not (isGivenOrSolvedCt workItem)) $
                 kickOutRewritableInerts workItem'
               -- Add solved guy in inerts anyway
               ; updInertSetTcS workItem'
               -- .. and Stop 
               ; return Stop }

kickOutRewritableInerts :: Ct -> TcS () 
-- Pre:  ct is a CTyEqCan 
-- Post: the TcS monad is left with the thinner non-rewritable inerts; the 
--       rewritable end up in the worklist
kickOutRewritableInerts ct 
  = do { wl <- modifyInertTcS (kick_out_rewritable ct)

         -- Rewrite the rewritable solved on the spot and stick them back in the inerts

{- DV: I am commenting out the solved story altogether because I did not see any performance
       improvement compared to just kicking out the solved ones any way. In fact there were
       situations where performance got worse.

       ; let subst = unitVarEnv (cc_tyvar ct) (ct, mkEqVarLCo (cc_id ct))
             inscope = mkInScopeSet $ tyVarsOfCt ct
       ; solved_rewritten <- mapBagM (rewrite_solved (subst,inscope)) solved_out
       ; _unused <- modifyInertTcS (add_new_solveds solved_rewritten)
      
-}
       ; traceTcS "Kick out" (ppr ct $$ ppr wl)
       ; updWorkListTcS (unionWorkList wl) }
{- 
  where rewrite_solved inert_eqs solved_ct 
          = do { (new_ev,_) <- rewriteFromInertEqs inert_eqs fl ev
               ; mk_canonical new_ev }
          where fl = cc_flavor solved_ct
                ev = cc_id solved_ct
                d  = cc_depth solved_ct
                mk_canonical new_ev
                  -- A bit of an overkill to call the canonicalizer, but ok ...
                  = do { let new_pty = evVarPred new_ev
                       ; r <- canEvVar new_ev (classifyPredType new_pty) d fl
                       ; case r of
                           Stop -> pprPanic "kickOutRewritableInerts" $ 
                                   vcat [ text "Should never Stop, solved constraint IS canonical!"
                                        , text "Orig (solved)     =" <+> ppr solved_ct
                                        , text "Rewritten (solved)=" <+> ppr new_pty ]
                           ContinueWith ct -> return ct }
        add_new_solveds cts is = ((), is { inert_solved = new_solved })
           where orig_solveds     = inert_solved is
                 do_one slvmap ct = let ct_key = mkPredKeyForTypeMap ct
                                    in alterTM ct_key (\_ -> Just ct) slvmap
                 new_solved       = foldlBag do_one orig_solveds cts
-}
358

359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
kick_out_rewritable :: Ct -> InertSet -> (WorkList,InertSet)
kick_out_rewritable ct (IS { inert_eqs    = eqmap
                           , inert_eq_tvs = inscope
                           , inert_dicts  = dictmap
                           , inert_ips    = ipmap
                           , inert_funeqs = funeqmap
                           , inert_irreds = irreds
                           , inert_frozen = frozen
                           } )
  = (kicked_out, remaining)
  where

    kicked_out = WorkList { wl_eqs  = eqs_out ++ bagToList feqs_out
                          , wl_rest = bagToList (fro_out `andCts` dicts_out 
                                        `andCts` ips_out `andCts` irs_out) }
  
    remaining = IS { inert_eqs = eqs_in
                   , inert_eq_tvs = inscope -- keep the same, safe and cheap
                   , inert_dicts = dicts_in
                   , inert_ips = ips_in
                   , inert_funeqs = feqs_in
                   , inert_irreds = irs_in
                   , inert_frozen = fro_in 
                   }

    fl = cc_flavor ct
    tv = cc_tyvar ct

    (eqs_out,   eqs_in)   = partitionEqMap rewritable eqmap
    (ips_out,   ips_in)   = partitionCCanMap rewritable ipmap 

    (feqs_out,  feqs_in)  = partitionCtTypeMap rewritable funeqmap
    (dicts_out, dicts_in) = partitionCCanMap rewritable dictmap

    (irs_out,   irs_in)   = partitionBag rewritable irreds
    (fro_out,   fro_in)   = partitionBag rewritable frozen
    rewritable ct = (fl `canRewrite` cc_flavor ct) && 
                    (tv `elemVarSet` tyVarsOfCt ct)


                             
data SPSolveResult = SPCantSolve
                   | SPSolved WorkItem 
402

403 404 405
-- SPCantSolve means that we can't do the unification because e.g. the variable is untouchable
-- SPSolved workItem' gives us a new *given* to go on 

406
-- @trySpontaneousSolve wi@ solves equalities where one side is a
407
-- touchable unification variable.
408
--     	    See Note [Touchables and givens] 
409
trySpontaneousSolve :: WorkItem -> TcS SPSolveResult
410 411
trySpontaneousSolve workItem@(CTyEqCan { cc_id = eqv, cc_flavor = gw
                                       , cc_tyvar = tv1, cc_rhs = xi, cc_depth = d })
dimitris's avatar
dimitris committed
412
  | isGivenOrSolved gw
413
  = return SPCantSolve
414 415 416 417
  | Just tv2 <- tcGetTyVar_maybe xi
  = do { tch1 <- isTouchableMetaTyVar tv1
       ; tch2 <- isTouchableMetaTyVar tv2
       ; case (tch1, tch2) of
418 419 420
           (True,  True)  -> trySpontaneousEqTwoWay d eqv gw tv1 tv2
           (True,  False) -> trySpontaneousEqOneWay d eqv gw tv1 xi
           (False, True)  -> trySpontaneousEqOneWay d eqv gw tv2 (mkTyVarTy tv1)
421
	   _ -> return SPCantSolve }
422 423
  | otherwise
  = do { tch1 <- isTouchableMetaTyVar tv1
424 425 426
       ; if tch1 then trySpontaneousEqOneWay d eqv gw tv1 xi
                 else do { traceTcS "Untouchable LHS, can't spontaneously solve workitem:" $
                           ppr workItem 
427
                         ; return SPCantSolve }
428
       }
429 430 431 432

  -- No need for 
  --      trySpontaneousSolve (CFunEqCan ...) = ...
  -- See Note [No touchables as FunEq RHS] in TcSMonad
433
trySpontaneousSolve _ = return SPCantSolve
434 435

----------------
436 437
trySpontaneousEqOneWay :: SubGoalDepth 
                       -> EqVar -> CtFlavor -> TcTyVar -> Xi -> TcS SPSolveResult
438
-- tv is a MetaTyVar, not untouchable
439
trySpontaneousEqOneWay d eqv gw tv xi	
440
  | not (isSigTyVar tv) || isTyVarTy xi 
441 442
  = do { let kxi = typeKind xi -- NB: 'xi' is fully rewritten according to the inerts 
                               -- so we have its more specific kind in our hands
dreixel's avatar
dreixel committed
443 444
       ; is_sub_kind <- kxi `isSubKindTcS` tyVarKind tv
       ; if is_sub_kind then
445
             solveWithIdentity d eqv gw tv xi
446
         else return SPCantSolve
447
       }
448
  | otherwise -- Still can't solve, sig tyvar and non-variable rhs
449
  = return SPCantSolve
450 451

----------------
452 453
trySpontaneousEqTwoWay :: SubGoalDepth 
                       -> EqVar -> CtFlavor -> TcTyVar -> TcTyVar -> TcS SPSolveResult
454
-- Both tyvars are *touchable* MetaTyvars so there is only a chance for kind error here
455 456

trySpontaneousEqTwoWay d eqv gw tv1 tv2
dreixel's avatar
dreixel committed
457 458
  = do { k1_sub_k2 <- k1 `isSubKindTcS` k2
       ; if k1_sub_k2 && nicer_to_update_tv2
459
         then solveWithIdentity d eqv gw tv2 (mkTyVarTy tv1)
dreixel's avatar
dreixel committed
460 461 462
         else do
       { k2_sub_k1 <- k2 `isSubKindTcS` k1
       ; MASSERT( k2_sub_k1 )  -- they were unified in TcCanonical
463
       ; solveWithIdentity d eqv gw tv1 (mkTyVarTy tv2) } }
464 465 466 467
  where
    k1 = tyVarKind tv1
    k2 = tyVarKind tv2
    nicer_to_update_tv2 = isSigTyVar tv1 || isSystemName (Var.varName tv2)
dreixel's avatar
dreixel committed
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
{-
-- Previous code below (before kind polymorphism and unification):
  -- | k1 `isSubKind` k2
  -- , nicer_to_update_tv2 = solveWithIdentity eqv gw tv2 (mkTyVarTy tv1)
  -- | k2 `isSubKind` k1 
  -- = solveWithIdentity eqv gw tv1 (mkTyVarTy tv2)
  -- | otherwise -- None is a subkind of the other, but they are both touchable! 
  -- = return SPCantSolve
  --   -- do { addErrorTcS KindError gw (mkTyVarTy tv1) (mkTyVarTy tv2)
  --   --   ; return SPError }
  -- where
  --   k1 = tyVarKind tv1
  --   k2 = tyVarKind tv2
  --   nicer_to_update_tv2 = isSigTyVar tv1 || isSystemName (Var.varName tv2)
-}
483 484
\end{code}

485 486 487 488
Note [Kind errors] 
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider the wanted problem: 
      alpha ~ (# Int, Int #) 
489
where alpha :: ArgKind and (# Int, Int #) :: (#). We can't spontaneously solve this constraint, 
490
but we should rather reject the program that give rise to it. If 'trySpontaneousEqTwoWay' 
491
simply returns @CantSolve@ then that wanted constraint is going to propagate all the way and 
492
get quantified over in inference mode. That's bad because we do know at this point that the 
493
constraint is insoluble. Instead, we call 'recKindErrorTcS' here, which will fail later on.
494 495

The same applies in canonicalization code in case of kind errors in the givens. 
496

497
However, when we canonicalize givens we only check for compatibility (@compatKind@). 
498
If there were a kind error in the givens, this means some form of inconsistency or dead code.
499

500 501 502 503 504
You may think that when we spontaneously solve wanteds we may have to look through the 
bindings to determine the right kind of the RHS type. E.g one may be worried that xi is 
@alpha@ where alpha :: ? and a previous spontaneous solving has set (alpha := f) with (f :: *).
But we orient our constraints so that spontaneously solved ones can rewrite all other constraint
so this situation can't happen. 
505

506 507
Note [Spontaneous solving and kind compatibility] 
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
508 509 510
Note that our canonical constraints insist that *all* equalities (tv ~
xi) or (F xis ~ rhs) require the LHS and the RHS to have *compatible*
the same kinds.  ("compatible" means one is a subKind of the other.)
511

512 513 514 515 516 517 518 519 520 521 522 523 524 525
  - It can't be *equal* kinds, because
     b) wanted constraints don't necessarily have identical kinds
               eg   alpha::? ~ Int
     b) a solved wanted constraint becomes a given

  - SPJ thinks that *given* constraints (tv ~ tau) always have that
    tau has a sub-kind of tv; and when solving wanted constraints
    in trySpontaneousEqTwoWay we re-orient to achieve this.

  - Note that the kind invariant is maintained by rewriting.
    Eg wanted1 rewrites wanted2; if both were compatible kinds before,
       wanted2 will be afterwards.  Similarly givens.

Caveat:
526 527 528 529 530 531 532 533 534
  - Givens from higher-rank, such as: 
          type family T b :: * -> * -> * 
          type instance T Bool = (->) 

          f :: forall a. ((T a ~ (->)) => ...) -> a -> ... 
          flop = f (...) True 
     Whereas we would be able to apply the type instance, we would not be able to 
     use the given (T Bool ~ (->)) in the body of 'flop' 

535 536 537 538 539 540 541

Note [Avoid double unifications] 
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The spontaneous solver has to return a given which mentions the unified unification
variable *on the left* of the equality. Here is what happens if not: 
  Original wanted:  (a ~ alpha),  (alpha ~ Int) 
We spontaneously solve the first wanted, without changing the order! 
542
      given : a ~ alpha      [having unified alpha := a] 
543 544 545
Now the second wanted comes along, but he cannot rewrite the given, so we simply continue.
At the end we spontaneously solve that guy, *reunifying*  [alpha := Int] 

546
We avoid this problem by orienting the resulting given so that the unification
547 548
variable is on the left.  [Note that alternatively we could attempt to
enforce this at canonicalization]
549

550 551 552
See also Note [No touchables as FunEq RHS] in TcSMonad; avoiding
double unifications is the main reason we disallow touchable
unification variables as RHS of type family equations: F xis ~ alpha.
553 554 555

\begin{code}
----------------
556

557 558
solveWithIdentity :: SubGoalDepth 
                  -> EqVar -> CtFlavor -> TcTyVar -> Xi -> TcS SPSolveResult
559 560
-- Solve with the identity coercion 
-- Precondition: kind(xi) is a sub-kind of kind(tv)
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
561 562 563
-- Precondition: CtFlavor is Wanted or Derived
-- See [New Wanted Superclass Work] to see why solveWithIdentity 
--     must work for Derived as well as Wanted
564
-- Returns: workItem where 
565
--        workItem = the new Given constraint
566
solveWithIdentity d eqv wd tv xi 
567 568
  = do { traceTcS "Sneaky unification:" $ 
                       vcat [text "Coercion variable:  " <+> ppr wd, 
569 570 571
                             text "Coercion:           " <+> pprEq (mkTyVarTy tv) xi,
                             text "Left  Kind is     : " <+> ppr (typeKind (mkTyVarTy tv)),
                             text "Right Kind is     : " <+> ppr (typeKind xi)
572
                            ]
573

574
       ; setWantedTyBind tv xi
575
       ; let refl_xi = mkReflCo xi
576 577 578

       ; let solved_fl = mkSolvedFlavor wd UnkSkol 
       ; eqv_given <- newGivenEqVar solved_fl (mkTyVarTy tv) xi refl_xi
579

batterseapower's avatar
batterseapower committed
580
       ; when (isWanted wd) (setEqBind eqv refl_xi)
581
           -- We don't want to do this for Derived, that's why we use 'when (isWanted wd)'
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604
       ; return $ SPSolved (CTyEqCan { cc_id     = eqv_given
                                     , cc_flavor = solved_fl
                                     , cc_tyvar  = tv, cc_rhs = xi, cc_depth = d }) }
\end{code}

*********************************************************************************
*                                                                               *
*                         Interact with inert equalities                        *
*                                                                               *
*********************************************************************************

\begin{code}

interactWithInertEqsStage  :: WorkItem -> TcS StopOrContinue
interactWithInertEqsStage  ct 
  | isCTyEqCan ct
  = do { kickOutRewritableInerts ct
       ; if isGivenOrSolved (cc_flavor ct) then updInertSetTcS ct >> return Stop
         else continueWith ct } -- If wanted or derived we may spontaneously solve him
  | isCNonCanonical ct
  = pprPanic "Interact with inerts eqs stage met non-canonical constraint!" (ppr ct)
  | otherwise
  = continueWith ct
605 606 607 608 609 610 611 612 613
\end{code}


*********************************************************************************
*                                                                               * 
                       The interact-with-inert Stage
*                                                                               *
*********************************************************************************

614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638
Note [The Solver Invariant]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
We always add Givens first.  So you might think that the solver has
the invariant

   If the work-item is Given, 
   then the inert item must Given

But this isn't quite true.  Suppose we have, 
    c1: [W] beta ~ [alpha], c2 : [W] blah, c3 :[W] alpha ~ Int
After processing the first two, we get
     c1: [G] beta ~ [alpha], c2 : [W] blah
Now, c3 does not interact with the the given c1, so when we spontaneously
solve c3, we must re-react it with the inert set.  So we can attempt a 
reaction between inert c2 [W] and work-item c3 [G].

It *is* true that [Solver Invariant]
   If the work-item is Given, 
   AND there is a reaction
   then the inert item must Given
or, equivalently,
   If the work-item is Given, 
   and the inert item is Wanted/Derived
   then there is no reaction

639 640 641
\begin{code}
-- Interaction result of  WorkItem <~> AtomicInert

642 643 644 645
data InteractResult 
    = IRWorkItemConsumed { ir_fire :: String } 
    | IRInertConsumed    { ir_fire :: String } 
    | IRKeepGoing        { ir_fire :: String }
646

647 648
irWorkItemConsumed :: String -> TcS InteractResult
irWorkItemConsumed str = return (IRWorkItemConsumed str) 
649

650 651
irInertConsumed :: String -> TcS InteractResult
irInertConsumed str = return (IRInertConsumed str) 
652

653 654 655 656
irKeepGoing :: String -> TcS InteractResult 
irKeepGoing str = return (IRKeepGoing str) 
-- You can't discard neither workitem or inert, but you must keep 
-- going. It's possible that new work is waiting in the TcS worklist. 
657 658


659 660 661 662
interactWithInertsStage :: WorkItem -> TcS StopOrContinue 
-- Precondition: if the workitem is a CTyEqCan then it will not be able to 
-- react with anything at this stage. 
interactWithInertsStage wi 
663
  = do { ctxt <- getTcSContext
664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694
       ; if simplEqsOnly ctxt then 
             return (ContinueWith wi)
         else 
             extractRelevantInerts wi >>= 
               foldlBagM interact_next (ContinueWith wi) }

  where interact_next Stop atomic_inert 
          = updInertSetTcS atomic_inert >> return Stop
        interact_next (ContinueWith wi) atomic_inert 
          = do { ir <- doInteractWithInert atomic_inert wi
               ; let mk_msg rule keep_doc 
                       = text rule <+> keep_doc
      	                 <+> vcat [ ptext (sLit "Inert =") <+> ppr atomic_inert
      	                          , ptext (sLit "Work =")  <+> ppr wi ]
               ; case ir of 
                   IRWorkItemConsumed { ir_fire = rule } 
                       -> do { bumpStepCountTcS
                             ; traceFireTcS (cc_depth wi) 
                                            (mk_msg rule (text "WorkItemConsumed"))
                             ; updInertSetTcS atomic_inert
                             ; return Stop } 
                   IRInertConsumed { ir_fire = rule }
                       -> do { bumpStepCountTcS
                             ; traceFireTcS (cc_depth atomic_inert) 
                                            (mk_msg rule (text "InertItemConsumed"))
                             ; return (ContinueWith wi) }
                   IRKeepGoing {} -- Should we do a bumpStepCountTcS? No for now.
                       -> do { updInertSetTcS atomic_inert
                             ; return (ContinueWith wi) }
               }
   
695
--------------------------------------------
696
data WhichComesFromInert = LeftComesFromInert | RightComesFromInert
697

698 699
doInteractWithInert :: Ct -> Ct -> TcS InteractResult
-- Identical class constraints.
700
doInteractWithInert
701
  inertItem@(CDictCan { cc_id = d1, cc_flavor = fl1, cc_class = cls1, cc_tyargs = tys1 }) 
702
   workItem@(CDictCan { cc_id = _d2, cc_flavor = fl2, cc_class = cls2, cc_tyargs = tys2 })
703

704
  | cls1 == cls2  
batterseapower's avatar
batterseapower committed
705 706
  = do { let pty1 = mkClassPred cls1 tys1
             pty2 = mkClassPred cls2 tys2
707
             inert_pred_loc     = (pty1, pprFlavorArising fl1)
708
             work_item_pred_loc = (pty2, pprFlavorArising fl2)
709

710 711 712
       ; traceTcS "doInteractWithInert" (vcat [ text "inertItem = " <+> ppr inertItem
                                              , text "workItem  = " <+> ppr workItem ])

713 714 715 716 717 718 719 720 721 722 723 724 725 726 727
       ; any_fundeps 
           <- if isGivenOrSolved fl1 && isGivenOrSolved fl2 then return Nothing
              -- NB: We don't create fds for given (and even solved), have not seen a useful
              -- situation for these and even if we did we'd have to be very careful to only
              -- create Derived's and not Wanteds. 

              else let fd_eqns = improveFromAnother inert_pred_loc work_item_pred_loc
                       wloc    = get_workitem_wloc fl2 
                   in rewriteWithFunDeps fd_eqns tys2 wloc
                      -- See Note [Efficient Orientation], [When improvement happens]

       ; case any_fundeps of
           -- No Functional Dependencies 
           Nothing             
               | eqTypes tys1 tys2 -> solveOneFromTheOther "Cls/Cls" (EvId d1,fl1) workItem
728
               | otherwise         -> irKeepGoing "NOP"
729 730

           -- Actual Functional Dependencies
731 732
           Just (_rewritten_tys2,_cos2,fd_work)
              -- Standard thing: create derived fds and keep on going. Importantly we don't
733
               -- throw workitem back in the worklist because this can cause loops. See #5236.
734 735
               -> do { emitFDWorkAsDerived fd_work (cc_depth workItem)
                     ; irKeepGoing "Cls/Cls (new fundeps)" } -- Just keep going without droping the inert 
736 737 738 739 740
       }
  where get_workitem_wloc (Wanted wl)  = wl 
        get_workitem_wloc (Derived wl) = wl 
        get_workitem_wloc (Given {})   = panic "Unexpected given!"

741

742 743 744 745 746 747 748 749
-- Two pieces of irreducible evidence: if their types are *exactly identical* we can
-- rewrite them. We can never improve using this: if we want ty1 :: Constraint and have
-- ty2 :: Constraint it clearly does not mean that (ty1 ~ ty2)
doInteractWithInert (CIrredEvCan { cc_id = id1, cc_flavor = ifl, cc_ty = ty1 })
           workItem@(CIrredEvCan { cc_ty = ty2 })
  | ty1 `eqType` ty2
  = solveOneFromTheOther "Irred/Irred" (EvId id1,ifl) workItem

750 751 752 753 754
-- Two implicit parameter constraints.  If the names are the same,
-- but their types are not, we generate a wanted type equality 
-- that equates the type (this is "improvement").  
-- However, we don't actually need the coercion evidence,
-- so we just generate a fresh coercion variable that isn't used anywhere.
755
doInteractWithInert (CIPCan { cc_id = id1, cc_flavor = ifl, cc_ip_nm = nm1, cc_ip_ty = ty1 }) 
756
           workItem@(CIPCan { cc_flavor = wfl, cc_ip_nm = nm2, cc_ip_ty = ty2 })
dimitris's avatar
dimitris committed
757
  | nm1 == nm2 && isGivenOrSolved wfl && isGivenOrSolved ifl
758 759 760
  = 	-- See Note [Overriding implicit parameters]
        -- Dump the inert item, override totally with the new one
	-- Do not require type equality
761 762
	-- For example, given let ?x::Int = 3 in let ?x::Bool = True in ...
	--              we must *override* the outer one with the inner one
763
    irInertConsumed "IP/IP (override inert)"
764

765
  | nm1 == nm2 && ty1 `eqType` ty2 
766
  = solveOneFromTheOther "IP/IP" (EvId id1,ifl) workItem 
767

768
  | nm1 == nm2
769
  =  	-- See Note [When improvement happens]
770 771 772 773 774 775 776 777
    do { let flav = Wanted (combineCtLoc ifl wfl)
       ; eqv <- newEqVar flav ty2 ty1 -- See Note [Efficient Orientation]
       ; when (isNewEvVar eqv) $
              (let ct = CNonCanonical { cc_id     = evc_the_evvar eqv 
                                      , cc_flavor = flav
                                      , cc_depth  = cc_depth workItem }
              in updWorkListTcS (extendWorkListEq ct))

778 779 780 781
       ; case wfl of
           Given   {} -> pprPanic "Unexpected given IP" (ppr workItem)
           Derived {} -> pprPanic "Unexpected derived IP" (ppr workItem)
           Wanted  {} ->
782 783 784 785
               do { setEvBind (cc_id workItem) $ 
                    mkEvCast id1 (mkSymCo (mkTyConAppCo (ipTyCon nm1) [mkEqVarLCo (evc_the_evvar eqv)]))
                    -- DV: Changing: used to be (mkSymCo (mkEqVarLCo eqv))
                  ; irWorkItemConsumed "IP/IP (solved by rewriting)" } }
786

batterseapower's avatar
batterseapower committed
787
doInteractWithInert (CFunEqCan { cc_id = eqv1, cc_flavor = fl1, cc_fun = tc1
788 789 790 791 792 793 794 795 796 797 798 799 800
                               , cc_tyargs = args1, cc_rhs = xi1, cc_depth = d1 }) 
                    (CFunEqCan { cc_id = eqv2, cc_flavor = fl2, cc_fun = tc2
                               , cc_tyargs = args2, cc_rhs = xi2, cc_depth = d2 })
  | lhss_match  
  , Just GivenSolved <- isGiven_maybe fl1 -- Inert is solved and we can simply ignore it
                                          -- when workitem is given/solved
  , isGivenOrSolved fl2
  = irInertConsumed "FunEq/FunEq"
  | lhss_match 
  , Just GivenSolved <- isGiven_maybe fl2 -- Workitem is solved and we can ignore it when
                                          -- the inert is given/solved
  , isGivenOrSolved fl1                 
  = irWorkItemConsumed "FunEq/FunEq" 
801
  | fl1 `canSolve` fl2 && lhss_match
802 803 804
  = do { rewriteEqLHS LeftComesFromInert  (eqv1,xi1) (eqv2,d2,fl2,xi2) 
       ; irWorkItemConsumed "FunEq/FunEq" }

805
  | fl2 `canSolve` fl1 && lhss_match
806 807
  = do { rewriteEqLHS RightComesFromInert (eqv2,xi2) (eqv1,d1,fl1,xi1) 
       ; irInertConsumed "FunEq/FunEq"}
808
  where
809
    lhss_match = tc1 == tc2 && eqTypes args1 args2 
810 811


812 813 814 815
doInteractWithInert _ _ = irKeepGoing "NOP"


rewriteEqLHS :: WhichComesFromInert -> (EqVar,Xi) -> (EqVar,SubGoalDepth,CtFlavor,Xi) -> TcS ()
816
-- Used to ineract two equalities of the following form: 
817 818
-- First Equality:   co1: (XXX ~ xi1)  
-- Second Equality:  cv2: (XXX ~ xi2) 
819
-- Where the cv1 `canRewrite` cv2 equality 
820 821
-- We have an option of creating new work (xi1 ~ xi2) OR (xi2 ~ xi1), 
--    See Note [Efficient Orientation] for that 
822 823 824 825
rewriteEqLHS LeftComesFromInert (eqv1,xi1) (eqv2,d,gw,xi2) 
  = do { delCachedEvVar eqv2 -- Similarly to canonicalization!
       ; evc <- newEqVar gw xi2 xi1
       ; let eqv2' = evc_the_evvar evc
826
       ; case gw of 
827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843
           Wanted {} 
               -> setEqBind eqv2 $ 
                  mkEqVarLCo eqv1 `mkTransCo` mkSymCo (mkEqVarLCo eqv2')
           Given {}  
               -> setEqBind eqv2' $ 
                  mkSymCo (mkEqVarLCo eqv2) `mkTransCo` mkEqVarLCo eqv1
           Derived {} 
               -> return ()
       ; when (isNewEvVar evc) $ 
              updWorkListTcS (extendWorkListEq (CNonCanonical { cc_id     = eqv2'
                                                              , cc_flavor = gw
                                                              , cc_depth  = d } ) ) }

rewriteEqLHS RightComesFromInert (eqv1,xi1) (eqv2,d,gw,xi2) 
  = do { delCachedEvVar eqv2 -- Similarly to canonicalization!
       ; evc <- newEqVar gw xi1 xi2
       ; let eqv2' = evc_the_evvar evc
844
       ; case gw of
845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866
           Wanted {} 
               -> setEqBind eqv2 $ 
                  mkEqVarLCo eqv1 `mkTransCo` mkEqVarLCo eqv2'
           Given {}  
               -> setEqBind eqv2' $
                  mkSymCo (mkEqVarLCo eqv1) `mkTransCo` mkEqVarLCo eqv2
           Derived {} 
               -> return ()

       ; when (isNewEvVar evc) $
              updWorkListTcS (extendWorkListEq (CNonCanonical { cc_id = eqv2'
                                                              , cc_flavor = gw
                                                              , cc_depth  = d } ) ) }

solveOneFromTheOther :: String             -- Info 
                     -> (EvTerm, CtFlavor) -- Inert 
                     -> Ct        -- WorkItem 
                     -> TcS InteractResult
-- Preconditions: 
-- 1) inert and work item represent evidence for the /same/ predicate
-- 2) ip/class/irred evidence (no coercions) only
solveOneFromTheOther info (ev_term,ifl) workItem
867
  | isDerived wfl
868
  = irWorkItemConsumed ("Solved[DW] " ++ info)
869

870 871 872
  | isDerived ifl -- The inert item is Derived, we can just throw it away, 
    	      	  -- The workItem is inert wrt earlier inert-set items, 
		  -- so it's safe to continue on from this point
873
  = irInertConsumed ("Solved[DI] " ++ info)
874
  
dimitris's avatar
dimitris committed
875 876
  | Just GivenSolved <- isGiven_maybe ifl, isGivenOrSolved wfl
    -- Same if the inert is a GivenSolved -- just get rid of it
877
  = irInertConsumed ("Solved[SI] " ++ info)
dimitris's avatar
dimitris committed
878

879 880 881 882 883 884
  | otherwise
  = ASSERT( ifl `canSolve` wfl )
      -- Because of Note [The Solver Invariant], plus Derived dealt with
    do { when (isWanted wfl) $ setEvBind wid ev_term
           -- Overwrite the binding, if one exists
	   -- If both are Given, we already have evidence; no need to duplicate
885
       ; irWorkItemConsumed ("Solved " ++ info) }
886 887 888
  where 
     wfl = cc_flavor workItem
     wid = cc_id workItem
889

890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906
\end{code}

Note [Superclasses and recursive dictionaries]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Overlaps with Note [SUPERCLASS-LOOP 1]
                  Note [SUPERCLASS-LOOP 2]
                  Note [Recursive instances and superclases]
    ToDo: check overlap and delete redundant stuff

Right before adding a given into the inert set, we must
produce some more work, that will bring the superclasses 
of the given into scope. The superclass constraints go into 
our worklist. 

When we simplify a wanted constraint, if we first see a matching
instance, we may produce new wanted work. To (1) avoid doing this work 
twice in the future and (2) to handle recursive dictionaries we may ``cache'' 
907 908 909
this item as given into our inert set WITHOUT adding its superclass constraints, 
otherwise we'd be in danger of creating a loop [In fact this was the exact reason
for doing the isGoodRecEv check in an older version of the type checker]. 
910 911 912 913 914 915 916 917 918 919

But now we have added partially solved constraints to the worklist which may 
interact with other wanteds. Consider the example: 

Example 1: 

    class Eq b => Foo a b        --- 0-th selector
    instance Eq a => Foo [a] a   --- fooDFun

and wanted (Foo [t] t). We are first going to see that the instance matches 
920
and create an inert set that includes the solved (Foo [t] t) but not its superclasses:
921 922 923 924
       d1 :_g Foo [t] t                 d1 := EvDFunApp fooDFun d3 
Our work list is going to contain a new *wanted* goal
       d3 :_w Eq t 

925
Ok, so how do we get recursive dictionaries, at all: 
926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239

Example 2:

    data D r = ZeroD | SuccD (r (D r));
    
    instance (Eq (r (D r))) => Eq (D r) where
        ZeroD     == ZeroD     = True
        (SuccD a) == (SuccD b) = a == b
        _         == _         = False;
    
    equalDC :: D [] -> D [] -> Bool;
    equalDC = (==);

We need to prove (Eq (D [])). Here's how we go:

	d1 :_w Eq (D [])

by instance decl, holds if
	d2 :_w Eq [D []]
	where 	d1 = dfEqD d2

*BUT* we have an inert set which gives us (no superclasses): 
        d1 :_g Eq (D []) 
By the instance declaration of Eq we can show the 'd2' goal if 
	d3 :_w Eq (D [])
	where	d2 = dfEqList d3
		d1 = dfEqD d2
Now, however this wanted can interact with our inert d1 to set: 
        d3 := d1 
and solve the goal. Why was this interaction OK? Because, if we chase the 
evidence of d1 ~~> dfEqD d2 ~~-> dfEqList d3, so by setting d3 := d1 we 
are really setting
        d3 := dfEqD2 (dfEqList d3) 
which is FINE because the use of d3 is protected by the instance function 
applications. 

So, our strategy is to try to put solved wanted dictionaries into the
inert set along with their superclasses (when this is meaningful,
i.e. when new wanted goals are generated) but solve a wanted dictionary
from a given only in the case where the evidence variable of the
wanted is mentioned in the evidence of the given (recursively through
the evidence binds) in a protected way: more instance function applications 
than superclass selectors.

Here are some more examples from GHC's previous type checker


Example 3: 
This code arises in the context of "Scrap Your Boilerplate with Class"

    class Sat a
    class Data ctx a
    instance  Sat (ctx Char)             => Data ctx Char       -- dfunData1
    instance (Sat (ctx [a]), Data ctx a) => Data ctx [a]        -- dfunData2

    class Data Maybe a => Foo a    

    instance Foo t => Sat (Maybe t)                             -- dfunSat

    instance Data Maybe a => Foo a                              -- dfunFoo1
    instance Foo a        => Foo [a]                            -- dfunFoo2
    instance                 Foo [Char]                         -- dfunFoo3

Consider generating the superclasses of the instance declaration
	 instance Foo a => Foo [a]

So our problem is this
    d0 :_g Foo t
    d1 :_w Data Maybe [t] 

We may add the given in the inert set, along with its superclasses
[assuming we don't fail because there is a matching instance, see 
 tryTopReact, given case ]
  Inert:
    d0 :_g Foo t 
  WorkList 
    d01 :_g Data Maybe t  -- d2 := EvDictSuperClass d0 0 
    d1 :_w Data Maybe [t] 
Then d2 can readily enter the inert, and we also do solving of the wanted
  Inert: 
    d0 :_g Foo t 
    d1 :_s Data Maybe [t]           d1 := dfunData2 d2 d3 
  WorkList
    d2 :_w Sat (Maybe [t])          
    d3 :_w Data Maybe t
    d01 :_g Data Maybe t 
Now, we may simplify d2 more: 
  Inert:
      d0 :_g Foo t 
      d1 :_s Data Maybe [t]           d1 := dfunData2 d2 d3 
      d1 :_g Data Maybe [t] 
      d2 :_g Sat (Maybe [t])          d2 := dfunSat d4 
  WorkList: 
      d3 :_w Data Maybe t 
      d4 :_w Foo [t] 
      d01 :_g Data Maybe t 

Now, we can just solve d3.
  Inert
      d0 :_g Foo t 
      d1 :_s Data Maybe [t]           d1 := dfunData2 d2 d3 
      d2 :_g Sat (Maybe [t])          d2 := dfunSat d4 
  WorkList
      d4 :_w Foo [t] 
      d01 :_g Data Maybe t 
And now we can simplify d4 again, but since it has superclasses we *add* them to the worklist:
  Inert
      d0 :_g Foo t 
      d1 :_s Data Maybe [t]           d1 := dfunData2 d2 d3 
      d2 :_g Sat (Maybe [t])          d2 := dfunSat d4 
      d4 :_g Foo [t]                  d4 := dfunFoo2 d5 
  WorkList:
      d5 :_w Foo t 
      d6 :_g Data Maybe [t]           d6 := EvDictSuperClass d4 0
      d01 :_g Data Maybe t 
Now, d5 can be solved! (and its superclass enter scope) 
  Inert
      d0 :_g Foo t 
      d1 :_s Data Maybe [t]           d1 := dfunData2 d2 d3 
      d2 :_g Sat (Maybe [t])          d2 := dfunSat d4 
      d4 :_g Foo [t]                  d4 := dfunFoo2 d5 
      d5 :_g Foo t                    d5 := dfunFoo1 d7
  WorkList:
      d7 :_w Data Maybe t
      d6 :_g Data Maybe [t]
      d8 :_g Data Maybe t            d8 := EvDictSuperClass d5 0
      d01 :_g Data Maybe t 

Now, two problems: 
   [1] Suppose we pick d8 and we react him with d01. Which of the two givens should 
       we keep? Well, we *MUST NOT* drop d01 because d8 contains recursive evidence 
       that must not be used (look at case interactInert where both inert and workitem
       are givens). So we have several options: 
       - Drop the workitem always (this will drop d8)
              This feels very unsafe -- what if the work item was the "good" one
              that should be used later to solve another wanted?
       - Don't drop anyone: the inert set may contain multiple givens! 
              [This is currently implemented] 

The "don't drop anyone" seems the most safe thing to do, so now we come to problem 2: 
  [2] We have added both d6 and d01 in the inert set, and we are interacting our wanted
      d7. Now the [isRecDictEv] function in the ineration solver 
      [case inert-given workitem-wanted] will prevent us from interacting d7 := d8 
      precisely because chasing the evidence of d8 leads us to an unguarded use of d7. 

      So, no interaction happens there. Then we meet d01 and there is no recursion 
      problem there [isRectDictEv] gives us the OK to interact and we do solve d7 := d01! 
             
Note [SUPERCLASS-LOOP 1]
~~~~~~~~~~~~~~~~~~~~~~~~
We have to be very, very careful when generating superclasses, lest we
accidentally build a loop. Here's an example:

  class S a

  class S a => C a where { opc :: a -> a }
  class S b => D b where { opd :: b -> b }
  
  instance C Int where
     opc = opd
  
  instance D Int where
     opd = opc

From (instance C Int) we get the constraint set {ds1:S Int, dd:D Int}
Simplifying, we may well get:
	$dfCInt = :C ds1 (opd dd)
	dd  = $dfDInt
	ds1 = $p1 dd
Notice that we spot that we can extract ds1 from dd.  

Alas!  Alack! We can do the same for (instance D Int):

	$dfDInt = :D ds2 (opc dc)
	dc  = $dfCInt
	ds2 = $p1 dc

And now we've defined the superclass in terms of itself.
Two more nasty cases are in
	tcrun021
	tcrun033

Solution: 
  - Satisfy the superclass context *all by itself* 
    (tcSimplifySuperClasses)
  - And do so completely; i.e. no left-over constraints
    to mix with the constraints arising from method declarations


Note [SUPERCLASS-LOOP 2]
~~~~~~~~~~~~~~~~~~~~~~~~
We need to be careful when adding "the constaint we are trying to prove".
Suppose we are *given* d1:Ord a, and want to deduce (d2:C [a]) where

	class Ord a => C a where
	instance Ord [a] => C [a] where ...

Then we'll use the instance decl to deduce C [a] from Ord [a], and then add the
superclasses of C [a] to avails.  But we must not overwrite the binding
for Ord [a] (which is obtained from Ord a) with a superclass selection or we'll just
build a loop! 

Here's another variant, immortalised in tcrun020
	class Monad m => C1 m
	class C1 m => C2 m x
	instance C2 Maybe Bool
For the instance decl we need to build (C1 Maybe), and it's no good if
we run around and add (C2 Maybe Bool) and its superclasses to the avails 
before we search for C1 Maybe.

Here's another example 
 	class Eq b => Foo a b
	instance Eq a => Foo [a] a
If we are reducing
	(Foo [t] t)

we'll first deduce that it holds (via the instance decl).  We must not
then overwrite the Eq t constraint with a superclass selection!

At first I had a gross hack, whereby I simply did not add superclass constraints
in addWanted, though I did for addGiven and addIrred.  This was sub-optimal,
becuase it lost legitimate superclass sharing, and it still didn't do the job:
I found a very obscure program (now tcrun021) in which improvement meant the
simplifier got two bites a the cherry... so something seemed to be an Stop
first time, but reducible next time.

Now we implement the Right Solution, which is to check for loops directly 
when adding superclasses.  It's a bit like the occurs check in unification.

Note [Recursive instances and superclases]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider this code, which arises in the context of "Scrap Your 
Boilerplate with Class".  

    class Sat a
    class Data ctx a
    instance  Sat (ctx Char)             => Data ctx Char
    instance (Sat (ctx [a]), Data ctx a) => Data ctx [a]

    class Data Maybe a => Foo a

    instance Foo t => Sat (Maybe t)

    instance Data Maybe a => Foo a
    instance Foo a        => Foo [a]
    instance                 Foo [Char]

In the instance for Foo [a], when generating evidence for the superclasses
(ie in tcSimplifySuperClasses) we need a superclass (Data Maybe [a]).
Using the instance for Data, we therefore need
        (Sat (Maybe [a], Data Maybe a)
But we are given (Foo a), and hence its superclass (Data Maybe a).
So that leaves (Sat (Maybe [a])).  Using the instance for Sat means
we need (Foo [a]).  And that is the very dictionary we are bulding
an instance for!  So we must put that in the "givens".  So in this
case we have
	Given:  Foo a, Foo [a]
	Wanted: Data Maybe [a]

BUT we must *not not not* put the *superclasses* of (Foo [a]) in
the givens, which is what 'addGiven' would normally do. Why? Because
(Data Maybe [a]) is the superclass, so we'd "satisfy" the wanted 
by selecting a superclass from Foo [a], which simply makes a loop.

On the other hand we *must* put the superclasses of (Foo a) in
the givens, as you can see from the derivation described above.

Conclusion: in the very special case of tcSimplifySuperClasses
we have one 'given' (namely the "this" dictionary) whose superclasses
must not be added to 'givens' by addGiven.  

There is a complication though.  Suppose there are equalities
      instance (Eq a, a~b) => Num (a,b)
Then we normalise the 'givens' wrt the equalities, so the original
given "this" dictionary is cast to one of a different type.  So it's a
bit trickier than before to identify the "special" dictionary whose
superclasses must not be added. See test
   indexed-types/should_run/EqInInstance

We need a persistent property of the dictionary to record this
special-ness.  Current I'm using the InstLocOrigin (a bit of a hack,
but cool), which is maintained by dictionary normalisation.
Specifically, the InstLocOrigin is
	     NoScOrigin
then the no-superclass thing kicks in.  WATCH OUT if you fiddle
with InstLocOrigin!

Note [MATCHING-SYNONYMS]
~~~~~~~~~~~~~~~~~~~~~~~~
When trying to match a dictionary (D tau) to a top-level instance, or a 
type family equation (F taus_1 ~ tau_2) to a top-level family instance, 
we do *not* need to expand type synonyms because the matcher will do that for us.


Note [RHS-FAMILY-SYNONYMS] 
~~~~~~~~~~~~~~~~~~~~~~~~~~
The RHS of a family instance is represented as yet another constructor which is 
like a type synonym for the real RHS the programmer declared. Eg: 
    type instance F (a,a) = [a] 
Becomes: 
    :R32 a = [a]      -- internal type synonym introduced
    F (a,a) ~ :R32 a  -- instance 

When we react a family instance with a type family equation in the work list 
we keep the synonym-using RHS without expansion. 


*********************************************************************************
*                                                                               * 
                       The top-reaction Stage
*                                                                               *
*********************************************************************************

\begin{code}
1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262

topReactionsStage :: SimplifierStage 
topReactionsStage workItem 
 = tryTopReact workItem 
   

tryTopReact :: WorkItem -> TcS StopOrContinue
tryTopReact wi 
 = do { inerts <- getTcSInerts
      ; ctxt   <- getTcSContext
      ; if simplEqsOnly ctxt then return (ContinueWith wi) -- or Stop?
        else 
            do { tir <- doTopReact inerts wi
               ; case tir of 
                   NoTopInt 
                       -> return (ContinueWith wi)
                   SomeTopInt rule what_next 
                       -> do { bumpStepCountTcS 
                             ; traceFireTcS (cc_depth wi) $
                               ptext (sLit "Top react:") <+> text rule
                             ; return what_next }
               } }

1263
data TopInteractResult 
1264 1265
 = NoTopInt
 | SomeTopInt { tir_rule :: String, tir_new_item :: StopOrContinue }
1266 1267


dimitris's avatar
dimitris committed
1268
doTopReact :: InertSet -> WorkItem -> TcS TopInteractResult
1269 1270 1271 1272 1273 1274 1275

-- The work item does not react with the inert set, so try interaction
-- with top-level instances 
-- NB: The place to add superclasses in *not*
-- in doTopReact stage. Instead superclasses are added in the worklist
-- as part of the canonicalisation process. See Note [Adding superclasses].

1276

1277
-- Given dictionary
1278
-- See Note [Given constraint that matches an instance declaration]
dimitris's avatar
dimitris committed
1279
doTopReact _inerts (CDictCan { cc_flavor = Given {} })
1280
  = return NoTopInt -- NB: Superclasses already added since it's canonical
1281

1282
-- Derived dictionary: just look for functional dependencies
1283
doTopReact _inerts workItem@(CDictCan { cc_flavor = Derived loc
dimitris's avatar
dimitris committed
1284
                                      , cc_class = cls, cc_tyargs = xis })
1285 1286
  = do { instEnvs <- getInstEnvs
       ; let fd_eqns = improveFromInstEnv instEnvs
1287
                           (mkClassPred cls xis, pprArisingAt loc)
1288
       ; m <- rewriteWithFunDeps fd_eqns xis loc
1289 1290 1291 1292 1293
       ; case m of
           Nothing -> return NoTopInt
           Just (xis',_,fd_work) ->
               let workItem' = workItem { cc_tyargs = xis' }
                   -- Deriveds are not supposed to have identity (cc_id is unused!)
1294 1295 1296 1297
               in do { emitFDWorkAsDerived fd_work (cc_depth workItem)
                     ; return $ 
                       SomeTopInt { tir_rule  = "Derived Cls fundeps" 
                                  , tir_new_item = ContinueWith workItem' } }
1298 1299
       }

1300
-- Wanted dictionary
1301
doTopReact inerts workItem@(CDictCan { cc_flavor = fl@(Wanted loc)
dimitris's avatar
dimitris committed
1302
                                     , cc_class = cls, cc_tyargs = xis })
1303 1304 1305
  -- See Note [MATCHING-SYNONYMS]
  = do { traceTcS "doTopReact" (ppr workItem)
       ; instEnvs <- getInstEnvs
1306 1307
       ; let fd_eqns = improveFromInstEnv instEnvs 
                            (mkClassPred cls xis, pprArisingAt loc)
1308 1309 1310 1311 1312 1313 1314 1315

       ; any_fundeps <- rewriteWithFunDeps fd_eqns xis loc
       ; case any_fundeps of
           -- No Functional Dependencies
           Nothing ->
               do { lkup_inst_res  <- matchClassInst inerts cls xis loc
                  ; case lkup_inst_res of
                      GenInst wtvs ev_term
1316
                          -> doSolveFromInstance wtvs ev_term workItem
1317 1318 1319 1320
                      NoInstance
                          -> return NoTopInt
                  }
           -- Actual Functional Dependencies
1321 1322 1323 1324
           Just (_xis',_cos,fd_work) ->
               do { emitFDWorkAsDerived fd_work (cc_depth workItem)
                  ; return SomeTopInt { tir_rule = "Dict/Top (fundeps)"
                                      , tir_new_item = ContinueWith workItem } } }
1325 1326 1327

   where doSolveFromInstance :: [WantedEvVar] 
                             -> EvTerm 
1328 1329
                             -> Ct 
                             -> TcS TopInteractResult
1330
         -- Precondition: evidence term matches the predicate of cc_id of workItem
1331
         doSolveFromInstance wtvs ev_term workItem
1332 1333
            | null wtvs
            = do { traceTcS "doTopReact/found nullary instance for" (ppr (cc_id workItem))
batterseapower's avatar
batterseapower committed
1334
                 ; setEvBind (cc_id workItem) ev_term
1335 1336 1337
                 ; return $ 
                   SomeTopInt { tir_rule = "Dict/Top (solved, no new work)" 
                              , tir_new_item = Stop } } -- Don't put him in the inerts
1338
            | otherwise 
1339 1340
            = do { traceTcS "doTopReact/found non-nullary instance for" $ 
                   ppr (cc_id workItem)
batterseapower's avatar
batterseapower committed
1341
                 ; setEvBind (cc_id workItem) ev_term 
1342
                        -- Solved and new wanted work produced, you may cache the 
dimitris's avatar
dimitris committed
1343
                        -- (tentatively solved) dictionary as Solved given.
1344 1345 1346 1347 1348 1349 1350 1351 1352 1353
                 ; let solved = workItem { cc_flavor = solved_fl }
                       solved_fl = mkSolvedFlavor fl UnkSkol
                 ; let ct_from_wev (EvVarX v fl)
                           = CNonCanonical { cc_id = v, cc_flavor = Wanted fl
                                           , cc_depth  = cc_depth workItem + 1 }
                       wtvs_cts = map ct_from_wev wtvs
                 ; updWorkListTcS (appendWorkListCt wtvs_cts)
                 ; return $ 
                   SomeTopInt { tir_rule     = "Dict/Top (solved, more work)"
                              , tir_new_item = ContinueWith solved } } -- Cache in inerts the Solved item
1354 1355

-- Type functions
dimitris's avatar
dimitris committed
1356 1357 1358 1359 1360
doTopReact _inerts (CFunEqCan { cc_flavor = fl })
  | Just GivenSolved <- isGiven_maybe fl
  = return NoTopInt -- If Solved, no more interactions should happen

-- Otherwise, it's a Given, Derived, or Wanted
batterseapower's avatar
batterseapower committed
1361
doTopReact _inerts workItem@(CFunEqCan { cc_id = eqv, cc_flavor = fl
dimitris's avatar
dimitris committed
1362
                                       , cc_fun = tc, cc_tyargs = args, cc_rhs = xi })
1363
  = ASSERT (isSynFamilyTyCon tc)   -- No associated data families have reached that far 
1364
    do { match_res <- matchFam tc args   -- See Note [MATCHING-SYNONYMS]
1365
       ; case match_res of 
1366 1367
           Nothing -> return NoTopInt 
           Just (rep_tc, rep_tys)
1368 1369 1370 1371 1372 1373
             -> do { let Just coe_tc = tyConFamilyCoercion_maybe rep_tc
                         Just rhs_ty = tcView (mkTyConApp rep_tc rep_tys)
			    -- Eagerly expand away the type synonym on the
			    -- RHS of a type function, so that it never
			    -- appears in an error message
                            -- See Note [Type synonym families] in TyCon
dimitris's avatar
dimitris committed
1374
                         coe = mkAxInstCo coe_tc rep_tys 
dimitris's avatar
dimitris committed
1375
                   ; case fl of
1376 1377
                       Wanted {} -> do { evc <- newEqVar fl rhs_ty xi -- Wanted version
                                       ; let eqv' = evc_the_evvar evc
batterseapower's avatar
batterseapower committed
1378
                                       ; setEqBind eqv (coe `mkTransCo` mkEqVarLCo eqv')
1379 1380 1381 1382 1383 1384
                                       ; when (isNewEvVar evc) $ 
                                            (let ct = CNonCanonical { cc_id = eqv'
                                                                    , cc_flavor = fl 
                                                                    , cc_depth = cc_depth workItem + 1} 
                                             in updWorkListTcS (extendWorkListEq ct))

dimitris's avatar
dimitris committed
1385 1386
                                       ; let solved = workItem { cc_flavor = solved_fl }
                                             solved_fl = mkSolvedFlavor fl UnkSkol
1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399

                                       ; return $ 
                                         SomeTopInt { tir_rule = "Fun/Top (solved, more work)"
                                                    , tir_new_item = ContinueWith solved } } 
                       -- Cache in inerts the Solved item

                       Given {} -> do { eqv' <- newGivenEqVar fl xi rhs_ty $ 
                                                mkSymCo (mkEqVarLCo eqv) `mkTransCo` coe
                                      ; let ct = CNonCanonical { cc_id = eqv'
                                                               , cc_flavor = fl
                                                               , cc_depth = cc_depth workItem + 1}  
                                      ; updWorkListTcS (extendWorkListEq ct) 

dimitris's avatar
dimitris committed
1400
                                      ; return $ 
1401 1402 1403 1404 1405 1406 1407 1408 1409
                                        SomeTopInt { tir_rule = "Fun/Top (given)"
                                                   , tir_new_item = ContinueWith workItem } }
                       Derived {} -> do { evc <- newEvVar fl (mkEqPred (xi, rhs_ty))
                                        ; let eqv' = evc_the_evvar evc
                                        ; when (isNewEvVar evc) $ 
                                            (let ct = CNonCanonical { cc_id  = eqv'
                                                                 , cc_flavor = fl
                                                                 , cc_depth  = cc_depth workItem + 1 } 
                                             in updWorkListTcS (extendWorkListEq ct)) 
dimitris's avatar
dimitris committed
1410
                                        ; return $ 
1411 1412
                                          SomeTopInt { tir_rule = "Fun/Top (derived)"
                                                     , tir_new_item = Stop } }
dimitris's avatar
dimitris committed
1413
                   }
1414 1415 1416 1417
       }


-- Any other work item does not react with any top-level equations
dimitris's avatar
dimitris committed
1418
doTopReact _inerts _workItem = return NoTopInt 
1419 1420
\end{code}

1421

1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449
Note [FunDep and implicit parameter reactions] 
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Currently, our story of interacting two dictionaries (or a dictionary
and top-level instances) for functional dependencies, and implicit
paramters, is that we simply produce new wanted equalities.  So for example

        class D a b | a -> b where ... 
    Inert: 
        d1 :g D Int Bool
    WorkItem: 
        d2 :w D Int alpha

    We generate the extra work item
        cv :w alpha ~ Bool
    where 'cv' is currently unused.  However, this new item reacts with d2,
    discharging it in favour of a new constraint d2' thus:
        d2' :w D Int Bool
	d2 := d2' |> D Int cv
    Now d2' can be discharged from d1

We could be more aggressive and try to *immediately* solve the dictionary 
using those extra equalities. With the same inert set and work item we
might dischard d2 directly:

        cv :w alpha ~ Bool
        d2 := d1 |> D Int cv

But in general it's a bit painful to figure out the necessary coercion,
1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460
so we just take the first approach. Here is a better example. Consider:
    class C a b c | a -> b 
And: 
     [Given]  d1 : C T Int Char 
     [Wanted] d2 : C T beta Int 
In this case, it's *not even possible* to solve the wanted immediately. 
So we should simply output the functional dependency and add this guy
[but NOT its superclasses] back in the worklist. Even worse: 
     [Given] d1 : C T Int beta 
     [Wanted] d2: C T beta Int 
Then it is solvable, but its very hard to detect this on the spot. 
1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534

It's exactly the same with implicit parameters, except that the
"aggressive" approach would be much easier to implement.

Note [When improvement happens]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We fire an improvement rule when

  * Two constraints match (modulo the fundep)
      e.g. C t1 t2, C t1 t3    where C a b | a->b
    The two match because the first arg is identical

  * At least one is not Given.  If they are both given, we don't fire
    the reaction because we have no way of constructing evidence for a
    new equality nor does it seem right to create a new wanted goal
    (because the goal will most likely contain untouchables, which
    can't be solved anyway)!
   
Note that we *do* fire the improvement if one is Given and one is Derived.
The latter can be a superclass of a wanted goal. Example (tcfail138)
    class L a b | a -> b
    class (G a, L a b) => C a b

    instance C a b' => G (Maybe a)
    instance C a b  => C (Maybe a) a
    instance L (Maybe a) a

When solving the superclasses of the (C (Maybe a) a) instance, we get
  Given:  C a b  ... and hance by superclasses, (G a, L a b)
  Wanted: G (Maybe a)
Use the instance decl to get
  Wanted: C a b'
The (C a b') is inert, so we generate its Derived superclasses (L a b'),
and now we need improvement between that derived superclass an the Given (L a b)

Note [Overriding implicit parameters]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
   f :: (?x::a) -> Bool -> a
  
   g v = let ?x::Int = 3 
         in (f v, let ?x::Bool = True in f v)

This should probably be well typed, with
   g :: Bool -> (Int, Bool)

So the inner binding for ?x::Bool *overrides* the outer one.
Hence a work-item Given overrides an inert-item Given.

Note [Given constraint that matches an instance declaration]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
What should we do when we discover that one (or more) top-level 
instances match a given (or solved) class constraint? We have 
two possibilities:

  1. Reject the program. The reason is that there may not be a unique
     best strategy for the solver. Example, from the OutsideIn(X) paper:
       instance P x => Q [x] 
       instance (x ~ y) => R [x] y 
     
       wob :: forall a b. (Q [b], R b a) => a -> Int 

       g :: forall a. Q [a] => [a] -> Int 
       g x = wob x 

       will generate the impliation constraint: 
            Q [a] => (Q [beta], R beta [a]) 
       If we react (Q [beta]) with its top-level axiom, we end up with a 
       (P beta), which we have no way of discharging. On the other hand, 
       if we react R beta [a] with the top-level we get  (beta ~ a), which 
       is solvable and can help us rewrite (Q [beta]) to (Q [a]) which is 
       now solvable by the given Q [a]. 
 
     However, this option is restrictive, for instance [Example 3] from 
batterseapower's avatar
batterseapower committed
1535
     Note [Recursive instances and superclases] will fail to work. 
1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546

  2. Ignore the problem, hoping that the situations where there exist indeed
     such multiple strategies are rare: Indeed the cause of the previous 
     problem is that (R [x] y) yields the new work (x ~ y) which can be 
     *spontaneously* solved, not using the givens. 

We are choosing option 2 below but we might consider having a flag as well.


Note [New Wanted Superclass Work] 
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1547 1548
Even in the case of wanted constraints, we may add some superclasses 
as new given work. The reason is: 
1549