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

/compiler/typecheck/TcEvidence.hs

http://github.com/ghc/ghc
Haskell | 828 lines | 363 code | 101 blank | 364 comment | 6 complexity | 1f808bd4f69b1a8eb9b2c8ab3e858af3 MD5 | raw file
Possible License(s): MIT, BSD-3-Clause, GPL-3.0
  1. -- (c) The University of Glasgow 2006
  2. {-# LANGUAGE CPP, DeriveDataTypeable #-}
  3. module TcEvidence (
  4. -- HsWrapper
  5. HsWrapper(..),
  6. (<.>), mkWpTyApps, mkWpEvApps, mkWpEvVarApps, mkWpTyLams,
  7. mkWpLams, mkWpLet, mkWpCastN, mkWpCastR,
  8. mkWpFun, mkWpFuns, idHsWrapper, isIdHsWrapper, pprHsWrapper,
  9. -- Evidence bindings
  10. TcEvBinds(..), EvBindsVar(..),
  11. EvBindMap(..), emptyEvBindMap, extendEvBinds,
  12. lookupEvBind, evBindMapBinds, foldEvBindMap,
  13. EvBind(..), emptyTcEvBinds, isEmptyTcEvBinds, mkGivenEvBind, mkWantedEvBind,
  14. sccEvBinds, evBindVar,
  15. EvTerm(..), mkEvCast, evVarsOfTerm, mkEvScSelectors,
  16. EvLit(..), evTermCoercion,
  17. EvCallStack(..),
  18. EvTypeable(..),
  19. -- TcCoercion
  20. TcCoercion, TcCoercionR, TcCoercionN, TcCoercionP, CoercionHole,
  21. Role(..), LeftOrRight(..), pickLR,
  22. mkTcReflCo, mkTcNomReflCo, mkTcRepReflCo,
  23. mkTcTyConAppCo, mkTcAppCo, mkTcFunCo,
  24. mkTcAxInstCo, mkTcUnbranchedAxInstCo, mkTcForAllCo, mkTcForAllCos,
  25. mkTcSymCo, mkTcTransCo, mkTcNthCo, mkTcLRCo, mkTcSubCo, maybeTcSubCo,
  26. tcDowngradeRole,
  27. mkTcAxiomRuleCo, mkTcCoherenceLeftCo, mkTcCoherenceRightCo, mkTcPhantomCo,
  28. mkTcKindCo,
  29. tcCoercionKind, coVarsOfTcCo,
  30. mkTcCoVarCo,
  31. isTcReflCo,
  32. tcCoercionRole,
  33. unwrapIP, wrapIP
  34. ) where
  35. #include "HsVersions.h"
  36. import Var
  37. import CoAxiom
  38. import Coercion
  39. import PprCore () -- Instance OutputableBndr TyVar
  40. import TcType
  41. import Type
  42. import TyCon
  43. import Class( Class )
  44. import PrelNames
  45. import DynFlags ( gopt, GeneralFlag(Opt_PrintTypecheckerElaboration) )
  46. import VarEnv
  47. import VarSet
  48. import Name
  49. import Pair
  50. import Util
  51. import Bag
  52. import Digraph
  53. import qualified Data.Data as Data
  54. import Outputable
  55. import FastString
  56. import SrcLoc
  57. import Data.IORef( IORef )
  58. import UniqFM
  59. {-
  60. Note [TcCoercions]
  61. ~~~~~~~~~~~~~~~~~~
  62. | TcCoercions are a hack used by the typechecker. Normally,
  63. Coercions have free variables of type (a ~# b): we call these
  64. CoVars. However, the type checker passes around equality evidence
  65. (boxed up) at type (a ~ b).
  66. An TcCoercion is simply a Coercion whose free variables have may be either
  67. boxed or unboxed. After we are done with typechecking the desugarer finds the
  68. boxed free variables, unboxes them, and creates a resulting real Coercion with
  69. kosher free variables.
  70. -}
  71. type TcCoercion = Coercion
  72. type TcCoercionN = CoercionN -- A Nominal coercion ~N
  73. type TcCoercionR = CoercionR -- A Representational coercion ~R
  74. type TcCoercionP = CoercionP -- a phantom coercion
  75. mkTcReflCo :: Role -> TcType -> TcCoercion
  76. mkTcSymCo :: TcCoercion -> TcCoercion
  77. mkTcTransCo :: TcCoercion -> TcCoercion -> TcCoercion
  78. mkTcNomReflCo :: TcType -> TcCoercionN
  79. mkTcRepReflCo :: TcType -> TcCoercionR
  80. mkTcTyConAppCo :: Role -> TyCon -> [TcCoercion] -> TcCoercion
  81. mkTcAppCo :: TcCoercion -> TcCoercionN -> TcCoercion
  82. mkTcFunCo :: Role -> TcCoercion -> TcCoercion -> TcCoercion
  83. mkTcAxInstCo :: Role -> CoAxiom br -> BranchIndex
  84. -> [TcType] -> [TcCoercion] -> TcCoercion
  85. mkTcUnbranchedAxInstCo :: CoAxiom Unbranched -> [TcType]
  86. -> [TcCoercion] -> TcCoercionR
  87. mkTcForAllCo :: TyVar -> TcCoercionN -> TcCoercion -> TcCoercion
  88. mkTcForAllCos :: [(TyVar, TcCoercionN)] -> TcCoercion -> TcCoercion
  89. mkTcNthCo :: Int -> TcCoercion -> TcCoercion
  90. mkTcLRCo :: LeftOrRight -> TcCoercion -> TcCoercion
  91. mkTcSubCo :: TcCoercionN -> TcCoercionR
  92. maybeTcSubCo :: EqRel -> TcCoercion -> TcCoercion
  93. tcDowngradeRole :: Role -> Role -> TcCoercion -> TcCoercion
  94. mkTcAxiomRuleCo :: CoAxiomRule -> [TcCoercion] -> TcCoercionR
  95. mkTcCoherenceLeftCo :: TcCoercion -> TcCoercionN -> TcCoercion
  96. mkTcCoherenceRightCo :: TcCoercion -> TcCoercionN -> TcCoercion
  97. mkTcPhantomCo :: TcCoercionN -> TcType -> TcType -> TcCoercionP
  98. mkTcKindCo :: TcCoercion -> TcCoercionN
  99. mkTcCoVarCo :: CoVar -> TcCoercion
  100. tcCoercionKind :: TcCoercion -> Pair TcType
  101. tcCoercionRole :: TcCoercion -> Role
  102. coVarsOfTcCo :: TcCoercion -> TcTyCoVarSet
  103. isTcReflCo :: TcCoercion -> Bool
  104. mkTcReflCo = mkReflCo
  105. mkTcSymCo = mkSymCo
  106. mkTcTransCo = mkTransCo
  107. mkTcNomReflCo = mkNomReflCo
  108. mkTcRepReflCo = mkRepReflCo
  109. mkTcTyConAppCo = mkTyConAppCo
  110. mkTcAppCo = mkAppCo
  111. mkTcFunCo = mkFunCo
  112. mkTcAxInstCo = mkAxInstCo
  113. mkTcUnbranchedAxInstCo = mkUnbranchedAxInstCo Representational
  114. mkTcForAllCo = mkForAllCo
  115. mkTcForAllCos = mkForAllCos
  116. mkTcNthCo = mkNthCo
  117. mkTcLRCo = mkLRCo
  118. mkTcSubCo = mkSubCo
  119. maybeTcSubCo = maybeSubCo
  120. tcDowngradeRole = downgradeRole
  121. mkTcAxiomRuleCo = mkAxiomRuleCo
  122. mkTcCoherenceLeftCo = mkCoherenceLeftCo
  123. mkTcCoherenceRightCo = mkCoherenceRightCo
  124. mkTcPhantomCo = mkPhantomCo
  125. mkTcKindCo = mkKindCo
  126. mkTcCoVarCo = mkCoVarCo
  127. tcCoercionKind = coercionKind
  128. tcCoercionRole = coercionRole
  129. coVarsOfTcCo = coVarsOfCo
  130. isTcReflCo = isReflCo
  131. {-
  132. %************************************************************************
  133. %* *
  134. HsWrapper
  135. * *
  136. ************************************************************************
  137. -}
  138. data HsWrapper
  139. = WpHole -- The identity coercion
  140. | WpCompose HsWrapper HsWrapper
  141. -- (wrap1 `WpCompose` wrap2)[e] = wrap1[ wrap2[ e ]]
  142. --
  143. -- Hence (\a. []) `WpCompose` (\b. []) = (\a b. [])
  144. -- But ([] a) `WpCompose` ([] b) = ([] b a)
  145. | WpFun HsWrapper HsWrapper TcType
  146. -- (WpFun wrap1 wrap2 t1)[e] = \(x:t1). wrap2[ e wrap1[x] ]
  147. -- So note that if wrap1 :: exp_arg <= act_arg
  148. -- wrap2 :: act_res <= exp_res
  149. -- then WpFun wrap1 wrap2 : (act_arg -> arg_res) <= (exp_arg -> exp_res)
  150. -- This isn't the same as for mkFunCo, but it has to be this way
  151. -- because we can't use 'sym' to flip around these HsWrappers
  152. -- The TcType is the "from" type of the first wrapper
  153. | WpCast TcCoercionR -- A cast: [] `cast` co
  154. -- Guaranteed not the identity coercion
  155. -- At role Representational
  156. -- Evidence abstraction and application
  157. -- (both dictionaries and coercions)
  158. | WpEvLam EvVar -- \d. [] the 'd' is an evidence variable
  159. | WpEvApp EvTerm -- [] d the 'd' is evidence for a constraint
  160. -- Kind and Type abstraction and application
  161. | WpTyLam TyVar -- \a. [] the 'a' is a type/kind variable (not coercion var)
  162. | WpTyApp KindOrType -- [] t the 't' is a type (not coercion)
  163. | WpLet TcEvBinds -- Non-empty (or possibly non-empty) evidence bindings,
  164. -- so that the identity coercion is always exactly WpHole
  165. deriving Data.Data
  166. (<.>) :: HsWrapper -> HsWrapper -> HsWrapper
  167. WpHole <.> c = c
  168. c <.> WpHole = c
  169. c1 <.> c2 = c1 `WpCompose` c2
  170. mkWpFun :: HsWrapper -> HsWrapper
  171. -> TcType -- the "from" type of the first wrapper
  172. -> TcType -- either type of the second wrapper (used only when the
  173. -- second wrapper is the identity)
  174. -> HsWrapper
  175. mkWpFun WpHole WpHole _ _ = WpHole
  176. mkWpFun WpHole (WpCast co2) t1 _ = WpCast (mkTcFunCo Representational (mkTcRepReflCo t1) co2)
  177. mkWpFun (WpCast co1) WpHole _ t2 = WpCast (mkTcFunCo Representational (mkTcSymCo co1) (mkTcRepReflCo t2))
  178. mkWpFun (WpCast co1) (WpCast co2) _ _ = WpCast (mkTcFunCo Representational (mkTcSymCo co1) co2)
  179. mkWpFun co1 co2 t1 _ = WpFun co1 co2 t1
  180. -- | @mkWpFuns [(ty1, wrap1), (ty2, wrap2)] ty_res wrap_res@,
  181. -- where @wrap1 :: ty1 "->" ty1'@ and @wrap2 :: ty2 "->" ty2'@,
  182. -- @wrap3 :: ty3 "->" ty3'@ and @ty_res@ is /either/ @ty3@ or @ty3'@,
  183. -- gives a wrapper @(ty1' -> ty2' -> ty3) "->" (ty1 -> ty2 -> ty3')@.
  184. -- Notice that the result wrapper goes the other way round to all
  185. -- the others. This is a result of sub-typing contravariance.
  186. mkWpFuns :: [(TcType, HsWrapper)] -> TcType -> HsWrapper -> HsWrapper
  187. mkWpFuns args res_ty res_wrap = snd $ go args res_ty res_wrap
  188. where
  189. go [] res_ty res_wrap = (res_ty, res_wrap)
  190. go ((arg_ty, arg_wrap) : args) res_ty res_wrap
  191. = let (tail_ty, tail_wrap) = go args res_ty res_wrap in
  192. (arg_ty `mkFunTy` tail_ty, mkWpFun arg_wrap tail_wrap arg_ty tail_ty)
  193. mkWpCastR :: TcCoercionR -> HsWrapper
  194. mkWpCastR co
  195. | isTcReflCo co = WpHole
  196. | otherwise = ASSERT2(tcCoercionRole co == Representational, ppr co)
  197. WpCast co
  198. mkWpCastN :: TcCoercionN -> HsWrapper
  199. mkWpCastN co
  200. | isTcReflCo co = WpHole
  201. | otherwise = ASSERT2(tcCoercionRole co == Nominal, ppr co)
  202. WpCast (mkTcSubCo co)
  203. -- The mkTcSubCo converts Nominal to Representational
  204. mkWpTyApps :: [Type] -> HsWrapper
  205. mkWpTyApps tys = mk_co_app_fn WpTyApp tys
  206. mkWpEvApps :: [EvTerm] -> HsWrapper
  207. mkWpEvApps args = mk_co_app_fn WpEvApp args
  208. mkWpEvVarApps :: [EvVar] -> HsWrapper
  209. mkWpEvVarApps vs = mk_co_app_fn WpEvApp (map EvId vs)
  210. mkWpTyLams :: [TyVar] -> HsWrapper
  211. mkWpTyLams ids = mk_co_lam_fn WpTyLam ids
  212. mkWpLams :: [Var] -> HsWrapper
  213. mkWpLams ids = mk_co_lam_fn WpEvLam ids
  214. mkWpLet :: TcEvBinds -> HsWrapper
  215. -- This no-op is a quite a common case
  216. mkWpLet (EvBinds b) | isEmptyBag b = WpHole
  217. mkWpLet ev_binds = WpLet ev_binds
  218. mk_co_lam_fn :: (a -> HsWrapper) -> [a] -> HsWrapper
  219. mk_co_lam_fn f as = foldr (\x wrap -> f x <.> wrap) WpHole as
  220. mk_co_app_fn :: (a -> HsWrapper) -> [a] -> HsWrapper
  221. -- For applications, the *first* argument must
  222. -- come *last* in the composition sequence
  223. mk_co_app_fn f as = foldr (\x wrap -> wrap <.> f x) WpHole as
  224. idHsWrapper :: HsWrapper
  225. idHsWrapper = WpHole
  226. isIdHsWrapper :: HsWrapper -> Bool
  227. isIdHsWrapper WpHole = True
  228. isIdHsWrapper _ = False
  229. {-
  230. ************************************************************************
  231. * *
  232. Evidence bindings
  233. * *
  234. ************************************************************************
  235. -}
  236. data TcEvBinds
  237. = TcEvBinds -- Mutable evidence bindings
  238. EvBindsVar -- Mutable because they are updated "later"
  239. -- when an implication constraint is solved
  240. | EvBinds -- Immutable after zonking
  241. (Bag EvBind)
  242. data EvBindsVar = EvBindsVar (IORef EvBindMap) Unique
  243. -- The Unique is for debug printing only
  244. instance Data.Data TcEvBinds where
  245. -- Placeholder; we can't travers into TcEvBinds
  246. toConstr _ = abstractConstr "TcEvBinds"
  247. gunfold _ _ = error "gunfold"
  248. dataTypeOf _ = Data.mkNoRepType "TcEvBinds"
  249. -----------------
  250. newtype EvBindMap
  251. = EvBindMap {
  252. ev_bind_varenv :: DVarEnv EvBind
  253. } -- Map from evidence variables to evidence terms
  254. -- We use @DVarEnv@ here to get deterministic ordering when we
  255. -- turn it into a Bag.
  256. -- If we don't do that, when we generate let bindings for
  257. -- dictionaries in dsTcEvBinds they will be generated in random
  258. -- order.
  259. --
  260. -- For example:
  261. --
  262. -- let $dEq = GHC.Classes.$fEqInt in
  263. -- let $$dNum = GHC.Num.$fNumInt in ...
  264. --
  265. -- vs
  266. --
  267. -- let $dNum = GHC.Num.$fNumInt in
  268. -- let $dEq = GHC.Classes.$fEqInt in ...
  269. --
  270. -- See Note [Deterministic UniqFM] in UniqDFM for explanation why
  271. -- @UniqFM@ can lead to nondeterministic order.
  272. emptyEvBindMap :: EvBindMap
  273. emptyEvBindMap = EvBindMap { ev_bind_varenv = emptyDVarEnv }
  274. extendEvBinds :: EvBindMap -> EvBind -> EvBindMap
  275. extendEvBinds bs ev_bind
  276. = EvBindMap { ev_bind_varenv = extendDVarEnv (ev_bind_varenv bs)
  277. (eb_lhs ev_bind)
  278. ev_bind }
  279. lookupEvBind :: EvBindMap -> EvVar -> Maybe EvBind
  280. lookupEvBind bs = lookupDVarEnv (ev_bind_varenv bs)
  281. evBindMapBinds :: EvBindMap -> Bag EvBind
  282. evBindMapBinds = foldEvBindMap consBag emptyBag
  283. foldEvBindMap :: (EvBind -> a -> a) -> a -> EvBindMap -> a
  284. foldEvBindMap k z bs = foldDVarEnv k z (ev_bind_varenv bs)
  285. -----------------
  286. -- All evidence is bound by EvBinds; no side effects
  287. data EvBind
  288. = EvBind { eb_lhs :: EvVar
  289. , eb_rhs :: EvTerm
  290. , eb_is_given :: Bool -- True <=> given
  291. -- See Note [Tracking redundant constraints] in TcSimplify
  292. }
  293. evBindVar :: EvBind -> EvVar
  294. evBindVar = eb_lhs
  295. mkWantedEvBind :: EvVar -> EvTerm -> EvBind
  296. mkWantedEvBind ev tm = EvBind { eb_is_given = False, eb_lhs = ev, eb_rhs = tm }
  297. mkGivenEvBind :: EvVar -> EvTerm -> EvBind
  298. mkGivenEvBind ev tm = EvBind { eb_is_given = True, eb_lhs = ev, eb_rhs = tm }
  299. data EvTerm
  300. = EvId EvId -- Any sort of evidence Id, including coercions
  301. | EvCoercion TcCoercion -- coercion bindings
  302. -- See Note [Coercion evidence terms]
  303. | EvCast EvTerm TcCoercionR -- d |> co
  304. | EvDFunApp DFunId -- Dictionary instance application
  305. [Type] [EvTerm]
  306. | EvDelayedError Type FastString -- Used with Opt_DeferTypeErrors
  307. -- See Note [Deferring coercion errors to runtime]
  308. -- in TcSimplify
  309. | EvSuperClass EvTerm Int -- n'th superclass. Used for both equalities and
  310. -- dictionaries, even though the former have no
  311. -- selector Id. We count up from _0_
  312. | EvLit EvLit -- Dictionary for KnownNat and KnownSymbol classes.
  313. -- Note [KnownNat & KnownSymbol and EvLit]
  314. | EvCallStack EvCallStack -- Dictionary for CallStack implicit parameters
  315. | EvTypeable Type EvTypeable -- Dictionary for (Typeable ty)
  316. deriving Data.Data
  317. -- | Instructions on how to make a 'Typeable' dictionary.
  318. -- See Note [Typeable evidence terms]
  319. data EvTypeable
  320. = EvTypeableTyCon [EvTerm] -- ^ Dictionary for @Typeable (T k1..kn)@.
  321. -- The EvTerms are for the arguments
  322. | EvTypeableTyApp EvTerm EvTerm
  323. -- ^ Dictionary for @Typeable (s t)@,
  324. -- given a dictionaries for @s@ and @t@
  325. | EvTypeableTyLit EvTerm
  326. -- ^ Dictionary for a type literal,
  327. -- e.g. @Typeable "foo"@ or @Typeable 3@
  328. -- The 'EvTerm' is evidence of, e.g., @KnownNat 3@
  329. -- (see Trac #10348)
  330. deriving Data.Data
  331. data EvLit
  332. = EvNum Integer
  333. | EvStr FastString
  334. deriving Data.Data
  335. -- | Evidence for @CallStack@ implicit parameters.
  336. data EvCallStack
  337. -- See Note [Overview of implicit CallStacks]
  338. = EvCsEmpty
  339. | EvCsPushCall Name RealSrcSpan EvTerm
  340. -- ^ @EvCsPushCall name loc stk@ represents a call to @name@, occurring at
  341. -- @loc@, in a calling context @stk@.
  342. deriving Data.Data
  343. {-
  344. Note [Typeable evidence terms]
  345. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  346. The EvTypeable data type looks isomorphic to Type, but the EvTerms
  347. inside can be EvIds. Eg
  348. f :: forall a. Typeable a => a -> TypeRep
  349. f x = typeRep (undefined :: Proxy [a])
  350. Here for the (Typeable [a]) dictionary passed to typeRep we make
  351. evidence
  352. dl :: Typeable [a] = EvTypeable [a]
  353. (EvTypeableTyApp (EvTypeableTyCon []) (EvId d))
  354. where
  355. d :: Typable a
  356. is the lambda-bound dictionary passed into f.
  357. Note [Coercion evidence terms]
  358. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  359. A "coercion evidence term" takes one of these forms
  360. co_tm ::= EvId v where v :: t1 ~# t2
  361. | EvCoercion co
  362. | EvCast co_tm co
  363. We do quite often need to get a TcCoercion from an EvTerm; see
  364. 'evTermCoercion'.
  365. INVARIANT: The evidence for any constraint with type (t1 ~# t2) is
  366. a coercion evidence term. Consider for example
  367. [G] d :: F Int a
  368. If we have
  369. ax7 a :: F Int a ~ (a ~ Bool)
  370. then we do NOT generate the constraint
  371. [G] (d |> ax7 a) :: a ~ Bool
  372. because that does not satisfy the invariant (d is not a coercion variable).
  373. Instead we make a binding
  374. g1 :: a~Bool = g |> ax7 a
  375. and the constraint
  376. [G] g1 :: a~Bool
  377. See Trac [7238] and Note [Bind new Givens immediately] in TcRnTypes
  378. Note [EvBinds/EvTerm]
  379. ~~~~~~~~~~~~~~~~~~~~~
  380. How evidence is created and updated. Bindings for dictionaries,
  381. and coercions and implicit parameters are carried around in TcEvBinds
  382. which during constraint generation and simplification is always of the
  383. form (TcEvBinds ref). After constraint simplification is finished it
  384. will be transformed to t an (EvBinds ev_bag).
  385. Evidence for coercions *SHOULD* be filled in using the TcEvBinds
  386. However, all EvVars that correspond to *wanted* coercion terms in
  387. an EvBind must be mutable variables so that they can be readily
  388. inlined (by zonking) after constraint simplification is finished.
  389. Conclusion: a new wanted coercion variable should be made mutable.
  390. [Notice though that evidence variables that bind coercion terms
  391. from super classes will be "given" and hence rigid]
  392. Note [KnownNat & KnownSymbol and EvLit]
  393. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  394. A part of the type-level literals implementation are the classes
  395. "KnownNat" and "KnownSymbol", which provide a "smart" constructor for
  396. defining singleton values. Here is the key stuff from GHC.TypeLits
  397. class KnownNat (n :: Nat) where
  398. natSing :: SNat n
  399. newtype SNat (n :: Nat) = SNat Integer
  400. Conceptually, this class has infinitely many instances:
  401. instance KnownNat 0 where natSing = SNat 0
  402. instance KnownNat 1 where natSing = SNat 1
  403. instance KnownNat 2 where natSing = SNat 2
  404. ...
  405. In practice, we solve `KnownNat` predicates in the type-checker
  406. (see typecheck/TcInteract.hs) because we can't have infinately many instances.
  407. The evidence (aka "dictionary") for `KnownNat` is of the form `EvLit (EvNum n)`.
  408. We make the following assumptions about dictionaries in GHC:
  409. 1. The "dictionary" for classes with a single method---like `KnownNat`---is
  410. a newtype for the type of the method, so using a evidence amounts
  411. to a coercion, and
  412. 2. Newtypes use the same representation as their definition types.
  413. So, the evidence for `KnownNat` is just a value of the representation type,
  414. wrapped in two newtype constructors: one to make it into a `SNat` value,
  415. and another to make it into a `KnownNat` dictionary.
  416. Also note that `natSing` and `SNat` are never actually exposed from the
  417. library---they are just an implementation detail. Instead, users see
  418. a more convenient function, defined in terms of `natSing`:
  419. natVal :: KnownNat n => proxy n -> Integer
  420. The reason we don't use this directly in the class is that it is simpler
  421. and more efficient to pass around an integer rather than an entier function,
  422. especially when the `KnowNat` evidence is packaged up in an existential.
  423. The story for kind `Symbol` is analogous:
  424. * class KnownSymbol
  425. * newtype SSymbol
  426. * Evidence: EvLit (EvStr n)
  427. Note [Overview of implicit CallStacks]
  428. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  429. (See https://ghc.haskell.org/trac/ghc/wiki/ExplicitCallStack/ImplicitLocations)
  430. The goal of CallStack evidence terms is to reify locations
  431. in the program source as runtime values, without any support
  432. from the RTS. We accomplish this by assigning a special meaning
  433. to constraints of type GHC.Stack.Types.HasCallStack, an alias
  434. type HasCallStack = (?callStack :: CallStack)
  435. Implicit parameters of type GHC.Stack.Types.CallStack (the name is not
  436. important) are solved in three steps:
  437. 1. Occurrences of CallStack IPs are solved directly from the given IP,
  438. just like a regular IP. For example, the occurrence of `?stk` in
  439. error :: (?stk :: CallStack) => String -> a
  440. error s = raise (ErrorCall (s ++ prettyCallStack ?stk))
  441. will be solved for the `?stk` in `error`s context as before.
  442. 2. In a function call, instead of simply passing the given IP, we first
  443. append the current call-site to it. For example, consider a
  444. call to the callstack-aware `error` above.
  445. undefined :: (?stk :: CallStack) => a
  446. undefined = error "undefined!"
  447. Here we want to take the given `?stk` and append the current
  448. call-site, before passing it to `error`. In essence, we want to
  449. rewrite `error "undefined!"` to
  450. let ?stk = pushCallStack <error's location> ?stk
  451. in error "undefined!"
  452. We achieve this effect by emitting a NEW wanted
  453. [W] d :: IP "stk" CallStack
  454. from which we build the evidence term
  455. EvCsPushCall "error" <error's location> (EvId d)
  456. that we use to solve the call to `error`. The new wanted `d` will
  457. then be solved per rule (1), ie as a regular IP.
  458. (see TcInteract.interactDict)
  459. 3. We default any insoluble CallStacks to the empty CallStack. Suppose
  460. `undefined` did not request a CallStack, ie
  461. undefinedNoStk :: a
  462. undefinedNoStk = error "undefined!"
  463. Under the usual IP rules, the new wanted from rule (2) would be
  464. insoluble as there's no given IP from which to solve it, so we
  465. would get an "unbound implicit parameter" error.
  466. We don't ever want to emit an insoluble CallStack IP, so we add a
  467. defaulting pass to default any remaining wanted CallStacks to the
  468. empty CallStack with the evidence term
  469. EvCsEmpty
  470. (see TcSimplify.simpl_top and TcSimplify.defaultCallStacks)
  471. This provides a lightweight mechanism for building up call-stacks
  472. explicitly, but is notably limited by the fact that the stack will
  473. stop at the first function whose type does not include a CallStack IP.
  474. For example, using the above definition of `undefined`:
  475. head :: [a] -> a
  476. head [] = undefined
  477. head (x:_) = x
  478. g = head []
  479. the resulting CallStack will include the call to `undefined` in `head`
  480. and the call to `error` in `undefined`, but *not* the call to `head`
  481. in `g`, because `head` did not explicitly request a CallStack.
  482. Important Details:
  483. - GHC should NEVER report an insoluble CallStack constraint.
  484. - GHC should NEVER infer a CallStack constraint unless one was requested
  485. with a partial type signature (See TcType.pickQuantifiablePreds).
  486. - A CallStack (defined in GHC.Stack.Types) is a [(String, SrcLoc)],
  487. where the String is the name of the binder that is used at the
  488. SrcLoc. SrcLoc is also defined in GHC.Stack.Types and contains the
  489. package/module/file name, as well as the full source-span. Both
  490. CallStack and SrcLoc are kept abstract so only GHC can construct new
  491. values.
  492. - We will automatically solve any wanted CallStack regardless of the
  493. name of the IP, i.e.
  494. f = show (?stk :: CallStack)
  495. g = show (?loc :: CallStack)
  496. are both valid. However, we will only push new SrcLocs onto existing
  497. CallStacks when the IP names match, e.g. in
  498. head :: (?loc :: CallStack) => [a] -> a
  499. head [] = error (show (?stk :: CallStack))
  500. the printed CallStack will NOT include head's call-site. This reflects the
  501. standard scoping rules of implicit-parameters.
  502. - An EvCallStack term desugars to a CoreExpr of type `IP "some str" CallStack`.
  503. The desugarer will need to unwrap the IP newtype before pushing a new
  504. call-site onto a given stack (See DsBinds.dsEvCallStack)
  505. - When we emit a new wanted CallStack from rule (2) we set its origin to
  506. `IPOccOrigin ip_name` instead of the original `OccurrenceOf func`
  507. (see TcInteract.interactDict).
  508. This is a bit shady, but is how we ensure that the new wanted is
  509. solved like a regular IP.
  510. -}
  511. mkEvCast :: EvTerm -> TcCoercion -> EvTerm
  512. mkEvCast ev lco
  513. | ASSERT2(tcCoercionRole lco == Representational, (vcat [text "Coercion of wrong role passed to mkEvCast:", ppr ev, ppr lco]))
  514. isTcReflCo lco = ev
  515. | otherwise = EvCast ev lco
  516. mkEvScSelectors :: EvTerm -> Class -> [TcType] -> [(TcPredType, EvTerm)]
  517. mkEvScSelectors ev cls tys
  518. = zipWith mk_pr (immSuperClasses cls tys) [0..]
  519. where
  520. mk_pr pred i = (pred, EvSuperClass ev i)
  521. emptyTcEvBinds :: TcEvBinds
  522. emptyTcEvBinds = EvBinds emptyBag
  523. isEmptyTcEvBinds :: TcEvBinds -> Bool
  524. isEmptyTcEvBinds (EvBinds b) = isEmptyBag b
  525. isEmptyTcEvBinds (TcEvBinds {}) = panic "isEmptyTcEvBinds"
  526. evTermCoercion :: EvTerm -> TcCoercion
  527. -- Applied only to EvTerms of type (s~t)
  528. -- See Note [Coercion evidence terms]
  529. evTermCoercion (EvId v) = mkCoVarCo v
  530. evTermCoercion (EvCoercion co) = co
  531. evTermCoercion (EvCast tm co) = mkCoCast (evTermCoercion tm) co
  532. evTermCoercion tm = pprPanic "evTermCoercion" (ppr tm)
  533. evVarsOfTerm :: EvTerm -> VarSet
  534. evVarsOfTerm (EvId v) = unitVarSet v
  535. evVarsOfTerm (EvCoercion co) = coVarsOfCo co
  536. evVarsOfTerm (EvDFunApp _ _ evs) = mapUnionVarSet evVarsOfTerm evs
  537. evVarsOfTerm (EvSuperClass v _) = evVarsOfTerm v
  538. evVarsOfTerm (EvCast tm co) = evVarsOfTerm tm `unionVarSet` coVarsOfCo co
  539. evVarsOfTerm (EvDelayedError _ _) = emptyVarSet
  540. evVarsOfTerm (EvLit _) = emptyVarSet
  541. evVarsOfTerm (EvCallStack cs) = evVarsOfCallStack cs
  542. evVarsOfTerm (EvTypeable _ ev) = evVarsOfTypeable ev
  543. evVarsOfTerms :: [EvTerm] -> VarSet
  544. evVarsOfTerms = mapUnionVarSet evVarsOfTerm
  545. -- | Do SCC analysis on a bag of 'EvBind's.
  546. sccEvBinds :: Bag EvBind -> [SCC EvBind]
  547. sccEvBinds bs = stronglyConnCompFromEdgedVerticesUniq edges
  548. where
  549. edges :: [(EvBind, EvVar, [EvVar])]
  550. edges = foldrBag ((:) . mk_node) [] bs
  551. mk_node :: EvBind -> (EvBind, EvVar, [EvVar])
  552. mk_node b@(EvBind { eb_lhs = var, eb_rhs = term })
  553. = (b, var, nonDetEltsUFM (evVarsOfTerm term `unionVarSet`
  554. coVarsOfType (varType var)))
  555. -- It's OK to use nonDetEltsUFM here as stronglyConnCompFromEdgedVertices
  556. -- is still deterministic even if the edges are in nondeterministic order
  557. -- as explained in Note [Deterministic SCC] in Digraph.
  558. evVarsOfCallStack :: EvCallStack -> VarSet
  559. evVarsOfCallStack cs = case cs of
  560. EvCsEmpty -> emptyVarSet
  561. EvCsPushCall _ _ tm -> evVarsOfTerm tm
  562. evVarsOfTypeable :: EvTypeable -> VarSet
  563. evVarsOfTypeable ev =
  564. case ev of
  565. EvTypeableTyCon es -> evVarsOfTerms es
  566. EvTypeableTyApp e1 e2 -> evVarsOfTerms [e1,e2]
  567. EvTypeableTyLit e -> evVarsOfTerm e
  568. {-
  569. ************************************************************************
  570. * *
  571. Pretty printing
  572. * *
  573. ************************************************************************
  574. -}
  575. instance Outputable HsWrapper where
  576. ppr co_fn = pprHsWrapper co_fn (no_parens (text "<>"))
  577. pprHsWrapper ::HsWrapper -> (Bool -> SDoc) -> SDoc
  578. -- With -fprint-typechecker-elaboration, print the wrapper
  579. -- otherwise just print what's inside
  580. -- The pp_thing_inside function takes Bool to say whether
  581. -- it's in a position that needs parens for a non-atomic thing
  582. pprHsWrapper wrap pp_thing_inside
  583. = sdocWithDynFlags $ \ dflags ->
  584. if gopt Opt_PrintTypecheckerElaboration dflags
  585. then help pp_thing_inside wrap False
  586. else pp_thing_inside False
  587. where
  588. help :: (Bool -> SDoc) -> HsWrapper -> Bool -> SDoc
  589. -- True <=> appears in function application position
  590. -- False <=> appears as body of let or lambda
  591. help it WpHole = it
  592. help it (WpCompose f1 f2) = help (help it f2) f1
  593. help it (WpFun f1 f2 t1) = add_parens $ text "\\(x" <> dcolon <> ppr t1 <> text ")." <+>
  594. help (\_ -> it True <+> help (\_ -> text "x") f1 True) f2 False
  595. help it (WpCast co) = add_parens $ sep [it False, nest 2 (text "|>"
  596. <+> pprParendCo co)]
  597. help it (WpEvApp id) = no_parens $ sep [it True, nest 2 (ppr id)]
  598. help it (WpTyApp ty) = no_parens $ sep [it True, text "@" <+> pprParendType ty]
  599. help it (WpEvLam id) = add_parens $ sep [ text "\\" <> pp_bndr id, it False]
  600. help it (WpTyLam tv) = add_parens $ sep [text "/\\" <> pp_bndr tv, it False]
  601. help it (WpLet binds) = add_parens $ sep [text "let" <+> braces (ppr binds), it False]
  602. pp_bndr v = pprBndr LambdaBind v <> dot
  603. add_parens, no_parens :: SDoc -> Bool -> SDoc
  604. add_parens d True = parens d
  605. add_parens d False = d
  606. no_parens d _ = d
  607. instance Outputable TcEvBinds where
  608. ppr (TcEvBinds v) = ppr v
  609. ppr (EvBinds bs) = text "EvBinds" <> braces (vcat (map ppr (bagToList bs)))
  610. instance Outputable EvBindsVar where
  611. ppr (EvBindsVar _ u) = text "EvBindsVar" <> angleBrackets (ppr u)
  612. instance Uniquable EvBindsVar where
  613. getUnique (EvBindsVar _ u) = u
  614. instance Outputable EvBind where
  615. ppr (EvBind { eb_lhs = v, eb_rhs = e, eb_is_given = is_given })
  616. = sep [ pp_gw <+> ppr v
  617. , nest 2 $ equals <+> ppr e ]
  618. where
  619. pp_gw = brackets (if is_given then char 'G' else char 'W')
  620. -- We cheat a bit and pretend EqVars are CoVars for the purposes of pretty printing
  621. instance Outputable EvTerm where
  622. ppr (EvId v) = ppr v
  623. ppr (EvCast v co) = ppr v <+> (text "`cast`") <+> pprParendCo co
  624. ppr (EvCoercion co) = text "CO" <+> ppr co
  625. ppr (EvSuperClass d n) = text "sc" <> parens (ppr (d,n))
  626. ppr (EvDFunApp df tys ts) = ppr df <+> sep [ char '@' <> ppr tys, ppr ts ]
  627. ppr (EvLit l) = ppr l
  628. ppr (EvCallStack cs) = ppr cs
  629. ppr (EvDelayedError ty msg) = text "error"
  630. <+> sep [ char '@' <> ppr ty, ppr msg ]
  631. ppr (EvTypeable ty ev) = ppr ev <+> dcolon <+> text "Typeable" <+> ppr ty
  632. instance Outputable EvLit where
  633. ppr (EvNum n) = integer n
  634. ppr (EvStr s) = text (show s)
  635. instance Outputable EvCallStack where
  636. ppr EvCsEmpty
  637. = text "[]"
  638. ppr (EvCsPushCall name loc tm)
  639. = ppr (name,loc) <+> text ":" <+> ppr tm
  640. instance Outputable EvTypeable where
  641. ppr (EvTypeableTyCon ts) = text "TC" <+> ppr ts
  642. ppr (EvTypeableTyApp t1 t2) = parens (ppr t1 <+> ppr t2)
  643. ppr (EvTypeableTyLit t1) = text "TyLit" <> ppr t1
  644. ----------------------------------------------------------------------
  645. -- Helper functions for dealing with IP newtype-dictionaries
  646. ----------------------------------------------------------------------
  647. -- | Create a 'Coercion' that unwraps an implicit-parameter or
  648. -- overloaded-label dictionary to expose the underlying value. We
  649. -- expect the 'Type' to have the form `IP sym ty` or `IsLabel sym ty`,
  650. -- and return a 'Coercion' `co :: IP sym ty ~ ty` or
  651. -- `co :: IsLabel sym ty ~ Proxy# sym -> ty`. See also
  652. -- Note [Type-checking overloaded labels] in TcExpr.
  653. unwrapIP :: Type -> CoercionR
  654. unwrapIP ty =
  655. case unwrapNewTyCon_maybe tc of
  656. Just (_,_,ax) -> mkUnbranchedAxInstCo Representational ax tys []
  657. Nothing -> pprPanic "unwrapIP" $
  658. text "The dictionary for" <+> quotes (ppr tc)
  659. <+> text "is not a newtype!"
  660. where
  661. (tc, tys) = splitTyConApp ty
  662. -- | Create a 'Coercion' that wraps a value in an implicit-parameter
  663. -- dictionary. See 'unwrapIP'.
  664. wrapIP :: Type -> CoercionR
  665. wrapIP ty = mkSymCo (unwrapIP ty)