4e854fc8c8a11484db9ad5ab4d4a09352b035523
[ghc.git] / compiler / typecheck / Inst.hs
1 {-
2 (c) The University of Glasgow 2006
3 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4
5
6 The @Inst@ type: dictionaries or method instances
7 -}
8
9 {-# LANGUAGE CPP, MultiWayIf, TupleSections #-}
10 {-# LANGUAGE FlexibleContexts #-}
11
12 module Inst (
13 deeplySkolemise,
14 topInstantiate, topInstantiateInferred, deeplyInstantiate,
15 instCall, instDFunType, instStupidTheta, instTyVarsWith,
16 newWanted, newWanteds,
17
18 tcInstTyBinders, tcInstTyBinder,
19
20 newOverloadedLit, mkOverLit,
21
22 newClsInst,
23 tcGetInsts, tcGetInstEnvs, getOverlapFlag,
24 tcExtendLocalInstEnv,
25 instCallConstraints, newMethodFromName,
26 tcSyntaxName,
27
28 -- Simple functions over evidence variables
29 tyCoVarsOfWC,
30 tyCoVarsOfCt, tyCoVarsOfCts,
31 ) where
32
33 #include "HsVersions.h"
34
35 import GhcPrelude
36
37 import {-# SOURCE #-} TcExpr( tcPolyExpr, tcSyntaxOp )
38 import {-# SOURCE #-} TcUnify( unifyType, unifyKind )
39
40 import BasicTypes ( IntegralLit(..), SourceText(..) )
41 import FastString
42 import HsSyn
43 import TcHsSyn
44 import TcRnMonad
45 import TcEnv
46 import TcEvidence
47 import InstEnv
48 import TysWiredIn ( heqDataCon, eqDataCon )
49 import CoreSyn ( isOrphan )
50 import FunDeps
51 import TcMType
52 import Type
53 import TyCoRep
54 import TcType
55 import HscTypes
56 import Class( Class )
57 import MkId( mkDictFunId )
58 import CoreSyn( Expr(..) ) -- For the Coercion constructor
59 import Id
60 import Name
61 import Var ( EvVar, mkTyVar, tyVarName, TyVarBndr(..) )
62 import DataCon
63 import VarEnv
64 import PrelNames
65 import SrcLoc
66 import DynFlags
67 import Util
68 import Outputable
69 import qualified GHC.LanguageExtensions as LangExt
70
71 import Control.Monad( unless )
72
73 {-
74 ************************************************************************
75 * *
76 Creating and emittind constraints
77 * *
78 ************************************************************************
79 -}
80
81 newMethodFromName :: CtOrigin -> Name -> TcRhoType -> TcM (HsExpr GhcTcId)
82 -- Used when Name is the wired-in name for a wired-in class method,
83 -- so the caller knows its type for sure, which should be of form
84 -- forall a. C a => <blah>
85 -- newMethodFromName is supposed to instantiate just the outer
86 -- type variable and constraint
87
88 newMethodFromName origin name inst_ty
89 = do { id <- tcLookupId name
90 -- Use tcLookupId not tcLookupGlobalId; the method is almost
91 -- always a class op, but with -XRebindableSyntax GHC is
92 -- meant to find whatever thing is in scope, and that may
93 -- be an ordinary function.
94
95 ; let ty = piResultTy (idType id) inst_ty
96 (theta, _caller_knows_this) = tcSplitPhiTy ty
97 ; wrap <- ASSERT( not (isForAllTy ty) && isSingleton theta )
98 instCall origin [inst_ty] theta
99
100 ; return (mkHsWrap wrap (HsVar noExt (noLoc id))) }
101
102 {-
103 ************************************************************************
104 * *
105 Deep instantiation and skolemisation
106 * *
107 ************************************************************************
108
109 Note [Deep skolemisation]
110 ~~~~~~~~~~~~~~~~~~~~~~~~~
111 deeplySkolemise decomposes and skolemises a type, returning a type
112 with all its arrows visible (ie not buried under foralls)
113
114 Examples:
115
116 deeplySkolemise (Int -> forall a. Ord a => blah)
117 = ( wp, [a], [d:Ord a], Int -> blah )
118 where wp = \x:Int. /\a. \(d:Ord a). <hole> x
119
120 deeplySkolemise (forall a. Ord a => Maybe a -> forall b. Eq b => blah)
121 = ( wp, [a,b], [d1:Ord a,d2:Eq b], Maybe a -> blah )
122 where wp = /\a.\(d1:Ord a).\(x:Maybe a)./\b.\(d2:Ord b). <hole> x
123
124 In general,
125 if deeplySkolemise ty = (wrap, tvs, evs, rho)
126 and e :: rho
127 then wrap e :: ty
128 and 'wrap' binds tvs, evs
129
130 ToDo: this eta-abstraction plays fast and loose with termination,
131 because it can introduce extra lambdas. Maybe add a `seq` to
132 fix this
133 -}
134
135 deeplySkolemise :: TcSigmaType
136 -> TcM ( HsWrapper
137 , [(Name,TyVar)] -- All skolemised variables
138 , [EvVar] -- All "given"s
139 , TcRhoType )
140
141 deeplySkolemise ty
142 = go init_subst ty
143 where
144 init_subst = mkEmptyTCvSubst (mkInScopeSet (tyCoVarsOfType ty))
145
146 go subst ty
147 | Just (arg_tys, tvs, theta, ty') <- tcDeepSplitSigmaTy_maybe ty
148 = do { let arg_tys' = substTys subst arg_tys
149 ; ids1 <- newSysLocalIds (fsLit "dk") arg_tys'
150 ; (subst', tvs1) <- tcInstSkolTyVarsX subst tvs
151 ; ev_vars1 <- newEvVars (substTheta subst' theta)
152 ; (wrap, tvs_prs2, ev_vars2, rho) <- go subst' ty'
153 ; let tv_prs1 = map tyVarName tvs `zip` tvs1
154 ; return ( mkWpLams ids1
155 <.> mkWpTyLams tvs1
156 <.> mkWpLams ev_vars1
157 <.> wrap
158 <.> mkWpEvVarApps ids1
159 , tv_prs1 ++ tvs_prs2
160 , ev_vars1 ++ ev_vars2
161 , mkFunTys arg_tys' rho ) }
162
163 | otherwise
164 = return (idHsWrapper, [], [], substTy subst ty)
165 -- substTy is a quick no-op on an empty substitution
166
167 -- | Instantiate all outer type variables
168 -- and any context. Never looks through arrows.
169 topInstantiate :: CtOrigin -> TcSigmaType -> TcM (HsWrapper, TcRhoType)
170 -- if topInstantiate ty = (wrap, rho)
171 -- and e :: ty
172 -- then wrap e :: rho (that is, wrap :: ty "->" rho)
173 topInstantiate = top_instantiate True
174
175 -- | Instantiate all outer 'Inferred' binders
176 -- and any context. Never looks through arrows or specified type variables.
177 -- Used for visible type application.
178 topInstantiateInferred :: CtOrigin -> TcSigmaType
179 -> TcM (HsWrapper, TcSigmaType)
180 -- if topInstantiate ty = (wrap, rho)
181 -- and e :: ty
182 -- then wrap e :: rho
183 topInstantiateInferred = top_instantiate False
184
185 top_instantiate :: Bool -- True <=> instantiate *all* variables
186 -- False <=> instantiate only the inferred ones
187 -> CtOrigin -> TcSigmaType -> TcM (HsWrapper, TcRhoType)
188 top_instantiate inst_all orig ty
189 | not (null binders && null theta)
190 = do { let (inst_bndrs, leave_bndrs) = span should_inst binders
191 (inst_theta, leave_theta)
192 | null leave_bndrs = (theta, [])
193 | otherwise = ([], theta)
194 in_scope = mkInScopeSet (tyCoVarsOfType ty)
195 empty_subst = mkEmptyTCvSubst in_scope
196 inst_tvs = binderVars inst_bndrs
197 ; (subst, inst_tvs') <- mapAccumLM newMetaTyVarX empty_subst inst_tvs
198 ; let inst_theta' = substTheta subst inst_theta
199 sigma' = substTy subst (mkForAllTys leave_bndrs $
200 mkFunTys leave_theta rho)
201 inst_tv_tys' = mkTyVarTys inst_tvs'
202
203 ; wrap1 <- instCall orig inst_tv_tys' inst_theta'
204 ; traceTc "Instantiating"
205 (vcat [ text "all tyvars?" <+> ppr inst_all
206 , text "origin" <+> pprCtOrigin orig
207 , text "type" <+> debugPprType ty
208 , text "theta" <+> ppr theta
209 , text "leave_bndrs" <+> ppr leave_bndrs
210 , text "with" <+> vcat (map debugPprType inst_tv_tys')
211 , text "theta:" <+> ppr inst_theta' ])
212
213 ; (wrap2, rho2) <-
214 if null leave_bndrs
215
216 -- account for types like forall a. Num a => forall b. Ord b => ...
217 then top_instantiate inst_all orig sigma'
218
219 -- but don't loop if there were any un-inst'able tyvars
220 else return (idHsWrapper, sigma')
221
222 ; return (wrap2 <.> wrap1, rho2) }
223
224 | otherwise = return (idHsWrapper, ty)
225 where
226 (binders, phi) = tcSplitForAllTyVarBndrs ty
227 (theta, rho) = tcSplitPhiTy phi
228
229 should_inst bndr
230 | inst_all = True
231 | otherwise = binderArgFlag bndr == Inferred
232
233 deeplyInstantiate :: CtOrigin -> TcSigmaType -> TcM (HsWrapper, TcRhoType)
234 -- Int -> forall a. a -> a ==> (\x:Int. [] x alpha) :: Int -> alpha
235 -- In general if
236 -- if deeplyInstantiate ty = (wrap, rho)
237 -- and e :: ty
238 -- then wrap e :: rho
239 -- That is, wrap :: ty ~> rho
240 --
241 -- If you don't need the HsWrapper returned from this function, consider
242 -- using tcSplitNestedSigmaTys in TcType, which is a pure alternative that
243 -- only computes the returned TcRhoType.
244
245 deeplyInstantiate orig ty =
246 deeply_instantiate orig
247 (mkEmptyTCvSubst (mkInScopeSet (tyCoVarsOfType ty)))
248 ty
249
250 deeply_instantiate :: CtOrigin
251 -> TCvSubst
252 -> TcSigmaType -> TcM (HsWrapper, TcRhoType)
253 -- Internal function to deeply instantiate that builds on an existing subst.
254 -- It extends the input substitution and applies the final subtitution to
255 -- the types on return. See #12549.
256
257 deeply_instantiate orig subst ty
258 | Just (arg_tys, tvs, theta, rho) <- tcDeepSplitSigmaTy_maybe ty
259 = do { (subst', tvs') <- newMetaTyVarsX subst tvs
260 ; let arg_tys' = substTys subst' arg_tys
261 theta' = substTheta subst' theta
262 ; ids1 <- newSysLocalIds (fsLit "di") arg_tys'
263 ; wrap1 <- instCall orig (mkTyVarTys tvs') theta'
264 ; traceTc "Instantiating (deeply)" (vcat [ text "origin" <+> pprCtOrigin orig
265 , text "type" <+> ppr ty
266 , text "with" <+> ppr tvs'
267 , text "args:" <+> ppr ids1
268 , text "theta:" <+> ppr theta'
269 , text "subst:" <+> ppr subst'])
270 ; (wrap2, rho2) <- deeply_instantiate orig subst' rho
271 ; return (mkWpLams ids1
272 <.> wrap2
273 <.> wrap1
274 <.> mkWpEvVarApps ids1,
275 mkFunTys arg_tys' rho2) }
276
277 | otherwise
278 = do { let ty' = substTy subst ty
279 ; traceTc "deeply_instantiate final subst"
280 (vcat [ text "origin:" <+> pprCtOrigin orig
281 , text "type:" <+> ppr ty
282 , text "new type:" <+> ppr ty'
283 , text "subst:" <+> ppr subst ])
284 ; return (idHsWrapper, ty') }
285
286
287 instTyVarsWith :: CtOrigin -> [TyVar] -> [TcType] -> TcM TCvSubst
288 -- Use this when you want to instantiate (forall a b c. ty) with
289 -- types [ta, tb, tc], but when the kinds of 'a' and 'ta' might
290 -- not yet match (perhaps because there are unsolved constraints; Trac #14154)
291 -- If they don't match, emit a kind-equality to promise that they will
292 -- eventually do so, and thus make a kind-homongeneous substitution.
293 instTyVarsWith orig tvs tys
294 = go empty_subst tvs tys
295 where
296 empty_subst = mkEmptyTCvSubst (mkInScopeSet (tyCoVarsOfTypes tys))
297
298 go subst [] []
299 = return subst
300 go subst (tv:tvs) (ty:tys)
301 | tv_kind `tcEqType` ty_kind
302 = go (extendTCvSubst subst tv ty) tvs tys
303 | otherwise
304 = do { co <- emitWantedEq orig KindLevel Nominal ty_kind tv_kind
305 ; go (extendTCvSubst subst tv (ty `mkCastTy` co)) tvs tys }
306 where
307 tv_kind = substTy subst (tyVarKind tv)
308 ty_kind = typeKind ty
309
310 go _ _ _ = pprPanic "instTysWith" (ppr tvs $$ ppr tys)
311
312 {-
313 ************************************************************************
314 * *
315 Instantiating a call
316 * *
317 ************************************************************************
318
319 Note [Handling boxed equality]
320 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
321 The solver deals entirely in terms of unboxed (primitive) equality.
322 There should never be a boxed Wanted equality. Ever. But, what if
323 we are calling `foo :: forall a. (F a ~ Bool) => ...`? That equality
324 is boxed, so naive treatment here would emit a boxed Wanted equality.
325
326 So we simply check for this case and make the right boxing of evidence.
327
328 -}
329
330 ----------------
331 instCall :: CtOrigin -> [TcType] -> TcThetaType -> TcM HsWrapper
332 -- Instantiate the constraints of a call
333 -- (instCall o tys theta)
334 -- (a) Makes fresh dictionaries as necessary for the constraints (theta)
335 -- (b) Throws these dictionaries into the LIE
336 -- (c) Returns an HsWrapper ([.] tys dicts)
337
338 instCall orig tys theta
339 = do { dict_app <- instCallConstraints orig theta
340 ; return (dict_app <.> mkWpTyApps tys) }
341
342 ----------------
343 instCallConstraints :: CtOrigin -> TcThetaType -> TcM HsWrapper
344 -- Instantiates the TcTheta, puts all constraints thereby generated
345 -- into the LIE, and returns a HsWrapper to enclose the call site.
346
347 instCallConstraints orig preds
348 | null preds
349 = return idHsWrapper
350 | otherwise
351 = do { evs <- mapM go preds
352 ; traceTc "instCallConstraints" (ppr evs)
353 ; return (mkWpEvApps evs) }
354 where
355 go :: TcPredType -> TcM EvTerm
356 go pred
357 | Just (Nominal, ty1, ty2) <- getEqPredTys_maybe pred -- Try short-cut #1
358 = do { co <- unifyType Nothing ty1 ty2
359 ; return (evCoercion co) }
360
361 -- Try short-cut #2
362 | Just (tc, args@[_, _, ty1, ty2]) <- splitTyConApp_maybe pred
363 , tc `hasKey` heqTyConKey
364 = do { co <- unifyType Nothing ty1 ty2
365 ; return (evDFunApp (dataConWrapId heqDataCon) args [Coercion co]) }
366
367 | otherwise
368 = emitWanted orig pred
369
370 instDFunType :: DFunId -> [DFunInstType]
371 -> TcM ( [TcType] -- instantiated argument types
372 , TcThetaType ) -- instantiated constraint
373 -- See Note [DFunInstType: instantiating types] in InstEnv
374 instDFunType dfun_id dfun_inst_tys
375 = do { (subst, inst_tys) <- go empty_subst dfun_tvs dfun_inst_tys
376 ; return (inst_tys, substTheta subst dfun_theta) }
377 where
378 dfun_ty = idType dfun_id
379 (dfun_tvs, dfun_theta, _) = tcSplitSigmaTy dfun_ty
380 empty_subst = mkEmptyTCvSubst (mkInScopeSet (tyCoVarsOfType dfun_ty))
381 -- With quantified constraints, the
382 -- type of a dfun may not be closed
383
384 go :: TCvSubst -> [TyVar] -> [DFunInstType] -> TcM (TCvSubst, [TcType])
385 go subst [] [] = return (subst, [])
386 go subst (tv:tvs) (Just ty : mb_tys)
387 = do { (subst', tys) <- go (extendTvSubstAndInScope subst tv ty)
388 tvs
389 mb_tys
390 ; return (subst', ty : tys) }
391 go subst (tv:tvs) (Nothing : mb_tys)
392 = do { (subst', tv') <- newMetaTyVarX subst tv
393 ; (subst'', tys) <- go subst' tvs mb_tys
394 ; return (subst'', mkTyVarTy tv' : tys) }
395 go _ _ _ = pprPanic "instDFunTypes" (ppr dfun_id $$ ppr dfun_inst_tys)
396
397 ----------------
398 instStupidTheta :: CtOrigin -> TcThetaType -> TcM ()
399 -- Similar to instCall, but only emit the constraints in the LIE
400 -- Used exclusively for the 'stupid theta' of a data constructor
401 instStupidTheta orig theta
402 = do { _co <- instCallConstraints orig theta -- Discard the coercion
403 ; return () }
404
405 {-
406 ************************************************************************
407 * *
408 Instantiating Kinds
409 * *
410 ************************************************************************
411
412 Note [Constraints handled in types]
413 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
414 Generally, we cannot handle constraints written in types. For example,
415 if we declare
416
417 data C a where
418 MkC :: Show a => a -> C a
419
420 we will not be able to use MkC in types, as we have no way of creating
421 a type-level Show dictionary.
422
423 However, we make an exception for equality types. Consider
424
425 data T1 a where
426 MkT1 :: T1 Bool
427
428 data T2 a where
429 MkT2 :: a ~ Bool => T2 a
430
431 MkT1 has a constrained return type, while MkT2 uses an explicit equality
432 constraint. These two types are often written interchangeably, with a
433 reasonable expectation that they mean the same thing. For this to work --
434 and for us to be able to promote GADTs -- we need to be able to instantiate
435 equality constraints in types.
436
437 One wrinkle is that the equality in MkT2 is *lifted*. But, for proper
438 GADT equalities, GHC produces *unlifted* constraints. (This unlifting comes
439 from DataCon.eqSpecPreds, which uses mkPrimEqPred.) And, perhaps a wily
440 user will use (~~) for a heterogeneous equality. We thus must support
441 all of (~), (~~), and (~#) in types. (See Note [The equality types story]
442 in TysPrim for a primer on these equality types.)
443
444 The get_eq_tys_maybe function recognizes these three forms of equality,
445 returning a suitable type formation function and the two types related
446 by the equality constraint. In the lifted case, it uses mkHEqBoxTy or
447 mkEqBoxTy, which promote the datacons of the (~~) or (~) datatype,
448 respectively.
449
450 One might reasonably wonder who *unpacks* these boxes once they are
451 made. After all, there is no type-level `case` construct. The surprising
452 answer is that no one ever does. Instead, if a GADT constructor is used
453 on the left-hand side of a type family equation, that occurrence forces
454 GHC to unify the types in question. For example:
455
456 data G a where
457 MkG :: G Bool
458
459 type family F (x :: G a) :: a where
460 F MkG = False
461
462 When checking the LHS `F MkG`, GHC sees the MkG constructor and then must
463 unify F's implicit parameter `a` with Bool. This succeeds, making the equation
464
465 F Bool (MkG @Bool <Bool>) = False
466
467 Note that we never need unpack the coercion. This is because type family
468 equations are *not* parametric in their kind variables. That is, we could have
469 just said
470
471 type family H (x :: G a) :: a where
472 H _ = False
473
474 The presence of False on the RHS also forces `a` to become Bool, giving us
475
476 H Bool _ = False
477
478 The fact that any of this works stems from the lack of phase separation between
479 types and kinds (unlike the very present phase separation between terms and types).
480
481 Once we have the ability to pattern-match on types below top-level, this will
482 no longer cut it, but it seems fine for now.
483
484 -}
485
486 ---------------------------
487 -- | This is used to instantiate binders when type-checking *types* only.
488 -- The @VarEnv Kind@ gives some known instantiations.
489 -- See also Note [Bidirectional type checking]
490 tcInstTyBinders :: TCvSubst -> Maybe (VarEnv Kind)
491 -> [TyBinder] -> TcM (TCvSubst, [TcType])
492 tcInstTyBinders subst mb_kind_info bndrs
493 = do { (subst, args) <- mapAccumLM (tcInstTyBinder mb_kind_info) subst bndrs
494 ; traceTc "instantiating tybinders:"
495 (vcat $ zipWith (\bndr arg -> ppr bndr <+> text ":=" <+> ppr arg)
496 bndrs args)
497 ; return (subst, args) }
498
499 -- | Used only in *types*
500 tcInstTyBinder :: Maybe (VarEnv Kind)
501 -> TCvSubst -> TyBinder -> TcM (TCvSubst, TcType)
502 tcInstTyBinder mb_kind_info subst (Named (TvBndr tv _))
503 = case lookup_tv tv of
504 Just ki -> return (extendTvSubstAndInScope subst tv ki, ki)
505 Nothing -> do { (subst', tv') <- newMetaTyVarX subst tv
506 ; return (subst', mkTyVarTy tv') }
507 where
508 lookup_tv tv = do { env <- mb_kind_info -- `Maybe` monad
509 ; lookupVarEnv env tv }
510
511
512 tcInstTyBinder _ subst (Anon ty)
513 -- This is the *only* constraint currently handled in types.
514 | Just (mk, k1, k2) <- get_eq_tys_maybe substed_ty
515 = do { co <- unifyKind Nothing k1 k2
516 ; arg' <- mk co
517 ; return (subst, arg') }
518
519 | isPredTy substed_ty
520 = do { let (env, tidy_ty) = tidyOpenType emptyTidyEnv substed_ty
521 ; addErrTcM (env, text "Illegal constraint in a kind:" <+> ppr tidy_ty)
522
523 -- just invent a new variable so that we can continue
524 ; u <- newUnique
525 ; let name = mkSysTvName u (fsLit "dict")
526 ; return (subst, mkTyVarTy $ mkTyVar name substed_ty) }
527
528
529 | otherwise
530 = do { tv_ty <- newFlexiTyVarTy substed_ty
531 ; return (subst, tv_ty) }
532
533 where
534 substed_ty = substTy subst ty
535
536 -- See Note [Constraints handled in types]
537 get_eq_tys_maybe :: Type
538 -> Maybe ( Coercion -> TcM Type
539 -- given a coercion proving t1 ~# t2, produce the
540 -- right instantiation for the TyBinder at hand
541 , Type -- t1
542 , Type -- t2
543 )
544 get_eq_tys_maybe ty
545 -- unlifted equality (~#)
546 | Just (Nominal, k1, k2) <- getEqPredTys_maybe ty
547 = Just (\co -> return $ mkCoercionTy co, k1, k2)
548
549 -- lifted heterogeneous equality (~~)
550 | Just (tc, [_, _, k1, k2]) <- splitTyConApp_maybe ty
551 = if | tc `hasKey` heqTyConKey
552 -> Just (\co -> mkHEqBoxTy co k1 k2, k1, k2)
553 | otherwise
554 -> Nothing
555
556 -- lifted homogeneous equality (~)
557 | Just (tc, [_, k1, k2]) <- splitTyConApp_maybe ty
558 = if | tc `hasKey` eqTyConKey
559 -> Just (\co -> mkEqBoxTy co k1 k2, k1, k2)
560 | otherwise
561 -> Nothing
562
563 | otherwise
564 = Nothing
565
566 -------------------------------
567 -- | This takes @a ~# b@ and returns @a ~~ b@.
568 mkHEqBoxTy :: TcCoercion -> Type -> Type -> TcM Type
569 -- monadic just for convenience with mkEqBoxTy
570 mkHEqBoxTy co ty1 ty2
571 = return $
572 mkTyConApp (promoteDataCon heqDataCon) [k1, k2, ty1, ty2, mkCoercionTy co]
573 where k1 = typeKind ty1
574 k2 = typeKind ty2
575
576 -- | This takes @a ~# b@ and returns @a ~ b@.
577 mkEqBoxTy :: TcCoercion -> Type -> Type -> TcM Type
578 mkEqBoxTy co ty1 ty2
579 = return $
580 mkTyConApp (promoteDataCon eqDataCon) [k, ty1, ty2, mkCoercionTy co]
581 where k = typeKind ty1
582
583 {-
584 ************************************************************************
585 * *
586 Literals
587 * *
588 ************************************************************************
589
590 -}
591
592 {-
593 In newOverloadedLit we convert directly to an Int or Integer if we
594 know that's what we want. This may save some time, by not
595 temporarily generating overloaded literals, but it won't catch all
596 cases (the rest are caught in lookupInst).
597
598 -}
599
600 newOverloadedLit :: HsOverLit GhcRn
601 -> ExpRhoType
602 -> TcM (HsOverLit GhcTcId)
603 newOverloadedLit
604 lit@(OverLit { ol_val = val, ol_ext = rebindable }) res_ty
605 | not rebindable
606 -- all built-in overloaded lits are tau-types, so we can just
607 -- tauify the ExpType
608 = do { res_ty <- expTypeToType res_ty
609 ; dflags <- getDynFlags
610 ; case shortCutLit dflags val res_ty of
611 -- Do not generate a LitInst for rebindable syntax.
612 -- Reason: If we do, tcSimplify will call lookupInst, which
613 -- will call tcSyntaxName, which does unification,
614 -- which tcSimplify doesn't like
615 Just expr -> return (lit { ol_witness = expr
616 , ol_ext = OverLitTc False res_ty })
617 Nothing -> newNonTrivialOverloadedLit orig lit
618 (mkCheckExpType res_ty) }
619
620 | otherwise
621 = newNonTrivialOverloadedLit orig lit res_ty
622 where
623 orig = LiteralOrigin lit
624 newOverloadedLit XOverLit{} _ = panic "newOverloadedLit"
625
626 -- Does not handle things that 'shortCutLit' can handle. See also
627 -- newOverloadedLit in TcUnify
628 newNonTrivialOverloadedLit :: CtOrigin
629 -> HsOverLit GhcRn
630 -> ExpRhoType
631 -> TcM (HsOverLit GhcTcId)
632 newNonTrivialOverloadedLit orig
633 lit@(OverLit { ol_val = val, ol_witness = HsVar _ (L _ meth_name)
634 , ol_ext = rebindable }) res_ty
635 = do { hs_lit <- mkOverLit val
636 ; let lit_ty = hsLitType hs_lit
637 ; (_, fi') <- tcSyntaxOp orig (mkRnSyntaxExpr meth_name)
638 [synKnownType lit_ty] res_ty $
639 \_ -> return ()
640 ; let L _ witness = nlHsSyntaxApps fi' [nlHsLit hs_lit]
641 ; res_ty <- readExpType res_ty
642 ; return (lit { ol_witness = witness
643 , ol_ext = OverLitTc rebindable res_ty }) }
644 newNonTrivialOverloadedLit _ lit _
645 = pprPanic "newNonTrivialOverloadedLit" (ppr lit)
646
647 ------------
648 mkOverLit ::OverLitVal -> TcM (HsLit GhcTc)
649 mkOverLit (HsIntegral i)
650 = do { integer_ty <- tcMetaTy integerTyConName
651 ; return (HsInteger (il_text i)
652 (il_value i) integer_ty) }
653
654 mkOverLit (HsFractional r)
655 = do { rat_ty <- tcMetaTy rationalTyConName
656 ; return (HsRat noExt r rat_ty) }
657
658 mkOverLit (HsIsString src s) = return (HsString src s)
659
660 {-
661 ************************************************************************
662 * *
663 Re-mappable syntax
664
665 Used only for arrow syntax -- find a way to nuke this
666 * *
667 ************************************************************************
668
669 Suppose we are doing the -XRebindableSyntax thing, and we encounter
670 a do-expression. We have to find (>>) in the current environment, which is
671 done by the rename. Then we have to check that it has the same type as
672 Control.Monad.(>>). Or, more precisely, a compatible type. One 'customer' had
673 this:
674
675 (>>) :: HB m n mn => m a -> n b -> mn b
676
677 So the idea is to generate a local binding for (>>), thus:
678
679 let then72 :: forall a b. m a -> m b -> m b
680 then72 = ...something involving the user's (>>)...
681 in
682 ...the do-expression...
683
684 Now the do-expression can proceed using then72, which has exactly
685 the expected type.
686
687 In fact tcSyntaxName just generates the RHS for then72, because we only
688 want an actual binding in the do-expression case. For literals, we can
689 just use the expression inline.
690 -}
691
692 tcSyntaxName :: CtOrigin
693 -> TcType -- ^ Type to instantiate it at
694 -> (Name, HsExpr GhcRn) -- ^ (Standard name, user name)
695 -> TcM (Name, HsExpr GhcTcId)
696 -- ^ (Standard name, suitable expression)
697 -- USED ONLY FOR CmdTop (sigh) ***
698 -- See Note [CmdSyntaxTable] in HsExpr
699
700 tcSyntaxName orig ty (std_nm, HsVar _ (L _ user_nm))
701 | std_nm == user_nm
702 = do rhs <- newMethodFromName orig std_nm ty
703 return (std_nm, rhs)
704
705 tcSyntaxName orig ty (std_nm, user_nm_expr) = do
706 std_id <- tcLookupId std_nm
707 let
708 -- C.f. newMethodAtLoc
709 ([tv], _, tau) = tcSplitSigmaTy (idType std_id)
710 sigma1 = substTyWith [tv] [ty] tau
711 -- Actually, the "tau-type" might be a sigma-type in the
712 -- case of locally-polymorphic methods.
713
714 addErrCtxtM (syntaxNameCtxt user_nm_expr orig sigma1) $ do
715
716 -- Check that the user-supplied thing has the
717 -- same type as the standard one.
718 -- Tiresome jiggling because tcCheckSigma takes a located expression
719 span <- getSrcSpanM
720 expr <- tcPolyExpr (L span user_nm_expr) sigma1
721 return (std_nm, unLoc expr)
722
723 syntaxNameCtxt :: HsExpr GhcRn -> CtOrigin -> Type -> TidyEnv
724 -> TcRn (TidyEnv, SDoc)
725 syntaxNameCtxt name orig ty tidy_env
726 = do { inst_loc <- getCtLocM orig (Just TypeLevel)
727 ; let msg = vcat [ text "When checking that" <+> quotes (ppr name)
728 <+> text "(needed by a syntactic construct)"
729 , nest 2 (text "has the required type:"
730 <+> ppr (tidyType tidy_env ty))
731 , nest 2 (pprCtLoc inst_loc) ]
732 ; return (tidy_env, msg) }
733
734 {-
735 ************************************************************************
736 * *
737 Instances
738 * *
739 ************************************************************************
740 -}
741
742 getOverlapFlag :: Maybe OverlapMode -> TcM OverlapFlag
743 -- Construct the OverlapFlag from the global module flags,
744 -- but if the overlap_mode argument is (Just m),
745 -- set the OverlapMode to 'm'
746 getOverlapFlag overlap_mode
747 = do { dflags <- getDynFlags
748 ; let overlap_ok = xopt LangExt.OverlappingInstances dflags
749 incoherent_ok = xopt LangExt.IncoherentInstances dflags
750 use x = OverlapFlag { isSafeOverlap = safeLanguageOn dflags
751 , overlapMode = x }
752 default_oflag | incoherent_ok = use (Incoherent NoSourceText)
753 | overlap_ok = use (Overlaps NoSourceText)
754 | otherwise = use (NoOverlap NoSourceText)
755
756 final_oflag = setOverlapModeMaybe default_oflag overlap_mode
757 ; return final_oflag }
758
759 tcGetInsts :: TcM [ClsInst]
760 -- Gets the local class instances.
761 tcGetInsts = fmap tcg_insts getGblEnv
762
763 newClsInst :: Maybe OverlapMode -> Name -> [TyVar] -> ThetaType
764 -> Class -> [Type] -> TcM ClsInst
765 newClsInst overlap_mode dfun_name tvs theta clas tys
766 = do { (subst, tvs') <- freshenTyVarBndrs tvs
767 -- Be sure to freshen those type variables,
768 -- so they are sure not to appear in any lookup
769 ; let tys' = substTys subst tys
770
771 dfun = mkDictFunId dfun_name tvs theta clas tys
772 -- The dfun uses the original 'tvs' because
773 -- (a) they don't need to be fresh
774 -- (b) they may be mentioned in the ib_binds field of
775 -- an InstInfo, and in TcEnv.pprInstInfoDetails it's
776 -- helpful to use the same names
777
778 ; oflag <- getOverlapFlag overlap_mode
779 ; let inst = mkLocalInstance dfun oflag tvs' clas tys'
780 ; warnIfFlag Opt_WarnOrphans
781 (isOrphan (is_orphan inst))
782 (instOrphWarn inst)
783 ; return inst }
784
785 instOrphWarn :: ClsInst -> SDoc
786 instOrphWarn inst
787 = hang (text "Orphan instance:") 2 (pprInstanceHdr inst)
788 $$ text "To avoid this"
789 $$ nest 4 (vcat possibilities)
790 where
791 possibilities =
792 text "move the instance declaration to the module of the class or of the type, or" :
793 text "wrap the type with a newtype and declare the instance on the new type." :
794 []
795
796 tcExtendLocalInstEnv :: [ClsInst] -> TcM a -> TcM a
797 -- Add new locally-defined instances
798 tcExtendLocalInstEnv dfuns thing_inside
799 = do { traceDFuns dfuns
800 ; env <- getGblEnv
801 ; (inst_env', cls_insts') <- foldlM addLocalInst
802 (tcg_inst_env env, tcg_insts env)
803 dfuns
804 ; let env' = env { tcg_insts = cls_insts'
805 , tcg_inst_env = inst_env' }
806 ; setGblEnv env' thing_inside }
807
808 addLocalInst :: (InstEnv, [ClsInst]) -> ClsInst -> TcM (InstEnv, [ClsInst])
809 -- Check that the proposed new instance is OK,
810 -- and then add it to the home inst env
811 -- If overwrite_inst, then we can overwrite a direct match
812 addLocalInst (home_ie, my_insts) ispec
813 = do {
814 -- Load imported instances, so that we report
815 -- duplicates correctly
816
817 -- 'matches' are existing instance declarations that are less
818 -- specific than the new one
819 -- 'dups' are those 'matches' that are equal to the new one
820 ; isGHCi <- getIsGHCi
821 ; eps <- getEps
822 ; tcg_env <- getGblEnv
823
824 -- In GHCi, we *override* any identical instances
825 -- that are also defined in the interactive context
826 -- See Note [Override identical instances in GHCi]
827 ; let home_ie'
828 | isGHCi = deleteFromInstEnv home_ie ispec
829 | otherwise = home_ie
830
831 global_ie = eps_inst_env eps
832 inst_envs = InstEnvs { ie_global = global_ie
833 , ie_local = home_ie'
834 , ie_visible = tcVisibleOrphanMods tcg_env }
835
836 -- Check for inconsistent functional dependencies
837 ; let inconsistent_ispecs = checkFunDeps inst_envs ispec
838 ; unless (null inconsistent_ispecs) $
839 funDepErr ispec inconsistent_ispecs
840
841 -- Check for duplicate instance decls.
842 ; let (_tvs, cls, tys) = instanceHead ispec
843 (matches, _, _) = lookupInstEnv False inst_envs cls tys
844 dups = filter (identicalClsInstHead ispec) (map fst matches)
845 ; unless (null dups) $
846 dupInstErr ispec (head dups)
847
848 ; return (extendInstEnv home_ie' ispec, ispec : my_insts) }
849
850 {-
851 Note [Signature files and type class instances]
852 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
853 Instances in signature files do not have an effect when compiling:
854 when you compile a signature against an implementation, you will
855 see the instances WHETHER OR NOT the instance is declared in
856 the file (this is because the signatures go in the EPS and we
857 can't filter them out easily.) This is also why we cannot
858 place the instance in the hi file: it would show up as a duplicate,
859 and we don't have instance reexports anyway.
860
861 However, you might find them useful when typechecking against
862 a signature: the instance is a way of indicating to GHC that
863 some instance exists, in case downstream code uses it.
864
865 Implementing this is a little tricky. Consider the following
866 situation (sigof03):
867
868 module A where
869 instance C T where ...
870
871 module ASig where
872 instance C T
873
874 When compiling ASig, A.hi is loaded, which brings its instances
875 into the EPS. When we process the instance declaration in ASig,
876 we should ignore it for the purpose of doing a duplicate check,
877 since it's not actually a duplicate. But don't skip the check
878 entirely, we still want this to fail (tcfail221):
879
880 module ASig where
881 instance C T
882 instance C T
883
884 Note that in some situations, the interface containing the type
885 class instances may not have been loaded yet at all. The usual
886 situation when A imports another module which provides the
887 instances (sigof02m):
888
889 module A(module B) where
890 import B
891
892 See also Note [Signature lazy interface loading]. We can't
893 rely on this, however, since sometimes we'll have spurious
894 type class instances in the EPS, see #9422 (sigof02dm)
895
896 ************************************************************************
897 * *
898 Errors and tracing
899 * *
900 ************************************************************************
901 -}
902
903 traceDFuns :: [ClsInst] -> TcRn ()
904 traceDFuns ispecs
905 = traceTc "Adding instances:" (vcat (map pp ispecs))
906 where
907 pp ispec = hang (ppr (instanceDFunId ispec) <+> colon)
908 2 (ppr ispec)
909 -- Print the dfun name itself too
910
911 funDepErr :: ClsInst -> [ClsInst] -> TcRn ()
912 funDepErr ispec ispecs
913 = addClsInstsErr (text "Functional dependencies conflict between instance declarations:")
914 (ispec : ispecs)
915
916 dupInstErr :: ClsInst -> ClsInst -> TcRn ()
917 dupInstErr ispec dup_ispec
918 = addClsInstsErr (text "Duplicate instance declarations:")
919 [ispec, dup_ispec]
920
921 addClsInstsErr :: SDoc -> [ClsInst] -> TcRn ()
922 addClsInstsErr herald ispecs
923 = setSrcSpan (getSrcSpan (head sorted)) $
924 addErr (hang herald 2 (pprInstances sorted))
925 where
926 sorted = sortWith getSrcLoc ispecs
927 -- The sortWith just arranges that instances are dislayed in order
928 -- of source location, which reduced wobbling in error messages,
929 -- and is better for users