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