PageRenderTime 64ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 1ms

/compiler/typecheck/TcInteract.lhs

https://github.com/luite/ghc
Haskell | 1888 lines | 1420 code | 321 blank | 147 comment | 79 complexity | 7e10f1be1ca6164d68bdd4c6535c6bee MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. \begin{code}
  2. {-# OPTIONS -fno-warn-tabs #-}
  3. -- The above warning supression flag is a temporary kludge.
  4. -- While working on this module you are encouraged to remove it and
  5. -- detab the module (please do the detabbing in a separate patch). See
  6. -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#TabsvsSpaces
  7. -- for details
  8. module TcInteract (
  9. solveInteractGiven, -- Solves [EvVar],GivenLoc
  10. solveInteract, -- Solves Cts
  11. ) where
  12. #include "HsVersions.h"
  13. import BasicTypes ()
  14. import TcCanonical
  15. import VarSet
  16. import Type
  17. import Unify
  18. import FamInstEnv
  19. import Coercion( mkAxInstRHS )
  20. import Var
  21. import TcType
  22. import PrelNames (singIClassName, ipClassNameKey )
  23. import Class
  24. import TyCon
  25. import Name
  26. import FunDeps
  27. import TcEvidence
  28. import Outputable
  29. import TcMType ( zonkTcPredType )
  30. import TcRnTypes
  31. import TcErrors
  32. import TcSMonad
  33. import Maybes( orElse )
  34. import Bag
  35. import Control.Monad ( foldM )
  36. import VarEnv
  37. import Control.Monad( when, unless )
  38. import Pair ()
  39. import Unique( hasKey )
  40. import UniqFM
  41. import FastString ( sLit )
  42. import DynFlags
  43. import Util
  44. \end{code}
  45. **********************************************************************
  46. * *
  47. * Main Interaction Solver *
  48. * *
  49. **********************************************************************
  50. Note [Basic Simplifier Plan]
  51. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  52. 1. Pick an element from the WorkList if there exists one with depth
  53. less thanour context-stack depth.
  54. 2. Run it down the 'stage' pipeline. Stages are:
  55. - canonicalization
  56. - inert reactions
  57. - spontaneous reactions
  58. - top-level intreactions
  59. Each stage returns a StopOrContinue and may have sideffected
  60. the inerts or worklist.
  61. The threading of the stages is as follows:
  62. - If (Stop) is returned by a stage then we start again from Step 1.
  63. - If (ContinueWith ct) is returned by a stage, we feed 'ct' on to
  64. the next stage in the pipeline.
  65. 4. If the element has survived (i.e. ContinueWith x) the last stage
  66. then we add him in the inerts and jump back to Step 1.
  67. If in Step 1 no such element exists, we have exceeded our context-stack
  68. depth and will simply fail.
  69. \begin{code}
  70. solveInteractGiven :: CtLoc -> [TcTyVar] -> [EvVar] -> TcS ()
  71. -- In principle the givens can kick out some wanteds from the inert
  72. -- resulting in solving some more wanted goals here which could emit
  73. -- implications. That's why I return a bag of implications. Not sure
  74. -- if this can happen in practice though.
  75. solveInteractGiven loc fsks givens
  76. = do { implics <- solveInteract (fsk_bag `unionBags` given_bag)
  77. ; ASSERT( isEmptyBag implics )
  78. return () } -- We do not decompose *given* polymorphic equalities
  79. -- (forall a. t1 ~ forall a. t2)
  80. -- What would the evidence look like?!
  81. -- See Note [Do not decompose given polytype equalities]
  82. -- in TcCanonical
  83. where
  84. given_bag = listToBag [ mkNonCanonical loc $ CtGiven { ctev_evtm = EvId ev_id
  85. , ctev_pred = evVarPred ev_id }
  86. | ev_id <- givens ]
  87. fsk_bag = listToBag [ mkNonCanonical loc $ CtGiven { ctev_evtm = EvCoercion (mkTcReflCo tv_ty)
  88. , ctev_pred = pred }
  89. | tv <- fsks
  90. , let FlatSkol fam_ty = tcTyVarDetails tv
  91. tv_ty = mkTyVarTy tv
  92. pred = mkTcEqPred fam_ty tv_ty
  93. ]
  94. -- The main solver loop implements Note [Basic Simplifier Plan]
  95. ---------------------------------------------------------------
  96. solveInteract :: Cts -> TcS (Bag Implication)
  97. -- Returns the final InertSet in TcS
  98. -- Has no effect on work-list or residual-iplications
  99. solveInteract cts
  100. = {-# SCC "solveInteract" #-}
  101. withWorkList cts $
  102. do { dyn_flags <- getDynFlags
  103. ; solve_loop (ctxtStkDepth dyn_flags) }
  104. where
  105. solve_loop max_depth
  106. = {-# SCC "solve_loop" #-}
  107. do { sel <- selectNextWorkItem max_depth
  108. ; case sel of
  109. NoWorkRemaining -- Done, successfuly (modulo frozen)
  110. -> return ()
  111. MaxDepthExceeded ct -- Failure, depth exceeded
  112. -> wrapErrTcS $ solverDepthErrorTcS ct
  113. NextWorkItem ct -- More work, loop around!
  114. -> do { runSolverPipeline thePipeline ct; solve_loop max_depth } }
  115. type WorkItem = Ct
  116. type SimplifierStage = WorkItem -> TcS StopOrContinue
  117. continueWith :: WorkItem -> TcS StopOrContinue
  118. continueWith work_item = return (ContinueWith work_item)
  119. data SelectWorkItem
  120. = NoWorkRemaining -- No more work left (effectively we're done!)
  121. | MaxDepthExceeded Ct -- More work left to do but this constraint has exceeded
  122. -- the max subgoal depth and we must stop
  123. | NextWorkItem Ct -- More work left, here's the next item to look at
  124. selectNextWorkItem :: SubGoalDepth -- Max depth allowed
  125. -> TcS SelectWorkItem
  126. selectNextWorkItem max_depth
  127. = updWorkListTcS_return pick_next
  128. where
  129. pick_next :: WorkList -> (SelectWorkItem, WorkList)
  130. pick_next wl
  131. = case selectWorkItem wl of
  132. (Nothing,_)
  133. -> (NoWorkRemaining,wl) -- No more work
  134. (Just ct, new_wl)
  135. | ctLocDepth (cc_loc ct) > max_depth -- Depth exceeded
  136. -> (MaxDepthExceeded ct,new_wl)
  137. (Just ct, new_wl)
  138. -> (NextWorkItem ct, new_wl) -- New workitem and worklist
  139. runSolverPipeline :: [(String,SimplifierStage)] -- The pipeline
  140. -> WorkItem -- The work item
  141. -> TcS ()
  142. -- Run this item down the pipeline, leaving behind new work and inerts
  143. runSolverPipeline pipeline workItem
  144. = do { initial_is <- getTcSInerts
  145. ; traceTcS "Start solver pipeline {" $
  146. vcat [ ptext (sLit "work item = ") <+> ppr workItem
  147. , ptext (sLit "inerts = ") <+> ppr initial_is]
  148. ; bumpStepCountTcS -- One step for each constraint processed
  149. ; final_res <- run_pipeline pipeline (ContinueWith workItem)
  150. ; final_is <- getTcSInerts
  151. ; case final_res of
  152. Stop -> do { traceTcS "End solver pipeline (discharged) }"
  153. (ptext (sLit "inerts = ") <+> ppr final_is)
  154. ; return () }
  155. ContinueWith ct -> do { traceFireTcS ct (ptext (sLit "Kept as inert:") <+> ppr ct)
  156. ; traceTcS "End solver pipeline (not discharged) }" $
  157. vcat [ ptext (sLit "final_item = ") <+> ppr ct
  158. , pprTvBndrs (varSetElems $ tyVarsOfCt ct)
  159. , ptext (sLit "inerts = ") <+> ppr final_is]
  160. ; insertInertItemTcS ct }
  161. }
  162. where run_pipeline :: [(String,SimplifierStage)] -> StopOrContinue -> TcS StopOrContinue
  163. run_pipeline [] res = return res
  164. run_pipeline _ Stop = return Stop
  165. run_pipeline ((stg_name,stg):stgs) (ContinueWith ct)
  166. = do { traceTcS ("runStage " ++ stg_name ++ " {")
  167. (text "workitem = " <+> ppr ct)
  168. ; res <- stg ct
  169. ; traceTcS ("end stage " ++ stg_name ++ " }") empty
  170. ; run_pipeline stgs res
  171. }
  172. \end{code}
  173. Example 1:
  174. Inert: {c ~ d, F a ~ t, b ~ Int, a ~ ty} (all given)
  175. Reagent: a ~ [b] (given)
  176. React with (c~d) ==> IR (ContinueWith (a~[b])) True []
  177. React with (F a ~ t) ==> IR (ContinueWith (a~[b])) False [F [b] ~ t]
  178. React with (b ~ Int) ==> IR (ContinueWith (a~[Int]) True []
  179. Example 2:
  180. Inert: {c ~w d, F a ~g t, b ~w Int, a ~w ty}
  181. Reagent: a ~w [b]
  182. React with (c ~w d) ==> IR (ContinueWith (a~[b])) True []
  183. React with (F a ~g t) ==> IR (ContinueWith (a~[b])) True [] (can't rewrite given with wanted!)
  184. etc.
  185. Example 3:
  186. Inert: {a ~ Int, F Int ~ b} (given)
  187. Reagent: F a ~ b (wanted)
  188. React with (a ~ Int) ==> IR (ContinueWith (F Int ~ b)) True []
  189. React with (F Int ~ b) ==> IR Stop True [] -- after substituting we re-canonicalize and get nothing
  190. \begin{code}
  191. thePipeline :: [(String,SimplifierStage)]
  192. thePipeline = [ ("canonicalization", TcCanonical.canonicalize)
  193. , ("spontaneous solve", spontaneousSolveStage)
  194. , ("interact with inerts", interactWithInertsStage)
  195. , ("top-level reactions", topReactionsStage) ]
  196. \end{code}
  197. *********************************************************************************
  198. * *
  199. The spontaneous-solve Stage
  200. * *
  201. *********************************************************************************
  202. \begin{code}
  203. spontaneousSolveStage :: SimplifierStage
  204. -- CTyEqCans are always consumed, returning Stop
  205. spontaneousSolveStage workItem
  206. = do { mb_solved <- trySpontaneousSolve workItem
  207. ; case mb_solved of
  208. SPCantSolve
  209. | CTyEqCan { cc_tyvar = tv, cc_ev = fl } <- workItem
  210. -- Unsolved equality
  211. -> do { n_kicked <- kickOutRewritable (ctEvFlavour fl) tv
  212. ; traceFireTcS workItem $
  213. ptext (sLit "Kept as inert") <+> ppr_kicked n_kicked <> colon
  214. <+> ppr workItem
  215. ; insertInertItemTcS workItem
  216. ; return Stop }
  217. | otherwise
  218. -> continueWith workItem
  219. SPSolved new_tv
  220. -- Post: tv ~ xi is now in TyBinds, no need to put in inerts as well
  221. -- see Note [Spontaneously solved in TyBinds]
  222. -> do { n_kicked <- kickOutRewritable Given new_tv
  223. ; traceFireTcS workItem $
  224. ptext (sLit "Spontaneously solved") <+> ppr_kicked n_kicked <> colon
  225. <+> ppr workItem
  226. ; return Stop } }
  227. ppr_kicked :: Int -> SDoc
  228. ppr_kicked 0 = empty
  229. ppr_kicked n = parens (int n <+> ptext (sLit "kicked out"))
  230. \end{code}
  231. Note [Spontaneously solved in TyBinds]
  232. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  233. When we encounter a constraint ([W] alpha ~ tau) which can be spontaneously solved,
  234. we record the equality on the TyBinds of the TcSMonad. In the past, we used to also
  235. add a /given/ version of the constraint ([G] alpha ~ tau) to the inert
  236. canonicals -- and potentially kick out other equalities that mention alpha.
  237. Then, the flattener only had to look in the inert equalities during flattening of a
  238. type (TcCanonical.flattenTyVar).
  239. However it is a bit silly to record these equalities /both/ in the inerts AND the
  240. TyBinds, so we have now eliminated spontaneously solved equalities from the inerts,
  241. and only record them in the TyBinds of the TcS monad. The flattener is now consulting
  242. these binds /and/ the inerts for potentially unsolved or other given equalities.
  243. \begin{code}
  244. kickOutRewritable :: CtFlavour -- Flavour of the equality that is
  245. -- being added to the inert set
  246. -> TcTyVar -- The new equality is tv ~ ty
  247. -> TcS Int
  248. kickOutRewritable new_flav new_tv
  249. = do { wl <- modifyInertTcS kick_out
  250. ; traceTcS "kickOutRewritable" $
  251. vcat [ text "tv = " <+> ppr new_tv
  252. , ptext (sLit "Kicked out =") <+> ppr wl]
  253. ; updWorkListTcS (appendWorkList wl)
  254. ; return (workListSize wl) }
  255. where
  256. kick_out :: InertSet -> (WorkList, InertSet)
  257. kick_out (is@(IS { inert_cans = IC { inert_eqs = tv_eqs
  258. , inert_dicts = dictmap
  259. , inert_funeqs = funeqmap
  260. , inert_irreds = irreds
  261. , inert_insols = insols } }))
  262. = (kicked_out, is { inert_cans = inert_cans_in })
  263. -- NB: Notice that don't rewrite
  264. -- inert_solved_dicts, and inert_solved_funeqs
  265. -- optimistically. But when we lookup we have to take the
  266. -- subsitution into account
  267. where
  268. inert_cans_in = IC { inert_eqs = tv_eqs_in
  269. , inert_dicts = dicts_in
  270. , inert_funeqs = feqs_in
  271. , inert_irreds = irs_in
  272. , inert_insols = insols_in }
  273. kicked_out = WorkList { wl_eqs = varEnvElts tv_eqs_out
  274. , wl_funeqs = foldrBag insertDeque emptyDeque feqs_out
  275. , wl_rest = bagToList (dicts_out `andCts` irs_out
  276. `andCts` insols_out) }
  277. (tv_eqs_out, tv_eqs_in) = partitionVarEnv kick_out_eq tv_eqs
  278. (feqs_out, feqs_in) = partCtFamHeadMap kick_out_ct funeqmap
  279. (dicts_out, dicts_in) = partitionCCanMap kick_out_ct dictmap
  280. (irs_out, irs_in) = partitionBag kick_out_ct irreds
  281. (insols_out, insols_in) = partitionBag kick_out_ct insols
  282. -- Kick out even insolubles; see Note [Kick out insolubles]
  283. kick_out_ct inert_ct = new_flav `canRewrite` (ctFlavour inert_ct) &&
  284. (new_tv `elemVarSet` tyVarsOfCt inert_ct)
  285. -- NB: tyVarsOfCt will return the type
  286. -- variables /and the kind variables/ that are
  287. -- directly visible in the type. Hence we will
  288. -- have exposed all the rewriting we care about
  289. -- to make the most precise kinds visible for
  290. -- matching classes etc. No need to kick out
  291. -- constraints that mention type variables whose
  292. -- kinds could contain this variable!
  293. kick_out_eq (CTyEqCan { cc_tyvar = tv, cc_rhs = rhs, cc_ev = ev })
  294. = (new_flav `canRewrite` inert_flav) -- See Note [Delicate equality kick-out]
  295. && (new_tv `elemVarSet` kind_vars || -- (1)
  296. (not (inert_flav `canRewrite` new_flav) && -- (2)
  297. new_tv `elemVarSet` (extendVarSet (tyVarsOfType rhs) tv)))
  298. where
  299. inert_flav = ctEvFlavour ev
  300. kind_vars = tyVarsOfType (tyVarKind tv) `unionVarSet`
  301. tyVarsOfType (typeKind rhs)
  302. kick_out_eq other_ct = pprPanic "kick_out_eq" (ppr other_ct)
  303. \end{code}
  304. Note [Kick out insolubles]
  305. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  306. Suppose we have an insoluble alpha ~ [alpha], which is insoluble
  307. because an occurs check. And then we unify alpha := [Int].
  308. Then we really want to rewrite the insouluble to [Int] ~ [[Int]].
  309. Now it can be decomposed. Otherwise we end up with a "Can't match
  310. [Int] ~ [[Int]]" which is true, but a bit confusing because the
  311. outer type constructors match.
  312. Note [Delicate equality kick-out]
  313. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  314. When adding an equality (a ~ xi), we kick out an inert type-variable
  315. equality (b ~ phi) in two cases
  316. (1) If the new tyvar can rewrite the kind LHS or RHS of the inert
  317. equality. Example:
  318. Work item: [W] k ~ *
  319. Inert: [W] (a:k) ~ ty
  320. [W] (b:*) ~ c :: k
  321. We must kick out those blocked inerts so that we rewrite them
  322. and can subsequently unify.
  323. (2) If the new tyvar can
  324. Work item: [G] a ~ b
  325. Inert: [W] b ~ [a]
  326. Now at this point the work item cannot be further rewritten by the
  327. inert (due to the weaker inert flavor). But we can't add the work item
  328. as-is because the inert set would then have a cyclic substitution,
  329. when rewriting a wanted type mentioning 'a'. So we must kick the inert out.
  330. We have to do this only if the inert *cannot* rewrite the work item;
  331. it it can, then the work item will have been fully rewritten by the
  332. inert during canonicalisation. So for example:
  333. Work item: [W] a ~ Int
  334. Inert: [W] b ~ [a]
  335. No need to kick out the inert, beause the inert substitution is not
  336. necessarily idemopotent. See Note [Non-idempotent inert substitution].
  337. See also point (8) of Note [Detailed InertCans Invariants]
  338. \begin{code}
  339. data SPSolveResult = SPCantSolve
  340. | SPSolved TcTyVar
  341. -- We solved this /unification/ variable to some type using reflexivity
  342. -- SPCantSolve means that we can't do the unification because e.g. the variable is untouchable
  343. -- SPSolved workItem' gives us a new *given* to go on
  344. -- @trySpontaneousSolve wi@ solves equalities where one side is a
  345. -- touchable unification variable.
  346. -- See Note [Touchables and givens]
  347. trySpontaneousSolve :: WorkItem -> TcS SPSolveResult
  348. trySpontaneousSolve workItem@(CTyEqCan { cc_ev = gw
  349. , cc_tyvar = tv1, cc_rhs = xi, cc_loc = d })
  350. | isGiven gw
  351. = return SPCantSolve
  352. | Just tv2 <- tcGetTyVar_maybe xi
  353. = do { tch1 <- isTouchableMetaTyVarTcS tv1
  354. ; tch2 <- isTouchableMetaTyVarTcS tv2
  355. ; case (tch1, tch2) of
  356. (True, True) -> trySpontaneousEqTwoWay d gw tv1 tv2
  357. (True, False) -> trySpontaneousEqOneWay d gw tv1 xi
  358. (False, True) -> trySpontaneousEqOneWay d gw tv2 (mkTyVarTy tv1)
  359. _ -> return SPCantSolve }
  360. | otherwise
  361. = do { tch1 <- isTouchableMetaTyVarTcS tv1
  362. ; if tch1 then trySpontaneousEqOneWay d gw tv1 xi
  363. else do { untch <- getUntouchables
  364. ; traceTcS "Untouchable LHS, can't spontaneously solve workitem" $
  365. vcat [text "Untouchables =" <+> ppr untch
  366. , text "Workitem =" <+> ppr workItem ]
  367. ; return SPCantSolve }
  368. }
  369. -- No need for
  370. -- trySpontaneousSolve (CFunEqCan ...) = ...
  371. -- See Note [No touchables as FunEq RHS] in TcSMonad
  372. trySpontaneousSolve _ = return SPCantSolve
  373. ----------------
  374. trySpontaneousEqOneWay :: CtLoc -> CtEvidence
  375. -> TcTyVar -> Xi -> TcS SPSolveResult
  376. -- tv is a MetaTyVar, not untouchable
  377. trySpontaneousEqOneWay d gw tv xi
  378. | not (isSigTyVar tv) || isTyVarTy xi
  379. , typeKind xi `tcIsSubKind` tyVarKind tv
  380. = solveWithIdentity d gw tv xi
  381. | otherwise -- Still can't solve, sig tyvar and non-variable rhs
  382. = return SPCantSolve
  383. ----------------
  384. trySpontaneousEqTwoWay :: CtLoc -> CtEvidence
  385. -> TcTyVar -> TcTyVar -> TcS SPSolveResult
  386. -- Both tyvars are *touchable* MetaTyvars so there is only a chance for kind error here
  387. trySpontaneousEqTwoWay d gw tv1 tv2
  388. | k1 `tcIsSubKind` k2 && nicer_to_update_tv2
  389. = solveWithIdentity d gw tv2 (mkTyVarTy tv1)
  390. | k2 `tcIsSubKind` k1
  391. = solveWithIdentity d gw tv1 (mkTyVarTy tv2)
  392. | otherwise
  393. = return SPCantSolve
  394. where
  395. k1 = tyVarKind tv1
  396. k2 = tyVarKind tv2
  397. nicer_to_update_tv2 = isSigTyVar tv1 || isSystemName (Var.varName tv2)
  398. \end{code}
  399. Note [Kind errors]
  400. ~~~~~~~~~~~~~~~~~~
  401. Consider the wanted problem:
  402. alpha ~ (# Int, Int #)
  403. where alpha :: ArgKind and (# Int, Int #) :: (#). We can't spontaneously solve this constraint,
  404. but we should rather reject the program that give rise to it. If 'trySpontaneousEqTwoWay'
  405. simply returns @CantSolve@ then that wanted constraint is going to propagate all the way and
  406. get quantified over in inference mode. That's bad because we do know at this point that the
  407. constraint is insoluble. Instead, we call 'recKindErrorTcS' here, which will fail later on.
  408. The same applies in canonicalization code in case of kind errors in the givens.
  409. However, when we canonicalize givens we only check for compatibility (@compatKind@).
  410. If there were a kind error in the givens, this means some form of inconsistency or dead code.
  411. You may think that when we spontaneously solve wanteds we may have to look through the
  412. bindings to determine the right kind of the RHS type. E.g one may be worried that xi is
  413. @alpha@ where alpha :: ? and a previous spontaneous solving has set (alpha := f) with (f :: *).
  414. But we orient our constraints so that spontaneously solved ones can rewrite all other constraint
  415. so this situation can't happen.
  416. Note [Spontaneous solving and kind compatibility]
  417. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  418. Note that our canonical constraints insist that *all* equalities (tv ~
  419. xi) or (F xis ~ rhs) require the LHS and the RHS to have *compatible*
  420. the same kinds. ("compatible" means one is a subKind of the other.)
  421. - It can't be *equal* kinds, because
  422. b) wanted constraints don't necessarily have identical kinds
  423. eg alpha::? ~ Int
  424. b) a solved wanted constraint becomes a given
  425. - SPJ thinks that *given* constraints (tv ~ tau) always have that
  426. tau has a sub-kind of tv; and when solving wanted constraints
  427. in trySpontaneousEqTwoWay we re-orient to achieve this.
  428. - Note that the kind invariant is maintained by rewriting.
  429. Eg wanted1 rewrites wanted2; if both were compatible kinds before,
  430. wanted2 will be afterwards. Similarly givens.
  431. Caveat:
  432. - Givens from higher-rank, such as:
  433. type family T b :: * -> * -> *
  434. type instance T Bool = (->)
  435. f :: forall a. ((T a ~ (->)) => ...) -> a -> ...
  436. flop = f (...) True
  437. Whereas we would be able to apply the type instance, we would not be able to
  438. use the given (T Bool ~ (->)) in the body of 'flop'
  439. Note [Avoid double unifications]
  440. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  441. The spontaneous solver has to return a given which mentions the unified unification
  442. variable *on the left* of the equality. Here is what happens if not:
  443. Original wanted: (a ~ alpha), (alpha ~ Int)
  444. We spontaneously solve the first wanted, without changing the order!
  445. given : a ~ alpha [having unified alpha := a]
  446. Now the second wanted comes along, but he cannot rewrite the given, so we simply continue.
  447. At the end we spontaneously solve that guy, *reunifying* [alpha := Int]
  448. We avoid this problem by orienting the resulting given so that the unification
  449. variable is on the left. [Note that alternatively we could attempt to
  450. enforce this at canonicalization]
  451. See also Note [No touchables as FunEq RHS] in TcSMonad; avoiding
  452. double unifications is the main reason we disallow touchable
  453. unification variables as RHS of type family equations: F xis ~ alpha.
  454. \begin{code}
  455. ----------------
  456. solveWithIdentity :: CtLoc -> CtEvidence -> TcTyVar -> Xi -> TcS SPSolveResult
  457. -- Solve with the identity coercion
  458. -- Precondition: kind(xi) is a sub-kind of kind(tv)
  459. -- Precondition: CtEvidence is Wanted or Derived
  460. -- See [New Wanted Superclass Work] to see why solveWithIdentity
  461. -- must work for Derived as well as Wanted
  462. -- Returns: workItem where
  463. -- workItem = the new Given constraint
  464. --
  465. -- NB: No need for an occurs check here, because solveWithIdentity always
  466. -- arises from a CTyEqCan, a *canonical* constraint. Its invariants
  467. -- say that in (a ~ xi), the type variable a does not appear in xi.
  468. -- See TcRnTypes.Ct invariants.
  469. solveWithIdentity _d wd tv xi
  470. = do { let tv_ty = mkTyVarTy tv
  471. ; traceTcS "Sneaky unification:" $
  472. vcat [text "Unifies:" <+> ppr tv <+> ptext (sLit ":=") <+> ppr xi,
  473. text "Coercion:" <+> pprEq tv_ty xi,
  474. text "Left Kind is:" <+> ppr (typeKind tv_ty),
  475. text "Right Kind is:" <+> ppr (typeKind xi) ]
  476. ; let xi' = defaultKind xi
  477. -- We only instantiate kind unification variables
  478. -- with simple kinds like *, not OpenKind or ArgKind
  479. -- cf TcUnify.uUnboundKVar
  480. ; setWantedTyBind tv xi'
  481. ; let refl_evtm = EvCoercion (mkTcReflCo xi')
  482. ; when (isWanted wd) $
  483. setEvBind (ctev_evar wd) refl_evtm
  484. ; return (SPSolved tv) }
  485. \end{code}
  486. *********************************************************************************
  487. * *
  488. The interact-with-inert Stage
  489. * *
  490. *********************************************************************************
  491. Note [
  492. Note [The Solver Invariant]
  493. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  494. We always add Givens first. So you might think that the solver has
  495. the invariant
  496. If the work-item is Given,
  497. then the inert item must Given
  498. But this isn't quite true. Suppose we have,
  499. c1: [W] beta ~ [alpha], c2 : [W] blah, c3 :[W] alpha ~ Int
  500. After processing the first two, we get
  501. c1: [G] beta ~ [alpha], c2 : [W] blah
  502. Now, c3 does not interact with the the given c1, so when we spontaneously
  503. solve c3, we must re-react it with the inert set. So we can attempt a
  504. reaction between inert c2 [W] and work-item c3 [G].
  505. It *is* true that [Solver Invariant]
  506. If the work-item is Given,
  507. AND there is a reaction
  508. then the inert item must Given
  509. or, equivalently,
  510. If the work-item is Given,
  511. and the inert item is Wanted/Derived
  512. then there is no reaction
  513. \begin{code}
  514. -- Interaction result of WorkItem <~> Ct
  515. data InteractResult
  516. = IRWorkItemConsumed { ir_fire :: String } -- Work item discharged by interaction; stop
  517. | IRReplace { ir_fire :: String } -- Inert item replaced by work item; stop
  518. | IRInertConsumed { ir_fire :: String } -- Inert item consumed, keep going with work item
  519. | IRKeepGoing { ir_fire :: String } -- Inert item remains, keep going with work item
  520. interactWithInertsStage :: WorkItem -> TcS StopOrContinue
  521. -- Precondition: if the workitem is a CTyEqCan then it will not be able to
  522. -- react with anything at this stage.
  523. interactWithInertsStage wi
  524. = do { traceTcS "interactWithInerts" $ text "workitem = " <+> ppr wi
  525. ; rels <- extractRelevantInerts wi
  526. ; traceTcS "relevant inerts are:" $ ppr rels
  527. ; foldlBagM interact_next (ContinueWith wi) rels }
  528. where interact_next Stop atomic_inert
  529. = do { insertInertItemTcS atomic_inert; return Stop }
  530. interact_next (ContinueWith wi) atomic_inert
  531. = do { ir <- doInteractWithInert atomic_inert wi
  532. ; let mk_msg rule keep_doc
  533. = vcat [ text rule <+> keep_doc
  534. , ptext (sLit "InertItem =") <+> ppr atomic_inert
  535. , ptext (sLit "WorkItem =") <+> ppr wi ]
  536. ; case ir of
  537. IRWorkItemConsumed { ir_fire = rule }
  538. -> do { traceFireTcS wi (mk_msg rule (text "WorkItemConsumed"))
  539. ; insertInertItemTcS atomic_inert
  540. ; return Stop }
  541. IRReplace { ir_fire = rule }
  542. -> do { traceFireTcS atomic_inert
  543. (mk_msg rule (text "InertReplace"))
  544. ; insertInertItemTcS wi
  545. ; return Stop }
  546. IRInertConsumed { ir_fire = rule }
  547. -> do { traceFireTcS atomic_inert
  548. (mk_msg rule (text "InertItemConsumed"))
  549. ; return (ContinueWith wi) }
  550. IRKeepGoing {}
  551. -> do { insertInertItemTcS atomic_inert
  552. ; return (ContinueWith wi) }
  553. }
  554. \end{code}
  555. \begin{code}
  556. --------------------------------------------
  557. doInteractWithInert :: Ct -> Ct -> TcS InteractResult
  558. -- Identical class constraints.
  559. doInteractWithInert inertItem@(CDictCan { cc_ev = fl1, cc_class = cls1, cc_tyargs = tys1, cc_loc = loc1 })
  560. workItem@(CDictCan { cc_ev = fl2, cc_class = cls2, cc_tyargs = tys2, cc_loc = loc2 })
  561. | cls1 == cls2
  562. = do { let pty1 = mkClassPred cls1 tys1
  563. pty2 = mkClassPred cls2 tys2
  564. inert_pred_loc = (pty1, pprArisingAt loc1)
  565. work_item_pred_loc = (pty2, pprArisingAt loc2)
  566. ; let fd_eqns = improveFromAnother inert_pred_loc work_item_pred_loc
  567. ; fd_work <- rewriteWithFunDeps fd_eqns loc2
  568. -- We don't really rewrite tys2, see below _rewritten_tys2, so that's ok
  569. -- NB: We do create FDs for given to report insoluble equations that arise
  570. -- from pairs of Givens, and also because of floating when we approximate
  571. -- implications. The relevant test is: typecheck/should_fail/FDsFromGivens.hs
  572. -- Also see Note [When improvement happens]
  573. ; traceTcS "doInteractWithInert:dict"
  574. (vcat [ text "inertItem =" <+> ppr inertItem
  575. , text "workItem =" <+> ppr workItem
  576. , text "fundeps =" <+> ppr fd_work ])
  577. ; case fd_work of
  578. -- No Functional Dependencies
  579. [] | eqTypes tys1 tys2 -> solveOneFromTheOther "Cls/Cls" fl1 workItem
  580. | otherwise -> return (IRKeepGoing "NOP")
  581. -- Actual Functional Dependencies
  582. _ | cls1 `hasKey` ipClassNameKey
  583. , isGiven fl1, isGiven fl2 -- See Note [Shadowing of Implicit Parameters]
  584. -> return (IRReplace ("Replace IP"))
  585. -- Standard thing: create derived fds and keep on going. Importantly we don't
  586. -- throw workitem back in the worklist because this can cause loops. See #5236.
  587. | otherwise
  588. -> do { updWorkListTcS (extendWorkListEqs fd_work)
  589. ; return (IRKeepGoing "Cls/Cls (new fundeps)") } -- Just keep going without droping the inert
  590. }
  591. -- Two pieces of irreducible evidence: if their types are *exactly identical*
  592. -- we can rewrite them. We can never improve using this:
  593. -- if we want ty1 :: Constraint and have ty2 :: Constraint it clearly does not
  594. -- mean that (ty1 ~ ty2)
  595. doInteractWithInert (CIrredEvCan { cc_ev = ifl })
  596. workItem@(CIrredEvCan { cc_ev = wfl })
  597. | ctEvPred ifl `eqType` ctEvPred wfl
  598. = solveOneFromTheOther "Irred/Irred" ifl workItem
  599. doInteractWithInert ii@(CFunEqCan { cc_ev = ev1, cc_fun = tc1
  600. , cc_tyargs = args1, cc_rhs = xi1, cc_loc = d1 })
  601. wi@(CFunEqCan { cc_ev = ev2, cc_fun = tc2
  602. , cc_tyargs = args2, cc_rhs = xi2, cc_loc = d2 })
  603. | i_solves_w && (not (w_solves_i && isMetaTyVarTy xi1))
  604. -- See Note [Carefully solve the right CFunEqCan]
  605. = ASSERT( lhss_match ) -- extractRelevantInerts ensures this
  606. do { traceTcS "interact with inerts: FunEq/FunEq" $
  607. vcat [ text "workItem =" <+> ppr wi
  608. , text "inertItem=" <+> ppr ii ]
  609. ; let xev = XEvTerm xcomp xdecomp
  610. -- xcomp : [(xi2 ~ xi1)] -> (F args ~ xi2)
  611. xcomp [x] = EvCoercion (co1 `mkTcTransCo` mk_sym_co x)
  612. xcomp _ = panic "No more goals!"
  613. -- xdecomp : (F args ~ xi2) -> [(xi2 ~ xi1)]
  614. xdecomp x = [EvCoercion (mk_sym_co x `mkTcTransCo` co1)]
  615. ; ctevs <- xCtFlavor ev2 [mkTcEqPred xi2 xi1] xev
  616. -- No caching! See Note [Cache-caused loops]
  617. -- Why not (mkTcEqPred xi1 xi2)? See Note [Efficient orientation]
  618. ; emitWorkNC d2 ctevs
  619. ; return (IRWorkItemConsumed "FunEq/FunEq") }
  620. | fl2 `canSolve` fl1
  621. = ASSERT( lhss_match ) -- extractRelevantInerts ensures this
  622. do { traceTcS "interact with inerts: FunEq/FunEq" $
  623. vcat [ text "workItem =" <+> ppr wi
  624. , text "inertItem=" <+> ppr ii ]
  625. ; let xev = XEvTerm xcomp xdecomp
  626. -- xcomp : [(xi2 ~ xi1)] -> [(F args ~ xi1)]
  627. xcomp [x] = EvCoercion (co2 `mkTcTransCo` evTermCoercion x)
  628. xcomp _ = panic "No more goals!"
  629. -- xdecomp : (F args ~ xi1) -> [(xi2 ~ xi1)]
  630. xdecomp x = [EvCoercion (mkTcSymCo co2 `mkTcTransCo` evTermCoercion x)]
  631. ; ctevs <- xCtFlavor ev1 [mkTcEqPred xi2 xi1] xev
  632. -- Why not (mkTcEqPred xi1 xi2)? See Note [Efficient orientation]
  633. ; emitWorkNC d1 ctevs
  634. ; return (IRInertConsumed "FunEq/FunEq") }
  635. where
  636. lhss_match = tc1 == tc2 && eqTypes args1 args2
  637. co1 = evTermCoercion $ ctEvTerm ev1
  638. co2 = evTermCoercion $ ctEvTerm ev2
  639. mk_sym_co x = mkTcSymCo (evTermCoercion x)
  640. fl1 = ctEvFlavour ev1
  641. fl2 = ctEvFlavour ev2
  642. i_solves_w = fl1 `canSolve` fl2
  643. w_solves_i = fl2 `canSolve` fl1
  644. doInteractWithInert _ _ = return (IRKeepGoing "NOP")
  645. \end{code}
  646. Note [Efficient Orientation]
  647. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  648. Suppose we are interacting two FunEqCans with the same LHS:
  649. (inert) ci :: (F ty ~ xi_i)
  650. (work) cw :: (F ty ~ xi_w)
  651. We prefer to keep the inert (else we pass the work item on down
  652. the pipeline, which is a bit silly). If we keep the inert, we
  653. will (a) discharge 'cw'
  654. (b) produce a new equality work-item (xi_w ~ xi_i)
  655. Notice the orientation (xi_w ~ xi_i) NOT (xi_i ~ xi_w):
  656. new_work :: xi_w ~ xi_i
  657. cw := ci ; sym new_work
  658. Why? Consider the simplest case when xi1 is a type variable. If
  659. we generate xi1~xi2, porcessing that constraint will kick out 'ci'.
  660. If we generate xi2~xi1, there is less chance of that happening.
  661. Of course it can and should still happen if xi1=a, xi1=Int, say.
  662. But we want to avoid it happening needlessly.
  663. Similarly, if we *can't* keep the inert item (because inert is Wanted,
  664. and work is Given, say), we prefer to orient the new equality (xi_i ~
  665. xi_w).
  666. Note [Carefully solve the right CFunEqCan]
  667. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  668. Consider the constraints
  669. c1 :: F Int ~ a -- Arising from an application line 5
  670. c2 :: F Int ~ Bool -- Arising from an application line 10
  671. Suppose that 'a' is a unification variable, arising only from
  672. flattening. So there is no error on line 5; it's just a flattening
  673. variable. But there is (or might be) an error on line 10.
  674. Two ways to combine them, leaving either (Plan A)
  675. c1 :: F Int ~ a -- Arising from an application line 5
  676. c3 :: a ~ Bool -- Arising from an application line 10
  677. or (Plan B)
  678. c2 :: F Int ~ Bool -- Arising from an application line 10
  679. c4 :: a ~ Bool -- Arising from an application line 5
  680. Plan A will unify c3, leaving c1 :: F Int ~ Bool as an error
  681. on the *totally innocent* line 5. An example is test SimpleFail16
  682. where the expected/actual message comes out backwards if we use
  683. the wrong plan.
  684. The second is the right thing to do. Hence the isMetaTyVarTy
  685. test when solving pairwise CFunEqCan.
  686. Note [Shadowing of Implicit Parameters]
  687. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  688. Consider the following example:
  689. f :: (?x :: Char) => Char
  690. f = let ?x = 'a' in ?x
  691. The "let ?x = ..." generates an implication constraint of the form:
  692. ?x :: Char => ?x :: Char
  693. Furthermore, the signature for `f` also generates an implication
  694. constraint, so we end up with the following nested implication:
  695. ?x :: Char => (?x :: Char => ?x :: Char)
  696. Note that the wanted (?x :: Char) constraint may be solved in
  697. two incompatible ways: either by using the parameter from the
  698. signature, or by using the local definition. Our intention is
  699. that the local definition should "shadow" the parameter of the
  700. signature, and we implement this as follows: when we add a new
  701. given implicit parameter to the inert set, it replaces any existing
  702. givens for the same implicit parameter.
  703. This works for the normal cases but it has an odd side effect
  704. in some pathological programs like this:
  705. -- This is accepted, the second parameter shadows
  706. f1 :: (?x :: Int, ?x :: Char) => Char
  707. f1 = ?x
  708. -- This is rejected, the second parameter shadows
  709. f2 :: (?x :: Int, ?x :: Char) => Int
  710. f2 = ?x
  711. Both of these are actually wrong: when we try to use either one,
  712. we'll get two incompatible wnated constraints (?x :: Int, ?x :: Char),
  713. which would lead to an error.
  714. I can think of two ways to fix this:
  715. 1. Simply disallow multiple constratits for the same implicit
  716. parameter---this is never useful, and it can be detected completely
  717. syntactically.
  718. 2. Move the shadowing machinery to the location where we nest
  719. implications, and add some code here that will produce an
  720. error if we get multiple givens for the same implicit parameter.
  721. Note [Cache-caused loops]
  722. ~~~~~~~~~~~~~~~~~~~~~~~~~
  723. It is very dangerous to cache a rewritten wanted family equation as 'solved' in our
  724. solved cache (which is the default behaviour or xCtFlavor), because the interaction
  725. may not be contributing towards a solution. Here is an example:
  726. Initial inert set:
  727. [W] g1 : F a ~ beta1
  728. Work item:
  729. [W] g2 : F a ~ beta2
  730. The work item will react with the inert yielding the _same_ inert set plus:
  731. i) Will set g2 := g1 `cast` g3
  732. ii) Will add to our solved cache that [S] g2 : F a ~ beta2
  733. iii) Will emit [W] g3 : beta1 ~ beta2
  734. Now, the g3 work item will be spontaneously solved to [G] g3 : beta1 ~ beta2
  735. and then it will react the item in the inert ([W] g1 : F a ~ beta1). So it
  736. will set
  737. g1 := g ; sym g3
  738. and what is g? Well it would ideally be a new goal of type (F a ~ beta2) but
  739. remember that we have this in our solved cache, and it is ... g2! In short we
  740. created the evidence loop:
  741. g2 := g1 ; g3
  742. g3 := refl
  743. g1 := g2 ; sym g3
  744. To avoid this situation we do not cache as solved any workitems (or inert)
  745. which did not really made a 'step' towards proving some goal. Solved's are
  746. just an optimization so we don't lose anything in terms of completeness of
  747. solving.
  748. \begin{code}
  749. solveOneFromTheOther :: String -- Info
  750. -> CtEvidence -- Inert
  751. -> Ct -- WorkItem
  752. -> TcS InteractResult
  753. -- Preconditions:
  754. -- 1) inert and work item represent evidence for the /same/ predicate
  755. -- 2) ip/class/irred evidence (no coercions) only
  756. solveOneFromTheOther info ifl workItem
  757. | isDerived wfl
  758. = return (IRWorkItemConsumed ("Solved[DW] " ++ info))
  759. | isDerived ifl -- The inert item is Derived, we can just throw it away,
  760. -- The workItem is inert wrt earlier inert-set items,
  761. -- so it's safe to continue on from this point
  762. = return (IRInertConsumed ("Solved[DI] " ++ info))
  763. | CtWanted { ctev_evar = ev_id } <- wfl
  764. = do { setEvBind ev_id (ctEvTerm ifl); return (IRWorkItemConsumed ("Solved(w) " ++ info)) }
  765. | CtWanted { ctev_evar = ev_id } <- ifl
  766. = do { setEvBind ev_id (ctEvTerm wfl); return (IRInertConsumed ("Solved(g) " ++ info)) }
  767. | otherwise -- If both are Given, we already have evidence; no need to duplicate
  768. -- But the work item *overrides* the inert item (hence IRReplace)
  769. -- See Note [Shadowing of Implicit Parameters]
  770. = return (IRReplace ("Replace(gg) " ++ info))
  771. where
  772. wfl = cc_ev workItem
  773. \end{code}
  774. Note [Shadowing of Implicit Parameters]
  775. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  776. Consider the following example:
  777. f :: (?x :: Char) => Char
  778. f = let ?x = 'a' in ?x
  779. The "let ?x = ..." generates an implication constraint of the form:
  780. ?x :: Char => ?x :: Char
  781. Furthermore, the signature for `f` also generates an implication
  782. constraint, so we end up with the following nested implication:
  783. ?x :: Char => (?x :: Char => ?x :: Char)
  784. Note that the wanted (?x :: Char) constraint may be solved in
  785. two incompatible ways: either by using the parameter from the
  786. signature, or by using the local definition. Our intention is
  787. that the local definition should "shadow" the parameter of the
  788. signature, and we implement this as follows: when we nest implications,
  789. we remove any implicit parameters in the outer implication, that
  790. have the same name as givens of the inner implication.
  791. Here is another variation of the example:
  792. f :: (?x :: Int) => Char
  793. f = let ?x = 'x' in ?x
  794. This program should also be accepted: the two constraints `?x :: Int`
  795. and `?x :: Char` never exist in the same context, so they don't get to
  796. interact to cause failure.
  797. Note [Superclasses and recursive dictionaries]
  798. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  799. Overlaps with Note [SUPERCLASS-LOOP 1]
  800. Note [SUPERCLASS-LOOP 2]
  801. Note [Recursive instances and superclases]
  802. ToDo: check overlap and delete redundant stuff
  803. Right before adding a given into the inert set, we must
  804. produce some more work, that will bring the superclasses
  805. of the given into scope. The superclass constraints go into
  806. our worklist.
  807. When we simplify a wanted constraint, if we first see a matching
  808. instance, we may produce new wanted work. To (1) avoid doing this work
  809. twice in the future and (2) to handle recursive dictionaries we may ``cache''
  810. this item as given into our inert set WITHOUT adding its superclass constraints,
  811. otherwise we'd be in danger of creating a loop [In fact this was the exact reason
  812. for doing the isGoodRecEv check in an older version of the type checker].
  813. But now we have added partially solved constraints to the worklist which may
  814. interact with other wanteds. Consider the example:
  815. Example 1:
  816. class Eq b => Foo a b --- 0-th selector
  817. instance Eq a => Foo [a] a --- fooDFun
  818. and wanted (Foo [t] t). We are first going to see that the instance matches
  819. and create an inert set that includes the solved (Foo [t] t) but not its superclasses:
  820. d1 :_g Foo [t] t d1 := EvDFunApp fooDFun d3
  821. Our work list is going to contain a new *wanted* goal
  822. d3 :_w Eq t
  823. Ok, so how do we get recursive dictionaries, at all:
  824. Example 2:
  825. data D r = ZeroD | SuccD (r (D r));
  826. instance (Eq (r (D r))) => Eq (D r) where
  827. ZeroD == ZeroD = True
  828. (SuccD a) == (SuccD b) = a == b
  829. _ == _ = False;
  830. equalDC :: D [] -> D [] -> Bool;
  831. equalDC = (==);
  832. We need to prove (Eq (D [])). Here's how we go:
  833. d1 :_w Eq (D [])
  834. by instance decl, holds if
  835. d2 :_w Eq [D []]
  836. where d1 = dfEqD d2
  837. *BUT* we have an inert set which gives us (no superclasses):
  838. d1 :_g Eq (D [])
  839. By the instance declaration of Eq we can show the 'd2' goal if
  840. d3 :_w Eq (D [])
  841. where d2 = dfEqList d3
  842. d1 = dfEqD d2
  843. Now, however this wanted can interact with our inert d1 to set:
  844. d3 := d1
  845. and solve the goal. Why was this interaction OK? Because, if we chase the
  846. evidence of d1 ~~> dfEqD d2 ~~-> dfEqList d3, so by setting d3 := d1 we
  847. are really setting
  848. d3 := dfEqD2 (dfEqList d3)
  849. which is FINE because the use of d3 is protected by the instance function
  850. applications.
  851. So, our strategy is to try to put solved wanted dictionaries into the
  852. inert set along with their superclasses (when this is meaningful,
  853. i.e. when new wanted goals are generated) but solve a wanted dictionary
  854. from a given only in the case where the evidence variable of the
  855. wanted is mentioned in the evidence of the given (recursively through
  856. the evidence binds) in a protected way: more instance function applications
  857. than superclass selectors.
  858. Here are some more examples from GHC's previous type checker
  859. Example 3:
  860. This code arises in the context of "Scrap Your Boilerplate with Class"
  861. class Sat a
  862. class Data ctx a
  863. instance Sat (ctx Char) => Data ctx Char -- dfunData1
  864. instance (Sat (ctx [a]), Data ctx a) => Data ctx [a] -- dfunData2
  865. class Data Maybe a => Foo a
  866. instance Foo t => Sat (Maybe t) -- dfunSat
  867. instance Data Maybe a => Foo a -- dfunFoo1
  868. instance Foo a => Foo [a] -- dfunFoo2
  869. instance Foo [Char] -- dfunFoo3
  870. Consider generating the superclasses of the instance declaration
  871. instance Foo a => Foo [a]
  872. So our problem is this
  873. d0 :_g Foo t
  874. d1 :_w Data Maybe [t]
  875. We may add the given in the inert set, along with its superclasses
  876. [assuming we don't fail because there is a matching instance, see
  877. topReactionsStage, given case ]
  878. Inert:
  879. d0 :_g Foo t
  880. WorkList
  881. d01 :_g Data Maybe t -- d2 := EvDictSuperClass d0 0
  882. d1 :_w Data Maybe [t]
  883. Then d2 can readily enter the inert, and we also do solving of the wanted
  884. Inert:
  885. d0 :_g Foo t
  886. d1 :_s Data Maybe [t] d1 := dfunData2 d2 d3
  887. WorkList
  888. d2 :_w Sat (Maybe [t])
  889. d3 :_w Data Maybe t
  890. d01 :_g Data Maybe t
  891. Now, we may simplify d2 more:
  892. Inert:
  893. d0 :_g Foo t
  894. d1 :_s Data Maybe [t] d1 := dfunData2 d2 d3
  895. d1 :_g Data Maybe [t]
  896. d2 :_g Sat (Maybe [t]) d2 := dfunSat d4
  897. WorkList:
  898. d3 :_w Data Maybe t
  899. d4 :_w Foo [t]
  900. d01 :_g Data Maybe t
  901. Now, we can just solve d3.
  902. Inert
  903. d0 :_g Foo t
  904. d1 :_s Data Maybe [t] d1 := dfunData2 d2 d3
  905. d2 :_g Sat (Maybe [t]) d2 := dfunSat d4
  906. WorkList
  907. d4 :_w Foo [t]
  908. d01 :_g Data Maybe t
  909. And now we can simplify d4 again, but since it has superclasses we *add* them to the worklist:
  910. Inert
  911. d0 :_g Foo t
  912. d1 :_s Data Maybe [t] d1 := dfunData2 d2 d3
  913. d2 :_g Sat (Maybe [t]) d2 := dfunSat d4
  914. d4 :_g Foo [t] d4 := dfunFoo2 d5
  915. WorkList:
  916. d5 :_w Foo t
  917. d6 :_g Data Maybe [t] d6 := EvDictSuperClass d4 0
  918. d01 :_g Data Maybe t
  919. Now, d5 can be solved! (and its superclass enter scope)
  920. Inert
  921. d0 :_g Foo t
  922. d1 :_s Data Maybe [t] d1 := dfunData2 d2 d3
  923. d2 :_g Sat (Maybe [t]) d2 := dfunSat d4
  924. d4 :_g Foo [t] d4 := dfunFoo2 d5
  925. d5 :_g Foo t d5 := dfunFoo1 d7
  926. WorkList:
  927. d7 :_w Data Maybe t
  928. d6 :_g Data Maybe [t]
  929. d8 :_g Data Maybe t d8 := EvDictSuperClass d5 0
  930. d01 :_g Data Maybe t
  931. Now, two problems:
  932. [1] Suppose we pick d8 and we react him with d01. Which of the two givens should
  933. we keep? Well, we *MUST NOT* drop d01 because d8 contains recursive evidence
  934. that must not be used (look at case interactInert where both inert and workitem
  935. are givens). So we have several options:
  936. - Drop the workitem always (this will drop d8)
  937. This feels very unsafe -- what if the work item was the "good" one
  938. that should be used later to solve another wanted?
  939. - Don't drop anyone: the inert set may contain multiple givens!
  940. [This is currently implemented]
  941. The "don't drop anyone" seems the most safe thing to do, so now we come to problem 2:
  942. [2] We have added both d6 and d01 in the inert set, and we are interacting our wanted
  943. d7. Now the [isRecDictEv] function in the ineration solver
  944. [case inert-given workitem-wanted] will prevent us from interacting d7 := d8
  945. precisely because chasing the evidence of d8 leads us to an unguarded use of d7.
  946. So, no interaction happens there. Then we meet d01 and there is no recursion
  947. problem there [isRectDictEv] gives us the OK to interact and we do solve d7 := d01!
  948. Note [SUPERCLASS-LOOP 1]
  949. ~~~~~~~~~~~~~~~~~~~~~~~~
  950. We have to be very, very careful when generating superclasses, lest we
  951. accidentally build a loop. Here's an example:
  952. class S a
  953. class S a => C a where { opc :: a -> a }
  954. class S b => D b where { opd :: b -> b }
  955. instance C Int where
  956. opc = opd
  957. instance D Int where
  958. opd = opc
  959. From (instance C Int) we get the constraint set {ds1:S Int, dd:D Int}
  960. Simplifying, we may well get:
  961. $dfCInt = :C ds1 (opd dd)
  962. dd = $dfDInt
  963. ds1 = $p1 dd
  964. Notice that we spot that we can extract ds1 from dd.
  965. Alas! Alack! We can do the same for (instance D Int):
  966. $dfDInt = :D ds2 (opc dc)
  967. dc = $dfCInt
  968. ds2 = $p1 dc
  969. And now we've defined the superclass in terms of itself.
  970. Two more nasty cases are in
  971. tcrun021
  972. tcrun033
  973. Solution:
  974. - Satisfy the superclass context *all by itself*
  975. (tcSimplifySuperClasses)
  976. - And do so completely; i.e. no left-over constraints
  977. to mix with the constraints arising from method declarations
  978. Note [SUPERCLASS-LOOP 2]
  979. ~~~~~~~~~~~~~~~~~~~~~~~~
  980. We need to be careful when adding "the constaint we are trying to prove".
  981. Suppose we are *given* d1:Ord a, and want to deduce (d2:C [a]) where
  982. class Ord a => C a where
  983. instance Ord [a] => C [a] where ...
  984. Then we'll use the instance decl to deduce C [a] from Ord [a], and then add the
  985. superclasses of C [a] to avails. But we must not overwrite the binding
  986. for Ord [a] (which is obtained from Ord a) with a superclass selection or we'll just
  987. build a loop!
  988. Here's another variant, immortalised in tcrun020
  989. class Monad m => C1 m
  990. class C1 m => C2 m x
  991. instance C2 Maybe Bool
  992. For the instance decl we need to build (C1 Maybe), and it's no good if
  993. we run around and add (C2 Maybe Bool) and its superclasses to the avails
  994. before we search for C1 Maybe.
  995. Here's another example
  996. class Eq b => Foo a b
  997. instance Eq a => Foo [a] a
  998. If we are reducing
  999. (Foo [t] t)
  1000. we'll first deduce that it holds (via the instance decl). We must not
  1001. then overwrite the Eq t constraint with a superclass selection!
  1002. At first I had a gross hack, whereby I simply did not add superclass constraints
  1003. in addWanted, though I did for addGiven and addIrred. This was sub-optimal,
  1004. because it lost legitimate superclass sharing, and it still didn't do the job:
  1005. I found a very obscure program (now tcrun021) in which improvement meant the
  1006. simplifier got two bites a the cherry... so

Large files files are truncated, but you can click here to view the full file