PageRenderTime 56ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/compiler/typecheck/TcInteract.lhs

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

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