PageRenderTime 36ms CodeModel.GetById 30ms RepoModel.GetById 1ms app.codeStats 0ms

/compiler/typecheck/TcInteract.lhs

https://github.com/luite/ghc
Haskell | 1888 lines | 1420 code | 321 blank | 147 comment | 79 complexity | 7e10f1be1ca6164d68bdd4c6535c6bee 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. , pprTvBndrs (varSetElems $ tyVarsOfCt ct)
  159. , ptext (sLit "inerts = ") <+> ppr final_is]
  160. ; insertInertItemTcS ct }
  161. }
  162. where run_pipeline :: [(String,SimplifierStage)] -> StopOrContinue -> TcS StopOrContinue
  163. run_pipeline [] res = return res
  164. run_pipeline _ Stop = return Stop
  165. run_pipeline ((stg_name,stg):stgs) (ContinueWith ct)
  166. = do { traceTcS ("runStage " ++ stg_name ++ " {")
  167. (text "workitem = " <+> ppr ct)
  168. ; res <- stg ct
  169. ; traceTcS ("end stage " ++ stg_name ++ " }") empty
  170. ; run_pipeline stgs res
  171. }
  172. \end{code}
  173. Example 1:
  174. Inert: {c ~ d, F a ~ t, b ~ Int, a ~ ty} (all given)
  175. Reagent: a ~ [b] (given)
  176. React with (c~d) ==> IR (ContinueWith (a~[b])) True []
  177. React with (F a ~ t) ==> IR (ContinueWith (a~[b])) False [F [b] ~ t]
  178. React with (b ~ Int) ==> IR (ContinueWith (a~[Int]) True []
  179. Example 2:
  180. Inert: {c ~w d, F a ~g t, b ~w Int, a ~w ty}
  181. Reagent: a ~w [b]
  182. React with (c ~w d) ==> IR (ContinueWith (a~[b])) True []
  183. React with (F a ~g t) ==> IR (ContinueWith (a~[b])) True [] (can't rewrite given with wanted!)
  184. etc.
  185. Example 3:
  186. Inert: {a ~ Int, F Int ~ b} (given)
  187. Reagent: F a ~ b (wanted)
  188. React with (a ~ Int) ==> IR (ContinueWith (F Int ~ b)) True []
  189. React with (F Int ~ b) ==> IR Stop True [] -- after substituting we re-canonicalize and get nothing
  190. \begin{code}
  191. thePipeline :: [(String,SimplifierStage)]
  192. thePipeline = [ ("canonicalization", TcCanonical.canonicalize)
  193. , ("spontaneous solve", spontaneousSolveStage)
  194. , ("interact with inerts", interactWithInertsStage)
  195. , ("top-level reactions", topReactionsStage) ]
  196. \end{code}
  197. *********************************************************************************
  198. * *
  199. The spontaneous-solve Stage
  200. * *
  201. *********************************************************************************
  202. \begin{code}
  203. spontaneousSolveStage :: SimplifierStage
  204. -- CTyEqCans are always consumed, returning Stop
  205. spontaneousSolveStage workItem
  206. = do { mb_solved <- trySpontaneousSolve workItem
  207. ; case mb_solved of
  208. SPCantSolve
  209. | CTyEqCan { cc_tyvar = tv, cc_ev = fl } <- workItem
  210. -- Unsolved equality
  211. -> do { n_kicked <- kickOutRewritable (ctEvFlavour fl) tv
  212. ; traceFireTcS workItem $
  213. ptext (sLit "Kept as inert") <+> ppr_kicked n_kicked <> colon
  214. <+> ppr workItem
  215. ; insertInertItemTcS workItem
  216. ; return Stop }
  217. | otherwise
  218. -> continueWith workItem
  219. SPSolved new_tv
  220. -- Post: tv ~ xi is now in TyBinds, no need to put in inerts as well
  221. -- see Note [Spontaneously solved in TyBinds]
  222. -> do { n_kicked <- kickOutRewritable Given new_tv
  223. ; traceFireTcS workItem $
  224. ptext (sLit "Spontaneously solved") <+> ppr_kicked n_kicked <> colon
  225. <+> ppr workItem
  226. ; return Stop } }
  227. ppr_kicked :: Int -> SDoc
  228. ppr_kicked 0 = empty
  229. ppr_kicked n = parens (int n <+> ptext (sLit "kicked out"))
  230. \end{code}
  231. Note [Spontaneously solved in TyBinds]
  232. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  233. When we encounter a constraint ([W] alpha ~ tau) which can be spontaneously solved,
  234. we record the equality on the TyBinds of the TcSMonad. In the past, we used to also
  235. add a /given/ version of the constraint ([G] alpha ~ tau) to the inert
  236. canonicals -- and potentially kick out other equalities that mention alpha.
  237. Then, the flattener only had to look in the inert equalities during flattening of a
  238. type (TcCanonical.flattenTyVar).
  239. However it is a bit silly to record these equalities /both/ in the inerts AND the
  240. TyBinds, so we have now eliminated spontaneously solved equalities from the inerts,
  241. and only record them in the TyBinds of the TcS monad. The flattener is now consulting
  242. these binds /and/ the inerts for potentially unsolved or other given equalities.
  243. \begin{code}
  244. kickOutRewritable :: CtFlavour -- Flavour of the equality that is
  245. -- being added to the inert set
  246. -> TcTyVar -- The new equality is tv ~ ty
  247. -> TcS Int
  248. kickOutRewritable new_flav new_tv
  249. = do { wl <- modifyInertTcS kick_out
  250. ; traceTcS "kickOutRewritable" $
  251. vcat [ text "tv = " <+> ppr new_tv
  252. , ptext (sLit "Kicked out =") <+> ppr wl]
  253. ; updWorkListTcS (appendWorkList wl)
  254. ; return (workListSize wl) }
  255. where
  256. kick_out :: InertSet -> (WorkList, InertSet)
  257. kick_out (is@(IS { inert_cans = IC { inert_eqs = tv_eqs
  258. , inert_dicts = dictmap
  259. , inert_funeqs = funeqmap
  260. , inert_irreds = irreds
  261. , inert_insols = insols } }))
  262. = (kicked_out, is { inert_cans = inert_cans_in })
  263. -- NB: Notice that don't rewrite
  264. -- inert_solved_dicts, and inert_solved_funeqs
  265. -- optimistically. But when we lookup we have to take the
  266. -- subsitution into account
  267. where
  268. inert_cans_in = IC { inert_eqs = tv_eqs_in
  269. , inert_dicts = dicts_in
  270. , inert_funeqs = feqs_in
  271. , inert_irreds = irs_in
  272. , inert_insols = insols_in }
  273. kicked_out = WorkList { wl_eqs = varEnvElts tv_eqs_out
  274. , wl_funeqs = foldrBag insertDeque emptyDeque feqs_out
  275. , wl_rest = bagToList (dicts_out `andCts` irs_out
  276. `andCts` insols_out) }
  277. (tv_eqs_out, tv_eqs_in) = partitionVarEnv kick_out_eq tv_eqs
  278. (feqs_out, feqs_in) = partCtFamHeadMap kick_out_ct funeqmap
  279. (dicts_out, dicts_in) = partitionCCanMap kick_out_ct dictmap
  280. (irs_out, irs_in) = partitionBag kick_out_ct irreds
  281. (insols_out, insols_in) = partitionBag kick_out_ct insols
  282. -- Kick out even insolubles; see Note [Kick out insolubles]
  283. kick_out_ct inert_ct = new_flav `canRewrite` (ctFlavour inert_ct) &&
  284. (new_tv `elemVarSet` tyVarsOfCt inert_ct)
  285. -- NB: tyVarsOfCt will return the type
  286. -- variables /and the kind variables/ that are
  287. -- directly visible in the type. Hence we will
  288. -- have exposed all the rewriting we care about
  289. -- to make the most precise kinds visible for
  290. -- matching classes etc. No need to kick out
  291. -- constraints that mention type variables whose
  292. -- kinds could contain this variable!
  293. kick_out_eq (CTyEqCan { cc_tyvar = tv, cc_rhs = rhs, cc_ev = ev })
  294. = (new_flav `canRewrite` inert_flav) -- See Note [Delicate equality kick-out]
  295. && (new_tv `elemVarSet` kind_vars || -- (1)
  296. (not (inert_flav `canRewrite` new_flav) && -- (2)
  297. new_tv `elemVarSet` (extendVarSet (tyVarsOfType rhs) tv)))
  298. where
  299. inert_flav = ctEvFlavour ev
  300. kind_vars = tyVarsOfType (tyVarKind tv) `unionVarSet`
  301. tyVarsOfType (typeKind rhs)
  302. kick_out_eq other_ct = pprPanic "kick_out_eq" (ppr other_ct)
  303. \end{code}
  304. Note [Kick out insolubles]
  305. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  306. Suppose we have an insoluble alpha ~ [alpha], which is insoluble
  307. because an occurs check. And then we unify alpha := [Int].
  308. Then we really want to rewrite the insouluble to [Int] ~ [[Int]].
  309. Now it can be decomposed. Otherwise we end up with a "Can't match
  310. [Int] ~ [[Int]]" which is true, but a bit confusing because the
  311. outer type constructors match.
  312. Note [Delicate equality kick-out]
  313. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  314. When adding an equality (a ~ xi), we kick out an inert type-variable
  315. equality (b ~ phi) in two cases
  316. (1) If the new tyvar can rewrite the kind LHS or RHS of the inert
  317. equality. Example:
  318. Work item: [W] k ~ *
  319. Inert: [W] (a:k) ~ ty
  320. [W] (b:*) ~ c :: k
  321. We must kick out those blocked inerts so that we rewrite them
  322. and can subsequently unify.
  323. (2) If the new tyvar can
  324. Work item: [G] a ~ b
  325. Inert: [W] b ~ [a]
  326. Now at this point the work item cannot be further rewritten by the
  327. inert (due to the weaker inert flavor). But we can't add the work item
  328. as-is because the inert set would then have a cyclic substitution,
  329. when rewriting a wanted type mentioning 'a'. So we must kick the inert out.
  330. We have to do this only if the inert *cannot* rewrite the work item;
  331. it it can, then the work item will have been fully rewritten by the
  332. inert during canonicalisation. So for example:
  333. Work item: [W] a ~ Int
  334. Inert: [W] b ~ [a]
  335. No need to kick out the inert, beause the inert substitution is not
  336. necessarily idemopotent. See Note [Non-idempotent inert substitution].
  337. See also point (8) of Note [Detailed InertCans Invariants]
  338. \begin{code}
  339. data SPSolveResult = SPCantSolve
  340. | SPSolved TcTyVar
  341. -- We solved this /unification/ variable to some type using reflexivity
  342. -- SPCantSolve means that we can't do the unification because e.g. the variable is untouchable
  343. -- SPSolved workItem' gives us a new *given* to go on
  344. -- @trySpontaneousSolve wi@ solves equalities where one side is a
  345. -- touchable unification variable.
  346. -- See Note [Touchables and givens]
  347. trySpontaneousSolve :: WorkItem -> TcS SPSolveResult
  348. trySpontaneousSolve workItem@(CTyEqCan { cc_ev = gw
  349. , cc_tyvar = tv1, cc_rhs = xi, cc_loc = d })
  350. | isGiven gw
  351. = return SPCantSolve
  352. | Just tv2 <- tcGetTyVar_maybe xi
  353. = do { tch1 <- isTouchableMetaTyVarTcS tv1
  354. ; tch2 <- isTouchableMetaTyVarTcS tv2
  355. ; case (tch1, tch2) of
  356. (True, True) -> trySpontaneousEqTwoWay d gw tv1 tv2
  357. (True, False) -> trySpontaneousEqOneWay d gw tv1 xi
  358. (False, True) -> trySpontaneousEqOneWay d gw tv2 (mkTyVarTy tv1)
  359. _ -> return SPCantSolve }
  360. | otherwise
  361. = do { tch1 <- isTouchableMetaTyVarTcS tv1
  362. ; if tch1 then trySpontaneousEqOneWay d gw tv1 xi
  363. else do { untch <- getUntouchables
  364. ; traceTcS "Untouchable LHS, can't spontaneously solve workitem" $
  365. vcat [text "Untouchables =" <+> ppr untch
  366. , text "Workitem =" <+> ppr workItem ]
  367. ; return SPCantSolve }
  368. }
  369. -- No need for
  370. -- trySpontaneousSolve (CFunEqCan ...) = ...
  371. -- See Note [No touchables as FunEq RHS] in TcSMonad
  372. trySpontaneousSolve _ = return SPCantSolve
  373. ----------------
  374. trySpontaneousEqOneWay :: CtLoc -> CtEvidence
  375. -> TcTyVar -> Xi -> TcS SPSolveResult
  376. -- tv is a MetaTyVar, not untouchable
  377. trySpontaneousEqOneWay d gw tv xi
  378. | not (isSigTyVar tv) || isTyVarTy xi
  379. , typeKind xi `tcIsSubKind` tyVarKind tv
  380. = solveWithIdentity d gw tv xi
  381. | otherwise -- Still can't solve, sig tyvar and non-variable rhs
  382. = return SPCantSolve
  383. ----------------
  384. trySpontaneousEqTwoWay :: CtLoc -> CtEvidence
  385. -> TcTyVar -> TcTyVar -> TcS SPSolveResult
  386. -- Both tyvars are *touchable* MetaTyvars so there is only a chance for kind error here
  387. trySpontaneousEqTwoWay d gw tv1 tv2
  388. | k1 `tcIsSubKind` k2 && nicer_to_update_tv2
  389. = solveWithIdentity d gw tv2 (mkTyVarTy tv1)
  390. | k2 `tcIsSubKind` k1
  391. = solveWithIdentity d gw tv1 (mkTyVarTy tv2)
  392. | otherwise
  393. = return SPCantSolve
  394. where
  395. k1 = tyVarKind tv1
  396. k2 = tyVarKind tv2
  397. nicer_to_update_tv2 = isSigTyVar tv1 || isSystemName (Var.varName tv2)
  398. \end{code}
  399. Note [Kind errors]
  400. ~~~~~~~~~~~~~~~~~~
  401. Consider the wanted problem:
  402. alpha ~ (# Int, Int #)
  403. where alpha :: ArgKind and (# Int, Int #) :: (#). We can't spontaneously solve this constraint,
  404. but we should rather reject the program that give rise to it. If 'trySpontaneousEqTwoWay'
  405. simply returns @CantSolve@ then that wanted constraint is going to propagate all the way and
  406. get quantified over in inference mode. That's bad because we do know at this point that the
  407. constraint is insoluble. Instead, we call 'recKindErrorTcS' here, which will fail later on.
  408. The same applies in canonicalization code in case of kind errors in the givens.
  409. However, when we canonicalize givens we only check for compatibility (@compatKind@).
  410. If there were a kind error in the givens, this means some form of inconsistency or dead code.
  411. You may think that when we spontaneously solve wanteds we may have to look through the
  412. bindings to determine the right kind of the RHS type. E.g one may be worried that xi is
  413. @alpha@ where alpha :: ? and a previous spontaneous solving has set (alpha := f) with (f :: *).
  414. But we orient our constraints so that spontaneously solved ones can rewrite all other constraint
  415. so this situation can't happen.
  416. Note [Spontaneous solving and kind compatibility]
  417. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  418. Note that our canonical constraints insist that *all* equalities (tv ~
  419. xi) or (F xis ~ rhs) require the LHS and the RHS to have *compatible*
  420. the same kinds. ("compatible" means one is a subKind of the other.)
  421. - It can't be *equal* kinds, because
  422. b) wanted constraints don't necessarily have identical kinds
  423. eg alpha::? ~ Int
  424. b) a solved wanted constraint becomes a given
  425. - SPJ thinks that *given* constraints (tv ~ tau) always have that
  426. tau has a sub-kind of tv; and when solving wanted constraints
  427. in trySpontaneousEqTwoWay we re-orient to achieve this.
  428. - Note that the kind invariant is maintained by rewriting.
  429. Eg wanted1 rewrites wanted2; if both were compatible kinds before,
  430. wanted2 will be afterwards. Similarly givens.
  431. Caveat:
  432. - Givens from higher-rank, such as:
  433. type family T b :: * -> * -> *
  434. type instance T Bool = (->)
  435. f :: forall a. ((T a ~ (->)) => ...) -> a -> ...
  436. flop = f (...) True
  437. Whereas we would be able to apply the type instance, we would not be able to
  438. use the given (T Bool ~ (->)) in the body of 'flop'
  439. Note [Avoid double unifications]
  440. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  441. The spontaneous solver has to return a given which mentions the unified unification
  442. variable *on the left* of the equality. Here is what happens if not:
  443. Original wanted: (a ~ alpha), (alpha ~ Int)
  444. We spontaneously solve the first wanted, without changing the order!
  445. given : a ~ alpha [having unified alpha := a]
  446. Now the second wanted comes along, but he cannot rewrite the given, so we simply continue.
  447. At the end we spontaneously solve that guy, *reunifying* [alpha := Int]
  448. We avoid this problem by orienting the resulting given so that the unification
  449. variable is on the left. [Note that alternatively we could attempt to
  450. enforce this at canonicalization]
  451. See also Note [No touchables as FunEq RHS] in TcSMonad; avoiding
  452. double unifications is the main reason we disallow touchable
  453. unification variables as RHS of type family equations: F xis ~ alpha.
  454. \begin{code}
  455. ----------------
  456. solveWithIdentity :: CtLoc -> CtEvidence -> TcTyVar -> Xi -> TcS SPSolveResult
  457. -- Solve with the identity coercion
  458. -- Precondition: kind(xi) is a sub-kind of kind(tv)
  459. -- Precondition: CtEvidence is Wanted or Derived
  460. -- See [New Wanted Superclass Work] to see why solveWithIdentity
  461. -- must work for Derived as well as Wanted
  462. -- Returns: workItem where
  463. -- workItem = the new Given constraint
  464. --
  465. -- NB: No need for an occurs check here, because solveWithIdentity always
  466. -- arises from a CTyEqCan, a *canonical* constraint. Its invariants
  467. -- say that in (a ~ xi), the type variable a does not appear in xi.
  468. -- See TcRnTypes.Ct invariants.
  469. solveWithIdentity _d wd tv xi
  470. = do { let tv_ty = mkTyVarTy tv
  471. ; traceTcS "Sneaky unification:" $
  472. vcat [text "Unifies:" <+> ppr tv <+> ptext (sLit ":=") <+> ppr xi,
  473. text "Coercion:" <+> pprEq tv_ty xi,
  474. text "Left Kind is:" <+> ppr (typeKind tv_ty),
  475. text "Right Kind is:" <+> ppr (typeKind xi) ]
  476. ; let xi' = defaultKind xi
  477. -- We only instantiate kind unification variables
  478. -- with simple kinds like *, not OpenKind or ArgKind
  479. -- cf TcUnify.uUnboundKVar
  480. ; setWantedTyBind tv xi'
  481. ; let refl_evtm = EvCoercion (mkTcReflCo xi')
  482. ; when (isWanted wd) $
  483. setEvBind (ctev_evar wd) refl_evtm
  484. ; return (SPSolved tv) }
  485. \end{code}
  486. *********************************************************************************
  487. * *
  488. The interact-with-inert Stage
  489. * *
  490. *********************************************************************************
  491. Note [
  492. Note [The Solver Invariant]
  493. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  494. We always add Givens first. So you might think that the solver has
  495. the invariant
  496. If the work-item is Given,
  497. then the inert item must Given
  498. But this isn't quite true. Suppose we have,
  499. c1: [W] beta ~ [alpha], c2 : [W] blah, c3 :[W] alpha ~ Int
  500. After processing the first two, we get
  501. c1: [G] beta ~ [alpha], c2 : [W] blah
  502. Now, c3 does not interact with the the given c1, so when we spontaneously
  503. solve c3, we must re-react it with the inert set. So we can attempt a
  504. reaction between inert c2 [W] and work-item c3 [G].
  505. It *is* true that [Solver Invariant]
  506. If the work-item is Given,
  507. AND there is a reaction
  508. then the inert item must Given
  509. or, equivalently,
  510. If the work-item is Given,
  511. and the inert item is Wanted/Derived
  512. then there is no reaction
  513. \begin{code}
  514. -- Interaction result of WorkItem <~> Ct
  515. data InteractResult
  516. = IRWorkItemConsumed { ir_fire :: String } -- Work item discharged by interaction; stop
  517. | IRReplace { ir_fire :: String } -- Inert item replaced by work item; stop
  518. | IRInertConsumed { ir_fire :: String } -- Inert item consumed, keep going with work item
  519. | IRKeepGoing { ir_fire :: String } -- Inert item remains, keep going with work item
  520. interactWithInertsStage :: WorkItem -> TcS StopOrContinue
  521. -- Precondition: if the workitem is a CTyEqCan then it will not be able to
  522. -- react with anything at this stage.
  523. interactWithInertsStage wi
  524. = do { traceTcS "interactWithInerts" $ text "workitem = " <+> ppr wi
  525. ; rels <- extractRelevantInerts wi
  526. ; traceTcS "relevant inerts are:" $ ppr rels
  527. ; foldlBagM interact_next (ContinueWith wi) rels }
  528. where interact_next Stop atomic_inert
  529. = do { insertInertItemTcS atomic_inert; return Stop }
  530. interact_next (ContinueWith wi) atomic_inert
  531. = do { ir <- doInteractWithInert atomic_inert wi
  532. ; let mk_msg rule keep_doc
  533. = vcat [ text rule <+> keep_doc
  534. , ptext (sLit "InertItem =") <+> ppr atomic_inert
  535. , ptext (sLit "WorkItem =") <+> ppr wi ]
  536. ; case ir of
  537. IRWorkItemConsumed { ir_fire = rule }
  538. -> do { traceFireTcS wi (mk_msg rule (text "WorkItemConsumed"))
  539. ; insertInertItemTcS atomic_inert
  540. ; return Stop }
  541. IRReplace { ir_fire = rule }
  542. -> do { traceFireTcS atomic_inert
  543. (mk_msg rule (text "InertReplace"))
  544. ; insertInertItemTcS wi
  545. ; return Stop }
  546. IRInertConsumed { ir_fire = rule }
  547. -> do { traceFireTcS atomic_inert
  548. (mk_msg rule (text "InertItemConsumed"))
  549. ; return (ContinueWith wi) }
  550. IRKeepGoing {}
  551. -> do { insertInertItemTcS atomic_inert
  552. ; return (ContinueWith wi) }
  553. }
  554. \end{code}
  555. \begin{code}
  556. --------------------------------------------
  557. doInteractWithInert :: Ct -> Ct -> TcS InteractResult
  558. -- Identical class constraints.
  559. doInteractWithInert inertItem@(CDictCan { cc_ev = fl1, cc_class = cls1, cc_tyargs = tys1, cc_loc = loc1 })
  560. workItem@(CDictCan { cc_ev = fl2, cc_class = cls2, cc_tyargs = tys2, cc_loc = loc2 })
  561. | cls1 == cls2
  562. = do { let pty1 = mkClassPred cls1 tys1
  563. pty2 = mkClassPred cls2 tys2
  564. inert_pred_loc = (pty1, pprArisingAt loc1)
  565. work_item_pred_loc = (pty2, pprArisingAt loc2)
  566. ; let fd_eqns = improveFromAnother inert_pred_loc work_item_pred_loc
  567. ; fd_work <- rewriteWithFunDeps fd_eqns loc2
  568. -- We don't really rewrite tys2, see below _rewritten_tys2, so that's ok
  569. -- NB: We do create FDs for given to report insoluble equations that arise
  570. -- from pairs of Givens, and also because of floating when we approximate
  571. -- implications. The relevant test is: typecheck/should_fail/FDsFromGivens.hs
  572. -- Also see Note [When improvement happens]
  573. ; traceTcS "doInteractWithInert:dict"
  574. (vcat [ text "inertItem =" <+> ppr inertItem
  575. , text "workItem =" <+> ppr workItem
  576. , text "fundeps =" <+> ppr fd_work ])
  577. ; case fd_work of
  578. -- No Functional Dependencies
  579. [] | eqTypes tys1 tys2 -> solveOneFromTheOther "Cls/Cls" fl1 workItem
  580. | otherwise -> return (IRKeepGoing "NOP")
  581. -- Actual Functional Dependencies
  582. _ | cls1 `hasKey` ipClassNameKey
  583. , isGiven fl1, isGiven fl2 -- See Note [Shadowing of Implicit Parameters]
  584. -> return (IRReplace ("Replace IP"))
  585. -- Standard thing: create derived fds and keep on going. Importantly we don't
  586. -- throw workitem back in the worklist because this can cause loops. See #5236.
  587. | otherwise
  588. -> do { updWorkListTcS (extendWorkListEqs fd_work)
  589. ; return (IRKeepGoing "Cls/Cls (new fundeps)") } -- Just keep going without droping the inert
  590. }
  591. -- Two pieces of irreducible evidence: if their types are *exactly identical*
  592. -- we can rewrite them. We can never improve using this:
  593. -- if we want ty1 :: Constraint and have ty2 :: Constraint it clearly does not
  594. -- mean that (ty1 ~ ty2)
  595. doInteractWithInert (CIrredEvCan { cc_ev = ifl })
  596. workItem@(CIrredEvCan { cc_ev = wfl })
  597. | ctEvPred ifl `eqType` ctEvPred wfl
  598. = solveOneFromTheOther "Irred/Irred" ifl workItem
  599. doInteractWithInert ii@(CFunEqCan { cc_ev = ev1, cc_fun = tc1
  600. , cc_tyargs = args1, cc_rhs = xi1, cc_loc = d1 })
  601. wi@(CFunEqCan { cc_ev = ev2, cc_fun = tc2
  602. , cc_tyargs = args2, cc_rhs = xi2, cc_loc = d2 })
  603. | i_solves_w && (not (w_solves_i && isMetaTyVarTy xi1))
  604. -- See Note [Carefully solve the right CFunEqCan]
  605. = ASSERT( lhss_match ) -- extractRelevantInerts ensures this
  606. do { traceTcS "interact with inerts: FunEq/FunEq" $
  607. vcat [ text "workItem =" <+> ppr wi
  608. , text "inertItem=" <+> ppr ii ]
  609. ; let xev = XEvTerm xcomp xdecomp
  610. -- xcomp : [(xi2 ~ xi1)] -> (F args ~ xi2)
  611. xcomp [x] = EvCoercion (co1 `mkTcTransCo` mk_sym_co x)
  612. xcomp _ = panic "No more goals!"
  613. -- xdecomp : (F args ~ xi2) -> [(xi2 ~ xi1)]
  614. xdecomp x = [EvCoercion (mk_sym_co x `mkTcTransCo` co1)]
  615. ; ctevs <- xCtFlavor ev2 [mkTcEqPred xi2 xi1] xev
  616. -- No caching! See Note [Cache-caused loops]
  617. -- Why not (mkTcEqPred xi1 xi2)? See Note [Efficient orientation]
  618. ; emitWorkNC d2 ctevs
  619. ; return (IRWorkItemConsumed "FunEq/FunEq") }
  620. | fl2 `canSolve` fl1
  621. = ASSERT( lhss_match ) -- extractRelevantInerts ensures this
  622. do { traceTcS "interact with inerts: FunEq/FunEq" $
  623. vcat [ text "workItem =" <+> ppr wi
  624. , text "inertItem=" <+> ppr ii ]
  625. ; let xev = XEvTerm xcomp xdecomp
  626. -- xcomp : [(xi2 ~ xi1)] -> [(F args ~ xi1)]
  627. xcomp [x] = EvCoercion (co2 `mkTcTransCo` evTermCoercion x)
  628. xcomp _ = panic "No more goals!"
  629. -- xdecomp : (F args ~ xi1) -> [(xi2 ~ xi1)]
  630. xdecomp x = [EvCoercion (mkTcSymCo co2 `mkTcTransCo` evTermCoercion x)]
  631. ; ctevs <- xCtFlavor ev1 [mkTcEqPred xi2 xi1] xev
  632. -- Why not (mkTcEqPred xi1 xi2)? See Note [Efficient orientation]
  633. ; emitWorkNC d1 ctevs
  634. ; return (IRInertConsumed "FunEq/FunEq") }
  635. where
  636. lhss_match = tc1 == tc2 && eqTypes args1 args2
  637. co1 = evTermCoercion $ ctEvTerm ev1
  638. co2 = evTermCoercion $ ctEvTerm ev2
  639. mk_sym_co x = mkTcSymCo (evTermCoercion x)
  640. fl1 = ctEvFlavour ev1
  641. fl2 = ctEvFlavour ev2
  642. i_solves_w = fl1 `canSolve` fl2
  643. w_solves_i = fl2 `canSolve` fl1
  644. doInteractWithInert _ _ = return (IRKeepGoing "NOP")
  645. \end{code}
  646. Note [Efficient Orientation]
  647. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  648. Suppose we are interacting two FunEqCans with the same LHS:
  649. (inert) ci :: (F ty ~ xi_i)
  650. (work) cw :: (F ty ~ xi_w)
  651. We prefer to keep the inert (else we pass the work item on down
  652. the pipeline, which is a bit silly). If we keep the inert, we
  653. will (a) discharge 'cw'
  654. (b) produce a new equality work-item (xi_w ~ xi_i)
  655. Notice the orientation (xi_w ~ xi_i) NOT (xi_i ~ xi_w):
  656. new_work :: xi_w ~ xi_i
  657. cw := ci ; sym new_work
  658. Why? Consider the simplest case when xi1 is a type variable. If
  659. we generate xi1~xi2, porcessing that constraint will kick out 'ci'.
  660. If we generate xi2~xi1, there is less chance of that happening.
  661. Of course it can and should still happen if xi1=a, xi1=Int, say.
  662. But we want to avoid it happening needlessly.
  663. Similarly, if we *can't* keep the inert item (because inert is Wanted,
  664. and work is Given, say), we prefer to orient the new equality (xi_i ~
  665. xi_w).
  666. Note [Carefully solve the right CFunEqCan]
  667. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  668. Consider the constraints
  669. c1 :: F Int ~ a -- Arising from an application line 5
  670. c2 :: F Int ~ Bool -- Arising from an application line 10
  671. Suppose that 'a' is a unification variable, arising only from
  672. flattening. So there is no error on line 5; it's just a flattening
  673. variable. But there is (or might be) an error on line 10.
  674. Two ways to combine them, leaving either (Plan A)
  675. c1 :: F Int ~ a -- Arising from an application line 5
  676. c3 :: a ~ Bool -- Arising from an application line 10
  677. or (Plan B)
  678. c2 :: F Int ~ Bool -- Arising from an application line 10
  679. c4 :: a ~ Bool -- Arising from an application line 5
  680. Plan A will unify c3, leaving c1 :: F Int ~ Bool as an error
  681. on the *totally innocent* line 5. An example is test SimpleFail16
  682. where the expected/actual message comes out backwards if we use
  683. the wrong plan.
  684. The second is the right thing to do. Hence the isMetaTyVarTy
  685. test when solving pairwise CFunEqCan.
  686. Note [Shadowing of Implicit Parameters]
  687. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  688. Consider the following example:
  689. f :: (?x :: Char) => Char
  690. f = let ?x = 'a' in ?x
  691. The "let ?x = ..." generates an implication constraint of the form:
  692. ?x :: Char => ?x :: Char
  693. Furthermore, the signature for `f` also generates an implication
  694. constraint, so we end up with the following nested implication:
  695. ?x :: Char => (?x :: Char => ?x :: Char)
  696. Note that the wanted (?x :: Char) constraint may be solved in
  697. two incompatible ways: either by using the parameter from the
  698. signature, or by using the local definition. Our intention is
  699. that the local definition should "shadow" the parameter of the
  700. signature, and we implement this as follows: when we add a new
  701. given implicit parameter to the inert set, it replaces any existing
  702. givens for the same implicit parameter.
  703. This works for the normal cases but it has an odd side effect
  704. in some pathological programs like this:
  705. -- This is accepted, the second parameter shadows
  706. f1 :: (?x :: Int, ?x :: Char) => Char
  707. f1 = ?x
  708. -- This is rejected, the second parameter shadows
  709. f2 :: (?x :: Int, ?x :: Char) => Int
  710. f2 = ?x
  711. Both of these are actually wrong: when we try to use either one,
  712. we'll get two incompatible wnated constraints (?x :: Int, ?x :: Char),
  713. which would lead to an error.
  714. I can think of two ways to fix this:
  715. 1. Simply disallow multiple constratits for the same implicit
  716. parameter---this is never useful, and it can be detected completely
  717. syntactically.
  718. 2. Move the shadowing machinery to the location where we nest
  719. implications, and add some code here that will produce an
  720. error if we get multiple givens for the same implicit parameter.
  721. Note [Cache-caused loops]
  722. ~~~~~~~~~~~~~~~~~~~~~~~~~
  723. It is very dangerous to cache a rewritten wanted family equation as 'solved' in our
  724. solved cache (which is the default behaviour or xCtFlavor), because the interaction
  725. may not be contributing towards a solution. Here is an example:
  726. Initial inert set:
  727. [W] g1 : F a ~ beta1
  728. Work item:
  729. [W] g2 : F a ~ beta2
  730. The work item will react with the inert yielding the _same_ inert set plus:
  731. i) Will set g2 := g1 `cast` g3
  732. ii) Will add to our solved cache that [S] g2 : F a ~ beta2
  733. iii) Will emit [W] g3 : beta1 ~ beta2
  734. Now, the g3 work item will be spontaneously solved to [G] g3 : beta1 ~ beta2
  735. and then it will react the item in the inert ([W] g1 : F a ~ beta1). So it
  736. will set
  737. g1 := g ; sym g3
  738. and what is g? Well it would ideally be a new goal of type (F a ~ beta2) but
  739. remember that we have this in our solved cache, and it is ... g2! In short we
  740. created the evidence loop:
  741. g2 := g1 ; g3
  742. g3 := refl
  743. g1 := g2 ; sym g3
  744. To avoid this situation we do not cache as solved any workitems (or inert)
  745. which did not really made a 'step' towards proving some goal. Solved's are
  746. just an optimization so we don't lose anything in terms of completeness of
  747. solving.
  748. \begin{code}
  749. solveOneFromTheOther :: String -- Info
  750. -> CtEvidence -- Inert
  751. -> Ct -- WorkItem
  752. -> TcS InteractResult
  753. -- Preconditions:
  754. -- 1) inert and work item represent evidence for the /same/ predicate
  755. -- 2) ip/class/irred evidence (no coercions) only
  756. solveOneFromTheOther info ifl workItem
  757. | isDerived wfl
  758. = return (IRWorkItemConsumed ("Solved[DW] " ++ info))
  759. | isDerived ifl -- The inert item is Derived, we can just throw it away,
  760. -- The workItem is inert wrt earlier inert-set items,
  761. -- so it's safe to continue on from this point
  762. = return (IRInertConsumed ("Solved[DI] " ++ info))
  763. | CtWanted { ctev_evar = ev_id } <- wfl
  764. = do { setEvBind ev_id (ctEvTerm ifl); return (IRWorkItemConsumed ("Solved(w) " ++ info)) }
  765. | CtWanted { ctev_evar = ev_id } <- ifl
  766. = do { setEvBind ev_id (ctEvTerm wfl); return (IRInertConsumed ("Solved(g) " ++ info)) }
  767. | otherwise -- If both are Given, we already have evidence; no need to duplicate
  768. -- But the work item *overrides* the inert item (hence IRReplace)
  769. -- See Note [Shadowing of Implicit Parameters]
  770. = return (IRReplace ("Replace(gg) " ++ info))
  771. where
  772. wfl = cc_ev workItem
  773. \end{code}
  774. Note [Shadowing of Implicit Parameters]
  775. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  776. Consider the following example:
  777. f :: (?x :: Char) => Char
  778. f = let ?x = 'a' in ?x
  779. The "let ?x = ..." generates an implication constraint of the form:
  780. ?x :: Char => ?x :: Char
  781. Furthermore, the signature for `f` also generates an implication
  782. constraint, so we end up with the following nested implication:
  783. ?x :: Char => (?x :: Char => ?x :: Char)
  784. Note that the wanted (?x :: Char) constraint may be solved in
  785. two incompatible ways: either by using the parameter from the
  786. signature, or by using the local definition. Our intention is
  787. that the local definition should "shadow" the parameter of the
  788. signature, and we implement this as follows: when we nest implications,
  789. we remove any implicit parameters in the outer implication, that
  790. have the same name as givens of the inner implication.
  791. Here is another variation of the example:
  792. f :: (?x :: Int) => Char
  793. f = let ?x = 'x' in ?x
  794. This program should also be accepted: the two constraints `?x :: Int`
  795. and `?x :: Char` never exist in the same context, so they don't get to
  796. interact to cause failure.
  797. Note [Superclasses and recursive dictionaries]
  798. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  799. Overlaps with Note [SUPERCLASS-LOOP 1]
  800. Note [SUPERCLASS-LOOP 2]
  801. Note [Recursive instances and superclases]
  802. ToDo: check overlap and delete redundant stuff
  803. Right before adding a given into the inert set, we must
  804. produce some more work, that will bring the superclasses
  805. of the given into scope. The superclass constraints go into
  806. our worklist.
  807. When we simplify a wanted constraint, if we first see a matching
  808. instance, we may produce new wanted work. To (1) avoid doing this work
  809. twice in the future and (2) to handle recursive dictionaries we may ``cache''
  810. this item as given into our inert set WITHOUT adding its superclass constraints,
  811. otherwise we'd be in danger of creating a loop [In fact this was the exact reason
  812. for doing the isGoodRecEv check in an older version of the type checker].
  813. But now we have added partially solved constraints to the worklist which may
  814. interact with other wanteds. Consider the example:
  815. Example 1:
  816. class Eq b => Foo a b --- 0-th selector
  817. instance Eq a => Foo [a] a --- fooDFun
  818. and wanted (Foo [t] t). We are first going to see that the instance matches
  819. and create an inert set that includes the solved (Foo [t] t) but not its superclasses:
  820. d1 :_g Foo [t] t d1 := EvDFunApp fooDFun d3
  821. Our work list is going to contain a new *wanted* goal
  822. d3 :_w Eq t
  823. Ok, so how do we get recursive dictionaries, at all:
  824. Example 2:
  825. data D r = ZeroD | SuccD (r (D r));
  826. instance (Eq (r (D r))) => Eq (D r) where
  827. ZeroD == ZeroD = True
  828. (SuccD a) == (SuccD b) = a == b
  829. _ == _ = False;
  830. equalDC :: D [] -> D [] -> Bool;
  831. equalDC = (==);
  832. We need to prove (Eq (D [])). Here's how we go:
  833. d1 :_w Eq (D [])
  834. by instance decl, holds if
  835. d2 :_w Eq [D []]
  836. where d1 = dfEqD d2
  837. *BUT* we have an inert set which gives us (no superclasses):
  838. d1 :_g Eq (D [])
  839. By the instance declaration of Eq we can show the 'd2' goal if
  840. d3 :_w Eq (D [])
  841. where d2 = dfEqList d3
  842. d1 = dfEqD d2
  843. Now, however this wanted can interact with our inert d1 to set:
  844. d3 := d1
  845. and solve the goal. Why was this interaction OK? Because, if we chase the
  846. evidence of d1 ~~> dfEqD d2 ~~-> dfEqList d3, so by setting d3 := d1 we
  847. are really setting
  848. d3 := dfEqD2 (dfEqList d3)
  849. which is FINE because the use of d3 is protected by the instance function
  850. applications.
  851. So, our strategy is to try to put solved wanted dictionaries into the
  852. inert set along with their superclasses (when this is meaningful,
  853. i.e. when new wanted goals are generated) but solve a wanted dictionary
  854. from a given only in the case where the evidence variable of the
  855. wanted is mentioned in the evidence of the given (recursively through
  856. the evidence binds) in a protected way: more instance function applications
  857. than superclass selectors.
  858. Here are some more examples from GHC's previous type checker
  859. Example 3:
  860. This code arises in the context of "Scrap Your Boilerplate with Class"
  861. class Sat a
  862. class Data ctx a
  863. instance Sat (ctx Char) => Data ctx Char -- dfunData1
  864. instance (Sat (ctx [a]), Data ctx a) => Data ctx [a] -- dfunData2
  865. class Data Maybe a => Foo a
  866. instance Foo t => Sat (Maybe t) -- dfunSat
  867. instance Data Maybe a => Foo a -- dfunFoo1
  868. instance Foo a => Foo [a] -- dfunFoo2
  869. instance Foo [Char] -- dfunFoo3
  870. Consider generating the superclasses of the instance declaration
  871. instance Foo a => Foo [a]
  872. So our problem is this
  873. d0 :_g Foo t
  874. d1 :_w Data Maybe [t]
  875. We may add the given in the inert set, along with its superclasses
  876. [assuming we don't fail because there is a matching instance, see
  877. topReactionsStage, given case ]
  878. Inert:
  879. d0 :_g Foo t
  880. WorkList
  881. d01 :_g Data Maybe t -- d2 := EvDictSuperClass d0 0
  882. d1 :_w Data Maybe [t]
  883. Then d2 can readily enter the inert, and we also do solving of the wanted
  884. Inert:
  885. d0 :_g Foo t
  886. d1 :_s Data Maybe [t] d1 := dfunData2 d2 d3
  887. WorkList
  888. d2 :_w Sat (Maybe [t])
  889. d3 :_w Data Maybe t
  890. d01 :_g Data Maybe t
  891. Now, we may simplify d2 more:
  892. Inert:
  893. d0 :_g Foo t
  894. d1 :_s Data Maybe [t] d1 := dfunData2 d2 d3
  895. d1 :_g Data Maybe [t]
  896. d2 :_g Sat (Maybe [t]) d2 := dfunSat d4
  897. WorkList:
  898. d3 :_w Data Maybe t
  899. d4 :_w Foo [t]
  900. d01 :_g Data Maybe t
  901. Now, we can just solve d3.
  902. Inert
  903. d0 :_g Foo t
  904. d1 :_s Data Maybe [t] d1 := dfunData2 d2 d3
  905. d2 :_g Sat (Maybe [t]) d2 := dfunSat d4
  906. WorkList
  907. d4 :_w Foo [t]
  908. d01 :_g Data Maybe t
  909. And now we can simplify d4 again, but since it has superclasses we *add* them to the worklist:
  910. Inert
  911. d0 :_g Foo t
  912. d1 :_s Data Maybe [t] d1 := dfunData2 d2 d3
  913. d2 :_g Sat (Maybe [t]) d2 := dfunSat d4
  914. d4 :_g Foo [t] d4 := dfunFoo2 d5
  915. WorkList:
  916. d5 :_w Foo t
  917. d6 :_g Data Maybe [t] d6 := EvDictSuperClass d4 0
  918. d01 :_g Data Maybe t
  919. Now, d5 can be solved! (and its superclass enter scope)
  920. Inert
  921. d0 :_g Foo t
  922. d1 :_s Data Maybe [t] d1 := dfunData2 d2 d3
  923. d2 :_g Sat (Maybe [t]) d2 := dfunSat d4
  924. d4 :_g Foo [t] d4 := dfunFoo2 d5
  925. d5 :_g Foo t d5 := dfunFoo1 d7
  926. WorkList:
  927. d7 :_w Data Maybe t
  928. d6 :_g Data Maybe [t]
  929. d8 :_g Data Maybe t d8 := EvDictSuperClass d5 0
  930. d01 :_g Data Maybe t
  931. Now, two problems:
  932. [1] Suppose we pick d8 and we react him with d01. Which of the two givens should
  933. we keep? Well, we *MUST NOT* drop d01 because d8 contains recursive evidence
  934. that must not be used (look at case interactInert where both inert and workitem
  935. are givens). So we have several options:
  936. - Drop the workitem always (this will drop d8)
  937. This feels very unsafe -- what if the work item was the "good" one
  938. that should be used later to solve another wanted?
  939. - Don't drop anyone: the inert set may contain multiple givens!
  940. [This is currently implemented]
  941. The "don't drop anyone" seems the most safe thing to do, so now we come to problem 2:
  942. [2] We have added both d6 and d01 in the inert set, and we are interacting our wanted
  943. d7. Now the [isRecDictEv] function in the ineration solver
  944. [case inert-given workitem-wanted] will prevent us from interacting d7 := d8
  945. precisely because chasing the evidence of d8 leads us to an unguarded use of d7.
  946. So, no interaction happens there. Then we meet d01 and there is no recursion
  947. problem there [isRectDictEv] gives us the OK to interact and we do solve d7 := d01!
  948. Note [SUPERCLASS-LOOP 1]
  949. ~~~~~~~~~~~~~~~~~~~~~~~~
  950. We have to be very, very careful when generating superclasses, lest we
  951. accidentally build a loop. Here's an example:
  952. class S a
  953. class S a => C a where { opc :: a -> a }
  954. class S b => D b where { opd :: b -> b }
  955. instance C Int where
  956. opc = opd
  957. instance D Int where
  958. opd = opc
  959. From (instance C Int) we get the constraint set {ds1:S Int, dd:D Int}
  960. Simplifying, we may well get:
  961. $dfCInt = :C ds1 (opd dd)
  962. dd = $dfDInt
  963. ds1 = $p1 dd
  964. Notice that we spot that we can extract ds1 from dd.
  965. Alas! Alack! We can do the same for (instance D Int):
  966. $dfDInt = :D ds2 (opc dc)
  967. dc = $dfCInt
  968. ds2 = $p1 dc
  969. And now we've defined the superclass in terms of itself.
  970. Two more nasty cases are in
  971. tcrun021
  972. tcrun033
  973. Solution:
  974. - Satisfy the superclass context *all by itself*
  975. (tcSimplifySuperClasses)
  976. - And do so completely; i.e. no left-over constraints
  977. to mix with the constraints arising from method declarations
  978. Note [SUPERCLASS-LOOP 2]
  979. ~~~~~~~~~~~~~~~~~~~~~~~~
  980. We need to be careful when adding "the constaint we are trying to prove".
  981. Suppose we are *given* d1:Ord a, and want to deduce (d2:C [a]) where
  982. class Ord a => C a where
  983. instance Ord [a] => C [a] where ...
  984. Then we'll use the instance decl to deduce C [a] from Ord [a], and then add the
  985. superclasses of C [a] to avails. But we must not overwrite the binding
  986. for Ord [a] (which is obtained from Ord a) with a superclass selection or we'll just
  987. build a loop!
  988. Here's another variant, immortalised in tcrun020
  989. class Monad m => C1 m
  990. class C1 m => C2 m x
  991. instance C2 Maybe Bool
  992. For the instance decl we need to build (C1 Maybe), and it's no good if
  993. we run around and add (C2 Maybe Bool) and its superclasses to the avails
  994. before we search for C1 Maybe.
  995. Here's another example
  996. class Eq b => Foo a b
  997. instance Eq a => Foo [a] a
  998. If we are reducing
  999. (Foo [t] t)
  1000. we'll first deduce that it holds (via the instance decl). We must not
  1001. then overwrite the Eq t constraint with a superclass selection!
  1002. At first I had a gross hack, whereby I simply did not add superclass constraints
  1003. in addWanted, though I did for addGiven and addIrred. This was sub-optimal,
  1004. because it lost legitimate superclass sharing, and it still didn't do the job:
  1005. I found a very obscure program (now tcrun021) in which improvement meant the
  1006. simplifier got two bites a the cherry... so something seemed to be an Stop
  1007. first time, but reducible next time.
  1008. Now we implement the Right Solution, which is to check for loops directly
  1009. when adding superclasses. It's a bit like the occurs check in unification.
  1010. Note [Recursive instances and superclases]
  1011. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1012. Consider this code, which arises in the context of "Scrap Your
  1013. Boilerplate with Class".
  1014. class Sat a
  1015. class Data ctx a
  1016. instance Sat (ctx Char) => Data ctx Char
  1017. instance (Sat (ctx [a]), Data ctx a) => Data ctx [a]
  1018. class Data Maybe a => Foo a
  1019. instance Foo t => Sat (Maybe t)
  1020. instance Data Maybe a => Foo a
  1021. instance Foo a => Foo [a]
  1022. instance Foo [Char]
  1023. In the instance for Foo [a], when generating evidence for the superclasses
  1024. (ie in tcSimplifySuperClasses) we need a superclass (Data Maybe [a]).
  1025. Using the instance for Data, we therefore need
  1026. (Sat (Maybe [a], Data Maybe a)
  1027. But we are given (Foo a), and hence its superclass (Data Maybe a).
  1028. So that leaves (Sat (Maybe [a])). Using the instance for Sat means
  1029. we need (Foo [a]). And that is the very dictionary we are bulding
  1030. an instance for! So we must put that in the "givens". So in this
  1031. case we have
  1032. Given: Foo a, Foo [a]
  1033. Wanted: Data Maybe [a]
  1034. BUT we must *not not not* put the *superclasses* of (Foo [a]) in
  1035. the givens, which is what 'addGiven' would normally do. Why? Because
  1036. (Data Maybe [a]) is the superclass, so we'd "satisfy" the wanted
  1037. by selecting a superclass from Foo [a], which simply makes a loop.
  1038. On the other hand we *must* put the superclasses of (Foo a) in
  1039. the givens, as you can see from the derivation described above.
  1040. Conclusion: in the very special case of tcSimplifySuperClasses
  1041. we have one 'given' (namely the "this" dictionary) whose superclasses
  1042. must not be added to 'givens' by addGiven.
  1043. There is a complication though. Suppose there are equalities
  1044. instance (Eq a, a~b) => Num (a,b)
  1045. Then we normalise the 'givens' wrt the equalities, so the original
  1046. given "this" dictionary is cast to one of a different type. So it's a
  1047. bit trickier than before to identify the "special" dictionary whose
  1048. superclasses must not be added. See test
  1049. indexed-types/should_run/EqInInstance
  1050. We need a persistent property of the dictionary to record this
  1051. special-ness. Current I'm using the InstLocOrigin (a bit of a hack,
  1052. but cool), which is maintained by dictionary normalisation.
  1053. Specifically, the InstLocOrigin is
  1054. NoScOrigin
  1055. then the no-superclass thing kicks in. WATCH OUT if you fiddle
  1056. with InstLocOrigin!
  1057. Note [MATCHING-SYNONYMS]
  1058. ~~~~~~~~~~~~~~~~~~~~~~~~
  1059. When trying to match a dictionary (D tau) to a top-level instance, or a
  1060. type family equation (F taus_1 ~ tau_2) to a top-level family instance,
  1061. we do *not* need to expand type synonyms because the matcher will do that for us.
  1062. Note [RHS-FAMILY-SYNONYMS]
  1063. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  1064. The RHS of a family instance is represented as yet another constructor which is
  1065. like a type synonym for the real RHS the programmer declared. Eg:
  1066. type instance F (a,a) = [a]
  1067. Becomes:
  1068. :R32 a = [a] -- internal type synonym introduced
  1069. F (a,a) ~ :R32 a -- instance
  1070. When we react a family instance with a type family equation in the work list
  1071. we keep the synonym-using RHS without expansion.
  1072. %************************************************************************
  1073. %* *
  1074. %* Functional dependencies, instantiation of equations
  1075. %* *
  1076. %************************************************************************
  1077. When we spot an equality arising from a functional dependency,
  1078. we now use that equality (a "wanted") to rewrite the work-item
  1079. constraint right away. This avoids two dangers
  1080. Danger 1: If we send the original constraint on down the pipeline
  1081. it may react with an instance declaration, and in delicate
  1082. situations (when a Given overlaps with an instance) that
  1083. may produce new insoluble goals: see Trac #4952
  1084. Danger 2: If we don't rewrite the constraint, it may re-react
  1085. with the same thing later, and produce the same equality
  1086. again --> termination worries.
  1087. To achieve this required some refactoring of FunDeps.lhs (nicer
  1088. now!).
  1089. \begin{code}
  1090. rewriteWithFunDeps :: [Equation] -> CtLoc -> TcS [Ct]
  1091. -- NB: The returned constraints are all Derived
  1092. -- Post: returns no trivial equalities (identities) and all EvVars returned are fresh
  1093. rewriteWithFunDeps eqn_pred_locs loc
  1094. = do { fd_cts <- mapM (instFunDepEqn loc) eqn_pred_locs
  1095. ; return (concat fd_cts) }
  1096. instFunDepEqn :: CtLoc -> Equation -> TcS [Ct]
  1097. -- Post: Returns the position index as well as the corresponding FunDep equality
  1098. instFunDepEqn loc (FDEqn { fd_qtvs = tvs, fd_eqs = eqs
  1099. , fd_pred1 = d1, fd_pred2 = d2 })
  1100. = do { (subst, _) <- instFlexiTcS tvs -- Takes account of kind substitution
  1101. ; foldM (do_one subst) [] eqs }
  1102. where
  1103. der_loc = pushErrCtxt FunDepOrigin (False, mkEqnMsg d1 d2) loc
  1104. do_one subst ievs (FDEq { fd_ty_left = ty1, fd_ty_right = ty2 })
  1105. | eqType sty1 sty2
  1106. = return ievs -- Return no trivial equalities
  1107. | otherwise
  1108. = do { mb_eqv <- newDerived (mkTcEqPred sty1 sty2)
  1109. ; case mb_eqv of
  1110. Just ev -> return (mkNonCanonical der_loc ev : ievs)
  1111. Nothing -> return ievs }
  1112. -- We are eventually going to emit FD work back in the work list so
  1113. -- it is important that we only return the /freshly created/ and not
  1114. -- some existing equality!
  1115. where
  1116. sty1 = Type.substTy subst ty1
  1117. sty2 = Type.substTy subst ty2
  1118. mkEqnMsg :: (TcPredType, SDoc)
  1119. -> (TcPredType, SDoc) -> TidyEnv -> TcM (TidyEnv, SDoc)
  1120. mkEqnMsg (pred1,from1) (pred2,from2) tidy_env
  1121. = do { zpred1 <- zonkTcPredType pred1
  1122. ; zpred2 <- zonkTcPredType pred2
  1123. ; let { tpred1 = tidyType tidy_env zpred1
  1124. ; tpred2 = tidyType tidy_env zpred2 }
  1125. ; let msg = vcat [ptext (sLit "When using functional dependencies to combine"),
  1126. nest 2 (sep [ppr tpred1 <> comma, nest 2 from1]),
  1127. nest 2 (sep [ppr tpred2 <> comma, nest 2 from2])]
  1128. ; return (tidy_env, msg) }
  1129. \end{code}
  1130. *********************************************************************************
  1131. * *
  1132. The top-reaction Stage
  1133. * *
  1134. *********************************************************************************
  1135. \begin{code}
  1136. topReactionsStage :: WorkItem -> TcS StopOrContinue
  1137. topReactionsStage wi
  1138. = do { inerts <- getTcSInerts
  1139. ; tir <- doTopReact inerts wi
  1140. ; case tir of
  1141. NoTopInt -> return (ContinueWith wi)
  1142. SomeTopInt rule what_next
  1143. -> do { traceFireTcS wi $
  1144. vcat [ ptext (sLit "Top react:") <+> text rule
  1145. , text "WorkItem =" <+> ppr wi ]
  1146. ; return what_next } }
  1147. data TopInteractResult
  1148. = NoTopInt
  1149. | SomeTopInt { tir_rule :: String, tir_new_item :: StopOrContinue }
  1150. doTopReact :: InertSet -> WorkItem -> TcS TopInteractResult
  1151. -- The work item does not react with the inert set, so try interaction with top-level
  1152. -- instances. Note:
  1153. --
  1154. -- (a) The place to add superclasses in not here in doTopReact stage.
  1155. -- Instead superclasses are added in the worklist as part of the
  1156. -- canonicalization process. See Note [Adding superclasses].
  1157. --
  1158. -- (b) See Note [Given constraint that matches an instance declaration]
  1159. -- for some design decisions for given dictionaries.
  1160. doTopReact inerts workItem
  1161. = do { traceTcS "doTopReact" (ppr workItem)
  1162. ; case workItem of
  1163. CDictCan { cc_ev = fl, cc_class = cls, cc_tyargs = xis
  1164. , cc_loc = d }
  1165. -> doTopReactDict inerts fl cls xis d
  1166. CFunEqCan { cc_ev = fl, cc_fun = tc, cc_tyargs = args
  1167. , cc_rhs = xi, cc_loc = d }
  1168. -> doTopReactFunEq workItem fl tc args xi d
  1169. _ -> -- Any other work item does not react with any top-level equations
  1170. return NoTopInt }
  1171. --------------------
  1172. doTopReactDict :: InertSet -> CtEvidence -> Class -> [Xi]
  1173. -> CtLoc -> TcS TopInteractResult
  1174. doTopReactDict inerts fl cls xis loc
  1175. | not (isWanted fl)
  1176. = try_fundeps_and_return
  1177. | Just ev <- lookupSolvedDict inerts pred -- Cached
  1178. = do { setEvBind dict_id (ctEvTerm ev);
  1179. ; return $ SomeTopInt { tir_rule = "Dict/Top (cached)"
  1180. , tir_new_item = Stop } }
  1181. | otherwise -- Not cached
  1182. = do { lkup_inst_res <- matchClassInst inerts cls xis loc
  1183. ; case lkup_inst_res of
  1184. GenInst wtvs ev_term -> do { addSolvedDict fl
  1185. ; solve_from_instance wtvs ev_term }
  1186. NoInstance -> try_fundeps_and_return }
  1187. where
  1188. arising_sdoc = pprArisingAt loc
  1189. dict_id = ctEvId fl
  1190. pred = mkClassPred cls xis
  1191. solve_from_instance :: [CtEvidence] -> EvTerm -> TcS TopInteractResult
  1192. -- Precondition: evidence term matches the predicate workItem
  1193. solve_from_instance evs ev_term
  1194. | null evs
  1195. = do { traceTcS "doTopReact/found nullary instance for" $
  1196. ppr dict_id
  1197. ; setEvBind dict_id ev_term
  1198. ; return $
  1199. SomeTopInt { tir_rule = "Dict/Top (solved, no new work)"
  1200. , tir_new_item = Stop } }
  1201. | otherwise
  1202. = do { traceTcS "doTopReact/found non-nullary instance for" $
  1203. ppr dict_id
  1204. ; setEvBind dict_id ev_term
  1205. ; let mk_new_wanted ev
  1206. = CNonCanonical { cc_ev = ev
  1207. , cc_loc = bumpCtLocDepth loc }
  1208. ; updWorkListTcS (extendWorkListCts (map mk_new_wanted evs))
  1209. ; return $
  1210. SomeTopInt { tir_rule = "Dict/Top (solved, more work)"
  1211. , tir_new_item = Stop } }
  1212. -- We didn't solve it; so try functional dependencies with
  1213. -- the instance environment, and return
  1214. -- NB: even if there *are* some functional dependencies against the
  1215. -- instance environment, there might be a unique match, and if
  1216. -- so we make sure we get on and solve it first. See Note [Weird fundeps]
  1217. try_fundeps_and_return
  1218. = do { instEnvs <- getInstEnvs
  1219. ; let fd_eqns = improveFromInstEnv instEnvs (pred, arising_sdoc)
  1220. ; fd_work <- rewriteWithFunDeps fd_eqns loc
  1221. ; unless (null fd_work) (updWorkListTcS (extendWorkListEqs fd_work))
  1222. ; return NoTopInt }
  1223. --------------------
  1224. doTopReactFunEq :: Ct -> CtEvidence -> TyCon -> [Xi] -> Xi
  1225. -> CtLoc -> TcS TopInteractResult
  1226. doTopReactFunEq _ct fl fun_tc args xi loc
  1227. = ASSERT (isSynFamilyTyCon fun_tc) -- No associated data families have
  1228. -- reached this far
  1229. -- Look in the cache of solved funeqs
  1230. do { fun_eq_cache <- getTcSInerts >>= (return . inert_solved_funeqs)
  1231. ; case lookupFamHead fun_eq_cache fam_ty of {
  1232. Just (ctev, rhs_ty)
  1233. | ctEvFlavour ctev `canRewrite` ctEvFlavour fl
  1234. -> ASSERT( not (isDerived ctev) )
  1235. succeed_with "Fun/Cache" (evTermCoercion (ctEvTerm ctev)) rhs_ty ;
  1236. _other ->
  1237. -- Look up in top-level instances
  1238. do { match_res <- matchFam fun_tc args -- See Note [MATCHING-SYNONYMS]
  1239. ; case match_res of {
  1240. Nothing -> return NoTopInt ;
  1241. Just (FamInstMatch { fim_instance = famInst
  1242. , fim_index = index
  1243. , fim_tys = rep_tys }) ->
  1244. -- Found a top-level instance
  1245. do { -- Add it to the solved goals
  1246. unless (isDerived fl) (addSolvedFunEq fam_ty fl xi)
  1247. ; let coe_ax = famInstAxiom famInst
  1248. ; succeed_with "Fun/Top" (mkTcAxInstCo coe_ax index rep_tys)
  1249. (mkAxInstRHS coe_ax index rep_tys) } } } } }
  1250. where
  1251. fam_ty = mkTyConApp fun_tc args
  1252. succeed_with :: String -> TcCoercion -> TcType -> TcS TopInteractResult
  1253. succeed_with str co rhs_ty -- co :: fun_tc args ~ rhs_ty
  1254. = do { ctevs <- xCtFlavor fl [mkTcEqPred rhs_ty xi] xev
  1255. ; traceTcS ("doTopReactFunEq " ++ str) (ppr ctevs)
  1256. ; case ctevs of
  1257. [ctev] -> updWorkListTcS $ extendWorkListEq $
  1258. CNonCanonical { cc_ev = ctev
  1259. , cc_loc = bumpCtLocDepth loc }
  1260. ctevs -> -- No subgoal (because it's cached)
  1261. ASSERT( null ctevs) return ()
  1262. ; return $ SomeTopInt { tir_rule = str
  1263. , tir_new_item = Stop } }
  1264. where
  1265. xdecomp x = [EvCoercion (mkTcSymCo co `mkTcTransCo` evTermCoercion x)]
  1266. xcomp [x] = EvCoercion (co `mkTcTransCo` evTermCoercion x)
  1267. xcomp _ = panic "No more goals!"
  1268. xev = XEvTerm xcomp xdecomp
  1269. \end{code}
  1270. Note [FunDep and implicit parameter reactions]
  1271. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1272. Currently, our story of interacting two dictionaries (or a dictionary
  1273. and top-level instances) for functional dependencies, and implicit
  1274. paramters, is that we simply produce new Derived equalities. So for example
  1275. class D a b | a -> b where ...
  1276. Inert:
  1277. d1 :g D Int Bool
  1278. WorkItem:
  1279. d2 :w D Int alpha
  1280. We generate the extra work item
  1281. cv :d alpha ~ Bool
  1282. where 'cv' is currently unused. However, this new item can perhaps be
  1283. spontaneously solved to become given and react with d2,
  1284. discharging it in favour of a new constraint d2' thus:
  1285. d2' :w D Int Bool
  1286. d2 := d2' |> D Int cv
  1287. Now d2' can be discharged from d1
  1288. We could be more aggressive and try to *immediately* solve the dictionary
  1289. using those extra equalities, but that requires those equalities to carry
  1290. evidence and derived do not carry evidence.
  1291. If that were the case with the same inert set and work item we might dischard
  1292. d2 directly:
  1293. cv :w alpha ~ Bool
  1294. d2 := d1 |> D Int cv
  1295. But in general it's a bit painful to figure out the necessary coercion,
  1296. so we just take the first approach. Here is a better example. Consider:
  1297. class C a b c | a -> b
  1298. And:
  1299. [Given] d1 : C T Int Char
  1300. [Wanted] d2 : C T beta Int
  1301. In this case, it's *not even possible* to solve the wanted immediately.
  1302. So we should simply output the functional dependency and add this guy
  1303. [but NOT its superclasses] back in the worklist. Even worse:
  1304. [Given] d1 : C T Int beta
  1305. [Wanted] d2: C T beta Int
  1306. Then it is solvable, but its very hard to detect this on the spot.
  1307. It's exactly the same with implicit parameters, except that the
  1308. "aggressive" approach would be much easier to implement.
  1309. Note [When improvement happens]
  1310. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1311. We fire an improvement rule when
  1312. * Two constraints match (modulo the fundep)
  1313. e.g. C t1 t2, C t1 t3 where C a b | a->b
  1314. The two match because the first arg is identical
  1315. Note that we *do* fire the improvement if one is Given and one is Derived (e.g. a
  1316. superclass of a Wanted goal) or if both are Given.
  1317. Example (tcfail138)
  1318. class L a b | a -> b
  1319. class (G a, L a b) => C a b
  1320. instance C a b' => G (Maybe a)
  1321. instance C a b => C (Maybe a) a
  1322. instance L (Maybe a) a
  1323. When solving the superclasses of the (C (Maybe a) a) instance, we get
  1324. Given: C a b ... and hance by superclasses, (G a, L a b)
  1325. Wanted: G (Maybe a)
  1326. Use the instance decl to get
  1327. Wanted: C a b'
  1328. The (C a b') is inert, so we generate its Derived superclasses (L a b'),
  1329. and now we need improvement between that derived superclass an the Given (L a b)
  1330. Test typecheck/should_fail/FDsFromGivens also shows why it's a good idea to
  1331. emit Derived FDs for givens as well.
  1332. Note [Weird fundeps]
  1333. ~~~~~~~~~~~~~~~~~~~~
  1334. Consider class Het a b | a -> b where
  1335. het :: m (f c) -> a -> m b
  1336. class GHet (a :: * -> *) (b :: * -> *) | a -> b
  1337. instance GHet (K a) (K [a])
  1338. instance Het a b => GHet (K a) (K b)
  1339. The two instances don't actually conflict on their fundeps,
  1340. although it's pretty strange. So they are both accepted. Now
  1341. try [W] GHet (K Int) (K Bool)
  1342. This triggers fudeps from both instance decls; but it also
  1343. matches a *unique* instance decl, and we should go ahead and
  1344. pick that one right now. Otherwise, if we don't, it ends up
  1345. unsolved in the inert set and is reported as an error.
  1346. Trac #7875 is a case in point.
  1347. Note [Overriding implicit parameters]
  1348. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1349. Consider
  1350. f :: (?x::a) -> Bool -> a
  1351. g v = let ?x::Int = 3
  1352. in (f v, let ?x::Bool = True in f v)
  1353. This should probably be well typed, with
  1354. g :: Bool -> (Int, Bool)
  1355. So the inner binding for ?x::Bool *overrides* the outer one.
  1356. Hence a work-item Given overrides an inert-item Given.
  1357. Note [Given constraint that matches an instance declaration]
  1358. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1359. What should we do when we discover that one (or more) top-level
  1360. instances match a given (or solved) class constraint? We have
  1361. two possibilities:
  1362. 1. Reject the program. The reason is that there may not be a unique
  1363. best strategy for the solver. Example, from the OutsideIn(X) paper:
  1364. instance P x => Q [x]
  1365. instance (x ~ y) => R [x] y
  1366. wob :: forall a b. (Q [b], R b a) => a -> Int
  1367. g :: forall a. Q [a] => [a] -> Int
  1368. g x = wob x
  1369. will generate the impliation constraint:
  1370. Q [a] => (Q [beta], R beta [a])
  1371. If we react (Q [beta]) with its top-level axiom, we end up with a
  1372. (P beta), which we have no way of discharging. On the other hand,
  1373. if we react R beta [a] with the top-level we get (beta ~ a), which
  1374. is solvable and can help us rewrite (Q [beta]) to (Q [a]) which is
  1375. now solvable by the given Q [a].
  1376. However, this option is restrictive, for instance [Example 3] from
  1377. Note [Recursive instances and superclases] will fail to work.
  1378. 2. Ignore the problem, hoping that the situations where there exist indeed
  1379. such multiple strategies are rare: Indeed the cause of the previous
  1380. problem is that (R [x] y) yields the new work (x ~ y) which can be
  1381. *spontaneously* solved, not using the givens.
  1382. We are choosing option 2 below but we might consider having a flag as well.
  1383. Note [New Wanted Superclass Work]
  1384. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1385. Even in the case of wanted constraints, we may add some superclasses
  1386. as new given work. The reason is:
  1387. To allow FD-like improvement for type families. Assume that
  1388. we have a class
  1389. class C a b | a -> b
  1390. and we have to solve the implication constraint:
  1391. C a b => C a beta
  1392. Then, FD improvement can help us to produce a new wanted (beta ~ b)
  1393. We want to have the same effect with the type family encoding of
  1394. functional dependencies. Namely, consider:
  1395. class (F a ~ b) => C a b
  1396. Now suppose that we have:
  1397. given: C a b
  1398. wanted: C a beta
  1399. By interacting the given we will get given (F a ~ b) which is not
  1400. enough by itself to make us discharge (C a beta). However, we
  1401. may create a new derived equality from the super-class of the
  1402. wanted constraint (C a beta), namely derived (F a ~ beta).
  1403. Now we may interact this with given (F a ~ b) to get:
  1404. derived : beta ~ b
  1405. But 'beta' is a touchable unification variable, and hence OK to
  1406. unify it with 'b', replacing the derived evidence with the identity.
  1407. This requires trySpontaneousSolve to solve *derived*
  1408. equalities that have a touchable in their RHS, *in addition*
  1409. to solving wanted equalities.
  1410. We also need to somehow use the superclasses to quantify over a minimal,
  1411. constraint see note [Minimize by Superclasses] in TcSimplify.
  1412. Finally, here is another example where this is useful.
  1413. Example 1:
  1414. ----------
  1415. class (F a ~ b) => C a b
  1416. And we are given the wanteds:
  1417. w1 : C a b
  1418. w2 : C a c
  1419. w3 : b ~ c
  1420. We surely do *not* want to quantify over (b ~ c), since if someone provides
  1421. dictionaries for (C a b) and (C a c), these dictionaries can provide a proof
  1422. of (b ~ c), hence no extra evidence is necessary. Here is what will happen:
  1423. Step 1: We will get new *given* superclass work,
  1424. provisionally to our solving of w1 and w2
  1425. g1: F a ~ b, g2 : F a ~ c,
  1426. w1 : C a b, w2 : C a c, w3 : b ~ c
  1427. The evidence for g1 and g2 is a superclass evidence term:
  1428. g1 := sc w1, g2 := sc w2
  1429. Step 2: The givens will solve the wanted w3, so that
  1430. w3 := sym (sc w1) ; sc w2
  1431. Step 3: Now, one may naively assume that then w2 can be solve from w1
  1432. after rewriting with the (now solved equality) (b ~ c).
  1433. But this rewriting is ruled out by the isGoodRectDict!
  1434. Conclusion, we will (correctly) end up with the unsolved goals
  1435. (C a b, C a c)
  1436. NB: The desugarer needs be more clever to deal with equalities
  1437. that participate in recursive dictionary bindings.
  1438. \begin{code}
  1439. data LookupInstResult
  1440. = NoInstance
  1441. | GenInst [CtEvidence] EvTerm
  1442. matchClassInst :: InertSet -> Class -> [Type] -> CtLoc -> TcS LookupInstResult
  1443. matchClassInst _ clas [ k, ty ] _
  1444. | className clas == singIClassName
  1445. , Just n <- isNumLitTy ty = makeDict (EvNum n)
  1446. | className clas == singIClassName
  1447. , Just s <- isStrLitTy ty = makeDict (EvStr s)
  1448. where
  1449. {- This adds a coercion that will convert the literal into a dictionary
  1450. of the appropriate type. See Note [SingI and EvLit] in TcEvidence.
  1451. The coercion happens in 3 steps:
  1452. evLit -> Sing_k_n -- literal to representation of data family
  1453. Sing_k_n -> Sing k n -- representation of data family to data family
  1454. Sing k n -> SingI k n -- data family to class dictionary.
  1455. -}
  1456. makeDict evLit =
  1457. case unwrapNewTyCon_maybe (classTyCon clas) of
  1458. Just (_,dictRep, axDict)
  1459. | Just tcSing <- tyConAppTyCon_maybe dictRep ->
  1460. do mbInst <- matchFam tcSing [k,ty]
  1461. case mbInst of
  1462. Just FamInstMatch
  1463. { fim_instance = FamInst { fi_axiom = axDataFam
  1464. , fi_flavor = DataFamilyInst tcon
  1465. }
  1466. , fim_index = ix, fim_tys = tys
  1467. } | Just (_,_,axSing) <- unwrapNewTyCon_maybe tcon ->
  1468. do let co1 = mkTcSymCo $ mkTcUnbranchedAxInstCo axSing tys
  1469. co2 = mkTcSymCo $ mkTcAxInstCo axDataFam ix tys
  1470. co3 = mkTcSymCo $ mkTcUnbranchedAxInstCo axDict [k,ty]
  1471. return $ GenInst [] $ EvCast (EvLit evLit) $
  1472. mkTcTransCo co1 $ mkTcTransCo co2 co3
  1473. _ -> unexpected
  1474. _ -> unexpected
  1475. unexpected = panicTcS (text "Unexpected evidence for SingI")
  1476. matchClassInst inerts clas tys loc
  1477. = do { dflags <- getDynFlags
  1478. ; let pred = mkClassPred clas tys
  1479. incoherent_ok = xopt Opt_IncoherentInstances dflags
  1480. ; mb_result <- matchClass clas tys
  1481. ; untch <- getUntouchables
  1482. ; traceTcS "matchClassInst" $ vcat [ text "pred =" <+> ppr pred
  1483. , text "inerts=" <+> ppr inerts
  1484. , text "untouchables=" <+> ppr untch ]
  1485. ; case mb_result of
  1486. MatchInstNo -> return NoInstance
  1487. MatchInstMany -> return NoInstance -- defer any reactions of a multitude until
  1488. -- we learn more about the reagent
  1489. MatchInstSingle (_,_)
  1490. | not incoherent_ok && given_overlap untch
  1491. -> -- see Note [Instance and Given overlap]
  1492. do { traceTcS "Delaying instance application" $
  1493. vcat [ text "Workitem=" <+> pprType (mkClassPred clas tys)
  1494. , text "Relevant given dictionaries=" <+> ppr givens_for_this_clas ]
  1495. ; return NoInstance
  1496. }
  1497. MatchInstSingle (dfun_id, mb_inst_tys) ->
  1498. do { checkWellStagedDFun pred dfun_id loc
  1499. -- mb_inst_tys :: Maybe TcType
  1500. -- See Note [DFunInstType: instantiating types] in InstEnv
  1501. ; (tys, dfun_phi) <- instDFunType dfun_id mb_inst_tys
  1502. ; let (theta, _) = tcSplitPhiTy dfun_phi
  1503. ; if null theta then
  1504. return (GenInst [] (EvDFunApp dfun_id tys []))
  1505. else do
  1506. { evc_vars <- instDFunConstraints theta
  1507. ; let new_ev_vars = freshGoals evc_vars
  1508. -- new_ev_vars are only the real new variables that can be emitted
  1509. dfun_app = EvDFunApp dfun_id tys (getEvTerms evc_vars)
  1510. ; return $ GenInst new_ev_vars dfun_app } }
  1511. }
  1512. where
  1513. givens_for_this_clas :: Cts
  1514. givens_for_this_clas
  1515. = lookupUFM (cts_given (inert_dicts $ inert_cans inerts)) clas
  1516. `orElse` emptyCts
  1517. given_overlap :: Untouchables -> Bool
  1518. given_overlap untch = anyBag (matchable untch) givens_for_this_clas
  1519. matchable untch (CDictCan { cc_class = clas_g, cc_tyargs = sys
  1520. , cc_ev = fl })
  1521. | isGiven fl
  1522. = ASSERT( clas_g == clas )
  1523. case tcUnifyTys (\tv -> if isTouchableMetaTyVar untch tv &&
  1524. tv `elemVarSet` tyVarsOfTypes tys
  1525. then BindMe else Skolem) tys sys of
  1526. -- We can't learn anything more about any variable at this point, so the only
  1527. -- cause of overlap can be by an instantiation of a touchable unification
  1528. -- variable. Hence we only bind touchable unification variables. In addition,
  1529. -- we use tcUnifyTys instead of tcMatchTys to rule out cyclic substitutions.
  1530. Nothing -> False
  1531. Just _ -> True
  1532. | otherwise = False -- No overlap with a solved, already been taken care of
  1533. -- by the overlap check with the instance environment.
  1534. matchable _tys ct = pprPanic "Expecting dictionary!" (ppr ct)
  1535. \end{code}
  1536. Note [Instance and Given overlap]
  1537. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1538. Assume that we have an inert set that looks as follows:
  1539. [Given] D [Int]
  1540. And an instance declaration:
  1541. instance C a => D [a]
  1542. A new wanted comes along of the form:
  1543. [Wanted] D [alpha]
  1544. One possibility is to apply the instance declaration which will leave us
  1545. with an unsolvable goal (C alpha). However, later on a new constraint may
  1546. arise (for instance due to a functional dependency between two later dictionaries),
  1547. that will add the equality (alpha ~ Int), in which case our ([Wanted] D [alpha])
  1548. will be transformed to [Wanted] D [Int], which could have been discharged by the given.
  1549. The solution is that in matchClassInst and eventually in topReact, we get back with
  1550. a matching instance, only when there is no Given in the inerts which is unifiable to
  1551. this particular dictionary.
  1552. The end effect is that, much as we do for overlapping instances, we delay choosing a
  1553. class instance if there is a possibility of another instance OR a given to match our
  1554. constraint later on. This fixes bugs #4981 and #5002.
  1555. This is arguably not easy to appear in practice due to our aggressive prioritization
  1556. of equality solving over other constraints, but it is possible. I've added a test case
  1557. in typecheck/should-compile/GivenOverlapping.hs
  1558. We ignore the overlap problem if -XIncoherentInstances is in force: see
  1559. Trac #6002 for a worked-out example where this makes a difference.
  1560. Moreover notice that our goals here are different than the goals of the top-level
  1561. overlapping checks. There we are interested in validating the following principle:
  1562. If we inline a function f at a site where the same global instance environment
  1563. is available as the instance environment at the definition site of f then we
  1564. should get the same behaviour.
  1565. But for the Given Overlap check our goal is just related to completeness of
  1566. constraint solving.