PageRenderTime 69ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 1ms

/compiler/typecheck/TcSMonad.lhs

http://github.com/ghc/ghc
Haskell | 1749 lines | 1215 code | 337 blank | 197 comment | 33 complexity | 7e7afee4a13313d3d92d5280c3d6fb1c MD5 | raw file
Possible License(s): MIT, BSD-3-Clause, GPL-3.0

Large files files are truncated, but you can click here to view the full 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://ghc.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. -- Marking stuff as used
  32. addUsedRdrNamesTcS,
  33. deferTcSForAllEq,
  34. setEvBind,
  35. XEvTerm(..),
  36. MaybeNew (..), isFresh, freshGoal, freshGoals, getEvTerm, getEvTerms,
  37. xCtFlavor, -- Transform a CtEvidence during a step
  38. rewriteCtFlavor, -- Specialized version of xCtFlavor for coercions
  39. newWantedEvVar, newWantedEvVarNC, instDFunConstraints,
  40. newDerived,
  41. -- Creation of evidence variables
  42. setWantedTyBind,
  43. getInstEnvs, getFamInstEnvs, -- Getting the environments
  44. getTopEnv, getGblEnv, getTcEvBinds, getUntouchables,
  45. getTcEvBindsMap, getTcSTyBinds, getTcSTyBindsMap,
  46. lookupFlatEqn, newFlattenSkolem, -- Flatten skolems
  47. -- Deque
  48. Deque(..), insertDeque, emptyDeque,
  49. -- Inerts
  50. InertSet(..), InertCans(..),
  51. getInertEqs,
  52. emptyInert, getTcSInerts, lookupInInerts,
  53. getInertUnsolved, checkAllSolved,
  54. prepareInertsForImplications,
  55. modifyInertTcS,
  56. insertInertItemTcS, partitionCCanMap, partitionEqMap,
  57. getRelevantCts, extractRelevantInerts,
  58. getInertsFunEqTyCon,
  59. CCanMap(..), CtTypeMap, CtFamHeadMap, CtPredMap,
  60. PredMap, FamHeadMap,
  61. partCtFamHeadMap, lookupFamHead, lookupSolvedDict,
  62. filterSolved,
  63. instDFunType, -- Instantiation
  64. newFlexiTcSTy, instFlexiTcS, instFlexiTcSHelperTcS,
  65. cloneMetaTyVar,
  66. Untouchables, isTouchableMetaTyVarTcS, isFilledMetaTyVar_maybe,
  67. zonkTyVarsAndFV,
  68. getDefaultInfo, getDynFlags, getGlobalRdrEnvTcS,
  69. matchFam, matchOpenFam,
  70. checkWellStagedDFun,
  71. pprEq -- Smaller utils, re-exported from TcM
  72. -- TODO (DV): these are only really used in the
  73. -- instance matcher in TcSimplify. I am wondering
  74. -- if the whole instance matcher simply belongs
  75. -- here
  76. ) where
  77. #include "HsVersions.h"
  78. import HscTypes
  79. import Inst
  80. import InstEnv
  81. import FamInst
  82. import FamInstEnv
  83. import qualified TcRnMonad as TcM
  84. import qualified TcMType as TcM
  85. import qualified TcEnv as TcM
  86. ( checkWellStaged, topIdLvl, tcGetDefaultTys )
  87. import Kind
  88. import TcType
  89. import DynFlags
  90. import Type
  91. import TcEvidence
  92. import Class
  93. import TyCon
  94. import Name
  95. import RdrName (RdrName, GlobalRdrEnv)
  96. import RnEnv (addUsedRdrNames)
  97. import Var
  98. import VarEnv
  99. import Outputable
  100. import Bag
  101. import MonadUtils
  102. import FastString
  103. import Util
  104. import Id
  105. import TcRnTypes
  106. import Unique
  107. import UniqFM
  108. import Maybes ( orElse, catMaybes, firstJust )
  109. import Pair ( pSnd )
  110. import Control.Monad( unless, when, zipWithM )
  111. import Data.IORef
  112. import TrieMap
  113. #ifdef DEBUG
  114. import StaticFlags( opt_PprStyle_Debug )
  115. import VarSet
  116. import Digraph
  117. #endif
  118. \end{code}
  119. %************************************************************************
  120. %* *
  121. %* Worklists *
  122. %* Canonical and non-canonical constraints that the simplifier has to *
  123. %* work on. Including their simplification depths. *
  124. %* *
  125. %* *
  126. %************************************************************************
  127. Note [WorkList priorities]
  128. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  129. A WorkList contains canonical and non-canonical items (of all flavors).
  130. Notice that each Ct now has a simplification depth. We may
  131. consider using this depth for prioritization as well in the future.
  132. As a simple form of priority queue, our worklist separates out
  133. equalities (wl_eqs) from the rest of the canonical constraints,
  134. so that it's easier to deal with them first, but the separation
  135. is not strictly necessary. Notice that non-canonical constraints
  136. are also parts of the worklist.
  137. Note [NonCanonical Semantics]
  138. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  139. Note that canonical constraints involve a CNonCanonical constructor. In the worklist
  140. we use this constructor for constraints that have not yet been canonicalized such as
  141. [Int] ~ [a]
  142. In other words, all constraints start life as NonCanonicals.
  143. On the other hand, in the Inert Set (see below) the presence of a NonCanonical somewhere
  144. means that we have a ``frozen error''.
  145. NonCanonical constraints never interact directly with other constraints -- but they can
  146. be rewritten by equalities (for instance if a non canonical exists in the inert, we'd
  147. better rewrite it as much as possible before reporting it as an error to the user)
  148. \begin{code}
  149. data Deque a = DQ [a] [a] -- Insert in RH field, remove from LH field
  150. -- First to remove is at head of LH field
  151. instance Outputable a => Outputable (Deque a) where
  152. ppr (DQ as bs) = ppr (as ++ reverse bs) -- Show first one to come out at the start
  153. emptyDeque :: Deque a
  154. emptyDeque = DQ [] []
  155. isEmptyDeque :: Deque a -> Bool
  156. isEmptyDeque (DQ as bs) = null as && null bs
  157. dequeSize :: Deque a -> Int
  158. dequeSize (DQ as bs) = length as + length bs
  159. insertDeque :: a -> Deque a -> Deque a
  160. insertDeque b (DQ as bs) = DQ as (b:bs)
  161. appendDeque :: Deque a -> Deque a -> Deque a
  162. appendDeque (DQ as1 bs1) (DQ as2 bs2) = DQ (as1 ++ reverse bs1 ++ as2) bs2
  163. extractDeque :: Deque a -> Maybe (Deque a, a)
  164. extractDeque (DQ [] []) = Nothing
  165. extractDeque (DQ (a:as) bs) = Just (DQ as bs, a)
  166. extractDeque (DQ [] bs) = case reverse bs of
  167. (a:as) -> Just (DQ as [], a)
  168. [] -> panic "extractDeque"
  169. -- See Note [WorkList priorities]
  170. data WorkList = WorkList { wl_eqs :: [Ct]
  171. , wl_funeqs :: Deque Ct
  172. , wl_rest :: [Ct]
  173. }
  174. appendWorkList :: WorkList -> WorkList -> WorkList
  175. appendWorkList new_wl orig_wl
  176. = WorkList { wl_eqs = wl_eqs new_wl ++ wl_eqs orig_wl
  177. , wl_funeqs = wl_funeqs new_wl `appendDeque` wl_funeqs orig_wl
  178. , wl_rest = wl_rest new_wl ++ wl_rest orig_wl }
  179. workListSize :: WorkList -> Int
  180. workListSize (WorkList { wl_eqs = eqs, wl_funeqs = funeqs, wl_rest = rest })
  181. = length eqs + dequeSize funeqs + length rest
  182. extendWorkListEq :: Ct -> WorkList -> WorkList
  183. -- Extension by equality
  184. extendWorkListEq ct wl
  185. | Just {} <- isCFunEqCan_maybe ct
  186. = extendWorkListFunEq ct wl
  187. | otherwise
  188. = wl { wl_eqs = ct : wl_eqs wl }
  189. extendWorkListFunEq :: Ct -> WorkList -> WorkList
  190. extendWorkListFunEq ct wl
  191. = wl { wl_funeqs = insertDeque ct (wl_funeqs wl) }
  192. extendWorkListEqs :: [Ct] -> WorkList -> WorkList
  193. -- Append a list of equalities
  194. extendWorkListEqs cts wl = foldr extendWorkListEq wl cts
  195. extendWorkListNonEq :: Ct -> WorkList -> WorkList
  196. -- Extension by non equality
  197. extendWorkListNonEq ct wl
  198. = wl { wl_rest = ct : wl_rest wl }
  199. extendWorkListCt :: Ct -> WorkList -> WorkList
  200. -- Agnostic
  201. extendWorkListCt ct wl
  202. | isEqPred (ctPred ct) = extendWorkListEq ct wl
  203. | otherwise = extendWorkListNonEq ct wl
  204. extendWorkListCts :: [Ct] -> WorkList -> WorkList
  205. -- Agnostic
  206. extendWorkListCts cts wl = foldr extendWorkListCt wl cts
  207. isEmptyWorkList :: WorkList -> Bool
  208. isEmptyWorkList wl
  209. = null (wl_eqs wl) && null (wl_rest wl) && isEmptyDeque (wl_funeqs wl)
  210. emptyWorkList :: WorkList
  211. emptyWorkList = WorkList { wl_eqs = [], wl_rest = [], wl_funeqs = emptyDeque }
  212. workListFromEq :: Ct -> WorkList
  213. workListFromEq ct = extendWorkListEq ct emptyWorkList
  214. workListFromNonEq :: Ct -> WorkList
  215. workListFromNonEq ct = extendWorkListNonEq ct emptyWorkList
  216. workListFromCt :: Ct -> WorkList
  217. -- Agnostic
  218. workListFromCt ct | isEqPred (ctPred ct) = workListFromEq ct
  219. | otherwise = workListFromNonEq ct
  220. selectWorkItem :: WorkList -> (Maybe Ct, WorkList)
  221. selectWorkItem wl@(WorkList { wl_eqs = eqs, wl_funeqs = feqs, wl_rest = rest })
  222. = case (eqs,feqs,rest) of
  223. (ct:cts,_,_) -> (Just ct, wl { wl_eqs = cts })
  224. (_,fun_eqs,_) | Just (fun_eqs', ct) <- extractDeque fun_eqs
  225. -> (Just ct, wl { wl_funeqs = fun_eqs' })
  226. (_,_,(ct:cts)) -> (Just ct, wl { wl_rest = cts })
  227. (_,_,_) -> (Nothing,wl)
  228. -- Pretty printing
  229. instance Outputable WorkList where
  230. ppr wl = vcat [ text "WorkList (eqs) = " <+> ppr (wl_eqs wl)
  231. , text "WorkList (funeqs)= " <+> ppr (wl_funeqs wl)
  232. , text "WorkList (rest) = " <+> ppr (wl_rest wl)
  233. ]
  234. -- Canonical constraint maps
  235. data CCanMap a
  236. = CCanMap { cts_given :: UniqFM Cts -- All Given
  237. , cts_derived :: UniqFM Cts -- All Derived
  238. , cts_wanted :: UniqFM Cts } -- All Wanted
  239. keepGivenCMap :: CCanMap a -> CCanMap a
  240. keepGivenCMap cc = emptyCCanMap { cts_given = cts_given cc }
  241. instance Outputable (CCanMap a) where
  242. ppr (CCanMap given derived wanted) = ptext (sLit "CCanMap") <+> (ppr given) <+> (ppr derived) <+> (ppr wanted)
  243. cCanMapToBag :: CCanMap a -> Cts
  244. cCanMapToBag cmap = foldUFM unionBags rest_wder (cts_given cmap)
  245. where rest_wder = foldUFM unionBags rest_der (cts_wanted cmap)
  246. rest_der = foldUFM unionBags emptyCts (cts_derived cmap)
  247. emptyCCanMap :: CCanMap a
  248. emptyCCanMap = CCanMap { cts_given = emptyUFM, cts_derived = emptyUFM, cts_wanted = emptyUFM }
  249. updCCanMap:: Uniquable a => (a,Ct) -> CCanMap a -> CCanMap a
  250. updCCanMap (a,ct) cmap
  251. = case cc_ev ct of
  252. CtWanted {} -> cmap { cts_wanted = insert_into (cts_wanted cmap) }
  253. CtGiven {} -> cmap { cts_given = insert_into (cts_given cmap) }
  254. CtDerived {} -> cmap { cts_derived = insert_into (cts_derived cmap) }
  255. where
  256. insert_into m = addToUFM_C unionBags m a (singleCt ct)
  257. getRelevantCts :: Uniquable a => a -> CCanMap a -> (Cts, CCanMap a)
  258. -- Gets the relevant constraints and returns the rest of the CCanMap
  259. getRelevantCts a cmap
  260. = let relevant = lookup (cts_wanted cmap) `unionBags`
  261. lookup (cts_given cmap) `unionBags`
  262. lookup (cts_derived cmap)
  263. residual_map = cmap { cts_wanted = delFromUFM (cts_wanted cmap) a
  264. , cts_given = delFromUFM (cts_given cmap) a
  265. , cts_derived = delFromUFM (cts_derived cmap) a }
  266. in (relevant, residual_map)
  267. where
  268. lookup map = lookupUFM map a `orElse` emptyCts
  269. lookupCCanMap :: Uniquable a => a -> (CtEvidence -> Bool) -> CCanMap a -> Maybe CtEvidence
  270. lookupCCanMap a pick_me map
  271. = findEvidence pick_me possible_cts
  272. where
  273. possible_cts = lookupUFM (cts_given map) a `plus` (
  274. lookupUFM (cts_wanted map) a `plus` (
  275. lookupUFM (cts_derived map) a `plus` emptyCts))
  276. plus Nothing cts2 = cts2
  277. plus (Just cts1) cts2 = cts1 `unionBags` cts2
  278. findEvidence :: (CtEvidence -> Bool) -> Cts -> Maybe CtEvidence
  279. findEvidence pick_me cts
  280. = foldrBag pick Nothing cts
  281. where
  282. pick :: Ct -> Maybe CtEvidence -> Maybe CtEvidence
  283. pick ct deflt | let ctev = cc_ev ct, pick_me ctev = Just ctev
  284. | otherwise = deflt
  285. partitionCCanMap :: (Ct -> Bool) -> CCanMap a -> (Cts,CCanMap a)
  286. -- All constraints that /match/ the predicate go in the bag, the rest remain in the map
  287. partitionCCanMap pred cmap
  288. = let (ws_map,ws) = foldUFM_Directly aux (emptyUFM,emptyCts) (cts_wanted cmap)
  289. (ds_map,ds) = foldUFM_Directly aux (emptyUFM,emptyCts) (cts_derived cmap)
  290. (gs_map,gs) = foldUFM_Directly aux (emptyUFM,emptyCts) (cts_given cmap)
  291. in (ws `andCts` ds `andCts` gs, cmap { cts_wanted = ws_map
  292. , cts_given = gs_map
  293. , cts_derived = ds_map })
  294. where aux k this_cts (mp,acc_cts) = (new_mp, new_acc_cts)
  295. where new_mp = addToUFM mp k cts_keep
  296. new_acc_cts = acc_cts `andCts` cts_out
  297. (cts_out, cts_keep) = partitionBag pred this_cts
  298. partitionEqMap :: (Ct -> Bool) -> TyVarEnv (Ct,TcCoercion) -> ([Ct], TyVarEnv (Ct,TcCoercion))
  299. partitionEqMap pred isubst
  300. = let eqs_out = foldVarEnv extend_if_pred [] isubst
  301. eqs_in = filterVarEnv_Directly (\_ (ct,_) -> not (pred ct)) isubst
  302. in (eqs_out, eqs_in)
  303. where extend_if_pred (ct,_) cts = if pred ct then ct : cts else cts
  304. extractUnsolvedCMap :: CCanMap a -> Cts
  305. -- Gets the wanted or derived constraints
  306. extractUnsolvedCMap cmap = foldUFM unionBags emptyCts (cts_wanted cmap)
  307. `unionBags` foldUFM unionBags emptyCts (cts_derived cmap)
  308. -- Maps from PredTypes to Constraints
  309. type CtTypeMap = TypeMap Ct
  310. type CtPredMap = PredMap Ct
  311. type CtFamHeadMap = FamHeadMap Ct
  312. newtype PredMap a = PredMap { unPredMap :: TypeMap a } -- Indexed by TcPredType
  313. newtype FamHeadMap a = FamHeadMap { unFamHeadMap :: TypeMap a } -- Indexed by family head
  314. instance Outputable a => Outputable (PredMap a) where
  315. ppr (PredMap m) = ppr (foldTM (:) m [])
  316. instance Outputable a => Outputable (FamHeadMap a) where
  317. ppr (FamHeadMap m) = ppr (foldTM (:) m [])
  318. sizePredMap :: PredMap a -> Int
  319. sizePredMap (PredMap m) = foldTypeMap (\_ x -> x+1) 0 m
  320. emptyFamHeadMap :: FamHeadMap a
  321. emptyFamHeadMap = FamHeadMap emptyTM
  322. sizeFamHeadMap :: FamHeadMap a -> Int
  323. sizeFamHeadMap (FamHeadMap m) = foldTypeMap (\_ x -> x+1) 0 m
  324. ctTypeMapCts :: TypeMap Ct -> Cts
  325. ctTypeMapCts ctmap = foldTM (\ct cts -> extendCts cts ct) ctmap emptyCts
  326. lookupFamHead :: FamHeadMap a -> TcType -> Maybe a
  327. lookupFamHead (FamHeadMap m) key = lookupTM key m
  328. insertFamHead :: FamHeadMap a -> TcType -> a -> FamHeadMap a
  329. insertFamHead (FamHeadMap m) key value = FamHeadMap (insertTM key value m)
  330. delFamHead :: FamHeadMap a -> TcType -> FamHeadMap a
  331. delFamHead (FamHeadMap m) key = FamHeadMap (deleteTM key m)
  332. anyFamHeadMap :: (Ct -> Bool) -> CtFamHeadMap -> Bool
  333. anyFamHeadMap f ctmap = foldTM ((||) . f) (unFamHeadMap ctmap) False
  334. partCtFamHeadMap :: (Ct -> Bool)
  335. -> CtFamHeadMap
  336. -> (Cts, CtFamHeadMap)
  337. partCtFamHeadMap f (FamHeadMap ctmap)
  338. = let (cts, tymap_final) = foldTM upd_acc ctmap (emptyBag, ctmap)
  339. in (cts, FamHeadMap tymap_final)
  340. where
  341. upd_acc ct (cts,acc_map)
  342. | f ct = (extendCts cts ct, deleteTM fam_head acc_map)
  343. | otherwise = (cts,acc_map)
  344. where
  345. fam_head = funEqHead ct
  346. funEqHead :: Ct -> Type
  347. funEqHead ct = case isCFunEqCan_maybe ct of
  348. Just (tc,tys) -> mkTyConApp tc tys
  349. Nothing -> pprPanic "funEqHead" (ppr ct)
  350. filterSolved :: (CtEvidence -> Bool) -> PredMap CtEvidence -> PredMap CtEvidence
  351. filterSolved p (PredMap mp) = PredMap (foldTM upd mp emptyTM)
  352. where upd a m = if p a then insertTM (ctEvPred a) a m
  353. else m
  354. \end{code}
  355. %************************************************************************
  356. %* *
  357. %* Inert Sets *
  358. %* *
  359. %* *
  360. %************************************************************************
  361. Note [Detailed InertCans Invariants]
  362. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  363. The InertCans represents a collection of constraints with the following properties:
  364. 1 All canonical
  365. 2 All Given or Wanted or Derived. No (partially) Solved
  366. 3 No two dictionaries with the same head
  367. 4 No two family equations with the same head
  368. NB: This is enforced by construction since we use a CtFamHeadMap for inert_funeqs
  369. 5 Family equations inert wrt top-level family axioms
  370. 6 Dictionaries have no matching top-level instance
  371. 7 Non-equality constraints are fully rewritten with respect to the equalities (CTyEqCan)
  372. 8 Equalities _do_not_ form an idempotent substitution, but they are
  373. guaranteed to not have any occurs errors. Additional notes:
  374. - The lack of idempotence of the inert substitution implies
  375. that we must make sure that when we rewrite a constraint we
  376. apply the substitution /recursively/ to the types
  377. involved. Currently the one AND ONLY way in the whole
  378. constraint solver that we rewrite types and constraints wrt
  379. to the inert substitution is TcCanonical/flattenTyVar.
  380. - In the past we did try to have the inert substitution as
  381. idempotent as possible but this would only be true for
  382. constraints of the same flavor, so in total the inert
  383. substitution could not be idempotent, due to flavor-related
  384. issued. Note [Non-idempotent inert substitution] explains
  385. what is going on.
  386. - Whenever a constraint ends up in the worklist we do
  387. recursively apply exhaustively the inert substitution to it
  388. to check for occurs errors. But if an equality is already in
  389. the inert set and we can guarantee that adding a new equality
  390. will not cause the first equality to have an occurs check
  391. then we do not rewrite the inert equality. This happens in
  392. TcInteract, rewriteInertEqsFromInertEq.
  393. See Note [Delicate equality kick-out] to see which inert
  394. equalities can safely stay in the inert set and which must be
  395. kicked out to be rewritten and re-checked for occurs errors.
  396. 9 Given family or dictionary constraints don't mention touchable unification variables
  397. Note [Solved constraints]
  398. ~~~~~~~~~~~~~~~~~~~~~~~~~
  399. When we take a step to simplify a constraint 'c', we call the original constraint "solved".
  400. For example: Wanted: ev :: [s] ~ [t]
  401. New goal: ev1 :: s ~ t
  402. Then 'ev' is now "solved".
  403. The reason for all this is simply to avoid re-solving goals we have solved already.
  404. * A solved Wanted may depend on as-yet-unsolved goals, so (for example) we should not
  405. use it to rewrite a Given; in that sense the solved goal is still a Wanted
  406. * A solved Given is just given
  407. * A solved Derived in inert_solved is possible; purpose is to avoid
  408. creating tons of identical Derived goals.
  409. But there are no solved Deriveds in inert_solved_funeqs
  410. Note [Type family equations]
  411. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  412. Type-family equations, of form (ev : F tys ~ ty), live in four places
  413. * The work-list, of course
  414. * The inert_flat_cache. This is used when flattening, to get maximal
  415. sharing. It contains lots of things that are still in the work-list.
  416. E.g Suppose we have (w1: F (G a) ~ Int), and (w2: H (G a) ~ Int) in the
  417. work list. Then we flatten w1, dumping (w3: G a ~ f1) in the work
  418. list. Now if we flatten w2 before we get to w3, we still want to
  419. share that (G a).
  420. Because it contains work-list things, DO NOT use the flat cache to solve
  421. a top-level goal. Eg in the above example we don't want to solve w3
  422. using w3 itself!
  423. * The inert_solved_funeqs. These are all "solved" goals (see Note [Solved constraints]),
  424. the result of using a top-level type-family instance.
  425. * THe inert_funeqs are un-solved but fully processed and in the InertCans.
  426. \begin{code}
  427. -- All Given (fully known) or Wanted or Derived
  428. -- See Note [Detailed InertCans Invariants] for more
  429. data InertCans
  430. = IC { inert_eqs :: TyVarEnv Ct
  431. -- Must all be CTyEqCans! If an entry exists of the form:
  432. -- a |-> ct,co
  433. -- Then ct = CTyEqCan { cc_tyvar = a, cc_rhs = xi }
  434. -- And co : a ~ xi
  435. , inert_dicts :: CCanMap Class
  436. -- Dictionaries only, index is the class
  437. -- NB: index is /not/ the whole type because FD reactions
  438. -- need to match the class but not necessarily the whole type.
  439. , inert_funeqs :: CtFamHeadMap
  440. -- Family equations, index is the whole family head type.
  441. , inert_irreds :: Cts
  442. -- Irreducible predicates
  443. , inert_insols :: Cts
  444. -- Frozen errors (as non-canonicals)
  445. }
  446. -- The Inert Set
  447. data InertSet
  448. = IS { inert_cans :: InertCans
  449. -- Canonical Given, Wanted, Derived (no Solved)
  450. -- Sometimes called "the inert set"
  451. , inert_flat_cache :: FamHeadMap (CtEvidence, TcType)
  452. -- See Note [Type family equations]
  453. -- Just a hash-cons cache for use when flattening only
  454. -- These include entirely un-processed goals, so don't use
  455. -- them to solve a top-level goal, else you may end up solving
  456. -- (w:F ty ~ a) by setting w:=w! We just use the flat-cache
  457. -- when allocating a new flatten-skolem.
  458. -- Not necessarily inert wrt top-level equations (or inert_cans)
  459. , inert_fsks :: [TcTyVar] -- Rigid flatten-skolems (arising from givens)
  460. -- allocated in this local scope
  461. , inert_solved_funeqs :: FamHeadMap (CtEvidence, TcType)
  462. -- See Note [Type family equations]
  463. -- Of form co :: F xis ~ xi
  464. -- Always the result of using a top-level family axiom F xis ~ tau
  465. -- No Deriveds
  466. -- Not necessarily fully rewritten (by type substitutions)
  467. , inert_solved_dicts :: PredMap CtEvidence
  468. -- Of form ev :: C t1 .. tn
  469. -- Always the result of using a top-level instance declaration
  470. -- See Note [Solved constraints]
  471. -- - Used to avoid creating a new EvVar when we have a new goal
  472. -- that we have solved in the past
  473. -- - Stored not necessarily as fully rewritten
  474. -- (ToDo: rewrite lazily when we lookup)
  475. }
  476. instance Outputable InertCans where
  477. ppr ics = vcat [ ptext (sLit "Equalities:")
  478. <+> vcat (map ppr (varEnvElts (inert_eqs ics)))
  479. , ptext (sLit "Type-function equalities:")
  480. <+> vcat (map ppr (Bag.bagToList $
  481. ctTypeMapCts (unFamHeadMap $ inert_funeqs ics)))
  482. , ptext (sLit "Dictionaries:")
  483. <+> vcat (map ppr (Bag.bagToList $ cCanMapToBag (inert_dicts ics)))
  484. , ptext (sLit "Irreds:")
  485. <+> vcat (map ppr (Bag.bagToList $ inert_irreds ics))
  486. , text "Insolubles =" <+> -- Clearly print frozen errors
  487. braces (vcat (map ppr (Bag.bagToList $ inert_insols ics)))
  488. ]
  489. instance Outputable InertSet where
  490. ppr is = vcat [ ppr $ inert_cans is
  491. , text "Solved dicts" <+> int (sizePredMap (inert_solved_dicts is))
  492. , text "Solved funeqs" <+> int (sizeFamHeadMap (inert_solved_funeqs is))]
  493. emptyInert :: InertSet
  494. emptyInert
  495. = IS { inert_cans = IC { inert_eqs = emptyVarEnv
  496. , inert_dicts = emptyCCanMap
  497. , inert_funeqs = emptyFamHeadMap
  498. , inert_irreds = emptyCts
  499. , inert_insols = emptyCts }
  500. , inert_fsks = []
  501. , inert_flat_cache = emptyFamHeadMap
  502. , inert_solved_dicts = PredMap emptyTM
  503. , inert_solved_funeqs = emptyFamHeadMap }
  504. insertInertItem :: Ct -> InertSet -> InertSet
  505. -- Add a new inert element to the inert set.
  506. insertInertItem item is
  507. = -- A canonical Given, Wanted, or Derived
  508. is { inert_cans = upd_inert_cans (inert_cans is) item }
  509. where upd_inert_cans :: InertCans -> Ct -> InertCans
  510. -- Precondition: item /is/ canonical
  511. upd_inert_cans ics item
  512. | isCTyEqCan item
  513. = let upd_err a b = pprPanic "insertInertItem" $
  514. vcat [ text "Multiple inert equalities:"
  515. , text "Old (already inert):" <+> ppr a
  516. , text "Trying to insert :" <+> ppr b ]
  517. eqs' = extendVarEnv_C upd_err (inert_eqs ics)
  518. (cc_tyvar item) item
  519. in ics { inert_eqs = eqs' }
  520. | isCIrredEvCan item -- Presently-irreducible evidence
  521. = ics { inert_irreds = inert_irreds ics `Bag.snocBag` item }
  522. | Just cls <- isCDictCan_Maybe item -- Dictionary
  523. = ics { inert_dicts = updCCanMap (cls,item) (inert_dicts ics) }
  524. | Just (tc,tys) <- isCFunEqCan_maybe item -- Function equality
  525. = let fam_head = mkTyConApp tc tys
  526. upd_funeqs Nothing = Just item
  527. upd_funeqs (Just _already_there)
  528. = panic "insertInertItem: item already there!"
  529. in ics { inert_funeqs = FamHeadMap
  530. (alterTM fam_head upd_funeqs $
  531. (unFamHeadMap $ inert_funeqs ics)) }
  532. | otherwise
  533. = pprPanic "upd_inert set: can't happen! Inserting " $
  534. ppr item -- Can't be CNonCanonical, CHoleCan,
  535. -- because they only land in inert_insols
  536. insertInertItemTcS :: Ct -> TcS ()
  537. -- Add a new item in the inerts of the monad
  538. insertInertItemTcS item
  539. = do { traceTcS "insertInertItemTcS {" $
  540. text "Trying to insert new inert item:" <+> ppr item
  541. ; updInertTcS (insertInertItem item)
  542. ; traceTcS "insertInertItemTcS }" $ empty }
  543. addSolvedDict :: CtEvidence -> TcS ()
  544. -- Add a new item in the solved set of the monad
  545. addSolvedDict item
  546. | isIPPred (ctEvPred item) -- Never cache "solved" implicit parameters (not sure why!)
  547. = return ()
  548. | otherwise
  549. = do { traceTcS "updSolvedSetTcs:" $ ppr item
  550. ; updInertTcS upd_solved_dicts }
  551. where
  552. upd_solved_dicts is
  553. = is { inert_solved_dicts = PredMap $ insertTM pred item $
  554. unPredMap $ inert_solved_dicts is }
  555. pred = ctEvPred item
  556. addSolvedFunEq :: TcType -> CtEvidence -> TcType -> TcS ()
  557. addSolvedFunEq fam_ty ev rhs_ty
  558. = updInertTcS $ \ inert ->
  559. inert { inert_solved_funeqs = insertFamHead (inert_solved_funeqs inert)
  560. fam_ty (ev, rhs_ty) }
  561. modifyInertTcS :: (InertSet -> (a,InertSet)) -> TcS a
  562. -- Modify the inert set with the supplied function
  563. modifyInertTcS upd
  564. = do { is_var <- getTcSInertsRef
  565. ; curr_inert <- wrapTcS (TcM.readTcRef is_var)
  566. ; let (a, new_inert) = upd curr_inert
  567. ; wrapTcS (TcM.writeTcRef is_var new_inert)
  568. ; return a }
  569. updInertTcS :: (InertSet -> InertSet) -> TcS ()
  570. -- Modify the inert set with the supplied function
  571. updInertTcS upd
  572. = do { is_var <- getTcSInertsRef
  573. ; curr_inert <- wrapTcS (TcM.readTcRef is_var)
  574. ; let new_inert = upd curr_inert
  575. ; wrapTcS (TcM.writeTcRef is_var new_inert) }
  576. prepareInertsForImplications :: InertSet -> InertSet
  577. -- See Note [Preparing inert set for implications]
  578. prepareInertsForImplications is
  579. = is { inert_cans = getGivens (inert_cans is)
  580. , inert_fsks = []
  581. , inert_flat_cache = emptyFamHeadMap }
  582. where
  583. getGivens (IC { inert_eqs = eqs
  584. , inert_irreds = irreds
  585. , inert_funeqs = FamHeadMap funeqs
  586. , inert_dicts = dicts })
  587. = IC { inert_eqs = filterVarEnv_Directly (\_ ct -> isGivenCt ct) eqs
  588. , inert_funeqs = FamHeadMap (foldTM given_from_wanted funeqs emptyTM)
  589. , inert_irreds = Bag.filterBag isGivenCt irreds
  590. , inert_dicts = keepGivenCMap dicts
  591. , inert_insols = emptyCts }
  592. given_from_wanted :: Ct -> TypeMap Ct -> TypeMap Ct
  593. given_from_wanted funeq fhm -- This is where the magic processing happens
  594. -- for type-function equalities
  595. -- See Note [Preparing inert set for implications]
  596. | isWanted ev = insert_one (funeq { cc_ev = given_ev }) fhm
  597. | isGiven ev = insert_one funeq fhm
  598. | otherwise = fhm -- Drop derived constraints
  599. where
  600. ev = ctEvidence funeq
  601. given_ev = CtGiven { ctev_evtm = EvId (ctev_evar ev)
  602. , ctev_pred = ctev_pred ev }
  603. insert_one :: Ct -> TypeMap Ct -> TypeMap Ct
  604. insert_one funeq fhm = insertTM (funEqHead funeq) funeq fhm
  605. \end{code}
  606. Note [Preparing inert set for implications]
  607. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  608. Before solving the nested implications, we trim the inert set,
  609. retaining only Givens. These givens can be used when solving
  610. the inner implications.
  611. With one wrinkle! We take all *wanted* *funeqs*, and turn them into givens.
  612. Consider (Trac #4935)
  613. type instance F True a b = a
  614. type instance F False a b = b
  615. [w] F c a b ~ gamma
  616. (c ~ True) => a ~ gamma
  617. (c ~ False) => b ~ gamma
  618. Obviously this is soluble with gamma := F c a b. But
  619. Since solveCTyFunEqs happens at the very end of solving, the only way
  620. to solve the two implications is temporarily consider (F c a b ~ gamma)
  621. as Given and push it inside the implications. Now, when we come
  622. out again at the end, having solved the implications solveCTyFunEqs
  623. will solve this equality.
  624. Turning type-function equalities into Givens is easy becase they
  625. *stay inert*. No need to re-process them.
  626. We don't try to turn any *other* Wanteds into Givens:
  627. * For example, we should not push given dictionaries in because
  628. of example LongWayOverlapping.hs, where we might get strange
  629. overlap errors between far-away constraints in the program.
  630. There might be cases where interactions between wanteds can help
  631. to solve a constraint. For example
  632. class C a b | a -> b
  633. (C Int alpha), (forall d. C d blah => C Int a)
  634. If we push the (C Int alpha) inwards, as a given, it can produce a
  635. fundep (alpha~a) and this can float out again and be used to fix
  636. alpha. (In general we can't float class constraints out just in case
  637. (C d blah) might help to solve (C Int a).) But we ignore this possiblity.
  638. For Derived constraints we don't have evidence, so we do not turn
  639. them into Givens. There can *be* deriving CFunEqCans; see Trac #8129.
  640. \begin{code}
  641. getInertEqs :: TcS (TyVarEnv Ct)
  642. getInertEqs = do { inert <- getTcSInerts
  643. ; return (inert_eqs (inert_cans inert)) }
  644. getInertUnsolved :: TcS (Cts, Cts)
  645. -- Return (unsolved-wanteds, insolubles)
  646. -- Both consist of a mixture of Wanted and Derived
  647. getInertUnsolved
  648. = do { is <- getTcSInerts
  649. ; let icans = inert_cans is
  650. unsolved_irreds = Bag.filterBag is_unsolved (inert_irreds icans)
  651. unsolved_dicts = extractUnsolvedCMap (inert_dicts icans)
  652. (unsolved_funeqs,_) = partCtFamHeadMap is_unsolved (inert_funeqs icans)
  653. unsolved_eqs = foldVarEnv add_if_unsolved emptyCts (inert_eqs icans)
  654. unsolved_flats = unsolved_eqs `unionBags` unsolved_irreds `unionBags`
  655. unsolved_dicts `unionBags` unsolved_funeqs
  656. ; return (unsolved_flats, inert_insols icans) }
  657. where
  658. add_if_unsolved ct cts
  659. | is_unsolved ct = cts `extendCts` ct
  660. | otherwise = cts
  661. is_unsolved ct = not (isGivenCt ct) -- Wanted or Derived
  662. checkAllSolved :: TcS Bool
  663. -- True if there are no unsolved wanteds
  664. -- Ignore Derived for this purpose, unless in insolubles
  665. checkAllSolved
  666. = do { is <- getTcSInerts
  667. ; let icans = inert_cans is
  668. unsolved_irreds = Bag.anyBag isWantedCt (inert_irreds icans)
  669. unsolved_dicts = not (isNullUFM (cts_wanted (inert_dicts icans)))
  670. unsolved_funeqs = anyFamHeadMap isWantedCt (inert_funeqs icans)
  671. unsolved_eqs = foldVarEnv ((||) . isWantedCt) False (inert_eqs icans)
  672. ; return (not (unsolved_eqs || unsolved_irreds
  673. || unsolved_dicts || unsolved_funeqs
  674. || not (isEmptyBag (inert_insols icans)))) }
  675. {- Get inert function equation constraints that have the given tycon
  676. in their head. Not that the constraints remain in the inert set.
  677. We use this to check for derived interactions with built-in type-function
  678. constructors. -}
  679. getInertsFunEqTyCon :: TyCon -> TcS [Ct]
  680. getInertsFunEqTyCon tc =
  681. do is <- getTcSInerts
  682. let mp = unFamHeadMap $ inert_funeqs $ inert_cans is
  683. return $ lookupTypeMapTyCon mp tc
  684. extractRelevantInerts :: Ct -> TcS Cts
  685. -- Returns the constraints from the inert set that are 'relevant' to react with
  686. -- this constraint. The monad is left with the 'thinner' inerts.
  687. -- NB: This function contains logic specific to the constraint solver, maybe move there?
  688. extractRelevantInerts wi
  689. = modifyInertTcS (extract_relevants wi)
  690. where
  691. extract_relevants :: Ct -> InertSet -> (Cts,InertSet)
  692. extract_relevants wi is
  693. = let (cts,ics') = extract_ics_relevants wi (inert_cans is)
  694. in (cts, is { inert_cans = ics' })
  695. extract_ics_relevants :: Ct -> InertCans -> (Cts, InertCans)
  696. extract_ics_relevants (CDictCan {cc_class = cl}) ics =
  697. let (cts,dict_map) = getRelevantCts cl (inert_dicts ics)
  698. in (cts, ics { inert_dicts = dict_map })
  699. extract_ics_relevants (CFunEqCan { cc_fun = tc, cc_tyargs = tys })
  700. ics@(IC { inert_funeqs = funeq_map })
  701. | let fam_head = mkTyConApp tc tys
  702. , Just ct <- lookupFamHead funeq_map fam_head
  703. = (singleCt ct, ics { inert_funeqs = delFamHead funeq_map fam_head })
  704. extract_ics_relevants (CHoleCan {}) ics
  705. = pprPanic "extractRelevantInerts" (ppr wi)
  706. -- Holes are put straight into inert_frozen, so never get here
  707. extract_ics_relevants (CIrredEvCan { }) ics =
  708. let cts = inert_irreds ics
  709. in (cts, ics { inert_irreds = emptyCts })
  710. extract_ics_relevants _ ics = (emptyCts,ics)
  711. lookupFlatEqn :: TcType -> TcS (Maybe (CtEvidence, TcType))
  712. lookupFlatEqn fam_ty
  713. = do { IS { inert_solved_funeqs = solved_funeqs
  714. , inert_flat_cache = flat_cache
  715. , inert_cans = IC { inert_funeqs = inert_funeqs } } <- getTcSInerts
  716. ; return (lookupFamHead solved_funeqs fam_ty `firstJust`
  717. lookup_in_inerts inert_funeqs `firstJust`
  718. lookupFamHead flat_cache fam_ty) }
  719. where
  720. lookup_in_inerts inert_funeqs
  721. = case lookupFamHead inert_funeqs fam_ty of
  722. Nothing -> Nothing
  723. Just ct -> Just (ctEvidence ct, cc_rhs ct)
  724. lookupInInerts :: TcPredType -> TcS (Maybe CtEvidence)
  725. -- Is this exact predicate type cached in the solved or canonicals of the InertSet
  726. lookupInInerts pty
  727. = do { inerts <- getTcSInerts
  728. ; case lookupSolvedDict inerts pty of
  729. Just ctev -> return (Just ctev)
  730. Nothing -> return (lookupInInertCans inerts pty) }
  731. lookupSolvedDict :: InertSet -> TcPredType -> Maybe CtEvidence
  732. -- Returns just if exactly this predicate type exists in the solved.
  733. lookupSolvedDict (IS { inert_solved_dicts = solved }) pty
  734. = lookupTM pty (unPredMap solved)
  735. lookupInInertCans :: InertSet -> TcPredType -> Maybe CtEvidence
  736. -- Returns Just if exactly this pred type exists in the inert canonicals
  737. lookupInInertCans (IS { inert_cans = ics }) pty
  738. = case (classifyPredType pty) of
  739. ClassPred cls _
  740. -> lookupCCanMap cls (\ct -> ctEvPred ct `eqType` pty) (inert_dicts ics)
  741. EqPred ty1 _ty2
  742. | Just tv <- getTyVar_maybe ty1 -- Tyvar equation
  743. , Just ct <- lookupVarEnv (inert_eqs ics) tv
  744. , let ctev = ctEvidence ct
  745. , ctEvPred ctev `eqType` pty
  746. -> Just ctev
  747. | Just _ <- splitTyConApp_maybe ty1 -- Family equation
  748. , Just ct <- lookupTM ty1 (unFamHeadMap $ inert_funeqs ics)
  749. , let ctev = ctEvidence ct
  750. , ctEvPred ctev `eqType` pty
  751. -> Just ctev
  752. IrredPred {} -> findEvidence (\ct -> ctEvPred ct `eqType` pty) (inert_irreds ics)
  753. _other -> Nothing -- NB: No caching for IPs or holes
  754. \end{code}
  755. %************************************************************************
  756. %* *
  757. %* The TcS solver monad *
  758. %* *
  759. %************************************************************************
  760. Note [The TcS monad]
  761. ~~~~~~~~~~~~~~~~~~~~
  762. The TcS monad is a weak form of the main Tc monad
  763. All you can do is
  764. * fail
  765. * allocate new variables
  766. * fill in evidence variables
  767. Filling in a dictionary evidence variable means to create a binding
  768. for it, so TcS carries a mutable location where the binding can be
  769. added. This is initialised from the innermost implication constraint.
  770. \begin{code}
  771. data TcSEnv
  772. = TcSEnv {
  773. tcs_ev_binds :: EvBindsVar,
  774. tcs_ty_binds :: IORef (TyVarEnv (TcTyVar, TcType)),
  775. -- Global type bindings
  776. tcs_count :: IORef Int, -- Global step count
  777. tcs_inerts :: IORef InertSet, -- Current inert set
  778. tcs_worklist :: IORef WorkList, -- Current worklist
  779. -- Residual implication constraints that are generated
  780. -- while solving or canonicalising the current worklist.
  781. -- Specifically, when canonicalising (forall a. t1 ~ forall a. t2)
  782. -- from which we get the implication (forall a. t1 ~ t2)
  783. tcs_implics :: IORef (Bag Implication)
  784. }
  785. \end{code}
  786. \begin{code}
  787. ---------------
  788. newtype TcS a = TcS { unTcS :: TcSEnv -> TcM a }
  789. instance Functor TcS where
  790. fmap f m = TcS $ fmap f . unTcS m
  791. instance Monad TcS where
  792. return x = TcS (\_ -> return x)
  793. fail err = TcS (\_ -> fail err)
  794. m >>= k = TcS (\ebs -> unTcS m ebs >>= \r -> unTcS (k r) ebs)
  795. -- Basic functionality
  796. -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  797. wrapTcS :: TcM a -> TcS a
  798. -- Do not export wrapTcS, because it promotes an arbitrary TcM to TcS,
  799. -- and TcS is supposed to have limited functionality
  800. wrapTcS = TcS . const -- a TcM action will not use the TcEvBinds
  801. wrapErrTcS :: TcM a -> TcS a
  802. -- The thing wrapped should just fail
  803. -- There's no static check; it's up to the user
  804. -- Having a variant for each error message is too painful
  805. wrapErrTcS = wrapTcS
  806. wrapWarnTcS :: TcM a -> TcS a
  807. -- The thing wrapped should just add a warning, or no-op
  808. -- There's no static check; it's up to the user
  809. wrapWarnTcS = wrapTcS
  810. failTcS, panicTcS :: SDoc -> TcS a
  811. failTcS = wrapTcS . TcM.failWith
  812. panicTcS doc = pprPanic "TcCanonical" doc
  813. traceTcS :: String -> SDoc -> TcS ()
  814. traceTcS herald doc = wrapTcS (TcM.traceTc herald doc)
  815. instance HasDynFlags TcS where
  816. getDynFlags = wrapTcS getDynFlags
  817. getGlobalRdrEnvTcS :: TcS GlobalRdrEnv
  818. getGlobalRdrEnvTcS = wrapTcS TcM.getGlobalRdrEnv
  819. bumpStepCountTcS :: TcS ()
  820. bumpStepCountTcS = TcS $ \env -> do { let ref = tcs_count env
  821. ; n <- TcM.readTcRef ref
  822. ; TcM.writeTcRef ref (n+1) }
  823. traceFireTcS :: Ct -> SDoc -> TcS ()
  824. -- Dump a rule-firing trace
  825. traceFireTcS ct doc
  826. = TcS $ \env ->
  827. TcM.whenDOptM Opt_D_dump_cs_trace $
  828. do { n <- TcM.readTcRef (tcs_count env)
  829. ; let msg = int n <> brackets (int (ctLocDepth (cc_loc ct))) <+> doc
  830. ; TcM.dumpTcRn msg }
  831. runTcS :: TcS a -- What to run
  832. -> TcM (a, Bag EvBind)
  833. runTcS tcs
  834. = do { ev_binds_var <- TcM.newTcEvBinds
  835. ; res <- runTcSWithEvBinds ev_binds_var tcs
  836. ; ev_binds <- TcM.getTcEvBinds ev_binds_var
  837. ; return (res, ev_binds) }
  838. runTcSWithEvBinds :: EvBindsVar
  839. -> TcS a
  840. -> TcM a
  841. runTcSWithEvBinds ev_binds_var tcs
  842. = do { ty_binds_var <- TcM.newTcRef emptyVarEnv
  843. ; step_count <- TcM.newTcRef 0
  844. ; inert_var <- TcM.newTcRef is
  845. ; let env = TcSEnv { tcs_ev_binds = ev_binds_var
  846. , tcs_ty_binds = ty_binds_var
  847. , tcs_count = step_count
  848. , tcs_inerts = inert_var
  849. , tcs_worklist = panic "runTcS: worklist"
  850. , tcs_implics = panic "runTcS: implics" }
  851. -- NB: Both these are initialised by withWorkList
  852. -- Run the computation
  853. ; res <- unTcS tcs env
  854. -- Perform the type unifications required
  855. ; ty_binds <- TcM.readTcRef ty_binds_var
  856. ; mapM_ do_unification (varEnvElts ty_binds)
  857. #ifdef DEBUG
  858. ; count <- TcM.readTcRef step_count
  859. ; when (opt_PprStyle_Debug && count > 0) $
  860. TcM.debugDumpTcRn (ptext (sLit "Constraint solver steps =") <+> int count )
  861. ; ev_binds <- TcM.getTcEvBinds ev_binds_var
  862. ; checkForCyclicBinds ev_binds
  863. #endif
  864. ; return res }
  865. where
  866. do_unification (tv,ty) = TcM.writeMetaTyVar tv ty
  867. is = emptyInert
  868. #ifdef DEBUG
  869. checkForCyclicBinds :: Bag EvBind -> TcM ()
  870. checkForCyclicBinds ev_binds
  871. | null cycles
  872. = return ()
  873. | null coercion_cycles
  874. = TcM.traceTc "Cycle in evidence binds" $ ppr cycles
  875. | otherwise
  876. = pprPanic "Cycle in coercion bindings" $ ppr coercion_cycles
  877. where
  878. cycles :: [[EvBind]]
  879. cycles = [c | CyclicSCC c <- stronglyConnCompFromEdgedVertices edges]
  880. coercion_cycles = [c | c <- cycles, any is_co_bind c]
  881. is_co_bind (EvBind b _) = isEqVar b
  882. edges :: [(EvBind, EvVar, [EvVar])]
  883. edges = [(bind, bndr, varSetElems (evVarsOfTerm rhs)) | bind@(EvBind bndr rhs) <- bagToList ev_binds]
  884. #endif
  885. nestImplicTcS :: EvBindsVar -> Untouchables -> InertSet -> TcS a -> TcS a
  886. nestImplicTcS ref inner_untch inerts (TcS thing_inside)
  887. = TcS $ \ TcSEnv { tcs_ty_binds = ty_binds
  888. , tcs_count = count } ->
  889. do { new_inert_var <- TcM.newTcRef inerts
  890. ; let nest_env = TcSEnv { tcs_ev_binds = ref
  891. , tcs_ty_binds = ty_binds
  892. , tcs_count = count
  893. , tcs_inerts = new_inert_var
  894. , tcs_worklist = panic "nextImplicTcS: worklist"
  895. , tcs_implics = panic "nextImplicTcS: implics"
  896. -- NB: Both these are initialised by withWorkList
  897. }
  898. ; res <- TcM.setUntouchables inner_untch $
  899. thing_inside nest_env
  900. #ifdef DEBUG
  901. -- Perform a check that the thing_inside did not cause cycles
  902. ; ev_binds <- TcM.getTcEvBinds ref
  903. ; checkForCyclicBinds ev_binds
  904. #endif
  905. ; return res }
  906. recoverTcS :: TcS a -> TcS a -> TcS a
  907. recoverTcS (TcS recovery_code) (TcS thing_inside)
  908. = TcS $ \ env ->
  909. TcM.recoverM (recovery_code env) (thing_inside env)
  910. nestTcS :: TcS a -> TcS a
  911. -- Use the current untouchables, augmenting the current
  912. -- evidence bindings, ty_binds, and solved caches
  913. -- But have no effect on the InertCans or insolubles
  914. nestTcS (TcS thing_inside)
  915. = TcS $ \ env@(TcSEnv { tcs_inerts = inerts_var }) ->
  916. do { inerts <- TcM.readTcRef inerts_var
  917. ; new_inert_var <- TcM.newTcRef inerts
  918. ; let nest_env = env { tcs_inerts = new_inert_var
  919. , tcs_worklist = panic "nextImplicTcS: worklist"
  920. , tcs_implics = panic "nextImplicTcS: implics" }
  921. ; thing_inside nest_env }
  922. tryTcS :: TcS a -> TcS a
  923. -- Like runTcS, but from within the TcS monad
  924. -- Completely afresh inerts and worklist, be careful!
  925. -- Moreover, we will simply throw away all the evidence generated.
  926. tryTcS (TcS thing_inside)
  927. = TcS $ \env ->
  928. do { is_var <- TcM.newTcRef emptyInert
  929. ; ty_binds_var <- TcM.newTcRef emptyVarEnv
  930. ; ev_binds_var <- TcM.newTcEvBinds
  931. ; let nest_env = env { tcs_ev_binds = ev_binds_var
  932. , tcs_ty_binds = ty_binds_var
  933. , tcs_inerts = is_var
  934. , tcs_worklist = panic "nextImplicTcS: worklist"
  935. , tcs_implics = panic "nextImplicTcS: implics" }
  936. ; thing_inside nest_env }
  937. -- Getters and setters of TcEnv fields
  938. -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  939. -- Getter of inerts and worklist
  940. getTcSInertsRef :: TcS (IORef InertSet)
  941. getTcSInertsRef = TcS (return . tcs_inerts)
  942. getTcSWorkListRef :: TcS (IORef WorkList)
  943. getTcSWorkListRef = TcS (return . tcs_worklist)
  944. getTcSInerts :: TcS InertSet
  945. getTcSInerts = getTcSInertsRef >>= wrapTcS . (TcM.readTcRef)
  946. updWorkListTcS :: (WorkList -> WorkList) -> TcS ()
  947. updWorkListTcS f
  948. = do { wl_var <- getTcSWorkListRef
  949. ; wl_curr <- wrapTcS (TcM.readTcRef wl_var)
  950. ; let new_work = f wl_curr
  951. ; wrapTcS (TcM.writeTcRef wl_var new_work) }
  952. updWorkListTcS_return :: (WorkList -> (a,WorkList)) -> TcS a
  953. -- Process the work list, returning a depleted work list,
  954. -- plus a value extracted from it (typically a work item removed from it)
  955. updWorkListTcS_return f
  956. = do { wl_var <- getTcSWorkListRef
  957. ; wl_curr <- wrapTcS (TcM.readTcRef wl_var)
  958. ; let (res,new_work) = f wl_curr
  959. ; wrapTcS (TcM.writeTcRef wl_var new_work)
  960. ; return res }
  961. withWorkList :: Cts -> TcS () -> TcS (Bag Implication)
  962. -- Use 'thing_inside' to solve 'work_items', extending the
  963. -- ambient InertSet, and returning any residual implications
  964. -- (arising from polytype equalities)
  965. -- We do this with fresh work list and residual-implications variables
  966. withWorkList work_items (TcS thing_inside)
  967. = TcS $ \ tcs_env ->
  968. do { let init_work_list = foldrBag extendWorkListCt emptyWorkList work_items
  969. ; new_wl_var <- TcM.newTcRef init_work_list
  970. ; new_implics_var <- TcM.newTcRef emptyBag
  971. ; thing_inside (tcs_env { tcs_worklist = new_wl_var
  972. , tcs_implics = new_implics_var })
  973. ; final_wl <- TcM.readTcRef new_wl_var
  974. ; implics <- TcM.readTcRef new_implics_var
  975. ; ASSERT( isEmptyWorkList final_wl )
  976. return implics }
  977. updTcSImplics :: (Bag Implication -> Bag Implication) -> TcS ()
  978. updTcSImplics f
  979. = do { impl_ref <- getTcSImplicsRef
  980. ; wrapTcS $ do { implics <- TcM.readTcRef impl_ref
  981. ; TcM.writeTcRef impl_ref (f implics) } }
  982. emitInsoluble :: Ct -> TcS ()
  983. -- Emits a non-canonical constraint that will stand for a frozen error in the inerts.
  984. emitInsoluble ct
  985. = do { traceTcS "Emit insoluble" (ppr ct)
  986. ; updInertTcS add_insol }
  987. where
  988. this_pred = ctPred ct
  989. add_insol is@(IS { inert_cans = ics@(IC { inert_insols = old_insols }) })
  990. | already_there = is
  991. | otherwise = is { inert_cans = ics { inert_insols = extendCts old_insols ct } }
  992. where
  993. already_there = not (isWantedCt ct) && anyBag (eqType this_pred . ctPred) old_insols
  994. -- See Note [Do not add duplicate derived insolubles]
  995. getTcSImplicsRef :: TcS (IORef (Bag Implication))
  996. getTcSImplicsRef = TcS (return . tcs_implics)
  997. getTcEvBinds :: TcS EvBindsVar
  998. getTcEvBinds = TcS (return . tcs_ev_binds)
  999. getUntouchables :: TcS Untouchables
  1000. getUntouchables = wrapTcS TcM.getUntouchables
  1001. getFlattenSkols :: TcS [TcTyVar]
  1002. getFlattenSkols = do { is <- getTcSInerts; return (inert_fsks is) }
  1003. getTcSTyBinds :: TcS (IORef (TyVarEnv (TcTyVar, TcType)))
  1004. getTcSTyBinds = TcS (return . tcs_ty_binds)
  1005. getTcSTyBindsMap :: TcS (TyVarEnv (TcTyVar, TcType))
  1006. getTcSTyBindsMap = getTcSTyBinds >>= wrapTcS . (TcM.readTcRef)
  1007. getTcEvBindsMap :: TcS EvBindMap
  1008. getTcEvBindsMap
  1009. = do { EvBindsVar ev_ref _ <- getTcEvBinds
  1010. ; wrapTcS $ TcM.readTcRef ev_ref }
  1011. setWantedTyBind :: TcTyVar -> TcType -> TcS ()
  1012. -- Add a type binding
  1013. -- We never do this twice!
  1014. setWantedTyBind tv ty
  1015. = ASSERT2( isMetaTyVar tv, ppr tv )
  1016. do { ref <- getTcSTyBinds
  1017. ; wrapTcS $
  1018. do { ty_binds <- TcM.readTcRef ref
  1019. ; when debugIsOn $
  1020. TcM.checkErr (not (tv `elemVarEnv` ty_binds)) $
  1021. vcat [ text "TERRIBLE ERROR: double set of meta type variable"
  1022. , ppr tv <+> text ":=" <+> ppr ty
  1023. , text "Old value =" <+> ppr (lookupVarEnv_NF ty_binds tv)]
  1024. ; TcM.traceTc "setWantedTyBind" (ppr tv <+> text ":=" <+> ppr ty)
  1025. ; TcM.writeTcRef ref (extendVarEnv ty_binds tv (tv,ty)) } }
  1026. \end{code}
  1027. \begin{code}
  1028. getDefaultInfo :: TcS ([Type], (Bool, Bool))
  1029. getDefaultInfo = wrapTcS TcM.tcGetDefaultTys
  1030. -- Just get some environments needed for instance looking up and matching
  1031. -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1032. getInstEnvs :: TcS (InstEnv, InstEnv)
  1033. getInstEnvs = wrapTcS $ Inst.tcGetInstEnvs
  1034. getFamInstEnvs :: TcS (FamInstEnv, FamInstEnv)
  1035. getFamInstEnvs = wrapTcS $ FamInst.tcG

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