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