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