PageRenderTime 34ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 0ms

/compiler/typecheck/TcSMonad.lhs

https://github.com/luite/ghc
Haskell | 1739 lines | 1215 code | 333 blank | 191 comment | 34 complexity | f1483cccaab79b5f3a5beca363a5ea58 MD5 | raw file
  1. \begin{code}
  2. {-# OPTIONS -fno-warn-tabs -w #-}
  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. -- Type definitions for the constraint solver
  9. module TcSMonad (
  10. -- Canonical constraints, definition is now in TcRnTypes
  11. WorkList(..), isEmptyWorkList, emptyWorkList,
  12. workListFromEq, workListFromNonEq, workListFromCt,
  13. extendWorkListEq, extendWorkListFunEq,
  14. extendWorkListNonEq, extendWorkListCt,
  15. extendWorkListCts, extendWorkListEqs, appendWorkList, selectWorkItem,
  16. withWorkList, workListSize,
  17. updWorkListTcS, updWorkListTcS_return,
  18. updTcSImplics,
  19. Ct(..), Xi, tyVarsOfCt, tyVarsOfCts,
  20. emitInsoluble,
  21. isWanted, isDerived,
  22. isGivenCt, isWantedCt, isDerivedCt,
  23. canRewrite, canSolve,
  24. mkGivenLoc,
  25. TcS, runTcS, runTcSWithEvBinds, failTcS, panicTcS, traceTcS, -- Basic functionality
  26. traceFireTcS, bumpStepCountTcS,
  27. tryTcS, nestTcS, nestImplicTcS, recoverTcS,
  28. wrapErrTcS, wrapWarnTcS,
  29. -- Getting and setting the flattening cache
  30. addSolvedDict, addSolvedFunEq, getFlattenSkols,
  31. deferTcSForAllEq,
  32. setEvBind,
  33. XEvTerm(..),
  34. MaybeNew (..), isFresh, freshGoals, getEvTerms,
  35. xCtFlavor, -- Transform a CtEvidence during a step
  36. rewriteCtFlavor, -- Specialized version of xCtFlavor for coercions
  37. newWantedEvVar, newWantedEvVarNC, instDFunConstraints,
  38. newDerived,
  39. -- Creation of evidence variables
  40. setWantedTyBind,
  41. getInstEnvs, getFamInstEnvs, -- Getting the environments
  42. getTopEnv, getGblEnv, getTcEvBinds, getUntouchables,
  43. getTcEvBindsMap, getTcSTyBinds, getTcSTyBindsMap,
  44. lookupFlatEqn, newFlattenSkolem, -- Flatten skolems
  45. -- Deque
  46. Deque(..), insertDeque, emptyDeque,
  47. -- Inerts
  48. InertSet(..), InertCans(..),
  49. getInertEqs,
  50. emptyInert, getTcSInerts, lookupInInerts,
  51. getInertUnsolved, checkAllSolved,
  52. prepareInertsForImplications,
  53. modifyInertTcS,
  54. insertInertItemTcS, partitionCCanMap, partitionEqMap,
  55. getRelevantCts, extractRelevantInerts,
  56. CCanMap(..), CtTypeMap, CtFamHeadMap, CtPredMap,
  57. PredMap, FamHeadMap,
  58. partCtFamHeadMap, lookupFamHead, lookupSolvedDict,
  59. filterSolved,
  60. instDFunType, -- Instantiation
  61. newFlexiTcSTy, instFlexiTcS, instFlexiTcSHelperTcS,
  62. cloneMetaTyVar,
  63. compatKind, mkKindErrorCtxtTcS,
  64. Untouchables, isTouchableMetaTyVarTcS, isFilledMetaTyVar_maybe,
  65. zonkTyVarsAndFV,
  66. getDefaultInfo, getDynFlags,
  67. matchClass, matchFam, MatchInstResult (..),
  68. checkWellStagedDFun,
  69. pprEq -- Smaller utils, re-exported from TcM
  70. -- TODO (DV): these are only really used in the
  71. -- instance matcher in TcSimplify. I am wondering
  72. -- if the whole instance matcher simply belongs
  73. -- here
  74. ) where
  75. #include "HsVersions.h"
  76. import HscTypes
  77. import Inst
  78. import InstEnv
  79. import FamInst
  80. import FamInstEnv
  81. import qualified TcRnMonad as TcM
  82. import qualified TcMType as TcM
  83. import qualified TcEnv as TcM
  84. ( checkWellStaged, topIdLvl, tcGetDefaultTys )
  85. import {-# SOURCE #-} qualified TcUnify as TcM ( mkKindErrorCtxt )
  86. import Kind
  87. import TcType
  88. import DynFlags
  89. import Type
  90. import TcEvidence
  91. import Class
  92. import TyCon
  93. import Name
  94. import Var
  95. import VarEnv
  96. import Outputable
  97. import Bag
  98. import MonadUtils
  99. import FastString
  100. import Util
  101. import Id
  102. import TcRnTypes
  103. import Unique
  104. import UniqFM
  105. import Maybes ( orElse, catMaybes, firstJust )
  106. import StaticFlags( opt_NoFlatCache )
  107. import Control.Monad( unless, when, zipWithM )
  108. import Data.IORef
  109. import TrieMap
  110. #ifdef DEBUG
  111. import StaticFlags( opt_PprStyle_Debug )
  112. import VarSet
  113. import Digraph
  114. #endif
  115. \end{code}
  116. \begin{code}
  117. compatKind :: Kind -> Kind -> Bool
  118. compatKind k1 k2 = k1 `tcIsSubKind` k2 || k2 `tcIsSubKind` k1
  119. mkKindErrorCtxtTcS :: Type -> Kind
  120. -> Type -> Kind
  121. -> ErrCtxt
  122. mkKindErrorCtxtTcS ty1 ki1 ty2 ki2
  123. = (False,TcM.mkKindErrorCtxt ty1 ty2 ki1 ki2)
  124. \end{code}
  125. %************************************************************************
  126. %* *
  127. %* Worklists *
  128. %* Canonical and non-canonical constraints that the simplifier has to *
  129. %* work on. Including their simplification depths. *
  130. %* *
  131. %* *
  132. %************************************************************************
  133. Note [WorkList priorities]
  134. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  135. A WorkList contains canonical and non-canonical items (of all flavors).
  136. Notice that each Ct now has a simplification depth. We may
  137. consider using this depth for prioritization as well in the future.
  138. As a simple form of priority queue, our worklist separates out
  139. equalities (wl_eqs) from the rest of the canonical constraints,
  140. so that it's easier to deal with them first, but the separation
  141. is not strictly necessary. Notice that non-canonical constraints
  142. are also parts of the worklist.
  143. Note [NonCanonical Semantics]
  144. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  145. Note that canonical constraints involve a CNonCanonical constructor. In the worklist
  146. we use this constructor for constraints that have not yet been canonicalized such as
  147. [Int] ~ [a]
  148. In other words, all constraints start life as NonCanonicals.
  149. On the other hand, in the Inert Set (see below) the presence of a NonCanonical somewhere
  150. means that we have a ``frozen error''.
  151. NonCanonical constraints never interact directly with other constraints -- but they can
  152. be rewritten by equalities (for instance if a non canonical exists in the inert, we'd
  153. better rewrite it as much as possible before reporting it as an error to the user)
  154. \begin{code}
  155. data Deque a = DQ [a] [a] -- Insert in RH field, remove from LH field
  156. -- First to remove is at head of LH field
  157. instance Outputable a => Outputable (Deque a) where
  158. ppr (DQ as bs) = ppr (as ++ reverse bs) -- Show first one to come out at the start
  159. emptyDeque :: Deque a
  160. emptyDeque = DQ [] []
  161. isEmptyDeque :: Deque a -> Bool
  162. isEmptyDeque (DQ as bs) = null as && null bs
  163. dequeSize :: Deque a -> Int
  164. dequeSize (DQ as bs) = length as + length bs
  165. insertDeque :: a -> Deque a -> Deque a
  166. insertDeque b (DQ as bs) = DQ as (b:bs)
  167. appendDeque :: Deque a -> Deque a -> Deque a
  168. appendDeque (DQ as1 bs1) (DQ as2 bs2) = DQ (as1 ++ reverse bs1 ++ as2) bs2
  169. extractDeque :: Deque a -> Maybe (Deque a, a)
  170. extractDeque (DQ [] []) = Nothing
  171. extractDeque (DQ (a:as) bs) = Just (DQ as bs, a)
  172. extractDeque (DQ [] bs) = case reverse bs of
  173. (a:as) -> Just (DQ as [], a)
  174. [] -> panic "extractDeque"
  175. -- See Note [WorkList priorities]
  176. data WorkList = WorkList { wl_eqs :: [Ct]
  177. , wl_funeqs :: Deque Ct
  178. , wl_rest :: [Ct]
  179. }
  180. appendWorkList :: WorkList -> WorkList -> WorkList
  181. appendWorkList new_wl orig_wl
  182. = WorkList { wl_eqs = wl_eqs new_wl ++ wl_eqs orig_wl
  183. , wl_funeqs = wl_funeqs new_wl `appendDeque` wl_funeqs orig_wl
  184. , wl_rest = wl_rest new_wl ++ wl_rest orig_wl }
  185. workListSize :: WorkList -> Int
  186. workListSize (WorkList { wl_eqs = eqs, wl_funeqs = funeqs, wl_rest = rest })
  187. = length eqs + dequeSize funeqs + length rest
  188. extendWorkListEq :: Ct -> WorkList -> WorkList
  189. -- Extension by equality
  190. extendWorkListEq ct wl
  191. | Just {} <- isCFunEqCan_Maybe ct
  192. = extendWorkListFunEq ct wl
  193. | otherwise
  194. = wl { wl_eqs = ct : wl_eqs wl }
  195. extendWorkListFunEq :: Ct -> WorkList -> WorkList
  196. extendWorkListFunEq ct wl
  197. = wl { wl_funeqs = insertDeque ct (wl_funeqs wl) }
  198. extendWorkListEqs :: [Ct] -> WorkList -> WorkList
  199. -- Append a list of equalities
  200. extendWorkListEqs cts wl = foldr extendWorkListEq wl cts
  201. extendWorkListNonEq :: Ct -> WorkList -> WorkList
  202. -- Extension by non equality
  203. extendWorkListNonEq ct wl
  204. = wl { wl_rest = ct : wl_rest wl }
  205. extendWorkListCt :: Ct -> WorkList -> WorkList
  206. -- Agnostic
  207. extendWorkListCt ct wl
  208. | isEqPred (ctPred ct) = extendWorkListEq ct wl
  209. | otherwise = extendWorkListNonEq ct wl
  210. extendWorkListCts :: [Ct] -> WorkList -> WorkList
  211. -- Agnostic
  212. extendWorkListCts cts wl = foldr extendWorkListCt wl cts
  213. isEmptyWorkList :: WorkList -> Bool
  214. isEmptyWorkList wl
  215. = null (wl_eqs wl) && null (wl_rest wl) && isEmptyDeque (wl_funeqs wl)
  216. emptyWorkList :: WorkList
  217. emptyWorkList = WorkList { wl_eqs = [], wl_rest = [], wl_funeqs = emptyDeque }
  218. workListFromEq :: Ct -> WorkList
  219. workListFromEq ct = extendWorkListEq ct emptyWorkList
  220. workListFromNonEq :: Ct -> WorkList
  221. workListFromNonEq ct = extendWorkListNonEq ct emptyWorkList
  222. workListFromCt :: Ct -> WorkList
  223. -- Agnostic
  224. workListFromCt ct | isEqPred (ctPred ct) = workListFromEq ct
  225. | otherwise = workListFromNonEq ct
  226. selectWorkItem :: WorkList -> (Maybe Ct, WorkList)
  227. selectWorkItem wl@(WorkList { wl_eqs = eqs, wl_funeqs = feqs, wl_rest = rest })
  228. = case (eqs,feqs,rest) of
  229. (ct:cts,_,_) -> (Just ct, wl { wl_eqs = cts })
  230. (_,fun_eqs,_) | Just (fun_eqs', ct) <- extractDeque fun_eqs
  231. -> (Just ct, wl { wl_funeqs = fun_eqs' })
  232. (_,_,(ct:cts)) -> (Just ct, wl { wl_rest = cts })
  233. (_,_,_) -> (Nothing,wl)
  234. -- Pretty printing
  235. instance Outputable WorkList where
  236. ppr wl = vcat [ text "WorkList (eqs) = " <+> ppr (wl_eqs wl)
  237. , text "WorkList (funeqs)= " <+> ppr (wl_funeqs wl)
  238. , text "WorkList (rest) = " <+> ppr (wl_rest wl)
  239. ]
  240. -- Canonical constraint maps
  241. data CCanMap a
  242. = CCanMap { cts_given :: UniqFM Cts -- All Given
  243. , cts_derived :: UniqFM Cts -- All Derived
  244. , cts_wanted :: UniqFM Cts } -- All Wanted
  245. keepGivenCMap :: CCanMap a -> CCanMap a
  246. keepGivenCMap cc = emptyCCanMap { cts_given = cts_given cc }
  247. instance Outputable (CCanMap a) where
  248. ppr (CCanMap given derived wanted) = ptext (sLit "CCanMap") <+> (ppr given) <+> (ppr derived) <+> (ppr wanted)
  249. cCanMapToBag :: CCanMap a -> Cts
  250. cCanMapToBag cmap = foldUFM unionBags rest_wder (cts_given cmap)
  251. where rest_wder = foldUFM unionBags rest_der (cts_wanted cmap)
  252. rest_der = foldUFM unionBags emptyCts (cts_derived cmap)
  253. emptyCCanMap :: CCanMap a
  254. emptyCCanMap = CCanMap { cts_given = emptyUFM, cts_derived = emptyUFM, cts_wanted = emptyUFM }
  255. updCCanMap:: Uniquable a => (a,Ct) -> CCanMap a -> CCanMap a
  256. updCCanMap (a,ct) cmap
  257. = case cc_ev ct of
  258. CtWanted {} -> cmap { cts_wanted = insert_into (cts_wanted cmap) }
  259. CtGiven {} -> cmap { cts_given = insert_into (cts_given cmap) }
  260. CtDerived {} -> cmap { cts_derived = insert_into (cts_derived cmap) }
  261. where
  262. insert_into m = addToUFM_C unionBags m a (singleCt ct)
  263. getRelevantCts :: Uniquable a => a -> CCanMap a -> (Cts, CCanMap a)
  264. -- Gets the relevant constraints and returns the rest of the CCanMap
  265. getRelevantCts a cmap
  266. = let relevant = lookup (cts_wanted cmap) `unionBags`
  267. lookup (cts_given cmap) `unionBags`
  268. lookup (cts_derived cmap)
  269. residual_map = cmap { cts_wanted = delFromUFM (cts_wanted cmap) a
  270. , cts_given = delFromUFM (cts_given cmap) a
  271. , cts_derived = delFromUFM (cts_derived cmap) a }
  272. in (relevant, residual_map)
  273. where
  274. lookup map = lookupUFM map a `orElse` emptyCts
  275. lookupCCanMap :: Uniquable a => a -> (CtEvidence -> Bool) -> CCanMap a -> Maybe CtEvidence
  276. lookupCCanMap a pick_me map
  277. = findEvidence pick_me possible_cts
  278. where
  279. possible_cts = lookupUFM (cts_given map) a `plus` (
  280. lookupUFM (cts_wanted map) a `plus` (
  281. lookupUFM (cts_derived map) a `plus` emptyCts))
  282. plus Nothing cts2 = cts2
  283. plus (Just cts1) cts2 = cts1 `unionBags` cts2
  284. findEvidence :: (CtEvidence -> Bool) -> Cts -> Maybe CtEvidence
  285. findEvidence pick_me cts
  286. = foldrBag pick Nothing cts
  287. where
  288. pick :: Ct -> Maybe CtEvidence -> Maybe CtEvidence
  289. pick ct deflt | let ctev = cc_ev ct, pick_me ctev = Just ctev
  290. | otherwise = deflt
  291. partitionCCanMap :: (Ct -> Bool) -> CCanMap a -> (Cts,CCanMap a)
  292. -- All constraints that /match/ the predicate go in the bag, the rest remain in the map
  293. partitionCCanMap pred cmap
  294. = let (ws_map,ws) = foldUFM_Directly aux (emptyUFM,emptyCts) (cts_wanted cmap)
  295. (ds_map,ds) = foldUFM_Directly aux (emptyUFM,emptyCts) (cts_derived cmap)
  296. (gs_map,gs) = foldUFM_Directly aux (emptyUFM,emptyCts) (cts_given cmap)
  297. in (ws `andCts` ds `andCts` gs, cmap { cts_wanted = ws_map
  298. , cts_given = gs_map
  299. , cts_derived = ds_map })
  300. where aux k this_cts (mp,acc_cts) = (new_mp, new_acc_cts)
  301. where new_mp = addToUFM mp k cts_keep
  302. new_acc_cts = acc_cts `andCts` cts_out
  303. (cts_out, cts_keep) = partitionBag pred this_cts
  304. partitionEqMap :: (Ct -> Bool) -> TyVarEnv (Ct,TcCoercion) -> ([Ct], TyVarEnv (Ct,TcCoercion))
  305. partitionEqMap pred isubst
  306. = let eqs_out = foldVarEnv extend_if_pred [] isubst
  307. eqs_in = filterVarEnv_Directly (\_ (ct,_) -> not (pred ct)) isubst
  308. in (eqs_out, eqs_in)
  309. where extend_if_pred (ct,_) cts = if pred ct then ct : cts else cts
  310. extractUnsolvedCMap :: CCanMap a -> Cts
  311. -- Gets the wanted or derived constraints
  312. extractUnsolvedCMap cmap = foldUFM unionBags emptyCts (cts_wanted cmap)
  313. `unionBags` foldUFM unionBags emptyCts (cts_derived cmap)
  314. -- Maps from PredTypes to Constraints
  315. type CtTypeMap = TypeMap Ct
  316. type CtPredMap = PredMap Ct
  317. type CtFamHeadMap = FamHeadMap Ct
  318. newtype PredMap a = PredMap { unPredMap :: TypeMap a } -- Indexed by TcPredType
  319. newtype FamHeadMap a = FamHeadMap { unFamHeadMap :: TypeMap a } -- Indexed by family head
  320. instance Outputable a => Outputable (PredMap a) where
  321. ppr (PredMap m) = ppr (foldTM (:) m [])
  322. instance Outputable a => Outputable (FamHeadMap a) where
  323. ppr (FamHeadMap m) = ppr (foldTM (:) m [])
  324. sizePredMap :: PredMap a -> Int
  325. sizePredMap (PredMap m) = foldTypeMap (\_ x -> x+1) 0 m
  326. emptyFamHeadMap :: FamHeadMap a
  327. emptyFamHeadMap = FamHeadMap emptyTM
  328. sizeFamHeadMap :: FamHeadMap a -> Int
  329. sizeFamHeadMap (FamHeadMap m) = foldTypeMap (\_ x -> x+1) 0 m
  330. ctTypeMapCts :: TypeMap Ct -> Cts
  331. ctTypeMapCts ctmap = foldTM (\ct cts -> extendCts cts ct) ctmap emptyCts
  332. lookupFamHead :: FamHeadMap a -> TcType -> Maybe a
  333. lookupFamHead (FamHeadMap m) key = lookupTM key m
  334. insertFamHead :: FamHeadMap a -> TcType -> a -> FamHeadMap a
  335. insertFamHead (FamHeadMap m) key value = FamHeadMap (alterTM key (const (Just value)) m)
  336. delFamHead :: FamHeadMap a -> TcType -> FamHeadMap a
  337. delFamHead (FamHeadMap m) key = FamHeadMap (alterTM key (const Nothing) m)
  338. anyFamHeadMap :: (Ct -> Bool) -> CtFamHeadMap -> Bool
  339. anyFamHeadMap f ctmap = foldTM ((||) . f) (unFamHeadMap ctmap) False
  340. partCtFamHeadMap :: (Ct -> Bool)
  341. -> CtFamHeadMap
  342. -> (Cts, CtFamHeadMap)
  343. partCtFamHeadMap f ctmap
  344. = let (cts,tymap_final) = foldTM upd_acc tymap_inside (emptyBag, tymap_inside)
  345. in (cts, FamHeadMap tymap_final)
  346. where
  347. tymap_inside = unFamHeadMap ctmap
  348. upd_acc ct (cts,acc_map)
  349. | f ct = (extendCts cts ct, alterTM ct_key (\_ -> Nothing) acc_map)
  350. | otherwise = (cts,acc_map)
  351. where ct_key | EqPred ty1 _ <- classifyPredType (ctPred ct)
  352. = ty1
  353. | otherwise
  354. = panic "partCtFamHeadMap, encountered non equality!"
  355. filterSolved :: (CtEvidence -> Bool) -> PredMap CtEvidence -> PredMap CtEvidence
  356. filterSolved p (PredMap mp) = PredMap (foldTM upd mp emptyTM)
  357. where upd a m = if p a then alterTM (ctEvPred a) (\_ -> Just a) m
  358. else m
  359. \end{code}
  360. %************************************************************************
  361. %* *
  362. %* Inert Sets *
  363. %* *
  364. %* *
  365. %************************************************************************
  366. Note [Detailed InertCans Invariants]
  367. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  368. The InertCans represents a collection of constraints with the following properties:
  369. 1 All canonical
  370. 2 All Given or Wanted or Derived. No (partially) Solved
  371. 3 No two dictionaries with the same head
  372. 4 No two family equations with the same head
  373. NB: This is enforced by construction since we use a CtFamHeadMap for inert_funeqs
  374. 5 Family equations inert wrt top-level family axioms
  375. 6 Dictionaries have no matching top-level instance
  376. 7 Non-equality constraints are fully rewritten with respect to the equalities (CTyEqCan)
  377. 8 Equalities _do_not_ form an idempotent substitution, but they are
  378. guaranteed to not have any occurs errors. Additional notes:
  379. - The lack of idempotence of the inert substitution implies
  380. that we must make sure that when we rewrite a constraint we
  381. apply the substitution /recursively/ to the types
  382. involved. Currently the one AND ONLY way in the whole
  383. constraint solver that we rewrite types and constraints wrt
  384. to the inert substitution is TcCanonical/flattenTyVar.
  385. - In the past we did try to have the inert substitution as
  386. idempotent as possible but this would only be true for
  387. constraints of the same flavor, so in total the inert
  388. substitution could not be idempotent, due to flavor-related
  389. issued. Note [Non-idempotent inert substitution] explains
  390. what is going on.
  391. - Whenever a constraint ends up in the worklist we do
  392. recursively apply exhaustively the inert substitution to it
  393. to check for occurs errors. But if an equality is already in
  394. the inert set and we can guarantee that adding a new equality
  395. will not cause the first equality to have an occurs check
  396. then we do not rewrite the inert equality. This happens in
  397. TcInteract, rewriteInertEqsFromInertEq.
  398. See Note [Delicate equality kick-out] to see which inert
  399. equalities can safely stay in the inert set and which must be
  400. kicked out to be rewritten and re-checked for occurs errors.
  401. 9 Given family or dictionary constraints don't mention touchable unification variables
  402. Note [Solved constraints]
  403. ~~~~~~~~~~~~~~~~~~~~~~~~~
  404. When we take a step to simplify a constraint 'c', we call the original constraint "solved".
  405. For example: Wanted: ev :: [s] ~ [t]
  406. New goal: ev1 :: s ~ t
  407. Then 'ev' is now "solved".
  408. The reason for all this is simply to avoid re-solving goals we have solved already.
  409. * A solved Wanted may depend on as-yet-unsolved goals, so (for example) we should not
  410. use it to rewrite a Given; in that sense the solved goal is still a Wanted
  411. * A solved Given is just given
  412. * A solved Derived in inert_solved is possible; purpose is to avoid
  413. creating tons of identical Derived goals.
  414. But there are no solved Deriveds in inert_solved_funeqs
  415. Note [Type family equations]
  416. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  417. Type-family equations, of form (ev : F tys ~ ty), live in four places
  418. * The work-list, of course
  419. * The inert_flat_cache. This is used when flattening, to get maximal
  420. sharing. It contains lots of things that are still in the work-list.
  421. E.g Suppose we have (w1: F (G a) ~ Int), and (w2: H (G a) ~ Int) in the
  422. work list. Then we flatten w1, dumping (w3: G a ~ f1) in the work
  423. list. Now if we flatten w2 before we get to w3, we still want to
  424. share that (G a).
  425. Because it contains work-list things, DO NOT use the flat cache to solve
  426. a top-level goal. Eg in the above example we don't want to solve w3
  427. using w3 itself!
  428. * The inert_solved_funeqs. These are all "solved" goals (see Note [Solved constraints]),
  429. the result of using a top-level type-family instance.
  430. * THe inert_funeqs are un-solved but fully processed and in the InertCans.
  431. \begin{code}
  432. -- All Given (fully known) or Wanted or Derived
  433. -- See Note [Detailed InertCans Invariants] for more
  434. data InertCans
  435. = IC { inert_eqs :: TyVarEnv Ct
  436. -- Must all be CTyEqCans! If an entry exists of the form:
  437. -- a |-> ct,co
  438. -- Then ct = CTyEqCan { cc_tyvar = a, cc_rhs = xi }
  439. -- And co : a ~ xi
  440. , inert_dicts :: CCanMap Class
  441. -- Dictionaries only, index is the class
  442. -- NB: index is /not/ the whole type because FD reactions
  443. -- need to match the class but not necessarily the whole type.
  444. , inert_funeqs :: CtFamHeadMap
  445. -- Family equations, index is the whole family head type.
  446. , inert_irreds :: Cts
  447. -- Irreducible predicates
  448. , inert_insols :: Cts
  449. -- Frozen errors (as non-canonicals)
  450. }
  451. -- The Inert Set
  452. data InertSet
  453. = IS { inert_cans :: InertCans
  454. -- Canonical Given, Wanted, Derived (no Solved)
  455. -- Sometimes called "the inert set"
  456. , inert_flat_cache :: FamHeadMap (CtEvidence, TcType)
  457. -- See Note [Type family equations]
  458. -- Just a hash-cons cache for use when flattening only
  459. -- These include entirely un-processed goals, so don't use
  460. -- them to solve a top-level goal, else you may end up solving
  461. -- (w:F ty ~ a) by setting w:=w! We just use the flat-cache
  462. -- when allocating a new flatten-skolem.
  463. -- Not necessarily inert wrt top-level equations (or inert_cans)
  464. , inert_fsks :: [TcTyVar] -- Rigid flatten-skolems (arising from givens)
  465. -- allocated in this local scope
  466. , inert_solved_funeqs :: FamHeadMap (CtEvidence, TcType)
  467. -- See Note [Type family equations]
  468. -- Of form co :: F xis ~ xi
  469. -- Always the result of using a top-level family axiom F xis ~ tau
  470. -- No Deriveds
  471. -- Not necessarily fully rewritten (by type substitutions)
  472. , inert_solved_dicts :: PredMap CtEvidence
  473. -- Of form ev :: C t1 .. tn
  474. -- Always the result of using a top-level instance declaration
  475. -- See Note [Solved constraints]
  476. -- - Used to avoid creating a new EvVar when we have a new goal
  477. -- that we have solved in the past
  478. -- - Stored not necessarily as fully rewritten
  479. -- (ToDo: rewrite lazily when we lookup)
  480. }
  481. instance Outputable InertCans where
  482. ppr ics = vcat [ ptext (sLit "Equalities:")
  483. <+> vcat (map ppr (varEnvElts (inert_eqs ics)))
  484. , ptext (sLit "Type-function equalities:")
  485. <+> vcat (map ppr (Bag.bagToList $
  486. ctTypeMapCts (unFamHeadMap $ inert_funeqs ics)))
  487. , ptext (sLit "Dictionaries:")
  488. <+> vcat (map ppr (Bag.bagToList $ cCanMapToBag (inert_dicts ics)))
  489. , ptext (sLit "Irreds:")
  490. <+> vcat (map ppr (Bag.bagToList $ inert_irreds ics))
  491. , text "Insolubles =" <+> -- Clearly print frozen errors
  492. braces (vcat (map ppr (Bag.bagToList $ inert_insols ics)))
  493. ]
  494. instance Outputable InertSet where
  495. ppr is = vcat [ ppr $ inert_cans is
  496. , text "Solved dicts" <+> int (sizePredMap (inert_solved_dicts is))
  497. , text "Solved funeqs" <+> int (sizeFamHeadMap (inert_solved_funeqs is))]
  498. emptyInert :: InertSet
  499. emptyInert
  500. = IS { inert_cans = IC { inert_eqs = emptyVarEnv
  501. , inert_dicts = emptyCCanMap
  502. , inert_funeqs = emptyFamHeadMap
  503. , inert_irreds = emptyCts
  504. , inert_insols = emptyCts }
  505. , inert_fsks = []
  506. , inert_flat_cache = emptyFamHeadMap
  507. , inert_solved_dicts = PredMap emptyTM
  508. , inert_solved_funeqs = emptyFamHeadMap }
  509. insertInertItem :: Ct -> InertSet -> InertSet
  510. -- Add a new inert element to the inert set.
  511. insertInertItem item is
  512. = -- A canonical Given, Wanted, or Derived
  513. is { inert_cans = upd_inert_cans (inert_cans is) item }
  514. where upd_inert_cans :: InertCans -> Ct -> InertCans
  515. -- Precondition: item /is/ canonical
  516. upd_inert_cans ics item
  517. | isCTyEqCan item
  518. = let upd_err a b = pprPanic "insertInertItem" $
  519. vcat [ text "Multiple inert equalities:"
  520. , text "Old (already inert):" <+> ppr a
  521. , text "Trying to insert :" <+> ppr b ]
  522. eqs' = extendVarEnv_C upd_err (inert_eqs ics)
  523. (cc_tyvar item) item
  524. in ics { inert_eqs = eqs' }
  525. | isCIrredEvCan item -- Presently-irreducible evidence
  526. = ics { inert_irreds = inert_irreds ics `Bag.snocBag` item }
  527. | Just cls <- isCDictCan_Maybe item -- Dictionary
  528. = ics { inert_dicts = updCCanMap (cls,item) (inert_dicts ics) }
  529. | Just _tc <- isCFunEqCan_Maybe item -- Function equality
  530. = let fam_head = mkTyConApp (cc_fun item) (cc_tyargs item)
  531. upd_funeqs Nothing = Just item
  532. upd_funeqs (Just _already_there)
  533. = panic "insertInertItem: item already there!"
  534. in ics { inert_funeqs = FamHeadMap
  535. (alterTM fam_head upd_funeqs $
  536. (unFamHeadMap $ inert_funeqs ics)) }
  537. | otherwise
  538. = pprPanic "upd_inert set: can't happen! Inserting " $
  539. ppr item -- Can't be CNonCanonical, CHoleCan,
  540. -- because they only land in inert_insols
  541. insertInertItemTcS :: Ct -> TcS ()
  542. -- Add a new item in the inerts of the monad
  543. insertInertItemTcS item
  544. = do { traceTcS "insertInertItemTcS {" $
  545. text "Trying to insert new inert item:" <+> ppr item
  546. ; updInertTcS (insertInertItem item)
  547. ; traceTcS "insertInertItemTcS }" $ empty }
  548. addSolvedDict :: CtEvidence -> TcS ()
  549. -- Add a new item in the solved set of the monad
  550. addSolvedDict item
  551. | isIPPred (ctEvPred item) -- Never cache "solved" implicit parameters (not sure why!)
  552. = return ()
  553. | otherwise
  554. = do { traceTcS "updSolvedSetTcs:" $ ppr item
  555. ; updInertTcS upd_solved_dicts }
  556. where
  557. upd_solved_dicts is
  558. = is { inert_solved_dicts = PredMap $ alterTM pred upd_solved $
  559. unPredMap $ inert_solved_dicts is }
  560. pred = ctEvPred item
  561. upd_solved _ = Just item
  562. addSolvedFunEq :: TcType -> CtEvidence -> TcType -> TcS ()
  563. addSolvedFunEq fam_ty ev rhs_ty
  564. = updInertTcS $ \ inert ->
  565. inert { inert_solved_funeqs = insertFamHead (inert_solved_funeqs inert)
  566. fam_ty (ev, rhs_ty) }
  567. modifyInertTcS :: (InertSet -> (a,InertSet)) -> TcS a
  568. -- Modify the inert set with the supplied function
  569. modifyInertTcS upd
  570. = do { is_var <- getTcSInertsRef
  571. ; curr_inert <- wrapTcS (TcM.readTcRef is_var)
  572. ; let (a, new_inert) = upd curr_inert
  573. ; wrapTcS (TcM.writeTcRef is_var new_inert)
  574. ; return a }
  575. updInertTcS :: (InertSet -> InertSet) -> TcS ()
  576. -- Modify the inert set with the supplied function
  577. updInertTcS upd
  578. = do { is_var <- getTcSInertsRef
  579. ; curr_inert <- wrapTcS (TcM.readTcRef is_var)
  580. ; let new_inert = upd curr_inert
  581. ; wrapTcS (TcM.writeTcRef is_var new_inert) }
  582. prepareInertsForImplications :: InertSet -> InertSet
  583. -- See Note [Preparing inert set for implications]
  584. prepareInertsForImplications is
  585. = is { inert_cans = getGivens (inert_cans is)
  586. , inert_fsks = []
  587. , inert_flat_cache = emptyFamHeadMap }
  588. where
  589. getGivens (IC { inert_eqs = eqs
  590. , inert_irreds = irreds
  591. , inert_funeqs = FamHeadMap funeqs
  592. , inert_dicts = dicts })
  593. = IC { inert_eqs = filterVarEnv_Directly (\_ ct -> isGivenCt ct) eqs
  594. , inert_funeqs = FamHeadMap (mapTM given_from_wanted funeqs)
  595. , inert_irreds = Bag.filterBag isGivenCt irreds
  596. , inert_dicts = keepGivenCMap dicts
  597. , inert_insols = emptyCts }
  598. given_from_wanted funeq -- This is where the magic processing happens
  599. | isGiven ev = funeq -- for type-function equalities
  600. -- See Note [Preparing inert set for implications]
  601. | otherwise = funeq { cc_ev = given_ev }
  602. where
  603. ev = ctEvidence funeq
  604. given_ev = CtGiven { ctev_evtm = EvId (ctev_evar ev)
  605. , ctev_pred = ctev_pred ev }
  606. \end{code}
  607. Note [Preparing inert set for implications]
  608. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  609. Before solving the nested implications, we trim the inert set,
  610. retaining only Givens. These givens can be used when solving
  611. the inner implications.
  612. With one wrinkle! We take all *wanted* *funeqs*, and turn them into givens.
  613. Consider (Trac #4935)
  614. type instance F True a b = a
  615. type instance F False a b = b
  616. [w] F c a b ~ gamma
  617. (c ~ True) => a ~ gamma
  618. (c ~ False) => b ~ gamma
  619. Obviously this is soluble with gamma := F c a b. But
  620. Since solveCTyFunEqs happens at the very end of solving, the only way
  621. to solve the two implications is temporarily consider (F c a b ~ gamma)
  622. as Given and push it inside the implications. Now, when we come
  623. out again at the end, having solved the implications solveCTyFunEqs
  624. will solve this equality.
  625. Turning type-function equalities into Givens is easy becase they
  626. *stay inert*. No need to re-process them.
  627. We don't try to turn any *other* Wanteds into Givens:
  628. * For example, we should not push given dictionaries in because
  629. of example LongWayOverlapping.hs, where we might get strange
  630. overlap errors between far-away constraints in the program.
  631. There might be cases where interactions between wanteds can help
  632. to solve a constraint. For example
  633. class C a b | a -> b
  634. (C Int alpha), (forall d. C d blah => C Int a)
  635. If we push the (C Int alpha) inwards, as a given, it can produce a
  636. fundep (alpha~a) and this can float out again and be used to fix
  637. alpha. (In general we can't float class constraints out just in case
  638. (C d blah) might help to solve (C Int a).) But we ignore this possiblity.
  639. \begin{code}
  640. getInertEqs :: TcS (TyVarEnv Ct)
  641. getInertEqs = do { inert <- getTcSInerts
  642. ; return (inert_eqs (inert_cans inert)) }
  643. getInertUnsolved :: TcS (Cts, Cts)
  644. -- Return (unsolved-wanteds, insolubles)
  645. -- Both consist of a mixture of Wanted and Derived
  646. getInertUnsolved
  647. = do { is <- getTcSInerts
  648. ; let icans = inert_cans is
  649. unsolved_irreds = Bag.filterBag is_unsolved (inert_irreds icans)
  650. unsolved_dicts = extractUnsolvedCMap (inert_dicts icans)
  651. (unsolved_funeqs,_) = partCtFamHeadMap is_unsolved (inert_funeqs icans)
  652. unsolved_eqs = foldVarEnv add_if_unsolved emptyCts (inert_eqs icans)
  653. unsolved_flats = unsolved_eqs `unionBags` unsolved_irreds `unionBags`
  654. unsolved_dicts `unionBags` unsolved_funeqs
  655. ; return (unsolved_flats, inert_insols icans) }
  656. where
  657. add_if_unsolved ct cts
  658. | is_unsolved ct = cts `extendCts` ct
  659. | otherwise = cts
  660. is_unsolved ct = not (isGivenCt ct) -- Wanted or Derived
  661. checkAllSolved :: TcS Bool
  662. -- True if there are no unsolved wanteds
  663. -- Ignore Derived for this purpose, unless in insolubles
  664. checkAllSolved
  665. = do { is <- getTcSInerts
  666. ; let icans = inert_cans is
  667. unsolved_irreds = Bag.anyBag isWantedCt (inert_irreds icans)
  668. unsolved_dicts = not (isNullUFM (cts_wanted (inert_dicts icans)))
  669. unsolved_funeqs = anyFamHeadMap isWantedCt (inert_funeqs icans)
  670. unsolved_eqs = foldVarEnv ((||) . isWantedCt) False (inert_eqs icans)
  671. ; return (not (unsolved_eqs || unsolved_irreds
  672. || unsolved_dicts || unsolved_funeqs
  673. || not (isEmptyBag (inert_insols icans)))) }
  674. extractRelevantInerts :: Ct -> TcS Cts
  675. -- Returns the constraints from the inert set that are 'relevant' to react with
  676. -- this constraint. The monad is left with the 'thinner' inerts.
  677. -- NB: This function contains logic specific to the constraint solver, maybe move there?
  678. extractRelevantInerts wi
  679. = modifyInertTcS (extract_relevants wi)
  680. where
  681. extract_relevants :: Ct -> InertSet -> (Cts,InertSet)
  682. extract_relevants wi is
  683. = let (cts,ics') = extract_ics_relevants wi (inert_cans is)
  684. in (cts, is { inert_cans = ics' })
  685. extract_ics_relevants :: Ct -> InertCans -> (Cts, InertCans)
  686. extract_ics_relevants (CDictCan {cc_class = cl}) ics =
  687. let (cts,dict_map) = getRelevantCts cl (inert_dicts ics)
  688. in (cts, ics { inert_dicts = dict_map })
  689. extract_ics_relevants ct@(CFunEqCan {}) ics@(IC { inert_funeqs = funeq_map })
  690. | Just ct <- lookupFamHead funeq_map fam_head
  691. = (singleCt ct, ics { inert_funeqs = delFamHead funeq_map fam_head })
  692. | otherwise
  693. = (emptyCts, ics)
  694. where
  695. fam_head = mkTyConApp (cc_fun ct) (cc_tyargs ct)
  696. extract_ics_relevants (CHoleCan {}) ics
  697. = pprPanic "extractRelevantInerts" (ppr wi)
  698. -- Holes are put straight into inert_frozen, so never get here
  699. extract_ics_relevants (CIrredEvCan { }) ics =
  700. let cts = inert_irreds ics
  701. in (cts, ics { inert_irreds = emptyCts })
  702. extract_ics_relevants _ ics = (emptyCts,ics)
  703. lookupFlatEqn :: TcType -> TcS (Maybe (CtEvidence, TcType))
  704. lookupFlatEqn fam_ty
  705. = do { IS { inert_solved_funeqs = solved_funeqs
  706. , inert_flat_cache = flat_cache
  707. , inert_cans = IC { inert_funeqs = inert_funeqs } } <- getTcSInerts
  708. ; return (lookupFamHead solved_funeqs fam_ty `firstJust`
  709. lookup_in_inerts inert_funeqs `firstJust`
  710. lookupFamHead flat_cache fam_ty) }
  711. where
  712. lookup_in_inerts inert_funeqs
  713. = case lookupFamHead inert_funeqs fam_ty of
  714. Nothing -> Nothing
  715. Just ct -> Just (ctEvidence ct, cc_rhs ct)
  716. lookupInInerts :: TcPredType -> TcS (Maybe CtEvidence)
  717. -- Is this exact predicate type cached in the solved or canonicals of the InertSet
  718. lookupInInerts pty
  719. = do { inerts <- getTcSInerts
  720. ; case lookupSolvedDict inerts pty of
  721. Just ctev -> return (Just ctev)
  722. Nothing -> return (lookupInInertCans inerts pty) }
  723. lookupSolvedDict :: InertSet -> TcPredType -> Maybe CtEvidence
  724. -- Returns just if exactly this predicate type exists in the solved.
  725. lookupSolvedDict (IS { inert_solved_dicts = solved }) pty
  726. = lookupTM pty (unPredMap solved)
  727. lookupInInertCans :: InertSet -> TcPredType -> Maybe CtEvidence
  728. -- Returns Just if exactly this pred type exists in the inert canonicals
  729. lookupInInertCans (IS { inert_cans = ics }) pty
  730. = case (classifyPredType pty) of
  731. ClassPred cls _
  732. -> lookupCCanMap cls (\ct -> ctEvPred ct `eqType` pty) (inert_dicts ics)
  733. EqPred ty1 _ty2
  734. | Just tv <- getTyVar_maybe ty1 -- Tyvar equation
  735. , Just ct <- lookupVarEnv (inert_eqs ics) tv
  736. , let ctev = ctEvidence ct
  737. , ctEvPred ctev `eqType` pty
  738. -> Just ctev
  739. | Just _ <- splitTyConApp_maybe ty1 -- Family equation
  740. , Just ct <- lookupTM ty1 (unFamHeadMap $ inert_funeqs ics)
  741. , let ctev = ctEvidence ct
  742. , ctEvPred ctev `eqType` pty
  743. -> Just ctev
  744. IrredPred {} -> findEvidence (\ct -> ctEvPred ct `eqType` pty) (inert_irreds ics)
  745. _other -> Nothing -- NB: No caching for IPs or holes
  746. \end{code}
  747. %************************************************************************
  748. %* *
  749. %* The TcS solver monad *
  750. %* *
  751. %************************************************************************
  752. Note [The TcS monad]
  753. ~~~~~~~~~~~~~~~~~~~~
  754. The TcS monad is a weak form of the main Tc monad
  755. All you can do is
  756. * fail
  757. * allocate new variables
  758. * fill in evidence variables
  759. Filling in a dictionary evidence variable means to create a binding
  760. for it, so TcS carries a mutable location where the binding can be
  761. added. This is initialised from the innermost implication constraint.
  762. \begin{code}
  763. data TcSEnv
  764. = TcSEnv {
  765. tcs_ev_binds :: EvBindsVar,
  766. tcs_ty_binds :: IORef (TyVarEnv (TcTyVar, TcType)),
  767. -- Global type bindings
  768. tcs_count :: IORef Int, -- Global step count
  769. tcs_inerts :: IORef InertSet, -- Current inert set
  770. tcs_worklist :: IORef WorkList, -- Current worklist
  771. -- Residual implication constraints that are generated
  772. -- while solving or canonicalising the current worklist.
  773. -- Specifically, when canonicalising (forall a. t1 ~ forall a. t2)
  774. -- from which we get the implication (forall a. t1 ~ t2)
  775. tcs_implics :: IORef (Bag Implication)
  776. }
  777. \end{code}
  778. \begin{code}
  779. ---------------
  780. newtype TcS a = TcS { unTcS :: TcSEnv -> TcM a }
  781. instance Functor TcS where
  782. fmap f m = TcS $ fmap f . unTcS m
  783. instance Monad TcS where
  784. return x = TcS (\_ -> return x)
  785. fail err = TcS (\_ -> fail err)
  786. m >>= k = TcS (\ebs -> unTcS m ebs >>= \r -> unTcS (k r) ebs)
  787. -- Basic functionality
  788. -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  789. wrapTcS :: TcM a -> TcS a
  790. -- Do not export wrapTcS, because it promotes an arbitrary TcM to TcS,
  791. -- and TcS is supposed to have limited functionality
  792. wrapTcS = TcS . const -- a TcM action will not use the TcEvBinds
  793. wrapErrTcS :: TcM a -> TcS a
  794. -- The thing wrapped should just fail
  795. -- There's no static check; it's up to the user
  796. -- Having a variant for each error message is too painful
  797. wrapErrTcS = wrapTcS
  798. wrapWarnTcS :: TcM a -> TcS a
  799. -- The thing wrapped should just add a warning, or no-op
  800. -- There's no static check; it's up to the user
  801. wrapWarnTcS = wrapTcS
  802. failTcS, panicTcS :: SDoc -> TcS a
  803. failTcS = wrapTcS . TcM.failWith
  804. panicTcS doc = pprPanic "TcCanonical" doc
  805. traceTcS :: String -> SDoc -> TcS ()
  806. traceTcS herald doc = wrapTcS (TcM.traceTc herald doc)
  807. instance HasDynFlags TcS where
  808. getDynFlags = wrapTcS getDynFlags
  809. bumpStepCountTcS :: TcS ()
  810. bumpStepCountTcS = TcS $ \env -> do { let ref = tcs_count env
  811. ; n <- TcM.readTcRef ref
  812. ; TcM.writeTcRef ref (n+1) }
  813. traceFireTcS :: Ct -> SDoc -> TcS ()
  814. -- Dump a rule-firing trace
  815. traceFireTcS ct doc
  816. = TcS $ \env ->
  817. TcM.whenDOptM Opt_D_dump_cs_trace $
  818. do { n <- TcM.readTcRef (tcs_count env)
  819. ; let msg = int n <> brackets (int (ctLocDepth (cc_loc ct))) <+> doc
  820. ; TcM.dumpTcRn msg }
  821. runTcS :: TcS a -- What to run
  822. -> TcM (a, Bag EvBind)
  823. runTcS tcs
  824. = do { ev_binds_var <- TcM.newTcEvBinds
  825. ; res <- runTcSWithEvBinds ev_binds_var tcs
  826. ; ev_binds <- TcM.getTcEvBinds ev_binds_var
  827. ; return (res, ev_binds) }
  828. runTcSWithEvBinds :: EvBindsVar
  829. -> TcS a
  830. -> TcM a
  831. runTcSWithEvBinds ev_binds_var tcs
  832. = do { ty_binds_var <- TcM.newTcRef emptyVarEnv
  833. ; step_count <- TcM.newTcRef 0
  834. ; inert_var <- TcM.newTcRef is
  835. ; let env = TcSEnv { tcs_ev_binds = ev_binds_var
  836. , tcs_ty_binds = ty_binds_var
  837. , tcs_count = step_count
  838. , tcs_inerts = inert_var
  839. , tcs_worklist = panic "runTcS: worklist"
  840. , tcs_implics = panic "runTcS: implics" }
  841. -- NB: Both these are initialised by withWorkList
  842. -- Run the computation
  843. ; res <- unTcS tcs env
  844. -- Perform the type unifications required
  845. ; ty_binds <- TcM.readTcRef ty_binds_var
  846. ; mapM_ do_unification (varEnvElts ty_binds)
  847. #ifdef DEBUG
  848. ; count <- TcM.readTcRef step_count
  849. ; when (opt_PprStyle_Debug && count > 0) $
  850. TcM.debugDumpTcRn (ptext (sLit "Constraint solver steps =") <+> int count )
  851. ; ev_binds <- TcM.getTcEvBinds ev_binds_var
  852. ; checkForCyclicBinds ev_binds
  853. #endif
  854. ; return res }
  855. where
  856. do_unification (tv,ty) = TcM.writeMetaTyVar tv ty
  857. is = emptyInert
  858. #ifdef DEBUG
  859. checkForCyclicBinds :: Bag EvBind -> TcM ()
  860. checkForCyclicBinds ev_binds
  861. | null cycles
  862. = return ()
  863. | null coercion_cycles
  864. = TcM.traceTc "Cycle in evidence binds" $ ppr cycles
  865. | otherwise
  866. = pprPanic "Cycle in coercion bindings" $ ppr coercion_cycles
  867. where
  868. cycles :: [[EvBind]]
  869. cycles = [c | CyclicSCC c <- stronglyConnCompFromEdgedVertices edges]
  870. coercion_cycles = [c | c <- cycles, any is_co_bind c]
  871. is_co_bind (EvBind b _) = isEqVar b
  872. edges :: [(EvBind, EvVar, [EvVar])]
  873. edges = [(bind, bndr, varSetElems (evVarsOfTerm rhs)) | bind@(EvBind bndr rhs) <- bagToList ev_binds]
  874. #endif
  875. nestImplicTcS :: EvBindsVar -> Untouchables -> InertSet -> TcS a -> TcS a
  876. nestImplicTcS ref inner_untch inerts (TcS thing_inside)
  877. = TcS $ \ TcSEnv { tcs_ty_binds = ty_binds
  878. , tcs_count = count } ->
  879. do { new_inert_var <- TcM.newTcRef inerts
  880. ; let nest_env = TcSEnv { tcs_ev_binds = ref
  881. , tcs_ty_binds = ty_binds
  882. , tcs_count = count
  883. , tcs_inerts = new_inert_var
  884. , tcs_worklist = panic "nextImplicTcS: worklist"
  885. , tcs_implics = panic "nextImplicTcS: implics"
  886. -- NB: Both these are initialised by withWorkList
  887. }
  888. ; res <- TcM.setUntouchables inner_untch $
  889. thing_inside nest_env
  890. #ifdef DEBUG
  891. -- Perform a check that the thing_inside did not cause cycles
  892. ; ev_binds <- TcM.getTcEvBinds ref
  893. ; checkForCyclicBinds ev_binds
  894. #endif
  895. ; return res }
  896. recoverTcS :: TcS a -> TcS a -> TcS a
  897. recoverTcS (TcS recovery_code) (TcS thing_inside)
  898. = TcS $ \ env ->
  899. TcM.recoverM (recovery_code env) (thing_inside env)
  900. nestTcS :: TcS a -> TcS a
  901. -- Use the current untouchables, augmenting the current
  902. -- evidence bindings, ty_binds, and solved caches
  903. -- But have no effect on the InertCans or insolubles
  904. nestTcS (TcS thing_inside)
  905. = TcS $ \ env@(TcSEnv { tcs_inerts = inerts_var }) ->
  906. do { inerts <- TcM.readTcRef inerts_var
  907. ; new_inert_var <- TcM.newTcRef inerts
  908. ; let nest_env = env { tcs_inerts = new_inert_var
  909. , tcs_worklist = panic "nextImplicTcS: worklist"
  910. , tcs_implics = panic "nextImplicTcS: implics" }
  911. ; thing_inside nest_env }
  912. tryTcS :: TcS a -> TcS a
  913. -- Like runTcS, but from within the TcS monad
  914. -- Completely afresh inerts and worklist, be careful!
  915. -- Moreover, we will simply throw away all the evidence generated.
  916. tryTcS (TcS thing_inside)
  917. = TcS $ \env ->
  918. do { is_var <- TcM.newTcRef emptyInert
  919. ; ty_binds_var <- TcM.newTcRef emptyVarEnv
  920. ; ev_binds_var <- TcM.newTcEvBinds
  921. ; let nest_env = env { tcs_ev_binds = ev_binds_var
  922. , tcs_ty_binds = ty_binds_var
  923. , tcs_inerts = is_var
  924. , tcs_worklist = panic "nextImplicTcS: worklist"
  925. , tcs_implics = panic "nextImplicTcS: implics" }
  926. ; thing_inside nest_env }
  927. -- Getters and setters of TcEnv fields
  928. -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  929. -- Getter of inerts and worklist
  930. getTcSInertsRef :: TcS (IORef InertSet)
  931. getTcSInertsRef = TcS (return . tcs_inerts)
  932. getTcSWorkListRef :: TcS (IORef WorkList)
  933. getTcSWorkListRef = TcS (return . tcs_worklist)
  934. getTcSInerts :: TcS InertSet
  935. getTcSInerts = getTcSInertsRef >>= wrapTcS . (TcM.readTcRef)
  936. updWorkListTcS :: (WorkList -> WorkList) -> TcS ()
  937. updWorkListTcS f
  938. = do { wl_var <- getTcSWorkListRef
  939. ; wl_curr <- wrapTcS (TcM.readTcRef wl_var)
  940. ; let new_work = f wl_curr
  941. ; wrapTcS (TcM.writeTcRef wl_var new_work) }
  942. updWorkListTcS_return :: (WorkList -> (a,WorkList)) -> TcS a
  943. -- Process the work list, returning a depleted work list,
  944. -- plus a value extracted from it (typically a work item removed from it)
  945. updWorkListTcS_return f
  946. = do { wl_var <- getTcSWorkListRef
  947. ; wl_curr <- wrapTcS (TcM.readTcRef wl_var)
  948. ; let (res,new_work) = f wl_curr
  949. ; wrapTcS (TcM.writeTcRef wl_var new_work)
  950. ; return res }
  951. withWorkList :: Cts -> TcS () -> TcS (Bag Implication)
  952. -- Use 'thing_inside' to solve 'work_items', extending the
  953. -- ambient InertSet, and returning any residual implications
  954. -- (arising from polytype equalities)
  955. -- We do this with fresh work list and residual-implications variables
  956. withWorkList work_items (TcS thing_inside)
  957. = TcS $ \ tcs_env ->
  958. do { let init_work_list = foldrBag extendWorkListCt emptyWorkList work_items
  959. ; new_wl_var <- TcM.newTcRef init_work_list
  960. ; new_implics_var <- TcM.newTcRef emptyBag
  961. ; thing_inside (tcs_env { tcs_worklist = new_wl_var
  962. , tcs_implics = new_implics_var })
  963. ; final_wl <- TcM.readTcRef new_wl_var
  964. ; implics <- TcM.readTcRef new_implics_var
  965. ; ASSERT( isEmptyWorkList final_wl )
  966. return implics }
  967. updTcSImplics :: (Bag Implication -> Bag Implication) -> TcS ()
  968. updTcSImplics f
  969. = do { impl_ref <- getTcSImplicsRef
  970. ; wrapTcS $ do { implics <- TcM.readTcRef impl_ref
  971. ; TcM.writeTcRef impl_ref (f implics) } }
  972. emitInsoluble :: Ct -> TcS ()
  973. -- Emits a non-canonical constraint that will stand for a frozen error in the inerts.
  974. emitInsoluble ct
  975. = do { traceTcS "Emit insoluble" (ppr ct)
  976. ; updInertTcS add_insol }
  977. where
  978. this_pred = ctPred ct
  979. add_insol is@(IS { inert_cans = ics@(IC { inert_insols = old_insols }) })
  980. | already_there = is
  981. | otherwise = is { inert_cans = ics { inert_insols = extendCts old_insols ct } }
  982. where
  983. already_there = not (isWantedCt ct) && anyBag (eqType this_pred . ctPred) old_insols
  984. -- See Note [Do not add duplicate derived insolubles]
  985. getTcSImplicsRef :: TcS (IORef (Bag Implication))
  986. getTcSImplicsRef = TcS (return . tcs_implics)
  987. getTcEvBinds :: TcS EvBindsVar
  988. getTcEvBinds = TcS (return . tcs_ev_binds)
  989. getUntouchables :: TcS Untouchables
  990. getUntouchables = wrapTcS TcM.getUntouchables
  991. getFlattenSkols :: TcS [TcTyVar]
  992. getFlattenSkols = do { is <- getTcSInerts; return (inert_fsks is) }
  993. getTcSTyBinds :: TcS (IORef (TyVarEnv (TcTyVar, TcType)))
  994. getTcSTyBinds = TcS (return . tcs_ty_binds)
  995. getTcSTyBindsMap :: TcS (TyVarEnv (TcTyVar, TcType))
  996. getTcSTyBindsMap = getTcSTyBinds >>= wrapTcS . (TcM.readTcRef)
  997. getTcEvBindsMap :: TcS EvBindMap
  998. getTcEvBindsMap
  999. = do { EvBindsVar ev_ref _ <- getTcEvBinds
  1000. ; wrapTcS $ TcM.readTcRef ev_ref }
  1001. setWantedTyBind :: TcTyVar -> TcType -> TcS ()
  1002. -- Add a type binding
  1003. -- We never do this twice!
  1004. setWantedTyBind tv ty
  1005. = ASSERT2( isMetaTyVar tv, ppr tv )
  1006. do { ref <- getTcSTyBinds
  1007. ; wrapTcS $
  1008. do { ty_binds <- TcM.readTcRef ref
  1009. ; when debugIsOn $
  1010. TcM.checkErr (not (tv `elemVarEnv` ty_binds)) $
  1011. vcat [ text "TERRIBLE ERROR: double set of meta type variable"
  1012. , ppr tv <+> text ":=" <+> ppr ty
  1013. , text "Old value =" <+> ppr (lookupVarEnv_NF ty_binds tv)]
  1014. ; TcM.traceTc "setWantedTyBind" (ppr tv <+> text ":=" <+> ppr ty)
  1015. ; TcM.writeTcRef ref (extendVarEnv ty_binds tv (tv,ty)) } }
  1016. \end{code}
  1017. \begin{code}
  1018. getDefaultInfo :: TcS ([Type], (Bool, Bool))
  1019. getDefaultInfo = wrapTcS TcM.tcGetDefaultTys
  1020. -- Just get some environments needed for instance looking up and matching
  1021. -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1022. getInstEnvs :: TcS (InstEnv, InstEnv)
  1023. getInstEnvs = wrapTcS $ Inst.tcGetInstEnvs
  1024. getFamInstEnvs :: TcS (FamInstEnv, FamInstEnv)
  1025. getFamInstEnvs = wrapTcS $ FamInst.tcGetFamInstEnvs
  1026. getTopEnv :: TcS HscEnv
  1027. getTopEnv = wrapTcS $ TcM.getTopEnv
  1028. getGblEnv :: TcS TcGblEnv
  1029. getGblEnv = wrapTcS $ TcM.getGblEnv
  1030. -- Various smaller utilities [TODO, maybe will be absorbed in the instance matcher]
  1031. -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1032. checkWellStagedDFun :: PredType -> DFunId -> CtLoc -> TcS ()
  1033. checkWellStagedDFun pred dfun_id loc
  1034. = wrapTcS $ TcM.setCtLoc loc $
  1035. do { use_stage <- TcM.getStage
  1036. ; TcM.checkWellStaged pp_thing bind_lvl (thLevel use_stage) }
  1037. where
  1038. pp_thing = ptext (sLit "instance for") <+> quotes (ppr pred)
  1039. bind_lvl = TcM.topIdLvl dfun_id
  1040. pprEq :: TcType -> TcType -> SDoc
  1041. pprEq ty1 ty2 = pprType $ mkEqPred ty1 ty2
  1042. isTouchableMetaTyVarTcS :: TcTyVar -> TcS Bool
  1043. isTouchableMetaTyVarTcS tv
  1044. = do { untch <- getUntouchables
  1045. ; return $ isTouchableMetaTyVar untch tv }
  1046. isFilledMetaTyVar_maybe :: TcTyVar -> TcS (Maybe Type)
  1047. isFilledMetaTyVar_maybe tv
  1048. = ASSERT2( isTcTyVar tv, ppr tv )
  1049. case tcTyVarDetails tv of
  1050. MetaTv { mtv_ref = ref }
  1051. -> do { cts <- wrapTcS (TcM.readTcRef ref)
  1052. ; case cts of
  1053. Indirect ty -> return (Just ty)
  1054. Flexi -> return Nothing }
  1055. _ -> return Nothing
  1056. zonkTyVarsAndFV :: TcTyVarSet -> TcS TcTyVarSet
  1057. zonkTyVarsAndFV tvs = wrapTcS (TcM.zonkTyVarsAndFV tvs)
  1058. \end{code}
  1059. Note [Do not add duplicate derived insolubles]
  1060. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1061. In general we *must* add an insoluble (Int ~ Bool) even if there is
  1062. one such there already, because they may come from distinct call
  1063. sites. Not only do we want an error message for each, but with
  1064. -fdefer-type-errors we must generate evidence for each. But for
  1065. *derived* insolubles, we only want to report each one once. Why?
  1066. (a) A constraint (C r s t) where r -> s, say, may generate the same fundep
  1067. equality many times, as the original constraint is sucessively rewritten.
  1068. (b) Ditto the successive iterations of the main solver itself, as it traverses
  1069. the constraint tree. See example below.
  1070. Also for *given* insolubles we may get repeated errors, as we
  1071. repeatedly traverse the constraint tree. These are relatively rare
  1072. anyway, so removing duplicates seems ok. (Alternatively we could take
  1073. the SrcLoc into account.)
  1074. Note that the test does not need to be particularly efficient because
  1075. it is only used if the program has a type error anyway.
  1076. Example of (b): assume a top-level class and instance declaration:
  1077. class D a b | a -> b
  1078. instance D [a] [a]
  1079. Assume we have started with an implication:
  1080. forall c. Eq c => { wc_flat = D [c] c [W] }
  1081. which we have simplified to:
  1082. forall c. Eq c => { wc_flat = D [c] c [W]
  1083. , wc_insols = (c ~ [c]) [D] }
  1084. For some reason, e.g. because we floated an equality somewhere else,
  1085. we might try to re-solve this implication. If we do not do a
  1086. dropDerivedWC, then we will end up trying to solve the following
  1087. constraints the second time:
  1088. (D [c] c) [W]
  1089. (c ~ [c]) [D]
  1090. which will result in two Deriveds to end up in the insoluble set:
  1091. wc_flat = D [c] c [W]
  1092. wc_insols = (c ~ [c]) [D], (c ~ [c]) [D]
  1093. \begin{code}
  1094. -- Flatten skolems
  1095. -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1096. newFlattenSkolem :: CtFlavour
  1097. -> TcType -- F xis
  1098. -> TcS (CtEvidence, TcType) -- co :: F xis ~ ty
  1099. -- We have already looked up in the cache; no need to so so again
  1100. newFlattenSkolem Given fam_ty
  1101. = do { tv <- wrapTcS $
  1102. do { uniq <- TcM.newUnique
  1103. ; let name = TcM.mkTcTyVarName uniq (fsLit "f")
  1104. ; return $ mkTcTyVar name (typeKind fam_ty) (FlatSkol fam_ty) }
  1105. ; traceTcS "New Flatten Skolem Born" $
  1106. ppr tv <+> text "[:= " <+> ppr fam_ty <+> text "]"
  1107. ; let rhs_ty = mkTyVarTy tv
  1108. ctev = CtGiven { ctev_pred = mkTcEqPred fam_ty rhs_ty
  1109. , ctev_evtm = EvCoercion (mkTcReflCo fam_ty) }
  1110. ; updInertTcS $ \ is@(IS { inert_fsks = fsks }) ->
  1111. extendFlatCache fam_ty ctev rhs_ty
  1112. is { inert_fsks = tv : fsks }
  1113. ; return (ctev, rhs_ty) }
  1114. newFlattenSkolem _ fam_ty -- Wanted or Derived: make new unification variable
  1115. = do { rhs_ty <- newFlexiTcSTy (typeKind fam_ty)
  1116. ; ctev <- newWantedEvVarNC (mkTcEqPred fam_ty rhs_ty)
  1117. -- NC (no-cache) version because we've already
  1118. -- looked in the solved goals an inerts (lookupFlatEqn)
  1119. ; updInertTcS $ extendFlatCache fam_ty ctev rhs_ty
  1120. ; return (ctev, rhs_ty) }
  1121. extendFlatCache :: TcType -> CtEvidence -> TcType -> InertSet -> InertSet
  1122. extendFlatCache
  1123. | opt_NoFlatCache
  1124. = \ _ _ _ is -> is
  1125. | otherwise
  1126. = \ fam_ty ctev rhs_ty is@(IS { inert_flat_cache = fc }) ->
  1127. is { inert_flat_cache = insertFamHead fc fam_ty (ctev,rhs_ty) }
  1128. -- Instantiations
  1129. -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1130. instDFunType :: DFunId -> [DFunInstType] -> TcS ([TcType], TcType)
  1131. instDFunType dfun_id mb_inst_tys
  1132. = wrapTcS $ go dfun_tvs mb_inst_tys (mkTopTvSubst [])
  1133. where
  1134. (dfun_tvs, dfun_phi) = tcSplitForAllTys (idType dfun_id)
  1135. go :: [TyVar] -> [DFunInstType] -> TvSubst -> TcM ([TcType], TcType)
  1136. go [] [] subst = return ([], substTy subst dfun_phi)
  1137. go (tv:tvs) (Just ty : mb_tys) subst
  1138. = do { (tys, phi) <- go tvs mb_tys (extendTvSubst subst tv ty)
  1139. ; return (ty : tys, phi) }
  1140. go (tv:tvs) (Nothing : mb_tys) subst
  1141. = do { ty <- instFlexiTcSHelper (tyVarName tv) (substTy subst (tyVarKind tv))
  1142. -- Don't forget to instantiate the kind!
  1143. -- cf TcMType.tcInstTyVarX
  1144. ; (tys, phi) <- go tvs mb_tys (extendTvSubst subst tv ty)
  1145. ; return (ty : tys, phi) }
  1146. go _ _ _ = pprPanic "instDFunTypes" (ppr dfun_id $$ ppr mb_inst_tys)
  1147. newFlexiTcSTy :: Kind -> TcS TcType
  1148. newFlexiTcSTy knd = wrapTcS (TcM.newFlexiTyVarTy knd)
  1149. cloneMetaTyVar :: TcTyVar -> TcS TcTyVar
  1150. cloneMetaTyVar tv = wrapTcS (TcM.cloneMetaTyVar tv)
  1151. instFlexiTcS :: [TKVar] -> TcS (TvSubst, [TcType])
  1152. instFlexiTcS tvs = wrapTcS (mapAccumLM inst_one emptyTvSubst tvs)
  1153. where
  1154. inst_one subst tv
  1155. = do { ty' <- instFlexiTcSHelper (tyVarName tv)
  1156. (substTy subst (tyVarKind tv))
  1157. ; return (extendTvSubst subst tv ty', ty') }
  1158. instFlexiTcSHelper :: Name -> Kind -> TcM TcType
  1159. instFlexiTcSHelper tvname kind
  1160. = do { uniq <- TcM.newUnique
  1161. ; details <- TcM.newMetaDetails TauTv
  1162. ; let name = setNameUnique tvname uniq
  1163. ; return (mkTyVarTy (mkTcTyVar name kind details)) }
  1164. instFlexiTcSHelperTcS :: Name -> Kind -> TcS TcType
  1165. instFlexiTcSHelperTcS n k = wrapTcS (instFlexiTcSHelper n k)
  1166. -- Creating and setting evidence variables and CtFlavors
  1167. -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1168. data XEvTerm =
  1169. XEvTerm { ev_comp :: [EvTerm] -> EvTerm
  1170. -- How to compose evidence
  1171. , ev_decomp :: EvTerm -> [EvTerm]
  1172. -- How to decompose evidence
  1173. }
  1174. data MaybeNew = Fresh CtEvidence | Cached EvTerm
  1175. isFresh :: MaybeNew -> Bool
  1176. isFresh (Fresh {}) = True
  1177. isFresh _ = False
  1178. getEvTerm :: MaybeNew -> EvTerm
  1179. getEvTerm (Fresh ctev) = ctEvTerm ctev
  1180. getEvTerm (Cached tm) = tm
  1181. getEvTerms :: [MaybeNew] -> [EvTerm]
  1182. getEvTerms = map getEvTerm
  1183. freshGoals :: [MaybeNew] -> [CtEvidence]
  1184. freshGoals mns = [ ctev | Fresh ctev <- mns ]
  1185. setEvBind :: EvVar -> EvTerm -> TcS ()
  1186. setEvBind the_ev tm
  1187. = do { traceTcS "setEvBind" $ vcat [ text "ev =" <+> ppr the_ev
  1188. , text "tm =" <+> ppr tm ]
  1189. ; tc_evbinds <- getTcEvBinds
  1190. ; wrapTcS $ TcM.addTcEvBind tc_evbinds the_ev tm }
  1191. newGivenEvVar :: TcPredType -> EvTerm -> TcS CtEvidence
  1192. -- Make a new variable of the given PredType,
  1193. -- immediately bind it to the given term
  1194. -- and return its CtEvidence
  1195. newGivenEvVar pred rhs
  1196. = do { new_ev <- wrapTcS $ TcM.newEvVar pred
  1197. ; setEvBind new_ev rhs
  1198. ; return (CtGiven { ctev_pred = pred, ctev_evtm = EvId new_ev }) }
  1199. newWantedEvVarNC :: TcPredType -> TcS CtEvidence
  1200. -- Don't look up in the solved/inerts; we know it's not there
  1201. newWantedEvVarNC pty
  1202. = do { new_ev <- wrapTcS $ TcM.newEvVar pty
  1203. ; return (CtWanted { ctev_pred = pty, ctev_evar = new_ev })}
  1204. newWantedEvVar :: TcPredType -> TcS MaybeNew
  1205. newWantedEvVar pty
  1206. = do { mb_ct <- lookupInInerts pty
  1207. ; case mb_ct of
  1208. Just ctev | not (isDerived ctev)
  1209. -> do { traceTcS "newWantedEvVar/cache hit" $ ppr ctev
  1210. ; return (Cached (ctEvTerm ctev)) }
  1211. _ -> do { ctev <- newWantedEvVarNC pty
  1212. ; traceTcS "newWantedEvVar/cache miss" $ ppr ctev
  1213. ; return (Fresh ctev) } }
  1214. newDerived :: TcPredType -> TcS (Maybe CtEvidence)
  1215. -- Returns Nothing if cached,
  1216. -- Just pred if not cached
  1217. newDerived pty
  1218. = do { mb_ct <- lookupInInerts pty
  1219. ; return (case mb_ct of
  1220. Just {} -> Nothing
  1221. Nothing -> Just (CtDerived { ctev_pred = pty })) }
  1222. instDFunConstraints :: TcThetaType -> TcS [MaybeNew]
  1223. instDFunConstraints = mapM newWantedEvVar
  1224. \end{code}
  1225. Note [xCFlavor]
  1226. ~~~~~~~~~~~~~~~
  1227. A call might look like this:
  1228. xCtFlavor ev subgoal-preds evidence-transformer
  1229. ev is Given => use ev_decomp to create new Givens for subgoal-preds,
  1230. and return them
  1231. ev is Wanted => create new wanteds for subgoal-preds,
  1232. use ev_comp to bind ev,
  1233. return fresh wanteds (ie ones not cached in inert_cans or solved)
  1234. ev is Derived => create new deriveds for subgoal-preds
  1235. (unless cached in inert_cans or solved)
  1236. Note: The [CtEvidence] returned is a subset of the subgoal-preds passed in
  1237. Ones that are already cached are not returned
  1238. Example
  1239. ev : Tree a b ~ Tree c d
  1240. xCtFlavor ev [a~c, b~d] (XEvTerm { ev_comp = \[c1 c2]. <Tree> c1 c2
  1241. , ev_decomp = \c. [nth 1 c, nth 2 c] })
  1242. (\fresh-goals. stuff)
  1243. Note [Bind new Givens immediately]
  1244. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1245. For Givens we make new EvVars and bind them immediately. We don't worry
  1246. about caching, but we don't expect complicated calculations among Givens.
  1247. It is important to bind each given:
  1248. class (a~b) => C a b where ....
  1249. f :: C a b => ....
  1250. Then in f's Givens we have g:(C a b) and the superclass sc(g,0):a~b.
  1251. But that superclass selector can't (yet) appear in a coercion
  1252. (see evTermCoercion), so the easy thing is to bind it to an Id.
  1253. See Note [Coercion evidence terms] in TcEvidence.
  1254. \begin{code}
  1255. xCtFlavor :: CtEvidence -- Original flavor
  1256. -> [TcPredType] -- New predicate types
  1257. -> XEvTerm -- Instructions about how to manipulate evidence
  1258. -> TcS [CtEvidence]
  1259. xCtFlavor (CtGiven { ctev_evtm = tm }) ptys xev
  1260. = ASSERT( equalLength ptys (ev_decomp xev tm) )
  1261. zipWithM newGivenEvVar ptys (ev_decomp xev tm)
  1262. -- See Note [Bind new Givens immediately]
  1263. xCtFlavor ctev@(CtWanted { ctev_evar = evar }) ptys xev
  1264. = do { new_evars <- mapM newWantedEvVar ptys
  1265. ; setEvBind evar (ev_comp xev (getEvTerms new_evars))
  1266. ; return (freshGoals new_evars) }
  1267. xCtFlavor (CtDerived {}) ptys _xev
  1268. = do { ders <- mapM newDerived ptys
  1269. ; return (catMaybes ders) }
  1270. -----------------------------
  1271. rewriteCtFlavor :: CtEvidence
  1272. -> TcPredType -- new predicate
  1273. -> TcCoercion -- new ~ old
  1274. -> TcS (Maybe CtEvidence)
  1275. -- Returns Just new_fl iff either (i) 'co' is reflexivity
  1276. -- or (ii) 'co' is not reflexivity, and 'new_pred' not cached
  1277. -- In either case, there is nothing new to do with new_fl
  1278. {-
  1279. rewriteCtFlavor old_fl new_pred co
  1280. Main purpose: create new evidence for new_pred;
  1281. unless new_pred is cached already
  1282. * Returns a new_fl : new_pred, with same wanted/given/derived flag as old_fl
  1283. * If old_fl was wanted, create a binding for old_fl, in terms of new_fl
  1284. * If old_fl was given, AND not cached, create a binding for new_fl, in terms of old_fl
  1285. * Returns Nothing if new_fl is already cached
  1286. Old evidence New predicate is Return new evidence
  1287. flavour of same flavor
  1288. -------------------------------------------------------------------
  1289. Wanted Already solved or in inert Nothing
  1290. or Derived Not Just new_evidence
  1291. Given Already in inert Nothing
  1292. Not Just new_evidence
  1293. -}
  1294. rewriteCtFlavor (CtDerived {}) new_pred _co
  1295. = -- If derived, don't even look at the coercion.
  1296. -- This is very important, DO NOT re-order the equations for
  1297. -- rewriteCtFlavor to put the isTcReflCo test first!
  1298. -- Why? Because for *Derived* constraints, c, the coercion, which
  1299. -- was produced by flattening, may contain suspended calls to
  1300. -- (ctEvTerm c), which fails for Derived constraints.
  1301. -- (Getting this wrong caused Trac #7384.)
  1302. newDerived new_pred
  1303. rewriteCtFlavor old_ev new_pred co
  1304. | isTcReflCo co -- If just reflexivity then you may re-use the same variable
  1305. = return (Just (if ctEvPred old_ev `eqType` new_pred
  1306. then old_ev
  1307. else old_ev { ctev_pred = new_pred }))
  1308. -- Even if the coercion is Refl, it might reflect the result of unification alpha := ty
  1309. -- so old_pred and new_pred might not *look* the same, and it's vital to proceed from
  1310. -- now on using new_pred.
  1311. -- However, if they *do* look the same, we'd prefer to stick with old_pred
  1312. -- then retain the old type, so that error messages come out mentioning synonyms
  1313. rewriteCtFlavor (CtGiven { ctev_evtm = old_tm }) new_pred co
  1314. = do { new_ev <- newGivenEvVar new_pred new_tm -- See Note [Bind new Givens immediately]
  1315. ; return (Just new_ev) }
  1316. where
  1317. new_tm = mkEvCast old_tm (mkTcSymCo co) -- mkEvCast optimises ReflCo
  1318. rewriteCtFlavor (CtWanted { ctev_evar = evar, ctev_pred = old_pred }) new_pred co
  1319. = do { new_evar <- newWantedEvVar new_pred
  1320. ; setEvBind evar (mkEvCast (getEvTerm new_evar) co)
  1321. ; case new_evar of
  1322. Fresh ctev -> return (Just ctev)
  1323. _ -> return Nothing }
  1324. -- Matching and looking up classes and family instances
  1325. -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1326. data MatchInstResult mi
  1327. = MatchInstNo -- No matching instance
  1328. | MatchInstSingle mi -- Single matching instance
  1329. | MatchInstMany -- Multiple matching instances
  1330. matchClass :: Class -> [Type] -> TcS (MatchInstResult (DFunId, [Maybe TcType]))
  1331. -- Look up a class constraint in the instance environment
  1332. matchClass clas tys
  1333. = do { let pred = mkClassPred clas tys
  1334. ; instEnvs <- getInstEnvs
  1335. ; case lookupInstEnv instEnvs clas tys of {
  1336. ([], _unifs, _) -- Nothing matches
  1337. -> do { traceTcS "matchClass not matching" $
  1338. vcat [ text "dict" <+> ppr pred
  1339. {- , ppr instEnvs -} ]
  1340. ; return MatchInstNo
  1341. } ;
  1342. ([(ispec, inst_tys)], [], _) -- A single match
  1343. -> do { let dfun_id = is_dfun ispec
  1344. ; traceTcS "matchClass success" $
  1345. vcat [text "dict" <+> ppr pred,
  1346. text "witness" <+> ppr dfun_id
  1347. <+> ppr (idType dfun_id) ]
  1348. -- Record that this dfun is needed
  1349. ; return $ MatchInstSingle (dfun_id, inst_tys)
  1350. } ;
  1351. (matches, _unifs, _) -- More than one matches
  1352. -> do { traceTcS "matchClass multiple matches, deferring choice" $
  1353. vcat [text "dict" <+> ppr pred,
  1354. text "matches" <+> ppr matches]
  1355. ; return MatchInstMany
  1356. }
  1357. }
  1358. }
  1359. matchFam :: TyCon -> [Type] -> TcS (Maybe FamInstMatch)
  1360. matchFam tycon args = wrapTcS $ tcLookupFamInst tycon args
  1361. \end{code}
  1362. \begin{code}
  1363. -- Deferring forall equalities as implications
  1364. -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1365. deferTcSForAllEq :: (CtLoc,EvVar) -- Original wanted equality flavor
  1366. -> ([TyVar],TcType) -- ForAll tvs1 body1
  1367. -> ([TyVar],TcType) -- ForAll tvs2 body2
  1368. -> TcS ()
  1369. -- Some of this functionality is repeated from TcUnify,
  1370. -- consider having a single place where we create fresh implications.
  1371. deferTcSForAllEq (loc,orig_ev) (tvs1,body1) (tvs2,body2)
  1372. = do { (subst1, skol_tvs) <- wrapTcS $ TcM.tcInstSkolTyVars tvs1
  1373. ; let tys = mkTyVarTys skol_tvs
  1374. phi1 = Type.substTy subst1 body1
  1375. phi2 = Type.substTy (zipTopTvSubst tvs2 tys) body2
  1376. skol_info = UnifyForAllSkol skol_tvs phi1
  1377. ; mev <- newWantedEvVar (mkTcEqPred phi1 phi2)
  1378. ; coe_inside <- case mev of
  1379. Cached ev_tm -> return (evTermCoercion ev_tm)
  1380. Fresh ctev -> do { ev_binds_var <- wrapTcS $ TcM.newTcEvBinds
  1381. ; env <- wrapTcS $ TcM.getLclEnv
  1382. ; let ev_binds = TcEvBinds ev_binds_var
  1383. new_ct = mkNonCanonical loc ctev
  1384. new_co = evTermCoercion (ctEvTerm ctev)
  1385. new_untch = pushUntouchables (tcl_untch env)
  1386. ; let wc = WC { wc_flat = singleCt new_ct
  1387. , wc_impl = emptyBag
  1388. , wc_insol = emptyCts }
  1389. imp = Implic { ic_untch = new_untch
  1390. , ic_skols = skol_tvs
  1391. , ic_fsks = []
  1392. , ic_given = []
  1393. , ic_wanted = wc
  1394. , ic_insol = False
  1395. , ic_binds = ev_binds_var
  1396. , ic_env = env
  1397. , ic_info = skol_info }
  1398. ; updTcSImplics (consBag imp)
  1399. ; return (TcLetCo ev_binds new_co) }
  1400. ; setEvBind orig_ev $
  1401. EvCoercion (foldr mkTcForAllCo coe_inside skol_tvs)
  1402. }
  1403. \end{code}