PageRenderTime 32ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

/compiler/typecheck/TcSMonad.lhs

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

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