PageRenderTime 84ms CodeModel.GetById 21ms 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

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://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_st

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