2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
6 TcInstDecls: Typechecking instance declarations
9 module TcInstDcls ( tcInstDecls1, tcInstDecls2 ) where
15 import TcPat( addInlinePrags )
23 import MkCore ( nO_METHOD_BINDING_ERROR_ID )
26 import RnSource ( addTcgDUs )
36 import CoreUtils ( mkPiTypes )
37 import CoreUnfold ( mkDFunUnfolding )
38 import CoreSyn ( Expr(Var), DFunArg(..), CoreExpr )
51 import Maybes ( orElse )
56 #include "HsVersions.h"
59 Typechecking instance declarations is done in two passes. The first
60 pass, made by @tcInstDecls1@, collects information to be used in the
63 This pre-processed info includes the as-yet-unprocessed bindings
64 inside the instance declaration. These are type-checked in the second
65 pass, when the class-instance envs and GVE contain all the info from
66 all the instance and value decls. Indeed that's the reason we need
67 two passes over the instance decls.
70 Note [How instance declarations are translated]
71 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
72 Here is how we translation instance declarations into Core
76 op1, op2 :: Ix b => a -> b -> b
80 {-# INLINE [2] op1 #-}
84 op1,op2 :: forall a. C a => forall b. Ix b => a -> b -> b
88 -- Default methods get the 'self' dictionary as argument
89 -- so they can call other methods at the same type
90 -- Default methods get the same type as their method selector
91 $dmop2 :: forall a. C a => forall b. Ix b => a -> b -> b
92 $dmop2 = /\a. \(d:C a). /\b. \(d2: Ix b). <dm-rhs>
93 -- NB: type variables 'a' and 'b' are *both* in scope in <dm-rhs>
94 -- Note [Tricky type variable scoping]
96 -- A top-level definition for each instance method
97 -- Here op1_i, op2_i are the "instance method Ids"
98 -- The INLINE pragma comes from the user pragma
99 {-# INLINE [2] op1_i #-} -- From the instance decl bindings
100 op1_i, op2_i :: forall a. C a => forall b. Ix b => [a] -> b -> b
101 op1_i = /\a. \(d:C a).
104 -- Note [Subtle interaction of recursion and overlap]
106 local_op1 :: forall b. Ix b => [a] -> b -> b
108 -- Source code; run the type checker on this
109 -- NB: Type variable 'a' (but not 'b') is in scope in <rhs>
110 -- Note [Tricky type variable scoping]
114 op2_i = /\a \d:C a. $dmop2 [a] (df_i a d)
116 -- The dictionary function itself
117 {-# NOINLINE CONLIKE df_i #-} -- Never inline dictionary functions
118 df_i :: forall a. C a -> C [a]
119 df_i = /\a. \d:C a. MkC (op1_i a d) (op2_i a d)
120 -- But see Note [Default methods in instances]
121 -- We can't apply the type checker to the default-method call
123 -- Use a RULE to short-circuit applications of the class ops
124 {-# RULE "op1@C[a]" forall a, d:C a.
125 op1 [a] (df_i d) = op1_i a d #-}
127 Note [Instances and loop breakers]
128 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
129 * Note that df_i may be mutually recursive with both op1_i and op2_i.
130 It's crucial that df_i is not chosen as the loop breaker, even
131 though op1_i has a (user-specified) INLINE pragma.
133 * Instead the idea is to inline df_i into op1_i, which may then select
134 methods from the MkC record, and thereby break the recursion with
135 df_i, leaving a *self*-recurisve op1_i. (If op1_i doesn't call op at
136 the same type, it won't mention df_i, so there won't be recursion in
139 * If op1_i is marked INLINE by the user there's a danger that we won't
140 inline df_i in it, and that in turn means that (since it'll be a
141 loop-breaker because df_i isn't), op1_i will ironically never be
142 inlined. But this is OK: the recursion breaking happens by way of
143 a RULE (the magic ClassOp rule above), and RULES work inside InlineRule
144 unfoldings. See Note [RULEs enabled in SimplGently] in SimplUtils
146 Note [ClassOp/DFun selection]
147 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
148 One thing we see a lot is stuff like
150 where 'op2' is a ClassOp and 'df' is DFun. Now, we could inline *both*
151 'op2' and 'df' to get
152 case (MkD ($cop1 d1 d2) ($cop2 d1 d2) ... of
153 MkD _ op2 _ _ _ -> op2
154 And that will reduce to ($cop2 d1 d2) which is what we wanted.
156 But it's tricky to make this work in practice, because it requires us to
157 inline both 'op2' and 'df'. But neither is keen to inline without having
158 seen the other's result; and it's very easy to get code bloat (from the
159 big intermediate) if you inline a bit too much.
161 Instead we use a cunning trick.
162 * We arrange that 'df' and 'op2' NEVER inline.
164 * We arrange that 'df' is ALWAYS defined in the sylised form
165 df d1 d2 = MkD ($cop1 d1 d2) ($cop2 d1 d2) ...
167 * We give 'df' a magical unfolding (DFunUnfolding [$cop1, $cop2, ..])
168 that lists its methods.
170 * We make CoreUnfold.exprIsConApp_maybe spot a DFunUnfolding and return
171 a suitable constructor application -- inlining df "on the fly" as it
174 * We give the ClassOp 'op2' a BuiltinRule that extracts the right piece
175 iff its argument satisfies exprIsConApp_maybe. This is done in
178 * We make 'df' CONLIKE, so that shared uses stil match; eg
180 in ...(op2 d)...(op1 d)...
182 Note [Single-method classes]
183 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
184 If the class has just one method (or, more accurately, just one element
185 of {superclasses + methods}), then we use a different strategy.
187 class C a where op :: a -> a
188 instance C a => C [a] where op = <blah>
190 We translate the class decl into a newtype, which just gives a
191 top-level axiom. The "constructor" MkC expands to a cast, as does the
194 axiom Co:C a :: C a ~ (a->a)
196 op :: forall a. C a -> (a -> a)
197 op a d = d |> (Co:C a)
199 MkC :: forall a. (a->a) -> C a
200 MkC = /\a.\op. op |> (sym Co:C a)
202 The clever RULE stuff doesn't work now, because ($df a d) isn't
203 a constructor application, so exprIsConApp_maybe won't return
206 Instead, we simply rely on the fact that casts are cheap:
208 $df :: forall a. C a => C [a]
209 {-# INLINE df #} -- NB: INLINE this
210 $df = /\a. \d. MkC [a] ($cop_list a d)
211 = $cop_list |> forall a. C a -> (sym (Co:C [a]))
213 $cop_list :: forall a. C a => [a] -> [a]
218 we'll inline 'op' and '$df', since both are simply casts, and
221 Why do we use this different strategy? Because otherwise we
222 end up with non-inlined dictionaries that look like
224 which adds an extra indirection to every use, which seems stupid. See
225 Trac #4138 for an example (although the regression reported there
226 wasn't due to the indirction).
228 There is an awkward wrinkle though: we want to be very
230 instance C a => C [a] where
233 then we'll get an INLINE pragma on $cop_list but it's important that
234 $cop_list only inlines when it's applied to *two* arguments (the
235 dictionary and the list argument). So we nust not eta-expand $df
236 above. We ensure that this doesn't happen by putting an INLINE
237 pragma on the dfun itself; after all, it ends up being just a cast.
239 There is one more dark corner to the INLINE story, even more deeply
240 buried. Consider this (Trac #3772):
242 class DeepSeq a => C a where
245 instance C a => C [a] where
248 class DeepSeq a where
249 deepSeq :: a -> b -> b
251 instance DeepSeq a => DeepSeq [a] where
252 {-# INLINE deepSeq #-}
253 deepSeq xs b = foldr deepSeq b xs
255 That gives rise to these defns:
257 $cdeepSeq :: DeepSeq a -> [a] -> b -> b
258 -- User INLINE( 3 args )!
259 $cdeepSeq a (d:DS a) b (x:[a]) (y:b) = ...
261 $fDeepSeq[] :: DeepSeq a -> DeepSeq [a]
262 -- DFun (with auto INLINE pragma)
263 $fDeepSeq[] a d = $cdeepSeq a d |> blah
265 $cp1 a d :: C a => DeepSep [a]
266 -- We don't want to eta-expand this, lest
267 -- $cdeepSeq gets inlined in it!
268 $cp1 a d = $fDeepSep[] a (scsel a d)
270 $fC[] :: C a => C [a]
272 $fC[] a d = MkC ($cp1 a d) ($cgen a d)
274 Here $cp1 is the code that generates the superclass for C [a]. The
275 issue is this: we must not eta-expand $cp1 either, or else $fDeepSeq[]
276 and then $cdeepSeq will inline there, which is definitely wrong. Like
277 on the dfun, we solve this by adding an INLINE pragma to $cp1.
279 Note [Subtle interaction of recursion and overlap]
280 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
282 class C a where { op1,op2 :: a -> a }
283 instance C a => C [a] where
284 op1 x = op2 x ++ op2 x
286 instance C [Int] where
289 When type-checking the C [a] instance, we need a C [a] dictionary (for
290 the call of op2). If we look up in the instance environment, we find
291 an overlap. And in *general* the right thing is to complain (see Note
292 [Overlapping instances] in InstEnv). But in *this* case it's wrong to
293 complain, because we just want to delegate to the op2 of this same
296 Why is this justified? Because we generate a (C [a]) constraint in
297 a context in which 'a' cannot be instantiated to anything that matches
298 other overlapping instances, or else we would not be excecuting this
299 version of op1 in the first place.
301 It might even be a bit disguised:
303 nullFail :: C [a] => [a] -> [a]
304 nullFail x = op2 x ++ op2 x
306 instance C a => C [a] where
309 Precisely this is used in package 'regex-base', module Context.hs.
310 See the overlapping instances for RegexContext, and the fact that they
311 call 'nullFail' just like the example above. The DoCon package also
312 does the same thing; it shows up in module Fraction.hs
314 Conclusion: when typechecking the methods in a C [a] instance, we want to
315 treat the 'a' as an *existential* type variable, in the sense described
316 by Note [Binding when looking up instances]. That is why isOverlappableTyVar
317 responds True to an InstSkol, which is the kind of skolem we use in
321 Note [Tricky type variable scoping]
322 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
325 op1, op2 :: Ix b => a -> b -> b
328 instance C a => C [a]
329 {-# INLINE [2] op1 #-}
332 note that 'a' and 'b' are *both* in scope in <dm-rhs>, but only 'a' is
333 in scope in <rhs>. In particular, we must make sure that 'b' is in
334 scope when typechecking <dm-rhs>. This is achieved by subFunTys,
335 which brings appropriate tyvars into scope. This happens for both
336 <dm-rhs> and for <rhs>, but that doesn't matter: the *renamer* will have
337 complained if 'b' is mentioned in <rhs>.
341 %************************************************************************
343 \subsection{Extracting instance decls}
345 %************************************************************************
347 Gather up the instance declarations from their various sources
350 tcInstDecls1 -- Deal with both source-code and imported instance decls
351 :: [LTyClDecl Name] -- For deriving stuff
352 -> [LInstDecl Name] -- Source code instance decls
353 -> [LDerivDecl Name] -- Source code stand-alone deriving decls
354 -> TcM (TcGblEnv, -- The full inst env
355 [InstInfo Name], -- Source-code instance decls to process;
356 -- contains all dfuns for this module
357 HsValBinds Name) -- Supporting bindings for derived instances
359 tcInstDecls1 tycl_decls inst_decls deriv_decls
361 do { -- Stop if addInstInfos etc discovers any errors
362 -- (they recover, so that we get more than one error each
365 -- (1) Do class and family instance declarations
366 ; idx_tycons <- mapAndRecoverM (tcFamInstDecl TopLevel) $
367 filter (isFamInstDecl . unLoc) tycl_decls
368 ; local_info_tycons <- mapAndRecoverM tcLocalInstDecl1 inst_decls
371 at_tycons_s) = unzip local_info_tycons
372 ; at_idx_tycons = concat at_tycons_s ++ idx_tycons
373 ; clas_decls = filter (isClassDecl . unLoc) tycl_decls
374 ; implicit_things = concatMap implicitTyThings at_idx_tycons
375 ; aux_binds = mkRecSelBinds at_idx_tycons
378 -- (2) Add the tycons of indexed types and their implicit
379 -- tythings to the global environment
380 ; tcExtendGlobalEnv (at_idx_tycons ++ implicit_things) $ do {
382 -- (3) Instances from generic class declarations
383 ; generic_inst_info <- getGenericInstances clas_decls
385 -- Next, construct the instance environment so far, consisting
387 -- (a) local instance decls
388 -- (b) generic instances
389 -- (c) local family instance decls
390 ; addInsts local_info $
391 addInsts generic_inst_info $
392 addFamInsts at_idx_tycons $ do {
394 -- (4) Compute instances from "deriving" clauses;
395 -- This stuff computes a context for the derived instance
396 -- decl, so it needs to know about all the instances possible
397 -- NB: class instance declarations can contain derivings as
398 -- part of associated data type declarations
399 failIfErrsM -- If the addInsts stuff gave any errors, don't
400 -- try the deriving stuff, becuase that may give
402 ; (deriv_inst_info, deriv_binds, deriv_dus)
403 <- tcDeriving tycl_decls inst_decls deriv_decls
404 ; gbl_env <- addInsts deriv_inst_info getGblEnv
405 ; return ( addTcgDUs gbl_env deriv_dus,
406 generic_inst_info ++ deriv_inst_info ++ local_info,
407 aux_binds `plusHsValBinds` deriv_binds)
410 addInsts :: [InstInfo Name] -> TcM a -> TcM a
411 addInsts infos thing_inside
412 = tcExtendLocalInstEnv (map iSpec infos) thing_inside
414 addFamInsts :: [TyThing] -> TcM a -> TcM a
415 addFamInsts tycons thing_inside
416 = tcExtendLocalFamInstEnv (map mkLocalFamInstTyThing tycons) thing_inside
418 mkLocalFamInstTyThing (ATyCon tycon) = mkLocalFamInst tycon
419 mkLocalFamInstTyThing tything = pprPanic "TcInstDcls.addFamInsts"
424 tcLocalInstDecl1 :: LInstDecl Name
425 -> TcM (InstInfo Name, [TyThing])
426 -- A source-file instance declaration
427 -- Type-check all the stuff before the "where"
429 -- We check for respectable instance type, and context
430 tcLocalInstDecl1 (L loc (InstDecl poly_ty binds uprags ats))
432 addErrCtxt (instDeclCtxt1 poly_ty) $
434 do { is_boot <- tcIsHsBoot
435 ; checkTc (not is_boot || (isEmptyLHsBinds binds && null uprags))
438 ; (tyvars, theta, clas, inst_tys) <- tcHsInstHead poly_ty
439 ; checkValidInstance poly_ty tyvars theta clas inst_tys
441 -- Next, process any associated types.
442 ; idx_tycons <- recoverM (return []) $
443 do { idx_tycons <- checkNoErrs $
444 mapAndRecoverM (tcFamInstDecl NotTopLevel) ats
445 ; checkValidAndMissingATs clas (tyvars, inst_tys)
447 ; return idx_tycons }
449 -- Finally, construct the Core representation of the instance.
450 -- (This no longer includes the associated types.)
451 ; dfun_name <- newDFunName clas inst_tys (getLoc poly_ty)
452 -- Dfun location is that of instance *header*
453 ; overlap_flag <- getOverlapFlag
454 ; let (eq_theta,dict_theta) = partition isEqPred theta
455 theta' = eq_theta ++ dict_theta
456 dfun = mkDictFunId dfun_name tyvars theta' clas inst_tys
457 ispec = mkLocalInstance dfun overlap_flag
459 ; return (InstInfo { iSpec = ispec, iBinds = VanillaInst binds uprags False },
463 -- We pass in the source form and the type checked form of the ATs. We
464 -- really need the source form only to be able to produce more informative
466 checkValidAndMissingATs :: Class
467 -> ([TyVar], [TcType]) -- instance types
468 -> [(LTyClDecl Name, -- source form of AT
469 TyThing)] -- Core form of AT
471 checkValidAndMissingATs clas inst_tys ats
472 = do { -- Issue a warning for each class AT that is not defined in this
474 ; let class_ats = map tyConName (classATs clas)
475 defined_ats = listToNameSet . map (tcdName.unLoc.fst) $ ats
476 omitted = filterOut (`elemNameSet` defined_ats) class_ats
477 ; warn <- doptM Opt_WarnMissingMethods
478 ; mapM_ (warnTc warn . omittedATWarn) omitted
480 -- Ensure that all AT indexes that correspond to class parameters
481 -- coincide with the types in the instance head. All remaining
482 -- AT arguments must be variables. Also raise an error for any
483 -- type instances that are not associated with this class.
484 ; mapM_ (checkIndexes clas inst_tys) ats
487 checkIndexes clas inst_tys (hsAT, ATyCon tycon)
488 -- !!!TODO: check that this does the Right Thing for indexed synonyms, too!
489 = checkIndexes' clas inst_tys hsAT
491 snd . fromJust . tyConFamInst_maybe $ tycon)
492 checkIndexes _ _ _ = panic "checkIndexes"
494 checkIndexes' clas (instTvs, instTys) hsAT (atTvs, atTys)
495 = let atName = tcdName . unLoc $ hsAT
497 setSrcSpan (getLoc hsAT) $
498 addErrCtxt (atInstCtxt atName) $
499 case find ((atName ==) . tyConName) (classATs clas) of
500 Nothing -> addErrTc $ badATErr clas atName -- not in this class
502 -- The following is tricky! We need to deal with three
503 -- complications: (1) The AT possibly only uses a subset of
504 -- the class parameters as indexes and those it uses may be in
505 -- a different order; (2) the AT may have extra arguments,
506 -- which must be type variables; and (3) variables in AT and
507 -- instance head will be different `Name's even if their
508 -- source lexemes are identical.
510 -- e.g. class C a b c where
511 -- data D b a :: * -> * -- NB (1) b a, omits c
512 -- instance C [x] Bool Char where
513 -- data D Bool [x] v = MkD x [v] -- NB (2) v
514 -- -- NB (3) the x in 'instance C...' have differnt
515 -- -- Names to x's in 'data D...'
517 -- Re (1), `poss' contains a permutation vector to extract the
518 -- class parameters in the right order.
520 -- Re (2), we wrap the (permuted) class parameters in a Maybe
521 -- type and use Nothing for any extra AT arguments. (First
522 -- equation of `checkIndex' below.)
524 -- Re (3), we replace any type variable in the AT parameters
525 -- that has the same source lexeme as some variable in the
526 -- instance types with the instance type variable sharing its
530 -- For *associated* type families, gives the position
531 -- of that 'TyVar' in the class argument list (0-indexed)
532 -- e.g. class C a b c where { type F c a :: *->* }
533 -- Then we get Just [2,0]
534 poss = catMaybes [ tv `elemIndex` classTyVars clas
535 | tv <- tyConTyVars atycon]
536 -- We will get Nothings for the "extra" type
537 -- variables in an associated data type
538 -- e.g. class C a where { data D a :: *->* }
539 -- here D gets arity 2 and has two tyvars
541 relevantInstTys = map (instTys !!) poss
542 instArgs = map Just relevantInstTys ++
543 repeat Nothing -- extra arguments
544 renaming = substSameTyVar atTvs instTvs
546 zipWithM_ checkIndex (substTys renaming atTys) instArgs
548 checkIndex ty Nothing
549 | isTyVarTy ty = return ()
550 | otherwise = addErrTc $ mustBeVarArgErr ty
551 checkIndex ty (Just instTy)
552 | ty `tcEqType` instTy = return ()
553 | otherwise = addErrTc $ wrongATArgErr ty instTy
555 listToNameSet = addListToNameSet emptyNameSet
557 substSameTyVar [] _ = emptyTvSubst
558 substSameTyVar (tv:tvs) replacingTvs =
559 let replacement = case find (tv `sameLexeme`) replacingTvs of
560 Nothing -> mkTyVarTy tv
561 Just rtv -> mkTyVarTy rtv
563 tv1 `sameLexeme` tv2 =
564 nameOccName (tyVarName tv1) == nameOccName (tyVarName tv2)
566 extendTvSubst (substSameTyVar tvs replacingTvs) tv replacement
570 %************************************************************************
572 Type-checking instance declarations, pass 2
574 %************************************************************************
577 tcInstDecls2 :: [LTyClDecl Name] -> [InstInfo Name]
579 -- (a) From each class declaration,
580 -- generate any default-method bindings
581 -- (b) From each instance decl
582 -- generate the dfun binding
584 tcInstDecls2 tycl_decls inst_decls
585 = do { -- (a) Default methods from class decls
586 let class_decls = filter (isClassDecl . unLoc) tycl_decls
587 ; dm_binds_s <- mapM tcClassDecl2 class_decls
588 ; let dm_binds = unionManyBags dm_binds_s
590 -- (b) instance declarations
591 ; let dm_ids = collectHsBindsBinders dm_binds
592 -- Add the default method Ids (again)
593 -- See Note [Default methods and instances]
594 ; inst_binds_s <- tcExtendIdEnv dm_ids $
595 mapM tcInstDecl2 inst_decls
598 ; return (dm_binds `unionBags` unionManyBags inst_binds_s) }
601 See Note [Default methods and instances]
602 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
603 The default method Ids are already in the type environment (see Note
604 [Default method Ids and Template Haskell] in TcTyClsDcls), BUT they
605 don't have their InlinePragmas yet. Usually that would not matter,
606 because the simplifier propagates information from binding site to
607 use. But, unusually, when compiling instance decls we *copy* the
608 INLINE pragma from the default method to the method for that
609 particular operation (see Note [INLINE and default methods] below).
611 So right here in tcInstDecl2 we must re-extend the type envt with
612 the default method Ids replete with their INLINE pragmas. Urk.
616 tcInstDecl2 :: InstInfo Name -> TcM (LHsBinds Id)
617 -- Returns a binding for the dfun
618 tcInstDecl2 (InstInfo { iSpec = ispec, iBinds = ibinds })
619 = recoverM (return emptyLHsBinds) $
621 addErrCtxt (instDeclCtxt2 (idType dfun_id)) $
622 do { -- Instantiate the instance decl with skolem constants
623 ; (inst_tyvars, dfun_theta, inst_head) <- tcSkolDFunType (idType dfun_id)
624 ; let (clas, inst_tys) = tcSplitDFunHead inst_head
625 (class_tyvars, sc_theta, _, op_items) = classBigSig clas
626 sc_theta' = substTheta (zipOpenTvSubst class_tyvars inst_tys) sc_theta
627 n_ty_args = length inst_tyvars
628 n_silent = dfunNSilent dfun_id
629 (silent_theta, orig_theta) = splitAt n_silent dfun_theta
631 ; silent_ev_vars <- mapM newSilentGiven silent_theta
632 ; orig_ev_vars <- newEvVars orig_theta
633 ; let dfun_ev_vars = silent_ev_vars ++ orig_ev_vars
635 ; (sc_dicts, sc_args)
636 <- mapAndUnzipM (tcSuperClass n_ty_args dfun_ev_vars) sc_theta'
638 -- Check that any superclasses gotten from a silent arguemnt
639 -- can be deduced from the originally-specified dfun arguments
640 ; ct_loc <- getCtLoc ScOrigin
641 ; _ <- checkConstraints skol_info inst_tyvars orig_ev_vars $
642 emitFlats $ listToBag $
643 [ mkEvVarX sc ct_loc | sc <- sc_dicts, isSilentEvVar sc ]
645 -- Deal with 'SPECIALISE instance' pragmas
646 -- See Note [SPECIALISE instance pragmas]
647 ; spec_info@(spec_inst_prags,_) <- tcSpecInstPrags dfun_id ibinds
649 -- Typecheck the methods
650 ; (meth_ids, meth_binds)
651 <- tcExtendTyVarEnv inst_tyvars $
652 -- The inst_tyvars scope over the 'where' part
653 -- Those tyvars are inside the dfun_id's type, which is a bit
654 -- bizarre, but OK so long as you realise it!
655 tcInstanceMethods dfun_id clas inst_tyvars dfun_ev_vars
659 -- Create the result bindings
660 ; self_dict <- newEvVar (ClassP clas inst_tys)
661 ; let class_tc = classTyCon clas
662 [dict_constr] = tyConDataCons class_tc
663 dict_bind = mkVarBind self_dict dict_rhs
664 dict_rhs = foldl mk_app inst_constr $
665 map HsVar sc_dicts ++ map (wrapId arg_wrapper) meth_ids
666 inst_constr = L loc $ wrapId (mkWpTyApps inst_tys)
667 (dataConWrapId dict_constr)
668 -- We don't produce a binding for the dict_constr; instead we
669 -- rely on the simplifier to unfold this saturated application
670 -- We do this rather than generate an HsCon directly, because
671 -- it means that the special cases (e.g. dictionary with only one
672 -- member) are dealt with by the common MkId.mkDataConWrapId
673 -- code rather than needing to be repeated here.
675 mk_app :: LHsExpr Id -> HsExpr Id -> LHsExpr Id
676 mk_app fun arg = L loc (HsApp fun (L loc arg))
678 arg_wrapper = mkWpEvVarApps dfun_ev_vars <.> mkWpTyApps (mkTyVarTys inst_tyvars)
680 -- Do not inline the dfun; instead give it a magic DFunFunfolding
681 -- See Note [ClassOp/DFun selection]
682 -- See also note [Single-method classes]
684 | isNewTyCon class_tc
685 = dfun_id `setInlinePragma` alwaysInlinePragma { inl_sat = Just 0 }
687 = dfun_id `setIdUnfolding` mkDFunUnfolding dfun_ty (sc_args ++ meth_args)
688 `setInlinePragma` dfunInlinePragma
689 meth_args = map (DFunPolyArg . Var) meth_ids
691 main_bind = AbsBinds { abs_tvs = inst_tyvars
692 , abs_ev_vars = dfun_ev_vars
693 , abs_exports = [(inst_tyvars, dfun_id_w_fun, self_dict,
694 SpecPrags spec_inst_prags)]
695 , abs_ev_binds = emptyTcEvBinds
696 , abs_binds = unitBag dict_bind }
698 ; return (unitBag (L loc main_bind) `unionBags`
699 listToBag meth_binds)
702 skol_info = InstSkol -- See Note [Subtle interaction of recursion and overlap]
703 dfun_ty = idType dfun_id
704 dfun_id = instanceDFunId ispec
705 loc = getSrcSpan dfun_id
707 ------------------------------
708 tcSuperClass :: Int -> [EvVar] -> PredType -> TcM (EvVar, DFunArg CoreExpr)
709 -- All superclasses should be either
710 -- (a) be one of the arguments to the dfun, of
711 -- (b) be a constant, soluble at top level
712 tcSuperClass n_ty_args ev_vars pred
713 | Just (ev, i) <- find n_ty_args ev_vars
714 = return (ev, DFunLamArg i)
716 = ASSERT2( isEmptyVarSet (tyVarsOfPred pred), ppr pred) -- Constant!
717 do { sc_dict <- emitWanted ScOrigin pred
718 ; return (sc_dict, DFunConstArg (Var sc_dict)) }
721 find i (ev:evs) | pred `tcEqPred` evVarPred ev = Just (ev, i)
722 | otherwise = find (i+1) evs
724 ------------------------------
725 tcSpecInstPrags :: DFunId -> InstBindings Name
726 -> TcM ([Located TcSpecPrag], PragFun)
727 tcSpecInstPrags _ (NewTypeDerived {})
728 = return ([], \_ -> [])
729 tcSpecInstPrags dfun_id (VanillaInst binds uprags _)
730 = do { spec_inst_prags <- mapM (wrapLocM (tcSpecInst dfun_id)) $
731 filter isSpecInstLSig uprags
732 -- The filter removes the pragmas for methods
733 ; return (spec_inst_prags, mkPragFun uprags binds) }
736 Note [Silent Superclass Arguments]
737 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
738 Consider the following (extreme) situation:
739 class C a => D a where ...
740 instance D [a] => D [a] where ...
741 Although this looks wrong (assume D [a] to prove D [a]), it is only a
742 more extreme case of what happens with recursive dictionaries.
744 To implement the dfun we must generate code for the superclass C [a],
745 which we can get by superclass selection from the supplied argument!
747 dfun :: forall a. D [a] -> D [a]
748 dfun = \d::D [a] -> MkD (scsel d) ..
750 However this means that if we later encounter a situation where
751 we have a [Wanted] dw::D [a] we could solve it thus:
753 Although recursive, this binding would pass the TcSMonadisGoodRecEv
754 check because it appears as guarded. But in reality, it will make a
755 bottom superclass. The trouble is that isGoodRecEv can't "see" the
756 superclass-selection inside dfun.
758 Our solution to this problem is to change the way ‘dfuns’ are created
759 for instances, so that we pass as first arguments to the dfun some
760 ``silent superclass arguments’’, which are the immediate superclasses
761 of the dictionary we are trying to construct. In our example:
762 dfun :: forall a. (C [a], D [a] -> D [a]
763 dfun = \(dc::C [a]) (dd::D [a]) -> DOrd dc ...
767 -----------------------------------------------------------
768 DFun Superclass Invariant
769 ~~~~~~~~~~~~~~~~~~~~~~~~
770 In the body of a DFun, every superclass argument to the
771 returned dictionary is
772 either * one of the arguments of the DFun,
773 or * constant, bound at top level
774 -----------------------------------------------------------
776 This means that no superclass is hidden inside a dfun application, so
777 the counting argument in isGoodRecEv (more dfun calls than superclass
778 selections) works correctly.
780 The extra arguments required to satisfy the DFun Superclass Invariant
781 always come first, and are called the "silent" arguments. DFun types
782 are built (only) by MkId.mkDictFunId, so that is where we decide
783 what silent arguments are to be added.
785 This net effect is that it is safe to treat a dfun application as
786 wrapping a dictionary constructor around its arguments (in particular,
787 a dfun never picks superclasses from the arguments under the dictionary
790 In our example, if we had [Wanted] dw :: D [a] we would get via the instance:
792 [Wanted] (d1 :: C [a])
793 [Wanted] (d2 :: D [a])
794 [Derived] (d :: D [a])
795 [Derived] (scd :: C [a]) scd := scsel d
796 [Derived] (scd2 :: C [a]) scd2 := scsel d2
798 And now, though we *can* solve:
800 we will get an isGoodRecEv failure when we try to solve:
805 Test case SCLoop tests this fix.
807 Note [SPECIALISE instance pragmas]
808 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
811 instance (Ix a, Ix b) => Ix (a,b) where
812 {-# SPECIALISE instance Ix (Int,Int) #-}
815 We do *not* want to make a specialised version of the dictionary
816 function. Rather, we want specialised versions of each method.
817 Thus we should generate something like this:
819 $dfIx :: (Ix a, Ix x) => Ix (a,b)
820 {- DFUN [$crange, ...] -}
821 $dfIx da db = Ix ($crange da db) (...other methods...)
823 $dfIxPair :: (Ix a, Ix x) => Ix (a,b)
824 {- DFUN [$crangePair, ...] -}
825 $dfIxPair = Ix ($crangePair da db) (...other methods...)
827 $crange :: (Ix a, Ix b) -> ((a,b),(a,b)) -> [(a,b)]
828 {-# SPECIALISE $crange :: ((Int,Int),(Int,Int)) -> [(Int,Int)] #-}
829 $crange da db = <blah>
831 {-# RULE range ($dfIx da db) = $crange da db #-}
835 * The RULE is unaffected by the specialisation. We don't want to
836 specialise $dfIx, because then it would need a specialised RULE
837 which is a pain. The single RULE works fine at all specialisations.
838 See Note [How instance declarations are translated] above
840 * Instead, we want to specialise the *method*, $crange
842 In practice, rather than faking up a SPECIALISE pragama for each
843 method (which is painful, since we'd have to figure out its
844 specialised type), we call tcSpecPrag *as if* were going to specialise
845 $dfIx -- you can see that in the call to tcSpecInst. That generates a
846 SpecPrag which, as it turns out, can be used unchanged for each method.
847 The "it turns out" bit is delicate, but it works fine!
850 tcSpecInst :: Id -> Sig Name -> TcM TcSpecPrag
851 tcSpecInst dfun_id prag@(SpecInstSig hs_ty)
852 = addErrCtxt (spec_ctxt prag) $
853 do { let name = idName dfun_id
854 ; (tyvars, theta, clas, tys) <- tcHsInstHead hs_ty
855 ; let (_, spec_dfun_ty) = mkDictFunTy tyvars theta clas tys
857 ; co_fn <- tcSubType (SpecPragOrigin name) SpecInstCtxt
858 (idType dfun_id) spec_dfun_ty
859 ; return (SpecPrag dfun_id co_fn defaultInlinePragma) }
861 spec_ctxt prag = hang (ptext (sLit "In the SPECIALISE pragma")) 2 (ppr prag)
863 tcSpecInst _ _ = panic "tcSpecInst"
866 %************************************************************************
868 Type-checking an instance method
870 %************************************************************************
873 - Make the method bindings, as a [(NonRec, HsBinds)], one per method
874 - Remembering to use fresh Name (the instance method Name) as the binder
875 - Bring the instance method Ids into scope, for the benefit of tcInstSig
876 - Use sig_fn mapping instance method Name -> instance tyvars
878 - Use tcValBinds to do the checking
881 tcInstanceMethods :: DFunId -> Class -> [TcTyVar]
884 -> ([Located TcSpecPrag], PragFun)
887 -> TcM ([Id], [LHsBind Id])
888 -- The returned inst_meth_ids all have types starting
889 -- forall tvs. theta => ...
890 tcInstanceMethods dfun_id clas tyvars dfun_ev_vars inst_tys
891 (spec_inst_prags, prag_fn)
892 op_items (VanillaInst binds _ standalone_deriv)
893 = mapAndUnzipM tc_item op_items
895 ----------------------
896 tc_item :: (Id, DefMeth) -> TcM (Id, LHsBind Id)
897 tc_item (sel_id, dm_info)
898 = case findMethodBind (idName sel_id) binds of
899 Just user_bind -> tc_body sel_id standalone_deriv user_bind
900 Nothing -> tc_default sel_id dm_info
902 ----------------------
903 tc_body :: Id -> Bool -> LHsBind Name -> TcM (TcId, LHsBind Id)
904 tc_body sel_id generated_code rn_bind
905 = add_meth_ctxt sel_id generated_code rn_bind $
906 do { (meth_id, local_meth_id) <- mkMethIds clas tyvars dfun_ev_vars
908 ; let prags = prag_fn (idName sel_id)
909 ; meth_id1 <- addInlinePrags meth_id prags
910 ; spec_prags <- tcSpecPrags meth_id1 prags
911 ; bind <- tcInstanceMethodBody InstSkol
913 meth_id1 local_meth_id meth_sig_fn
914 (mk_meth_spec_prags meth_id1 spec_prags)
916 ; return (meth_id1, bind) }
918 ----------------------
919 tc_default :: Id -> DefMeth -> TcM (TcId, LHsBind Id)
920 tc_default sel_id GenDefMeth -- Derivable type classes stuff
921 = do { meth_bind <- mkGenericDefMethBind clas inst_tys sel_id
922 ; tc_body sel_id False {- Not generated code? -} meth_bind }
924 tc_default sel_id NoDefMeth -- No default method at all
925 = do { warnMissingMethod sel_id
926 ; (meth_id, _) <- mkMethIds clas tyvars dfun_ev_vars
928 ; return (meth_id, mkVarBind meth_id $
929 mkLHsWrap lam_wrapper error_rhs) }
931 error_rhs = L loc $ HsApp error_fun error_msg
932 error_fun = L loc $ wrapId (WpTyApp meth_tau) nO_METHOD_BINDING_ERROR_ID
933 error_msg = L loc (HsLit (HsStringPrim (mkFastString error_string)))
934 meth_tau = funResultTy (applyTys (idType sel_id) inst_tys)
935 error_string = showSDoc (hcat [ppr loc, text "|", ppr sel_id ])
936 lam_wrapper = mkWpTyLams tyvars <.> mkWpLams dfun_ev_vars
938 tc_default sel_id (DefMeth dm_name) -- A polymorphic default method
939 = do { -- Build the typechecked version directly,
940 -- without calling typecheck_method;
941 -- see Note [Default methods in instances]
942 -- Generate /\as.\ds. let self = df as ds
943 -- in $dm inst_tys self
944 -- The 'let' is necessary only because HsSyn doesn't allow
945 -- you to apply a function to a dictionary *expression*.
947 ; self_dict <- newEvVar (ClassP clas inst_tys)
948 ; let self_ev_bind = EvBind self_dict $
949 EvDFunApp dfun_id (mkTyVarTys tyvars) dfun_ev_vars
951 ; (meth_id, local_meth_id) <- mkMethIds clas tyvars dfun_ev_vars
953 ; dm_id <- tcLookupId dm_name
954 ; let dm_inline_prag = idInlinePragma dm_id
955 rhs = HsWrap (mkWpEvVarApps [self_dict] <.> mkWpTyApps inst_tys) $
958 meth_bind = L loc $ VarBind { var_id = local_meth_id
959 , var_rhs = L loc rhs
960 , var_inline = False }
961 meth_id1 = meth_id `setInlinePragma` dm_inline_prag
962 -- Copy the inline pragma (if any) from the default
963 -- method to this version. Note [INLINE and default methods]
965 bind = AbsBinds { abs_tvs = tyvars, abs_ev_vars = dfun_ev_vars
966 , abs_exports = [( tyvars, meth_id1, local_meth_id
967 , mk_meth_spec_prags meth_id1 [])]
968 , abs_ev_binds = EvBinds (unitBag self_ev_bind)
969 , abs_binds = unitBag meth_bind }
970 -- Default methods in an instance declaration can't have their own
971 -- INLINE or SPECIALISE pragmas. It'd be possible to allow them, but
972 -- currently they are rejected with
973 -- "INLINE pragma lacks an accompanying binding"
975 ; return (meth_id1, L loc bind) }
977 ----------------------
978 mk_meth_spec_prags :: Id -> [LTcSpecPrag] -> TcSpecPrags
979 -- Adapt the SPECIALISE pragmas to work for this method Id
980 -- There are two sources:
981 -- * spec_inst_prags: {-# SPECIALISE instance :: <blah> #-}
982 -- These ones have the dfun inside, but [perhaps surprisingly]
983 -- the correct wrapper
984 -- * spec_prags_for_me: {-# SPECIALISE op :: <blah> #-}
985 mk_meth_spec_prags meth_id spec_prags_for_me
986 = SpecPrags (spec_prags_for_me ++
987 [ L loc (SpecPrag meth_id wrap inl)
988 | L loc (SpecPrag _ wrap inl) <- spec_inst_prags])
990 loc = getSrcSpan dfun_id
991 meth_sig_fn _ = Just ([],loc) -- The 'Just' says "yes, there's a type sig"
992 -- But there are no scoped type variables from local_method_id
993 -- Only the ones from the instance decl itself, which are already
994 -- in scope. Example:
995 -- class C a where { op :: forall b. Eq b => ... }
996 -- instance C [c] where { op = <rhs> }
997 -- In <rhs>, 'c' is scope but 'b' is not!
999 -- For instance decls that come from standalone deriving clauses
1000 -- we want to print out the full source code if there's an error
1001 -- because otherwise the user won't see the code at all
1002 add_meth_ctxt sel_id generated_code rn_bind thing
1003 | generated_code = addLandmarkErrCtxt (derivBindCtxt sel_id clas inst_tys rn_bind) thing
1007 tcInstanceMethods dfun_id clas tyvars dfun_ev_vars inst_tys
1008 _ op_items (NewTypeDerived coi _)
1011 -- class Show b => Foo a b where
1012 -- op :: a -> b -> b
1013 -- newtype N a = MkN (Tree [a])
1014 -- deriving instance (Show p, Foo Int p) => Foo Int (N p)
1015 -- -- NB: standalone deriving clause means
1016 -- -- that the contex is user-specified
1017 -- Hence op :: forall a b. Foo a b => a -> b -> b
1019 -- We're going to make an instance like
1020 -- instance (Show p, Foo Int p) => Foo Int (N p)
1023 -- $copT :: forall p. (Show p, Foo Int p) => Int -> N p -> N p
1024 -- $copT p (d1:Show p) (d2:Foo Int p)
1025 -- = op Int (Tree [p]) rep_d |> op_co
1027 -- rep_d :: Foo Int (Tree [p]) = ...d1...d2...
1028 -- op_co :: (Int -> Tree [p] -> Tree [p]) ~ (Int -> T p -> T p)
1029 -- We get op_co by substituting [Int/a] and [co/b] in type for op
1030 -- where co : [p] ~ T p
1032 -- Notice that the dictionary bindings "..d1..d2.." must be generated
1033 -- by the constraint solver, since the <context> may be
1036 = do { rep_d_stuff <- checkConstraints InstSkol tyvars dfun_ev_vars $
1037 emitWanted ScOrigin rep_pred
1039 ; mapAndUnzipM (tc_item rep_d_stuff) op_items }
1041 loc = getSrcSpan dfun_id
1043 inst_tvs = fst (tcSplitForAllTys (idType dfun_id))
1044 Just (init_inst_tys, _) = snocView inst_tys
1045 rep_ty = fst (coercionKind co) -- [p]
1046 rep_pred = mkClassPred clas (init_inst_tys ++ [rep_ty])
1049 co = substTyWith inst_tvs (mkTyVarTys tyvars) $
1050 case coi of { IdCo ty -> ty ;
1051 ACo co -> mkSymCoercion co }
1054 tc_item :: (TcEvBinds, EvVar) -> (Id, DefMeth) -> TcM (TcId, LHsBind TcId)
1055 tc_item (rep_ev_binds, rep_d) (sel_id, _)
1056 = do { (meth_id, local_meth_id) <- mkMethIds clas tyvars dfun_ev_vars
1059 ; let meth_rhs = wrapId (mk_op_wrapper sel_id rep_d) sel_id
1060 meth_bind = VarBind { var_id = local_meth_id
1061 , var_rhs = L loc meth_rhs
1062 , var_inline = False }
1064 bind = AbsBinds { abs_tvs = tyvars, abs_ev_vars = dfun_ev_vars
1065 , abs_exports = [(tyvars, meth_id,
1066 local_meth_id, noSpecPrags)]
1067 , abs_ev_binds = rep_ev_binds
1068 , abs_binds = unitBag $ L loc meth_bind }
1070 ; return (meth_id, L loc bind) }
1073 mk_op_wrapper :: Id -> EvVar -> HsWrapper
1074 mk_op_wrapper sel_id rep_d
1075 = WpCast (substTyWith sel_tvs (init_inst_tys ++ [co]) local_meth_ty)
1076 <.> WpEvApp (EvId rep_d)
1077 <.> mkWpTyApps (init_inst_tys ++ [rep_ty])
1079 (sel_tvs, sel_rho) = tcSplitForAllTys (idType sel_id)
1080 (_, local_meth_ty) = tcSplitPredFunTy_maybe sel_rho
1081 `orElse` pprPanic "tcInstanceMethods" (ppr sel_id)
1083 ----------------------
1084 mkMethIds :: Class -> [TcTyVar] -> [EvVar] -> [TcType] -> Id -> TcM (TcId, TcId)
1085 mkMethIds clas tyvars dfun_ev_vars inst_tys sel_id
1086 = do { uniq <- newUnique
1087 ; let meth_name = mkDerivedInternalName mkClassOpAuxOcc uniq sel_name
1088 ; local_meth_name <- newLocalName sel_name
1089 -- Base the local_meth_name on the selector name, becuase
1090 -- type errors from tcInstanceMethodBody come from here
1092 ; let meth_id = mkLocalId meth_name meth_ty
1093 local_meth_id = mkLocalId local_meth_name local_meth_ty
1094 ; return (meth_id, local_meth_id) }
1096 local_meth_ty = instantiateMethod clas sel_id inst_tys
1097 meth_ty = mkForAllTys tyvars $ mkPiTypes dfun_ev_vars local_meth_ty
1098 sel_name = idName sel_id
1100 ----------------------
1101 wrapId :: HsWrapper -> id -> HsExpr id
1102 wrapId wrapper id = mkHsWrap wrapper (HsVar id)
1104 derivBindCtxt :: Id -> Class -> [Type ] -> LHsBind Name -> SDoc
1105 derivBindCtxt sel_id clas tys _bind
1106 = vcat [ ptext (sLit "When typechecking the code for ") <+> quotes (ppr sel_id)
1107 , nest 2 (ptext (sLit "in a standalone derived instance for")
1108 <+> quotes (pprClassPred clas tys) <> colon)
1109 , nest 2 $ ptext (sLit "To see the code I am typechecking, use -ddump-deriv") ]
1112 -- , nest 2 $ pprSetDepth AllTheWay $ ppr bind ]
1114 warnMissingMethod :: Id -> TcM ()
1115 warnMissingMethod sel_id
1116 = do { warn <- doptM Opt_WarnMissingMethods
1117 ; warnTc (warn -- Warn only if -fwarn-missing-methods
1118 && not (startsWithUnderscore (getOccName sel_id)))
1119 -- Don't warn about _foo methods
1120 (ptext (sLit "No explicit method nor default method for")
1121 <+> quotes (ppr sel_id)) }
1124 Note [Export helper functions]
1125 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1126 We arrange to export the "helper functions" of an instance declaration,
1127 so that they are not subject to preInlineUnconditionally, even if their
1128 RHS is trivial. Reason: they are mentioned in the DFunUnfolding of
1129 the dict fun as Ids, not as CoreExprs, so we can't substitute a
1130 non-variable for them.
1132 We could change this by making DFunUnfoldings have CoreExprs, but it
1133 seems a bit simpler this way.
1135 Note [Default methods in instances]
1136 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1143 instance Baz Int Int
1145 From the class decl we get
1147 $dmfoo :: forall v x. Baz v x => x -> x
1150 Notice that the type is ambiguous. That's fine, though. The instance
1153 $dBazIntInt = MkBaz fooIntInt
1154 fooIntInt = $dmfoo Int Int $dBazIntInt
1156 BUT this does mean we must generate the dictionary translation of
1157 fooIntInt directly, rather than generating source-code and
1158 type-checking it. That was the bug in Trac #1061. In any case it's
1159 less work to generate the translated version!
1161 Note [INLINE and default methods]
1162 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1163 Default methods need special case. They are supposed to behave rather like
1164 macros. For exmample
1167 op1, op2 :: Bool -> a -> a
1170 op1 b x = op2 (not b) x
1172 instance Foo Int where
1173 -- op1 via default method
1176 The instance declaration should behave
1178 just as if 'op1' had been defined with the
1179 code, and INLINE pragma, from its original
1182 That is, just as if you'd written
1184 instance Foo Int where
1188 op1 b x = op2 (not b) x
1190 So for the above example we generate:
1193 {-# INLINE $dmop1 #-}
1194 -- $dmop1 has an InlineCompulsory unfolding
1195 $dmop1 d b x = op2 d (not b) x
1197 $fFooInt = MkD $cop1 $cop2
1199 {-# INLINE $cop1 #-}
1200 $cop1 = $dmop1 $fFooInt
1206 * We *copy* any INLINE pragma from the default method $dmop1 to the
1207 instance $cop1. Otherwise we'll just inline the former in the
1208 latter and stop, which isn't what the user expected
1210 * Regardless of its pragma, we give the default method an
1211 unfolding with an InlineCompulsory source. That means
1212 that it'll be inlined at every use site, notably in
1213 each instance declaration, such as $cop1. This inlining
1214 must happen even though
1215 a) $dmop1 is not saturated in $cop1
1216 b) $cop1 itself has an INLINE pragma
1218 It's vital that $dmop1 *is* inlined in this way, to allow the mutual
1219 recursion between $fooInt and $cop1 to be broken
1221 * To communicate the need for an InlineCompulsory to the desugarer
1222 (which makes the Unfoldings), we use the IsDefaultMethod constructor
1226 %************************************************************************
1228 \subsection{Error messages}
1230 %************************************************************************
1233 instDeclCtxt1 :: LHsType Name -> SDoc
1234 instDeclCtxt1 hs_inst_ty
1235 = inst_decl_ctxt (case unLoc hs_inst_ty of
1236 HsForAllTy _ _ _ (L _ (HsPredTy pred)) -> ppr pred
1237 HsPredTy pred -> ppr pred
1238 _ -> ppr hs_inst_ty) -- Don't expect this
1239 instDeclCtxt2 :: Type -> SDoc
1240 instDeclCtxt2 dfun_ty
1241 = inst_decl_ctxt (ppr (mkClassPred cls tys))
1243 (_,_,cls,tys) = tcSplitDFunTy dfun_ty
1245 inst_decl_ctxt :: SDoc -> SDoc
1246 inst_decl_ctxt doc = ptext (sLit "In the instance declaration for") <+> quotes doc
1248 atInstCtxt :: Name -> SDoc
1249 atInstCtxt name = ptext (sLit "In the associated type instance for") <+>
1252 mustBeVarArgErr :: Type -> SDoc
1253 mustBeVarArgErr ty =
1254 sep [ ptext (sLit "Arguments that do not correspond to a class parameter") <+>
1255 ptext (sLit "must be variables")
1256 , ptext (sLit "Instead of a variable, found") <+> ppr ty
1259 wrongATArgErr :: Type -> Type -> SDoc
1260 wrongATArgErr ty instTy =
1261 sep [ ptext (sLit "Type indexes must match class instance head")
1262 , ptext (sLit "Found") <+> quotes (ppr ty)
1263 <+> ptext (sLit "but expected") <+> quotes (ppr instTy)