PageRenderTime 37ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/compiler/typecheck/TcInteract.lhs

https://bitbucket.org/carter/ghc
Haskell | 1791 lines | 1344 code | 310 blank | 137 comment | 76 complexity | 0988bfe9a50fd5d683e2dd63cbc71365 MD5 | raw 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 superclasses
  1003. must not be added to 'givens' by addGiven.
  1004. There is a complication though. Suppose there are equalities
  1005. instance (Eq a, a~b) => Num (a,b)
  1006. Then we normalise the 'givens' wrt the equalities, so the original
  1007. given "this" dictionary is cast to one of a different type. So it's a
  1008. bit trickier than before to identify the "special" dictionary whose
  1009. superclasses must not be added. See test
  1010. indexed-types/should_run/EqInInstance
  1011. We need a persistent property of the dictionary to record this
  1012. special-ness. Current I'm using the InstLocOrigin (a bit of a hack,
  1013. but cool), which is maintained by dictionary normalisation.
  1014. Specifically, the InstLocOrigin is
  1015. NoScOrigin
  1016. then the no-superclass thing kicks in. WATCH OUT if you fiddle
  1017. with InstLocOrigin!
  1018. Note [MATCHING-SYNONYMS]
  1019. ~~~~~~~~~~~~~~~~~~~~~~~~
  1020. When trying to match a dictionary (D tau) to a top-level instance, or a
  1021. type family equation (F taus_1 ~ tau_2) to a top-level family instance,
  1022. we do *not* need to expand type synonyms because the matcher will do that for us.
  1023. Note [RHS-FAMILY-SYNONYMS]
  1024. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  1025. The RHS of a family instance is represented as yet another constructor which is
  1026. like a type synonym for the real RHS the programmer declared. Eg:
  1027. type instance F (a,a) = [a]
  1028. Becomes:
  1029. :R32 a = [a] -- internal type synonym introduced
  1030. F (a,a) ~ :R32 a -- instance
  1031. When we react a family instance with a type family equation in the work list
  1032. we keep the synonym-using RHS without expansion.
  1033. %************************************************************************
  1034. %* *
  1035. %* Functional dependencies, instantiation of equations
  1036. %* *
  1037. %************************************************************************
  1038. When we spot an equality arising from a functional dependency,
  1039. we now use that equality (a "wanted") to rewrite the work-item
  1040. constraint right away. This avoids two dangers
  1041. Danger 1: If we send the original constraint on down the pipeline
  1042. it may react with an instance declaration, and in delicate
  1043. situations (when a Given overlaps with an instance) that
  1044. may produce new insoluble goals: see Trac #4952
  1045. Danger 2: If we don't rewrite the constraint, it may re-react
  1046. with the same thing later, and produce the same equality
  1047. again --> termination worries.
  1048. To achieve this required some refactoring of FunDeps.lhs (nicer
  1049. now!).
  1050. \begin{code}
  1051. rewriteWithFunDeps :: [Equation] -> CtLoc -> TcS [Ct]
  1052. -- NB: The returned constraints are all Derived
  1053. -- Post: returns no trivial equalities (identities) and all EvVars returned are fresh
  1054. rewriteWithFunDeps eqn_pred_locs loc
  1055. = do { fd_cts <- mapM (instFunDepEqn loc) eqn_pred_locs
  1056. ; return (concat fd_cts) }
  1057. instFunDepEqn :: CtLoc -> Equation -> TcS [Ct]
  1058. -- Post: Returns the position index as well as the corresponding FunDep equality
  1059. instFunDepEqn loc (FDEqn { fd_qtvs = tvs, fd_eqs = eqs
  1060. , fd_pred1 = d1, fd_pred2 = d2 })
  1061. = do { (subst, _) <- instFlexiTcS tvs -- Takes account of kind substitution
  1062. ; foldM (do_one subst) [] eqs }
  1063. where
  1064. der_loc = pushErrCtxt FunDepOrigin (False, mkEqnMsg d1 d2) loc
  1065. do_one subst ievs (FDEq { fd_ty_left = ty1, fd_ty_right = ty2 })
  1066. | eqType sty1 sty2
  1067. = return ievs -- Return no trivial equalities
  1068. | otherwise
  1069. = do { mb_eqv <- newDerived (mkTcEqPred sty1 sty2)
  1070. ; case mb_eqv of
  1071. Just ev -> return (mkNonCanonical der_loc ev : ievs)
  1072. Nothing -> return ievs }
  1073. -- We are eventually going to emit FD work back in the work list so
  1074. -- it is important that we only return the /freshly created/ and not
  1075. -- some existing equality!
  1076. where
  1077. sty1 = Type.substTy subst ty1
  1078. sty2 = Type.substTy subst ty2
  1079. mkEqnMsg :: (TcPredType, SDoc)
  1080. -> (TcPredType, SDoc) -> TidyEnv -> TcM (TidyEnv, SDoc)
  1081. mkEqnMsg (pred1,from1) (pred2,from2) tidy_env
  1082. = do { zpred1 <- zonkTcPredType pred1
  1083. ; zpred2 <- zonkTcPredType pred2
  1084. ; let { tpred1 = tidyType tidy_env zpred1
  1085. ; tpred2 = tidyType tidy_env zpred2 }
  1086. ; let msg = vcat [ptext (sLit "When using functional dependencies to combine"),
  1087. nest 2 (sep [ppr tpred1 <> comma, nest 2 from1]),
  1088. nest 2 (sep [ppr tpred2 <> comma, nest 2 from2])]
  1089. ; return (tidy_env, msg) }
  1090. \end{code}
  1091. *********************************************************************************
  1092. * *
  1093. The top-reaction Stage
  1094. * *
  1095. *********************************************************************************
  1096. \begin{code}
  1097. topReactionsStage :: WorkItem -> TcS StopOrContinue
  1098. topReactionsStage wi
  1099. = do { inerts <- getTcSInerts
  1100. ; tir <- doTopReact inerts wi
  1101. ; case tir of
  1102. NoTopInt -> return (ContinueWith wi)
  1103. SomeTopInt rule what_next
  1104. -> do { traceFireTcS wi $
  1105. vcat [ ptext (sLit "Top react:") <+> text rule
  1106. , text "WorkItem =" <+> ppr wi ]
  1107. ; return what_next } }
  1108. data TopInteractResult
  1109. = NoTopInt
  1110. | SomeTopInt { tir_rule :: String, tir_new_item :: StopOrContinue }
  1111. doTopReact :: InertSet -> WorkItem -> TcS TopInteractResult
  1112. -- The work item does not react with the inert set, so try interaction with top-level
  1113. -- instances. Note:
  1114. --
  1115. -- (a) The place to add superclasses in not here in doTopReact stage.
  1116. -- Instead superclasses are added in the worklist as part of the
  1117. -- canonicalization process. See Note [Adding superclasses].
  1118. --
  1119. -- (b) See Note [Given constraint that matches an instance declaration]
  1120. -- for some design decisions for given dictionaries.
  1121. doTopReact inerts workItem
  1122. = do { traceTcS "doTopReact" (ppr workItem)
  1123. ; case workItem of
  1124. CDictCan { cc_ev = fl, cc_class = cls, cc_tyargs = xis
  1125. , cc_loc = d }
  1126. -> doTopReactDict inerts workItem fl cls xis d
  1127. CFunEqCan { cc_ev = fl, cc_fun = tc, cc_tyargs = args
  1128. , cc_rhs = xi, cc_loc = d }
  1129. -> doTopReactFunEq workItem fl tc args xi d
  1130. _ -> -- Any other work item does not react with any top-level equations
  1131. return NoTopInt }
  1132. --------------------
  1133. doTopReactDict :: InertSet -> WorkItem -> CtEvidence -> Class -> [Xi]
  1134. -> CtLoc -> TcS TopInteractResult
  1135. doTopReactDict inerts workItem fl cls xis loc
  1136. = do { instEnvs <- getInstEnvs
  1137. ; let pred = mkClassPred cls xis
  1138. fd_eqns = improveFromInstEnv instEnvs (pred, arising_sdoc)
  1139. ; fd_work <- rewriteWithFunDeps fd_eqns loc
  1140. ; if not (null fd_work) then
  1141. do { updWorkListTcS (extendWorkListEqs fd_work)
  1142. ; return SomeTopInt { tir_rule = "Dict/Top (fundeps)"
  1143. , tir_new_item = ContinueWith workItem } }
  1144. else if not (isWanted fl) then
  1145. return NoTopInt
  1146. else do
  1147. { solved_dicts <- getTcSInerts >>= (return . inert_solved_dicts)
  1148. ; case lookupSolvedDict solved_dicts pred of {
  1149. Just ev -> do { setEvBind dict_id (ctEvTerm ev);
  1150. ; return $
  1151. SomeTopInt { tir_rule = "Dict/Top (cached)"
  1152. , tir_new_item = Stop } } ;
  1153. Nothing -> do
  1154. { lkup_inst_res <- matchClassInst inerts cls xis loc
  1155. ; case lkup_inst_res of
  1156. GenInst wtvs ev_term -> do { addSolvedDict fl
  1157. ; doSolveFromInstance wtvs ev_term }
  1158. NoInstance -> return NoTopInt } } } }
  1159. where
  1160. arising_sdoc = pprArisingAt loc
  1161. dict_id = ctEvId fl
  1162. doSolveFromInstance :: [CtEvidence] -> EvTerm -> TcS TopInteractResult
  1163. -- Precondition: evidence term matches the predicate workItem
  1164. doSolveFromInstance evs ev_term
  1165. | null evs
  1166. = do { traceTcS "doTopReact/found nullary instance for" $
  1167. ppr dict_id
  1168. ; setEvBind dict_id ev_term
  1169. ; return $
  1170. SomeTopInt { tir_rule = "Dict/Top (solved, no new work)"
  1171. , tir_new_item = Stop } }
  1172. | otherwise
  1173. = do { traceTcS "doTopReact/found non-nullary instance for" $
  1174. ppr dict_id
  1175. ; setEvBind dict_id ev_term
  1176. ; let mk_new_wanted ev
  1177. = CNonCanonical { cc_ev = ev
  1178. , cc_loc = bumpCtLocDepth loc }
  1179. ; updWorkListTcS (extendWorkListCts (map mk_new_wanted evs))
  1180. ; return $
  1181. SomeTopInt { tir_rule = "Dict/Top (solved, more work)"
  1182. , tir_new_item = Stop } }
  1183. --------------------
  1184. doTopReactFunEq :: Ct -> CtEvidence -> TyCon -> [Xi] -> Xi
  1185. -> CtLoc -> TcS TopInteractResult
  1186. doTopReactFunEq _ct fl fun_tc args xi loc
  1187. = ASSERT (isSynFamilyTyCon fun_tc) -- No associated data families have
  1188. -- reached this far
  1189. -- Look in the cache of solved funeqs
  1190. do { fun_eq_cache <- getTcSInerts >>= (return . inert_solved_funeqs)
  1191. ; case lookupFamHead fun_eq_cache fam_ty of {
  1192. Just (ctev, rhs_ty)
  1193. | ctEvFlavour ctev `canRewrite` ctEvFlavour fl
  1194. -> ASSERT( not (isDerived ctev) )
  1195. succeed_with "Fun/Cache" (evTermCoercion (ctEvTerm ctev)) rhs_ty ;
  1196. _other ->
  1197. -- Look up in top-level instances
  1198. do { match_res <- matchFam fun_tc args -- See Note [MATCHING-SYNONYMS]
  1199. ; case match_res of {
  1200. Nothing -> return NoTopInt ;
  1201. Just (famInst, rep_tys) ->
  1202. -- Found a top-level instance
  1203. do { -- Add it to the solved goals
  1204. unless (isDerived fl) (addSolvedFunEq fam_ty fl xi)
  1205. ; let coe_ax = famInstAxiom famInst
  1206. ; succeed_with "Fun/Top" (mkTcAxInstCo coe_ax rep_tys)
  1207. (mkAxInstRHS coe_ax rep_tys) } } } } }
  1208. where
  1209. fam_ty = mkTyConApp fun_tc args
  1210. succeed_with :: String -> TcCoercion -> TcType -> TcS TopInteractResult
  1211. succeed_with str co rhs_ty -- co :: fun_tc args ~ rhs_ty
  1212. = do { ctevs <- xCtFlavor fl [mkTcEqPred rhs_ty xi] xev
  1213. ; traceTcS ("doTopReactFunEq " ++ str) (ppr ctevs)
  1214. ; case ctevs of
  1215. [ctev] -> updWorkListTcS $ extendWorkListEq $
  1216. CNonCanonical { cc_ev = ctev
  1217. , cc_loc = bumpCtLocDepth loc }
  1218. ctevs -> -- No subgoal (because it's cached)
  1219. ASSERT( null ctevs) return ()
  1220. ; return $ SomeTopInt { tir_rule = str
  1221. , tir_new_item = Stop } }
  1222. where
  1223. xdecomp x = [EvCoercion (mkTcSymCo co `mkTcTransCo` evTermCoercion x)]
  1224. xcomp [x] = EvCoercion (co `mkTcTransCo` evTermCoercion x)
  1225. xcomp _ = panic "No more goals!"
  1226. xev = XEvTerm xcomp xdecomp
  1227. \end{code}
  1228. Note [FunDep and implicit parameter reactions]
  1229. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1230. Currently, our story of interacting two dictionaries (or a dictionary
  1231. and top-level instances) for functional dependencies, and implicit
  1232. paramters, is that we simply produce new Derived equalities. So for example
  1233. class D a b | a -> b where ...
  1234. Inert:
  1235. d1 :g D Int Bool
  1236. WorkItem:
  1237. d2 :w D Int alpha
  1238. We generate the extra work item
  1239. cv :d alpha ~ Bool
  1240. where 'cv' is currently unused. However, this new item can perhaps be
  1241. spontaneously solved to become given and react with d2,
  1242. discharging it in favour of a new constraint d2' thus:
  1243. d2' :w D Int Bool
  1244. d2 := d2' |> D Int cv
  1245. Now d2' can be discharged from d1
  1246. We could be more aggressive and try to *immediately* solve the dictionary
  1247. using those extra equalities, but that requires those equalities to carry
  1248. evidence and derived do not carry evidence.
  1249. If that were the case with the same inert set and work item we might dischard
  1250. d2 directly:
  1251. cv :w alpha ~ Bool
  1252. d2 := d1 |> D Int cv
  1253. But in general it's a bit painful to figure out the necessary coercion,
  1254. so we just take the first approach. Here is a better example. Consider:
  1255. class C a b c | a -> b
  1256. And:
  1257. [Given] d1 : C T Int Char
  1258. [Wanted] d2 : C T beta Int
  1259. In this case, it's *not even possible* to solve the wanted immediately.
  1260. So we should simply output the functional dependency and add this guy
  1261. [but NOT its superclasses] back in the worklist. Even worse:
  1262. [Given] d1 : C T Int beta
  1263. [Wanted] d2: C T beta Int
  1264. Then it is solvable, but its very hard to detect this on the spot.
  1265. It's exactly the same with implicit parameters, except that the
  1266. "aggressive" approach would be much easier to implement.
  1267. Note [When improvement happens]
  1268. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1269. We fire an improvement rule when
  1270. * Two constraints match (modulo the fundep)
  1271. e.g. C t1 t2, C t1 t3 where C a b | a->b
  1272. The two match because the first arg is identical
  1273. Note that we *do* fire the improvement if one is Given and one is Derived (e.g. a
  1274. superclass of a Wanted goal) or if both are Given.
  1275. Example (tcfail138)
  1276. class L a b | a -> b
  1277. class (G a, L a b) => C a b
  1278. instance C a b' => G (Maybe a)
  1279. instance C a b => C (Maybe a) a
  1280. instance L (Maybe a) a
  1281. When solving the superclasses of the (C (Maybe a) a) instance, we get
  1282. Given: C a b ... and hance by superclasses, (G a, L a b)
  1283. Wanted: G (Maybe a)
  1284. Use the instance decl to get
  1285. Wanted: C a b'
  1286. The (C a b') is inert, so we generate its Derived superclasses (L a b'),
  1287. and now we need improvement between that derived superclass an the Given (L a b)
  1288. Test typecheck/should_fail/FDsFromGivens also shows why it's a good idea to
  1289. emit Derived FDs for givens as well.
  1290. Note [Overriding implicit parameters]
  1291. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1292. Consider
  1293. f :: (?x::a) -> Bool -> a
  1294. g v = let ?x::Int = 3
  1295. in (f v, let ?x::Bool = True in f v)
  1296. This should probably be well typed, with
  1297. g :: Bool -> (Int, Bool)
  1298. So the inner binding for ?x::Bool *overrides* the outer one.
  1299. Hence a work-item Given overrides an inert-item Given.
  1300. Note [Given constraint that matches an instance declaration]
  1301. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1302. What should we do when we discover that one (or more) top-level
  1303. instances match a given (or solved) class constraint? We have
  1304. two possibilities:
  1305. 1. Reject the program. The reason is that there may not be a unique
  1306. best strategy for the solver. Example, from the OutsideIn(X) paper:
  1307. instance P x => Q [x]
  1308. instance (x ~ y) => R [x] y
  1309. wob :: forall a b. (Q [b], R b a) => a -> Int
  1310. g :: forall a. Q [a] => [a] -> Int
  1311. g x = wob x
  1312. will generate the impliation constraint:
  1313. Q [a] => (Q [beta], R beta [a])
  1314. If we react (Q [beta]) with its top-level axiom, we end up with a
  1315. (P beta), which we have no way of discharging. On the other hand,
  1316. if we react R beta [a] with the top-level we get (beta ~ a), which
  1317. is solvable and can help us rewrite (Q [beta]) to (Q [a]) which is
  1318. now solvable by the given Q [a].
  1319. However, this option is restrictive, for instance [Example 3] from
  1320. Note [Recursive instances and superclases] will fail to work.
  1321. 2. Ignore the problem, hoping that the situations where there exist indeed
  1322. such multiple strategies are rare: Indeed the cause of the previous
  1323. problem is that (R [x] y) yields the new work (x ~ y) which can be
  1324. *spontaneously* solved, not using the givens.
  1325. We are choosing option 2 below but we might consider having a flag as well.
  1326. Note [New Wanted Superclass Work]
  1327. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1328. Even in the case of wanted constraints, we may add some superclasses
  1329. as new given work. The reason is:
  1330. To allow FD-like improvement for type families. Assume that
  1331. we have a class
  1332. class C a b | a -> b
  1333. and we have to solve the implication constraint:
  1334. C a b => C a beta
  1335. Then, FD improvement can help us to produce a new wanted (beta ~ b)
  1336. We want to have the same effect with the type family encoding of
  1337. functional dependencies. Namely, consider:
  1338. class (F a ~ b) => C a b
  1339. Now suppose that we have:
  1340. given: C a b
  1341. wanted: C a beta
  1342. By interacting the given we will get given (F a ~ b) which is not
  1343. enough by itself to make us discharge (C a beta). However, we
  1344. may create a new derived equality from the super-class of the
  1345. wanted constraint (C a beta), namely derived (F a ~ beta).
  1346. Now we may interact this with given (F a ~ b) to get:
  1347. derived : beta ~ b
  1348. But 'beta' is a touchable unification variable, and hence OK to
  1349. unify it with 'b', replacing the derived evidence with the identity.
  1350. This requires trySpontaneousSolve to solve *derived*
  1351. equalities that have a touchable in their RHS, *in addition*
  1352. to solving wanted equalities.
  1353. We also need to somehow use the superclasses to quantify over a minimal,
  1354. constraint see note [Minimize by Superclasses] in TcSimplify.
  1355. Finally, here is another example where this is useful.
  1356. Example 1:
  1357. ----------
  1358. class (F a ~ b) => C a b
  1359. And we are given the wanteds:
  1360. w1 : C a b
  1361. w2 : C a c
  1362. w3 : b ~ c
  1363. We surely do *not* want to quantify over (b ~ c), since if someone provides
  1364. dictionaries for (C a b) and (C a c), these dictionaries can provide a proof
  1365. of (b ~ c), hence no extra evidence is necessary. Here is what will happen:
  1366. Step 1: We will get new *given* superclass work,
  1367. provisionally to our solving of w1 and w2
  1368. g1: F a ~ b, g2 : F a ~ c,
  1369. w1 : C a b, w2 : C a c, w3 : b ~ c
  1370. The evidence for g1 and g2 is a superclass evidence term:
  1371. g1 := sc w1, g2 := sc w2
  1372. Step 2: The givens will solve the wanted w3, so that
  1373. w3 := sym (sc w1) ; sc w2
  1374. Step 3: Now, one may naively assume that then w2 can be solve from w1
  1375. after rewriting with the (now solved equality) (b ~ c).
  1376. But this rewriting is ruled out by the isGoodRectDict!
  1377. Conclusion, we will (correctly) end up with the unsolved goals
  1378. (C a b, C a c)
  1379. NB: The desugarer needs be more clever to deal with equalities
  1380. that participate in recursive dictionary bindings.
  1381. \begin{code}
  1382. data LookupInstResult
  1383. = NoInstance
  1384. | GenInst [CtEvidence] EvTerm
  1385. matchClassInst :: InertSet -> Class -> [Type] -> CtLoc -> TcS LookupInstResult
  1386. matchClassInst _ clas [ _, ty ] _
  1387. | className clas == singIClassName
  1388. , Just n <- isNumLitTy ty = return $ GenInst [] $ EvLit $ EvNum n
  1389. | className clas == singIClassName
  1390. , Just s <- isStrLitTy ty = return $ GenInst [] $ EvLit $ EvStr s
  1391. matchClassInst inerts clas tys loc
  1392. = do { dflags <- getDynFlags
  1393. ; let pred = mkClassPred clas tys
  1394. incoherent_ok = xopt Opt_IncoherentInstances dflags
  1395. ; mb_result <- matchClass clas tys
  1396. ; untch <- getUntouchables
  1397. ; traceTcS "matchClassInst" $ vcat [ text "pred =" <+> ppr pred
  1398. , text "inerts=" <+> ppr inerts
  1399. , text "untouchables=" <+> ppr untch ]
  1400. ; case mb_result of
  1401. MatchInstNo -> return NoInstance
  1402. MatchInstMany -> return NoInstance -- defer any reactions of a multitude until
  1403. -- we learn more about the reagent
  1404. MatchInstSingle (_,_)
  1405. | not incoherent_ok && given_overlap untch
  1406. -> -- see Note [Instance and Given overlap]
  1407. do { traceTcS "Delaying instance application" $
  1408. vcat [ text "Workitem=" <+> pprType (mkClassPred clas tys)
  1409. , text "Relevant given dictionaries=" <+> ppr givens_for_this_clas ]
  1410. ; return NoInstance
  1411. }
  1412. MatchInstSingle (dfun_id, mb_inst_tys) ->
  1413. do { checkWellStagedDFun pred dfun_id loc
  1414. -- mb_inst_tys :: Maybe TcType
  1415. -- See Note [DFunInstType: instantiating types] in InstEnv
  1416. ; (tys, dfun_phi) <- instDFunType dfun_id mb_inst_tys
  1417. ; let (theta, _) = tcSplitPhiTy dfun_phi
  1418. ; if null theta then
  1419. return (GenInst [] (EvDFunApp dfun_id tys []))
  1420. else do
  1421. { evc_vars <- instDFunConstraints theta
  1422. ; let new_ev_vars = freshGoals evc_vars
  1423. -- new_ev_vars are only the real new variables that can be emitted
  1424. dfun_app = EvDFunApp dfun_id tys (getEvTerms evc_vars)
  1425. ; return $ GenInst new_ev_vars dfun_app } }
  1426. }
  1427. where
  1428. givens_for_this_clas :: Cts
  1429. givens_for_this_clas
  1430. = lookupUFM (cts_given (inert_dicts $ inert_cans inerts)) clas
  1431. `orElse` emptyCts
  1432. given_overlap :: Untouchables -> Bool
  1433. given_overlap untch = anyBag (matchable untch) givens_for_this_clas
  1434. matchable untch (CDictCan { cc_class = clas_g, cc_tyargs = sys
  1435. , cc_ev = fl })
  1436. | isGiven fl
  1437. = ASSERT( clas_g == clas )
  1438. case tcUnifyTys (\tv -> if isTouchableMetaTyVar untch tv &&
  1439. tv `elemVarSet` tyVarsOfTypes tys
  1440. then BindMe else Skolem) tys sys of
  1441. -- We can't learn anything more about any variable at this point, so the only
  1442. -- cause of overlap can be by an instantiation of a touchable unification
  1443. -- variable. Hence we only bind touchable unification variables. In addition,
  1444. -- we use tcUnifyTys instead of tcMatchTys to rule out cyclic substitutions.
  1445. Nothing -> False
  1446. Just _ -> True
  1447. | otherwise = False -- No overlap with a solved, already been taken care of
  1448. -- by the overlap check with the instance environment.
  1449. matchable _tys ct = pprPanic "Expecting dictionary!" (ppr ct)
  1450. \end{code}
  1451. Note [Instance and Given overlap]
  1452. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1453. Assume that we have an inert set that looks as follows:
  1454. [Given] D [Int]
  1455. And an instance declaration:
  1456. instance C a => D [a]
  1457. A new wanted comes along of the form:
  1458. [Wanted] D [alpha]
  1459. One possibility is to apply the instance declaration which will leave us
  1460. with an unsolvable goal (C alpha). However, later on a new constraint may
  1461. arise (for instance due to a functional dependency between two later dictionaries),
  1462. that will add the equality (alpha ~ Int), in which case our ([Wanted] D [alpha])
  1463. will be transformed to [Wanted] D [Int], which could have been discharged by the given.
  1464. The solution is that in matchClassInst and eventually in topReact, we get back with
  1465. a matching instance, only when there is no Given in the inerts which is unifiable to
  1466. this particular dictionary.
  1467. The end effect is that, much as we do for overlapping instances, we delay choosing a
  1468. class instance if there is a possibility of another instance OR a given to match our
  1469. constraint later on. This fixes bugs #4981 and #5002.
  1470. This is arguably not easy to appear in practice due to our aggressive prioritization
  1471. of equality solving over other constraints, but it is possible. I've added a test case
  1472. in typecheck/should-compile/GivenOverlapping.hs
  1473. We ignore the overlap problem if -XIncoherentInstances is in force: see
  1474. Trac #6002 for a worked-out example where this makes a difference.
  1475. Moreover notice that our goals here are different than the goals of the top-level
  1476. overlapping checks. There we are interested in validating the following principle:
  1477. If we inline a function f at a site where the same global instance environment
  1478. is available as the instance environment at the definition site of f then we
  1479. should get the same behaviour.
  1480. But for the Given Overlap check our goal is just related to completeness of
  1481. constraint solving.