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 )
26 import RnSource ( addTcgDUs )
29 import MkCore ( nO_METHOD_BINDING_ERROR_ID )
38 import CoreUtils ( mkPiTypes )
39 import CoreUnfold ( mkDFunUnfolding )
40 import CoreSyn ( Expr(Var), DFunArg(..), CoreExpr )
53 import Maybes ( orElse )
58 #include "HsVersions.h"
61 Typechecking instance declarations is done in two passes. The first
62 pass, made by @tcInstDecls1@, collects information to be used in the
65 This pre-processed info includes the as-yet-unprocessed bindings
66 inside the instance declaration. These are type-checked in the second
67 pass, when the class-instance envs and GVE contain all the info from
68 all the instance and value decls. Indeed that's the reason we need
69 two passes over the instance decls.
72 Note [How instance declarations are translated]
73 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
74 Here is how we translation instance declarations into Core
78 op1, op2 :: Ix b => a -> b -> b
82 {-# INLINE [2] op1 #-}
86 op1,op2 :: forall a. C a => forall b. Ix b => a -> b -> b
90 -- Default methods get the 'self' dictionary as argument
91 -- so they can call other methods at the same type
92 -- Default methods get the same type as their method selector
93 $dmop2 :: forall a. C a => forall b. Ix b => a -> b -> b
94 $dmop2 = /\a. \(d:C a). /\b. \(d2: Ix b). <dm-rhs>
95 -- NB: type variables 'a' and 'b' are *both* in scope in <dm-rhs>
96 -- Note [Tricky type variable scoping]
98 -- A top-level definition for each instance method
99 -- Here op1_i, op2_i are the "instance method Ids"
100 -- The INLINE pragma comes from the user pragma
101 {-# INLINE [2] op1_i #-} -- From the instance decl bindings
102 op1_i, op2_i :: forall a. C a => forall b. Ix b => [a] -> b -> b
103 op1_i = /\a. \(d:C a).
106 -- Note [Subtle interaction of recursion and overlap]
108 local_op1 :: forall b. Ix b => [a] -> b -> b
110 -- Source code; run the type checker on this
111 -- NB: Type variable 'a' (but not 'b') is in scope in <rhs>
112 -- Note [Tricky type variable scoping]
116 op2_i = /\a \d:C a. $dmop2 [a] (df_i a d)
118 -- The dictionary function itself
119 {-# NOINLINE CONLIKE df_i #-} -- Never inline dictionary functions
120 df_i :: forall a. C a -> C [a]
121 df_i = /\a. \d:C a. MkC (op1_i a d) (op2_i a d)
122 -- But see Note [Default methods in instances]
123 -- We can't apply the type checker to the default-method call
125 -- Use a RULE to short-circuit applications of the class ops
126 {-# RULE "op1@C[a]" forall a, d:C a.
127 op1 [a] (df_i d) = op1_i a d #-}
129 Note [Instances and loop breakers]
130 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
131 * Note that df_i may be mutually recursive with both op1_i and op2_i.
132 It's crucial that df_i is not chosen as the loop breaker, even
133 though op1_i has a (user-specified) INLINE pragma.
135 * Instead the idea is to inline df_i into op1_i, which may then select
136 methods from the MkC record, and thereby break the recursion with
137 df_i, leaving a *self*-recurisve op1_i. (If op1_i doesn't call op at
138 the same type, it won't mention df_i, so there won't be recursion in
141 * If op1_i is marked INLINE by the user there's a danger that we won't
142 inline df_i in it, and that in turn means that (since it'll be a
143 loop-breaker because df_i isn't), op1_i will ironically never be
144 inlined. But this is OK: the recursion breaking happens by way of
145 a RULE (the magic ClassOp rule above), and RULES work inside InlineRule
146 unfoldings. See Note [RULEs enabled in SimplGently] in SimplUtils
148 Note [ClassOp/DFun selection]
149 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
150 One thing we see a lot is stuff like
152 where 'op2' is a ClassOp and 'df' is DFun. Now, we could inline *both*
153 'op2' and 'df' to get
154 case (MkD ($cop1 d1 d2) ($cop2 d1 d2) ... of
155 MkD _ op2 _ _ _ -> op2
156 And that will reduce to ($cop2 d1 d2) which is what we wanted.
158 But it's tricky to make this work in practice, because it requires us to
159 inline both 'op2' and 'df'. But neither is keen to inline without having
160 seen the other's result; and it's very easy to get code bloat (from the
161 big intermediate) if you inline a bit too much.
163 Instead we use a cunning trick.
164 * We arrange that 'df' and 'op2' NEVER inline.
166 * We arrange that 'df' is ALWAYS defined in the sylised form
167 df d1 d2 = MkD ($cop1 d1 d2) ($cop2 d1 d2) ...
169 * We give 'df' a magical unfolding (DFunUnfolding [$cop1, $cop2, ..])
170 that lists its methods.
172 * We make CoreUnfold.exprIsConApp_maybe spot a DFunUnfolding and return
173 a suitable constructor application -- inlining df "on the fly" as it
176 * We give the ClassOp 'op2' a BuiltinRule that extracts the right piece
177 iff its argument satisfies exprIsConApp_maybe. This is done in
180 * We make 'df' CONLIKE, so that shared uses stil match; eg
182 in ...(op2 d)...(op1 d)...
184 Note [Single-method classes]
185 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
186 If the class has just one method (or, more accurately, just one element
187 of {superclasses + methods}), then we use a different strategy.
189 class C a where op :: a -> a
190 instance C a => C [a] where op = <blah>
192 We translate the class decl into a newtype, which just gives a
193 top-level axiom. The "constructor" MkC expands to a cast, as does the
196 axiom Co:C a :: C a ~ (a->a)
198 op :: forall a. C a -> (a -> a)
199 op a d = d |> (Co:C a)
201 MkC :: forall a. (a->a) -> C a
202 MkC = /\a.\op. op |> (sym Co:C a)
204 The clever RULE stuff doesn't work now, because ($df a d) isn't
205 a constructor application, so exprIsConApp_maybe won't return
208 Instead, we simply rely on the fact that casts are cheap:
210 $df :: forall a. C a => C [a]
211 {-# INLINE df #-} -- NB: INLINE this
212 $df = /\a. \d. MkC [a] ($cop_list a d)
213 = $cop_list |> forall a. C a -> (sym (Co:C [a]))
215 $cop_list :: forall a. C a => [a] -> [a]
220 we'll inline 'op' and '$df', since both are simply casts, and
223 Why do we use this different strategy? Because otherwise we
224 end up with non-inlined dictionaries that look like
226 which adds an extra indirection to every use, which seems stupid. See
227 Trac #4138 for an example (although the regression reported there
228 wasn't due to the indirction).
230 There is an awkward wrinkle though: we want to be very
232 instance C a => C [a] where
235 then we'll get an INLINE pragma on $cop_list but it's important that
236 $cop_list only inlines when it's applied to *two* arguments (the
237 dictionary and the list argument). So we nust not eta-expand $df
238 above. We ensure that this doesn't happen by putting an INLINE
239 pragma on the dfun itself; after all, it ends up being just a cast.
241 There is one more dark corner to the INLINE story, even more deeply
242 buried. Consider this (Trac #3772):
244 class DeepSeq a => C a where
247 instance C a => C [a] where
250 class DeepSeq a where
251 deepSeq :: a -> b -> b
253 instance DeepSeq a => DeepSeq [a] where
254 {-# INLINE deepSeq #-}
255 deepSeq xs b = foldr deepSeq b xs
257 That gives rise to these defns:
259 $cdeepSeq :: DeepSeq a -> [a] -> b -> b
260 -- User INLINE( 3 args )!
261 $cdeepSeq a (d:DS a) b (x:[a]) (y:b) = ...
263 $fDeepSeq[] :: DeepSeq a -> DeepSeq [a]
264 -- DFun (with auto INLINE pragma)
265 $fDeepSeq[] a d = $cdeepSeq a d |> blah
267 $cp1 a d :: C a => DeepSep [a]
268 -- We don't want to eta-expand this, lest
269 -- $cdeepSeq gets inlined in it!
270 $cp1 a d = $fDeepSep[] a (scsel a d)
272 $fC[] :: C a => C [a]
274 $fC[] a d = MkC ($cp1 a d) ($cgen a d)
276 Here $cp1 is the code that generates the superclass for C [a]. The
277 issue is this: we must not eta-expand $cp1 either, or else $fDeepSeq[]
278 and then $cdeepSeq will inline there, which is definitely wrong. Like
279 on the dfun, we solve this by adding an INLINE pragma to $cp1.
281 Note [Subtle interaction of recursion and overlap]
282 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
284 class C a where { op1,op2 :: a -> a }
285 instance C a => C [a] where
286 op1 x = op2 x ++ op2 x
288 instance C [Int] where
291 When type-checking the C [a] instance, we need a C [a] dictionary (for
292 the call of op2). If we look up in the instance environment, we find
293 an overlap. And in *general* the right thing is to complain (see Note
294 [Overlapping instances] in InstEnv). But in *this* case it's wrong to
295 complain, because we just want to delegate to the op2 of this same
298 Why is this justified? Because we generate a (C [a]) constraint in
299 a context in which 'a' cannot be instantiated to anything that matches
300 other overlapping instances, or else we would not be excecuting this
301 version of op1 in the first place.
303 It might even be a bit disguised:
305 nullFail :: C [a] => [a] -> [a]
306 nullFail x = op2 x ++ op2 x
308 instance C a => C [a] where
311 Precisely this is used in package 'regex-base', module Context.hs.
312 See the overlapping instances for RegexContext, and the fact that they
313 call 'nullFail' just like the example above. The DoCon package also
314 does the same thing; it shows up in module Fraction.hs
316 Conclusion: when typechecking the methods in a C [a] instance, we want to
317 treat the 'a' as an *existential* type variable, in the sense described
318 by Note [Binding when looking up instances]. That is why isOverlappableTyVar
319 responds True to an InstSkol, which is the kind of skolem we use in
323 Note [Tricky type variable scoping]
324 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
327 op1, op2 :: Ix b => a -> b -> b
330 instance C a => C [a]
331 {-# INLINE [2] op1 #-}
334 note that 'a' and 'b' are *both* in scope in <dm-rhs>, but only 'a' is
335 in scope in <rhs>. In particular, we must make sure that 'b' is in
336 scope when typechecking <dm-rhs>. This is achieved by subFunTys,
337 which brings appropriate tyvars into scope. This happens for both
338 <dm-rhs> and for <rhs>, but that doesn't matter: the *renamer* will have
339 complained if 'b' is mentioned in <rhs>.
343 %************************************************************************
345 \subsection{Extracting instance decls}
347 %************************************************************************
349 Gather up the instance declarations from their various sources
352 tcInstDecls1 -- Deal with both source-code and imported instance decls
353 :: [LTyClDecl Name] -- For deriving stuff
354 -> [LInstDecl Name] -- Source code instance decls
355 -> [LDerivDecl Name] -- Source code stand-alone deriving decls
356 -> TcM (TcGblEnv, -- The full inst env
357 [InstInfo Name], -- Source-code instance decls to process;
358 -- contains all dfuns for this module
359 HsValBinds Name) -- Supporting bindings for derived instances
361 tcInstDecls1 tycl_decls inst_decls deriv_decls
363 do { -- Stop if addInstInfos etc discovers any errors
364 -- (they recover, so that we get more than one error each
367 -- (1) Do class and family instance declarations
368 ; idx_tycons <- mapAndRecoverM (tcFamInstDecl TopLevel) $
369 filter (isFamInstDecl . unLoc) tycl_decls
370 ; local_info_tycons <- mapAndRecoverM tcLocalInstDecl1 inst_decls
373 at_tycons_s) = unzip local_info_tycons
374 ; at_idx_tycons = concat at_tycons_s ++ idx_tycons
375 ; implicit_things = concatMap implicitTyConThings at_idx_tycons
376 ; 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 (map ATyCon at_idx_tycons ++ implicit_things) $ do {
383 -- Next, construct the instance environment so far, consisting
385 -- (a) local instance decls
386 -- (b) local family instance decls
387 ; addInsts local_info $
388 addFamInsts at_idx_tycons $ do {
390 -- (3) Compute instances from "deriving" clauses;
391 -- This stuff computes a context for the derived instance
392 -- decl, so it needs to know about all the instances possible
393 -- NB: class instance declarations can contain derivings as
394 -- part of associated data type declarations
395 failIfErrsM -- If the addInsts stuff gave any errors, don't
396 -- try the deriving stuff, because that may give
398 ; (deriv_inst_info, deriv_binds, deriv_dus, deriv_tys, deriv_ty_insts)
399 <- tcDeriving tycl_decls inst_decls deriv_decls
401 -- Extend the global environment also with the generated datatypes for
402 -- the generic representation
403 ; let all_tycons = map ATyCon (deriv_tys ++ deriv_ty_insts)
404 ; gbl_env <- tcExtendGlobalEnv all_tycons $
405 tcExtendGlobalEnv (concatMap implicitTyThings all_tycons) $
406 addFamInsts deriv_ty_insts $
407 addInsts deriv_inst_info getGblEnv
408 ; return ( addTcgDUs gbl_env deriv_dus,
409 deriv_inst_info ++ local_info,
410 aux_binds `plusHsValBinds` deriv_binds)
413 addInsts :: [InstInfo Name] -> TcM a -> TcM a
414 addInsts infos thing_inside
415 = tcExtendLocalInstEnv (map iSpec infos) thing_inside
417 addFamInsts :: [TyCon] -> TcM a -> TcM a
418 addFamInsts tycons thing_inside
419 = tcExtendLocalFamInstEnv (map mkLocalFamInst tycons) thing_inside
423 tcLocalInstDecl1 :: LInstDecl Name
424 -> TcM (InstInfo Name, [TyCon])
425 -- A source-file instance declaration
426 -- Type-check all the stuff before the "where"
428 -- We check for respectable instance type, and context
429 tcLocalInstDecl1 (L loc (InstDecl poly_ty binds uprags ats))
431 addErrCtxt (instDeclCtxt1 poly_ty) $
433 do { is_boot <- tcIsHsBoot
434 ; checkTc (not is_boot || (isEmptyLHsBinds binds && null uprags))
437 ; (tyvars, theta, clas, inst_tys) <- tcHsInstHead poly_ty
438 ; checkValidInstance poly_ty tyvars theta clas inst_tys
440 -- Next, process any associated types.
441 ; idx_tycons <- recoverM (return []) $
442 do { idx_tycons <- checkNoErrs $
443 mapAndRecoverM (tcFamInstDecl NotTopLevel) ats
444 ; checkValidAndMissingATs clas (tyvars, inst_tys)
446 ; return idx_tycons }
448 -- Finally, construct the Core representation of the instance.
449 -- (This no longer includes the associated types.)
450 ; dfun_name <- newDFunName clas inst_tys (getLoc poly_ty)
451 -- Dfun location is that of instance *header*
452 ; overlap_flag <- getOverlapFlag
453 ; let (eq_theta,dict_theta) = partition isEqPred theta
454 theta' = eq_theta ++ dict_theta
455 dfun = mkDictFunId dfun_name tyvars theta' clas inst_tys
456 ispec = mkLocalInstance dfun overlap_flag
458 ; return (InstInfo { iSpec = ispec, iBinds = VanillaInst binds uprags False },
462 -- We pass in the source form and the type checked form of the ATs. We
463 -- really need the source form only to be able to produce more informative
465 checkValidAndMissingATs :: Class
466 -> ([TyVar], [TcType]) -- instance types
467 -> [(LTyClDecl Name, -- source form of AT
468 TyCon)] -- Core form of AT
470 checkValidAndMissingATs clas inst_tys ats
471 = do { -- Issue a warning for each class AT that is not defined in this
473 ; let class_ats = map tyConName (classATs clas)
474 defined_ats = listToNameSet . map (tcdName.unLoc.fst) $ ats
475 omitted = filterOut (`elemNameSet` defined_ats) class_ats
476 ; warn <- doptM Opt_WarnMissingMethods
477 ; mapM_ (warnTc warn . omittedATWarn) omitted
479 -- Ensure that all AT indexes that correspond to class parameters
480 -- coincide with the types in the instance head. All remaining
481 -- AT arguments must be variables. Also raise an error for any
482 -- type instances that are not associated with this class.
483 ; mapM_ (checkIndexes clas inst_tys) ats
486 checkIndexes clas inst_tys (hsAT, tycon)
487 -- !!!TODO: check that this does the Right Thing for indexed synonyms, too!
488 = checkIndexes' clas inst_tys hsAT
490 snd . fromJust . tyConFamInst_maybe $ tycon)
492 checkIndexes' clas (instTvs, instTys) hsAT (atTvs, atTys)
493 = let atName = tcdName . unLoc $ hsAT
495 setSrcSpan (getLoc hsAT) $
496 addErrCtxt (atInstCtxt atName) $
497 case find ((atName ==) . tyConName) (classATs clas) of
498 Nothing -> addErrTc $ badATErr clas atName -- not in this class
500 -- The following is tricky! We need to deal with three
501 -- complications: (1) The AT possibly only uses a subset of
502 -- the class parameters as indexes and those it uses may be in
503 -- a different order; (2) the AT may have extra arguments,
504 -- which must be type variables; and (3) variables in AT and
505 -- instance head will be different `Name's even if their
506 -- source lexemes are identical.
508 -- e.g. class C a b c where
509 -- data D b a :: * -> * -- NB (1) b a, omits c
510 -- instance C [x] Bool Char where
511 -- data D Bool [x] v = MkD x [v] -- NB (2) v
512 -- -- NB (3) the x in 'instance C...' have differnt
513 -- -- Names to x's in 'data D...'
515 -- Re (1), `poss' contains a permutation vector to extract the
516 -- class parameters in the right order.
518 -- Re (2), we wrap the (permuted) class parameters in a Maybe
519 -- type and use Nothing for any extra AT arguments. (First
520 -- equation of `checkIndex' below.)
522 -- Re (3), we replace any type variable in the AT parameters
523 -- that has the same source lexeme as some variable in the
524 -- instance types with the instance type variable sharing its
528 -- For *associated* type families, gives the position
529 -- of that 'TyVar' in the class argument list (0-indexed)
530 -- e.g. class C a b c where { type F c a :: *->* }
531 -- Then we get Just [2,0]
532 poss = catMaybes [ tv `elemIndex` classTyVars clas
533 | tv <- tyConTyVars atycon]
534 -- We will get Nothings for the "extra" type
535 -- variables in an associated data type
536 -- e.g. class C a where { data D a :: *->* }
537 -- here D gets arity 2 and has two tyvars
539 relevantInstTys = map (instTys !!) poss
540 instArgs = map Just relevantInstTys ++
541 repeat Nothing -- extra arguments
542 renaming = substSameTyVar atTvs instTvs
544 zipWithM_ checkIndex (substTys renaming atTys) instArgs
546 checkIndex ty Nothing
547 | isTyVarTy ty = return ()
548 | otherwise = addErrTc $ mustBeVarArgErr ty
549 checkIndex ty (Just instTy)
550 | ty `eqType` instTy = return ()
551 | otherwise = addErrTc $ wrongATArgErr ty instTy
553 listToNameSet = addListToNameSet emptyNameSet
555 substSameTyVar [] _ = emptyTvSubst
556 substSameTyVar (tv:tvs) replacingTvs =
557 let replacement = case find (tv `sameLexeme`) replacingTvs of
558 Nothing -> mkTyVarTy tv
559 Just rtv -> mkTyVarTy rtv
561 tv1 `sameLexeme` tv2 =
562 nameOccName (tyVarName tv1) == nameOccName (tyVarName tv2)
564 TcType.extendTvSubst (substSameTyVar tvs replacingTvs) tv replacement
568 %************************************************************************
570 Type checking family instances
572 %************************************************************************
574 Family instances are somewhat of a hybrid. They are processed together with
575 class instance heads, but can contain data constructors and hence they share a
576 lot of kinding and type checking code with ordinary algebraic data types (and
580 tcFamInstDecl :: TopLevelFlag -> LTyClDecl Name -> TcM TyCon
581 tcFamInstDecl top_lvl (L loc decl)
582 = -- Prime error recovery, set source location
585 do { -- type family instances require -XTypeFamilies
586 -- and can't (currently) be in an hs-boot file
587 ; type_families <- xoptM Opt_TypeFamilies
588 ; is_boot <- tcIsHsBoot -- Are we compiling an hs-boot file?
589 ; checkTc type_families $ badFamInstDecl (tcdLName decl)
590 ; checkTc (not is_boot) $ badBootFamInstDeclErr
592 -- Perform kind and type checking
593 ; tc <- tcFamInstDecl1 decl
594 ; checkValidTyCon tc -- Remember to check validity;
595 -- no recursion to worry about here
597 -- Check that toplevel type instances are not for associated types.
598 ; when (isTopLevel top_lvl && isAssocFamily tc)
599 (addErr $ assocInClassErr (tcdName decl))
603 isAssocFamily :: TyCon -> Bool -- Is an assocaited type
605 = case tyConFamInst_maybe tycon of
606 Nothing -> panic "isAssocFamily: no family?!?"
607 Just (fam, _) -> isTyConAssoc fam
609 assocInClassErr :: Name -> SDoc
611 = ptext (sLit "Associated type") <+> quotes (ppr name) <+>
612 ptext (sLit "must be inside a class instance")
616 tcFamInstDecl1 :: TyClDecl Name -> TcM TyCon
619 tcFamInstDecl1 (decl@TySynonym {tcdLName = L loc tc_name})
620 = kcIdxTyPats decl $ \k_tvs k_typats resKind family ->
621 do { -- check that the family declaration is for a synonym
622 checkTc (isFamilyTyCon family) (notFamily family)
623 ; checkTc (isSynTyCon family) (wrongKindOfFamily family)
625 ; -- (1) kind check the right-hand side of the type equation
626 ; k_rhs <- kcCheckLHsType (tcdSynRhs decl) (EK resKind EkUnk)
627 -- ToDo: the ExpKind could be better
629 -- we need the exact same number of type parameters as the family
631 ; let famArity = tyConArity family
632 ; checkTc (length k_typats == famArity) $
633 wrongNumberOfParmsErr famArity
635 -- (2) type check type equation
636 ; tcTyVarBndrs k_tvs $ \t_tvs -> do { -- turn kinded into proper tyvars
637 ; t_typats <- mapM tcHsKindedType k_typats
638 ; t_rhs <- tcHsKindedType k_rhs
640 -- (3) check the well-formedness of the instance
641 ; checkValidTypeInst t_typats t_rhs
643 -- (4) construct representation tycon
644 ; rep_tc_name <- newFamInstTyConName tc_name t_typats loc
645 ; buildSynTyCon rep_tc_name t_tvs (SynonymTyCon t_rhs)
647 NoParentTyCon (Just (family, t_typats))
650 -- "newtype instance" and "data instance"
651 tcFamInstDecl1 (decl@TyData {tcdND = new_or_data, tcdLName = L loc tc_name,
653 = kcIdxTyPats decl $ \k_tvs k_typats resKind fam_tycon ->
654 do { -- check that the family declaration is for the right kind
655 checkTc (isFamilyTyCon fam_tycon) (notFamily fam_tycon)
656 ; checkTc (isAlgTyCon fam_tycon) (wrongKindOfFamily fam_tycon)
658 ; -- (1) kind check the data declaration as usual
659 ; k_decl <- kcDataDecl decl k_tvs
660 ; let k_ctxt = tcdCtxt k_decl
661 k_cons = tcdCons k_decl
663 -- result kind must be '*' (otherwise, we have too few patterns)
664 ; checkTc (isLiftedTypeKind resKind) $ tooFewParmsErr (tyConArity fam_tycon)
666 -- (2) type check indexed data type declaration
667 ; tcTyVarBndrs k_tvs $ \t_tvs -> do { -- turn kinded into proper tyvars
668 ; unbox_strict <- doptM Opt_UnboxStrictFields
670 -- kind check the type indexes and the context
671 ; t_typats <- mapM tcHsKindedType k_typats
672 ; stupid_theta <- tcHsKindedContext k_ctxt
675 -- (a) left-hand side contains no type family applications
676 -- (vanilla synonyms are fine, though, and we checked for
678 ; mapM_ checkTyFamFreeness t_typats
680 ; dataDeclChecks tc_name new_or_data stupid_theta k_cons
682 -- (4) construct representation tycon
683 ; rep_tc_name <- newFamInstTyConName tc_name t_typats loc
684 ; let ex_ok = True -- Existentials ok for type families!
685 ; fixM (\ rep_tycon -> do
686 { let orig_res_ty = mkTyConApp fam_tycon t_typats
687 ; data_cons <- tcConDecls unbox_strict ex_ok rep_tycon
688 (t_tvs, orig_res_ty) k_cons
691 DataType -> return (mkDataTyConRhs data_cons)
692 NewType -> ASSERT( not (null data_cons) )
693 mkNewTyConRhs rep_tc_name rep_tycon (head data_cons)
694 ; buildAlgTyCon rep_tc_name t_tvs stupid_theta tc_rhs Recursive
695 h98_syntax NoParentTyCon (Just (fam_tycon, t_typats))
696 -- We always assume that indexed types are recursive. Why?
697 -- (1) Due to their open nature, we can never be sure that a
698 -- further instance might not introduce a new recursive
699 -- dependency. (2) They are always valid loop breakers as
700 -- they involve a coercion.
704 h98_syntax = case cons of -- All constructors have same shape
705 L _ (ConDecl { con_res = ResTyGADT _ }) : _ -> False
708 tcFamInstDecl1 d = pprPanic "tcFamInstDecl1" (ppr d)
710 -- Kind checking of indexed types
713 -- Kind check type patterns and kind annotate the embedded type variables.
715 -- * Here we check that a type instance matches its kind signature, but we do
716 -- not check whether there is a pattern for each type index; the latter
717 -- check is only required for type synonym instances.
719 kcIdxTyPats :: TyClDecl Name
720 -> ([LHsTyVarBndr Name] -> [LHsType Name] -> Kind -> TyCon -> TcM a)
721 -- ^^kinded tvs ^^kinded ty pats ^^res kind
723 kcIdxTyPats decl thing_inside
724 = kcHsTyVars (tcdTyVars decl) $ \tvs ->
725 do { let tc_name = tcdLName decl
726 ; fam_tycon <- tcLookupLocatedTyCon tc_name
727 ; let { (kinds, resKind) = splitKindFunTys (tyConKind fam_tycon)
728 ; hs_typats = fromJust $ tcdTyPats decl }
730 -- we may not have more parameters than the kind indicates
731 ; checkTc (length kinds >= length hs_typats) $
732 tooManyParmsErr (tcdLName decl)
734 -- type functions can have a higher-kinded result
735 ; let resultKind = mkArrowKinds (drop (length hs_typats) kinds) resKind
736 ; typats <- zipWithM kcCheckLHsType hs_typats
737 [ EK kind (EkArg (ppr tc_name) n)
738 | (kind,n) <- kinds `zip` [1..]]
739 ; thing_inside tvs typats resultKind fam_tycon
744 %************************************************************************
746 Type-checking instance declarations, pass 2
748 %************************************************************************
751 tcInstDecls2 :: [LTyClDecl Name] -> [InstInfo Name]
753 -- (a) From each class declaration,
754 -- generate any default-method bindings
755 -- (b) From each instance decl
756 -- generate the dfun binding
758 tcInstDecls2 tycl_decls inst_decls
759 = do { -- (a) Default methods from class decls
760 let class_decls = filter (isClassDecl . unLoc) tycl_decls
761 ; dm_binds_s <- mapM tcClassDecl2 class_decls
762 ; let dm_binds = unionManyBags dm_binds_s
764 -- (b) instance declarations
765 ; let dm_ids = collectHsBindsBinders dm_binds
766 -- Add the default method Ids (again)
767 -- See Note [Default methods and instances]
768 ; inst_binds_s <- tcExtendIdEnv dm_ids $
769 mapM tcInstDecl2 inst_decls
772 ; return (dm_binds `unionBags` unionManyBags inst_binds_s) }
775 See Note [Default methods and instances]
776 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
777 The default method Ids are already in the type environment (see Note
778 [Default method Ids and Template Haskell] in TcTyClsDcls), BUT they
779 don't have their InlinePragmas yet. Usually that would not matter,
780 because the simplifier propagates information from binding site to
781 use. But, unusually, when compiling instance decls we *copy* the
782 INLINE pragma from the default method to the method for that
783 particular operation (see Note [INLINE and default methods] below).
785 So right here in tcInstDecl2 we must re-extend the type envt with
786 the default method Ids replete with their INLINE pragmas. Urk.
790 tcInstDecl2 :: InstInfo Name -> TcM (LHsBinds Id)
791 -- Returns a binding for the dfun
792 tcInstDecl2 (InstInfo { iSpec = ispec, iBinds = ibinds })
793 = recoverM (return emptyLHsBinds) $
795 addErrCtxt (instDeclCtxt2 (idType dfun_id)) $
796 do { -- Instantiate the instance decl with skolem constants
797 ; (inst_tyvars, dfun_theta, inst_head) <- tcSkolDFunType (idType dfun_id)
798 ; let (clas, inst_tys) = tcSplitDFunHead inst_head
799 (class_tyvars, sc_theta, _, op_items) = classBigSig clas
800 sc_theta' = substTheta (zipOpenTvSubst class_tyvars inst_tys) sc_theta
801 n_ty_args = length inst_tyvars
802 n_silent = dfunNSilent dfun_id
803 (silent_theta, orig_theta) = splitAt n_silent dfun_theta
805 ; silent_ev_vars <- mapM newSilentGiven silent_theta
806 ; orig_ev_vars <- newEvVars orig_theta
807 ; let dfun_ev_vars = silent_ev_vars ++ orig_ev_vars
809 ; (sc_dicts, sc_args)
810 <- mapAndUnzipM (tcSuperClass n_ty_args dfun_ev_vars) sc_theta'
812 -- Check that any superclasses gotten from a silent arguemnt
813 -- can be deduced from the originally-specified dfun arguments
814 ; ct_loc <- getCtLoc ScOrigin
815 ; _ <- checkConstraints skol_info inst_tyvars orig_ev_vars $
816 emitFlats $ listToBag $
817 [ mkEvVarX sc ct_loc | sc <- sc_dicts, isSilentEvVar sc ]
819 -- Deal with 'SPECIALISE instance' pragmas
820 -- See Note [SPECIALISE instance pragmas]
821 ; spec_info@(spec_inst_prags,_) <- tcSpecInstPrags dfun_id ibinds
823 -- Typecheck the methods
824 ; (meth_ids, meth_binds)
825 <- tcExtendTyVarEnv inst_tyvars $
826 -- The inst_tyvars scope over the 'where' part
827 -- Those tyvars are inside the dfun_id's type, which is a bit
828 -- bizarre, but OK so long as you realise it!
829 tcInstanceMethods dfun_id clas inst_tyvars dfun_ev_vars
833 -- Create the result bindings
834 ; self_dict <- newEvVar (ClassP clas inst_tys)
835 ; let class_tc = classTyCon clas
836 [dict_constr] = tyConDataCons class_tc
837 dict_bind = mkVarBind self_dict dict_rhs
838 dict_rhs = foldl mk_app inst_constr $
839 map HsVar sc_dicts ++ map (wrapId arg_wrapper) meth_ids
840 inst_constr = L loc $ wrapId (mkWpTyApps inst_tys)
841 (dataConWrapId dict_constr)
842 -- We don't produce a binding for the dict_constr; instead we
843 -- rely on the simplifier to unfold this saturated application
844 -- We do this rather than generate an HsCon directly, because
845 -- it means that the special cases (e.g. dictionary with only one
846 -- member) are dealt with by the common MkId.mkDataConWrapId
847 -- code rather than needing to be repeated here.
849 mk_app :: LHsExpr Id -> HsExpr Id -> LHsExpr Id
850 mk_app fun arg = L loc (HsApp fun (L loc arg))
852 arg_wrapper = mkWpEvVarApps dfun_ev_vars <.> mkWpTyApps (mkTyVarTys inst_tyvars)
854 -- Do not inline the dfun; instead give it a magic DFunFunfolding
855 -- See Note [ClassOp/DFun selection]
856 -- See also note [Single-method classes]
858 | isNewTyCon class_tc
859 = dfun_id `setInlinePragma` alwaysInlinePragma { inl_sat = Just 0 }
861 = dfun_id `setIdUnfolding` mkDFunUnfolding dfun_ty (sc_args ++ meth_args)
862 `setInlinePragma` dfunInlinePragma
863 meth_args = map (DFunPolyArg . Var) meth_ids
865 main_bind = AbsBinds { abs_tvs = inst_tyvars
866 , abs_ev_vars = dfun_ev_vars
867 , abs_exports = [(inst_tyvars, dfun_id_w_fun, self_dict,
868 SpecPrags spec_inst_prags)]
869 , abs_ev_binds = emptyTcEvBinds
870 , abs_binds = unitBag dict_bind }
872 ; return (unitBag (L loc main_bind) `unionBags`
873 listToBag meth_binds)
876 skol_info = InstSkol -- See Note [Subtle interaction of recursion and overlap]
877 dfun_ty = idType dfun_id
878 dfun_id = instanceDFunId ispec
879 loc = getSrcSpan dfun_id
881 ------------------------------
882 tcSuperClass :: Int -> [EvVar] -> PredType -> TcM (EvVar, DFunArg CoreExpr)
883 -- All superclasses should be either
884 -- (a) be one of the arguments to the dfun, of
885 -- (b) be a constant, soluble at top level
886 tcSuperClass n_ty_args ev_vars pred
887 | Just (ev, i) <- find n_ty_args ev_vars
888 = return (ev, DFunLamArg i)
890 = ASSERT2( isEmptyVarSet (tyVarsOfPred pred), ppr pred) -- Constant!
891 do { sc_dict <- emitWanted ScOrigin pred
892 ; return (sc_dict, DFunConstArg (Var sc_dict)) }
895 find i (ev:evs) | pred `eqPred` evVarPred ev = Just (ev, i)
896 | otherwise = find (i+1) evs
898 ------------------------------
899 tcSpecInstPrags :: DFunId -> InstBindings Name
900 -> TcM ([Located TcSpecPrag], PragFun)
901 tcSpecInstPrags _ (NewTypeDerived {})
902 = return ([], \_ -> [])
903 tcSpecInstPrags dfun_id (VanillaInst binds uprags _)
904 = do { spec_inst_prags <- mapM (wrapLocM (tcSpecInst dfun_id)) $
905 filter isSpecInstLSig uprags
906 -- The filter removes the pragmas for methods
907 ; return (spec_inst_prags, mkPragFun uprags binds) }
910 Note [Silent Superclass Arguments]
911 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
912 Consider the following (extreme) situation:
913 class C a => D a where ...
914 instance D [a] => D [a] where ...
915 Although this looks wrong (assume D [a] to prove D [a]), it is only a
916 more extreme case of what happens with recursive dictionaries.
918 To implement the dfun we must generate code for the superclass C [a],
919 which we can get by superclass selection from the supplied argument!
921 dfun :: forall a. D [a] -> D [a]
922 dfun = \d::D [a] -> MkD (scsel d) ..
924 However this means that if we later encounter a situation where
925 we have a [Wanted] dw::D [a] we could solve it thus:
927 Although recursive, this binding would pass the TcSMonadisGoodRecEv
928 check because it appears as guarded. But in reality, it will make a
929 bottom superclass. The trouble is that isGoodRecEv can't "see" the
930 superclass-selection inside dfun.
932 Our solution to this problem is to change the way ‘dfuns’ are created
933 for instances, so that we pass as first arguments to the dfun some
934 ``silent superclass arguments’’, which are the immediate superclasses
935 of the dictionary we are trying to construct. In our example:
936 dfun :: forall a. (C [a], D [a] -> D [a]
937 dfun = \(dc::C [a]) (dd::D [a]) -> DOrd dc ...
941 -----------------------------------------------------------
942 DFun Superclass Invariant
943 ~~~~~~~~~~~~~~~~~~~~~~~~
944 In the body of a DFun, every superclass argument to the
945 returned dictionary is
946 either * one of the arguments of the DFun,
947 or * constant, bound at top level
948 -----------------------------------------------------------
950 This means that no superclass is hidden inside a dfun application, so
951 the counting argument in isGoodRecEv (more dfun calls than superclass
952 selections) works correctly.
954 The extra arguments required to satisfy the DFun Superclass Invariant
955 always come first, and are called the "silent" arguments. DFun types
956 are built (only) by MkId.mkDictFunId, so that is where we decide
957 what silent arguments are to be added.
959 This net effect is that it is safe to treat a dfun application as
960 wrapping a dictionary constructor around its arguments (in particular,
961 a dfun never picks superclasses from the arguments under the dictionary
964 In our example, if we had [Wanted] dw :: D [a] we would get via the instance:
966 [Wanted] (d1 :: C [a])
967 [Wanted] (d2 :: D [a])
968 [Derived] (d :: D [a])
969 [Derived] (scd :: C [a]) scd := scsel d
970 [Derived] (scd2 :: C [a]) scd2 := scsel d2
972 And now, though we *can* solve:
974 we will get an isGoodRecEv failure when we try to solve:
979 Test case SCLoop tests this fix.
981 Note [SPECIALISE instance pragmas]
982 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
985 instance (Ix a, Ix b) => Ix (a,b) where
986 {-# SPECIALISE instance Ix (Int,Int) #-}
989 We do *not* want to make a specialised version of the dictionary
990 function. Rather, we want specialised versions of each method.
991 Thus we should generate something like this:
993 $dfIx :: (Ix a, Ix x) => Ix (a,b)
994 {- DFUN [$crange, ...] -}
995 $dfIx da db = Ix ($crange da db) (...other methods...)
997 $dfIxPair :: (Ix a, Ix x) => Ix (a,b)
998 {- DFUN [$crangePair, ...] -}
999 $dfIxPair = Ix ($crangePair da db) (...other methods...)
1001 $crange :: (Ix a, Ix b) -> ((a,b),(a,b)) -> [(a,b)]
1002 {-# SPECIALISE $crange :: ((Int,Int),(Int,Int)) -> [(Int,Int)] #-}
1003 $crange da db = <blah>
1005 {-# RULE range ($dfIx da db) = $crange da db #-}
1009 * The RULE is unaffected by the specialisation. We don't want to
1010 specialise $dfIx, because then it would need a specialised RULE
1011 which is a pain. The single RULE works fine at all specialisations.
1012 See Note [How instance declarations are translated] above
1014 * Instead, we want to specialise the *method*, $crange
1016 In practice, rather than faking up a SPECIALISE pragama for each
1017 method (which is painful, since we'd have to figure out its
1018 specialised type), we call tcSpecPrag *as if* were going to specialise
1019 $dfIx -- you can see that in the call to tcSpecInst. That generates a
1020 SpecPrag which, as it turns out, can be used unchanged for each method.
1021 The "it turns out" bit is delicate, but it works fine!
1024 tcSpecInst :: Id -> Sig Name -> TcM TcSpecPrag
1025 tcSpecInst dfun_id prag@(SpecInstSig hs_ty)
1026 = addErrCtxt (spec_ctxt prag) $
1027 do { let name = idName dfun_id
1028 ; (tyvars, theta, clas, tys) <- tcHsInstHead hs_ty
1029 ; let (_, spec_dfun_ty) = mkDictFunTy tyvars theta clas tys
1031 ; co_fn <- tcSubType (SpecPragOrigin name) SpecInstCtxt
1032 (idType dfun_id) spec_dfun_ty
1033 ; return (SpecPrag dfun_id co_fn defaultInlinePragma) }
1035 spec_ctxt prag = hang (ptext (sLit "In the SPECIALISE pragma")) 2 (ppr prag)
1037 tcSpecInst _ _ = panic "tcSpecInst"
1040 %************************************************************************
1042 Type-checking an instance method
1044 %************************************************************************
1047 - Make the method bindings, as a [(NonRec, HsBinds)], one per method
1048 - Remembering to use fresh Name (the instance method Name) as the binder
1049 - Bring the instance method Ids into scope, for the benefit of tcInstSig
1050 - Use sig_fn mapping instance method Name -> instance tyvars
1052 - Use tcValBinds to do the checking
1055 tcInstanceMethods :: DFunId -> Class -> [TcTyVar]
1058 -> ([Located TcSpecPrag], PragFun)
1060 -> InstBindings Name
1061 -> TcM ([Id], [LHsBind Id])
1062 -- The returned inst_meth_ids all have types starting
1063 -- forall tvs. theta => ...
1064 tcInstanceMethods dfun_id clas tyvars dfun_ev_vars inst_tys
1065 (spec_inst_prags, prag_fn)
1066 op_items (VanillaInst binds _ standalone_deriv)
1067 = mapAndUnzipM tc_item op_items
1069 ----------------------
1070 tc_item :: (Id, DefMeth) -> TcM (Id, LHsBind Id)
1071 tc_item (sel_id, dm_info)
1072 = case findMethodBind (idName sel_id) binds of
1073 Just user_bind -> tc_body sel_id standalone_deriv user_bind
1074 Nothing -> tc_default sel_id dm_info
1076 ----------------------
1077 tc_body :: Id -> Bool -> LHsBind Name -> TcM (TcId, LHsBind Id)
1078 tc_body sel_id generated_code rn_bind
1079 = add_meth_ctxt sel_id generated_code rn_bind $
1080 do { (meth_id, local_meth_id) <- mkMethIds clas tyvars dfun_ev_vars
1082 ; let prags = prag_fn (idName sel_id)
1083 ; meth_id1 <- addInlinePrags meth_id prags
1084 ; spec_prags <- tcSpecPrags meth_id1 prags
1085 ; bind <- tcInstanceMethodBody InstSkol
1087 meth_id1 local_meth_id meth_sig_fn
1088 (mk_meth_spec_prags meth_id1 spec_prags)
1090 ; return (meth_id1, bind) }
1092 ----------------------
1093 tc_default :: Id -> DefMeth -> TcM (TcId, LHsBind Id)
1095 tc_default sel_id (GenDefMeth dm_name)
1096 = do { meth_bind <- mkGenericDefMethBind clas inst_tys sel_id dm_name
1097 ; tc_body sel_id False {- Not generated code? -} meth_bind }
1099 tc_default sel_id GenDefMeth -- Derivable type classes stuff
1100 = do { meth_bind <- mkGenericDefMethBind clas inst_tys sel_id
1101 ; tc_body sel_id False {- Not generated code? -} meth_bind }
1103 tc_default sel_id NoDefMeth -- No default method at all
1104 = do { warnMissingMethod sel_id
1105 ; (meth_id, _) <- mkMethIds clas tyvars dfun_ev_vars
1107 ; return (meth_id, mkVarBind meth_id $
1108 mkLHsWrap lam_wrapper error_rhs) }
1110 error_rhs = L loc $ HsApp error_fun error_msg
1111 error_fun = L loc $ wrapId (WpTyApp meth_tau) nO_METHOD_BINDING_ERROR_ID
1112 error_msg = L loc (HsLit (HsStringPrim (mkFastString error_string)))
1113 meth_tau = funResultTy (applyTys (idType sel_id) inst_tys)
1114 error_string = showSDoc (hcat [ppr loc, text "|", ppr sel_id ])
1115 lam_wrapper = mkWpTyLams tyvars <.> mkWpLams dfun_ev_vars
1117 tc_default sel_id (DefMeth dm_name) -- A polymorphic default method
1118 = do { -- Build the typechecked version directly,
1119 -- without calling typecheck_method;
1120 -- see Note [Default methods in instances]
1121 -- Generate /\as.\ds. let self = df as ds
1122 -- in $dm inst_tys self
1123 -- The 'let' is necessary only because HsSyn doesn't allow
1124 -- you to apply a function to a dictionary *expression*.
1126 ; self_dict <- newEvVar (ClassP clas inst_tys)
1127 ; let self_ev_bind = EvBind self_dict $
1128 EvDFunApp dfun_id (mkTyVarTys tyvars) dfun_ev_vars
1130 ; (meth_id, local_meth_id) <- mkMethIds clas tyvars dfun_ev_vars
1132 ; dm_id <- tcLookupId dm_name
1133 ; let dm_inline_prag = idInlinePragma dm_id
1134 rhs = HsWrap (mkWpEvVarApps [self_dict] <.> mkWpTyApps inst_tys) $
1137 meth_bind = L loc $ VarBind { var_id = local_meth_id
1138 , var_rhs = L loc rhs
1139 , var_inline = False }
1140 meth_id1 = meth_id `setInlinePragma` dm_inline_prag
1141 -- Copy the inline pragma (if any) from the default
1142 -- method to this version. Note [INLINE and default methods]
1144 bind = AbsBinds { abs_tvs = tyvars, abs_ev_vars = dfun_ev_vars
1145 , abs_exports = [( tyvars, meth_id1, local_meth_id
1146 , mk_meth_spec_prags meth_id1 [])]
1147 , abs_ev_binds = EvBinds (unitBag self_ev_bind)
1148 , abs_binds = unitBag meth_bind }
1149 -- Default methods in an instance declaration can't have their own
1150 -- INLINE or SPECIALISE pragmas. It'd be possible to allow them, but
1151 -- currently they are rejected with
1152 -- "INLINE pragma lacks an accompanying binding"
1154 ; return (meth_id1, L loc bind) }
1156 ----------------------
1157 mk_meth_spec_prags :: Id -> [LTcSpecPrag] -> TcSpecPrags
1158 -- Adapt the SPECIALISE pragmas to work for this method Id
1159 -- There are two sources:
1160 -- * spec_inst_prags: {-# SPECIALISE instance :: <blah> #-}
1161 -- These ones have the dfun inside, but [perhaps surprisingly]
1162 -- the correct wrapper
1163 -- * spec_prags_for_me: {-# SPECIALISE op :: <blah> #-}
1164 mk_meth_spec_prags meth_id spec_prags_for_me
1165 = SpecPrags (spec_prags_for_me ++
1166 [ L loc (SpecPrag meth_id wrap inl)
1167 | L loc (SpecPrag _ wrap inl) <- spec_inst_prags])
1169 loc = getSrcSpan dfun_id
1170 meth_sig_fn _ = Just ([],loc) -- The 'Just' says "yes, there's a type sig"
1171 -- But there are no scoped type variables from local_method_id
1172 -- Only the ones from the instance decl itself, which are already
1173 -- in scope. Example:
1174 -- class C a where { op :: forall b. Eq b => ... }
1175 -- instance C [c] where { op = <rhs> }
1176 -- In <rhs>, 'c' is scope but 'b' is not!
1178 -- For instance decls that come from standalone deriving clauses
1179 -- we want to print out the full source code if there's an error
1180 -- because otherwise the user won't see the code at all
1181 add_meth_ctxt sel_id generated_code rn_bind thing
1182 | generated_code = addLandmarkErrCtxt (derivBindCtxt sel_id clas inst_tys rn_bind) thing
1186 tcInstanceMethods dfun_id clas tyvars dfun_ev_vars inst_tys
1187 _ op_items (NewTypeDerived coi _)
1190 -- class Show b => Foo a b where
1191 -- op :: a -> b -> b
1192 -- newtype N a = MkN (Tree [a])
1193 -- deriving instance (Show p, Foo Int p) => Foo Int (N p)
1194 -- -- NB: standalone deriving clause means
1195 -- -- that the contex is user-specified
1196 -- Hence op :: forall a b. Foo a b => a -> b -> b
1198 -- We're going to make an instance like
1199 -- instance (Show p, Foo Int p) => Foo Int (N p)
1202 -- $copT :: forall p. (Show p, Foo Int p) => Int -> N p -> N p
1203 -- $copT p (d1:Show p) (d2:Foo Int p)
1204 -- = op Int (Tree [p]) rep_d |> op_co
1206 -- rep_d :: Foo Int (Tree [p]) = ...d1...d2...
1207 -- op_co :: (Int -> Tree [p] -> Tree [p]) ~ (Int -> T p -> T p)
1208 -- We get op_co by substituting [Int/a] and [co/b] in type for op
1209 -- where co : [p] ~ T p
1211 -- Notice that the dictionary bindings "..d1..d2.." must be generated
1212 -- by the constraint solver, since the <context> may be
1215 = do { rep_d_stuff <- checkConstraints InstSkol tyvars dfun_ev_vars $
1216 emitWanted ScOrigin rep_pred
1218 ; mapAndUnzipM (tc_item rep_d_stuff) op_items }
1220 loc = getSrcSpan dfun_id
1222 inst_tvs = fst (tcSplitForAllTys (idType dfun_id))
1223 Just (init_inst_tys, _) = snocView inst_tys
1224 rep_ty = pFst (coercionKind co) -- [p]
1225 rep_pred = mkClassPred clas (init_inst_tys ++ [rep_ty])
1228 co = substCoWithTys inst_tvs (mkTyVarTys tyvars) $
1232 tc_item :: (TcEvBinds, EvVar) -> (Id, DefMeth) -> TcM (TcId, LHsBind TcId)
1233 tc_item (rep_ev_binds, rep_d) (sel_id, _)
1234 = do { (meth_id, local_meth_id) <- mkMethIds clas tyvars dfun_ev_vars
1237 ; let meth_rhs = wrapId (mk_op_wrapper sel_id rep_d) sel_id
1238 meth_bind = VarBind { var_id = local_meth_id
1239 , var_rhs = L loc meth_rhs
1240 , var_inline = False }
1242 bind = AbsBinds { abs_tvs = tyvars, abs_ev_vars = dfun_ev_vars
1243 , abs_exports = [(tyvars, meth_id,
1244 local_meth_id, noSpecPrags)]
1245 , abs_ev_binds = rep_ev_binds
1246 , abs_binds = unitBag $ L loc meth_bind }
1248 ; return (meth_id, L loc bind) }
1251 mk_op_wrapper :: Id -> EvVar -> HsWrapper
1252 mk_op_wrapper sel_id rep_d
1253 = WpCast (liftCoSubstWith sel_tvs (map mkReflCo init_inst_tys ++ [co])
1255 <.> WpEvApp (EvId rep_d)
1256 <.> mkWpTyApps (init_inst_tys ++ [rep_ty])
1258 (sel_tvs, sel_rho) = tcSplitForAllTys (idType sel_id)
1259 (_, local_meth_ty) = tcSplitPredFunTy_maybe sel_rho
1260 `orElse` pprPanic "tcInstanceMethods" (ppr sel_id)
1262 ----------------------
1263 mkMethIds :: Class -> [TcTyVar] -> [EvVar] -> [TcType] -> Id -> TcM (TcId, TcId)
1264 mkMethIds clas tyvars dfun_ev_vars inst_tys sel_id
1265 = do { uniq <- newUnique
1266 ; let meth_name = mkDerivedInternalName mkClassOpAuxOcc uniq sel_name
1267 ; local_meth_name <- newLocalName sel_name
1268 -- Base the local_meth_name on the selector name, becuase
1269 -- type errors from tcInstanceMethodBody come from here
1271 ; let meth_id = mkLocalId meth_name meth_ty
1272 local_meth_id = mkLocalId local_meth_name local_meth_ty
1273 ; return (meth_id, local_meth_id) }
1275 local_meth_ty = instantiateMethod clas sel_id inst_tys
1276 meth_ty = mkForAllTys tyvars $ mkPiTypes dfun_ev_vars local_meth_ty
1277 sel_name = idName sel_id
1279 ----------------------
1280 wrapId :: HsWrapper -> id -> HsExpr id
1281 wrapId wrapper id = mkHsWrap wrapper (HsVar id)
1283 derivBindCtxt :: Id -> Class -> [Type ] -> LHsBind Name -> SDoc
1284 derivBindCtxt sel_id clas tys _bind
1285 = vcat [ ptext (sLit "When typechecking the code for ") <+> quotes (ppr sel_id)
1286 , nest 2 (ptext (sLit "in a standalone derived instance for")
1287 <+> quotes (pprClassPred clas tys) <> colon)
1288 , nest 2 $ ptext (sLit "To see the code I am typechecking, use -ddump-deriv") ]
1291 -- , nest 2 $ pprSetDepth AllTheWay $ ppr bind ]
1293 warnMissingMethod :: Id -> TcM ()
1294 warnMissingMethod sel_id
1295 = do { warn <- doptM Opt_WarnMissingMethods
1296 ; warnTc (warn -- Warn only if -fwarn-missing-methods
1297 && not (startsWithUnderscore (getOccName sel_id)))
1298 -- Don't warn about _foo methods
1299 (ptext (sLit "No explicit method nor default method for")
1300 <+> quotes (ppr sel_id)) }
1303 Note [Export helper functions]
1304 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1305 We arrange to export the "helper functions" of an instance declaration,
1306 so that they are not subject to preInlineUnconditionally, even if their
1307 RHS is trivial. Reason: they are mentioned in the DFunUnfolding of
1308 the dict fun as Ids, not as CoreExprs, so we can't substitute a
1309 non-variable for them.
1311 We could change this by making DFunUnfoldings have CoreExprs, but it
1312 seems a bit simpler this way.
1314 Note [Default methods in instances]
1315 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1322 instance Baz Int Int
1324 From the class decl we get
1326 $dmfoo :: forall v x. Baz v x => x -> x
1329 Notice that the type is ambiguous. That's fine, though. The instance
1332 $dBazIntInt = MkBaz fooIntInt
1333 fooIntInt = $dmfoo Int Int $dBazIntInt
1335 BUT this does mean we must generate the dictionary translation of
1336 fooIntInt directly, rather than generating source-code and
1337 type-checking it. That was the bug in Trac #1061. In any case it's
1338 less work to generate the translated version!
1340 Note [INLINE and default methods]
1341 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1342 Default methods need special case. They are supposed to behave rather like
1343 macros. For exmample
1346 op1, op2 :: Bool -> a -> a
1349 op1 b x = op2 (not b) x
1351 instance Foo Int where
1352 -- op1 via default method
1355 The instance declaration should behave
1357 just as if 'op1' had been defined with the
1358 code, and INLINE pragma, from its original
1361 That is, just as if you'd written
1363 instance Foo Int where
1367 op1 b x = op2 (not b) x
1369 So for the above example we generate:
1372 {-# INLINE $dmop1 #-}
1373 -- $dmop1 has an InlineCompulsory unfolding
1374 $dmop1 d b x = op2 d (not b) x
1376 $fFooInt = MkD $cop1 $cop2
1378 {-# INLINE $cop1 #-}
1379 $cop1 = $dmop1 $fFooInt
1385 * We *copy* any INLINE pragma from the default method $dmop1 to the
1386 instance $cop1. Otherwise we'll just inline the former in the
1387 latter and stop, which isn't what the user expected
1389 * Regardless of its pragma, we give the default method an
1390 unfolding with an InlineCompulsory source. That means
1391 that it'll be inlined at every use site, notably in
1392 each instance declaration, such as $cop1. This inlining
1393 must happen even though
1394 a) $dmop1 is not saturated in $cop1
1395 b) $cop1 itself has an INLINE pragma
1397 It's vital that $dmop1 *is* inlined in this way, to allow the mutual
1398 recursion between $fooInt and $cop1 to be broken
1400 * To communicate the need for an InlineCompulsory to the desugarer
1401 (which makes the Unfoldings), we use the IsDefaultMethod constructor
1405 %************************************************************************
1407 \subsection{Error messages}
1409 %************************************************************************
1412 instDeclCtxt1 :: LHsType Name -> SDoc
1413 instDeclCtxt1 hs_inst_ty
1414 = inst_decl_ctxt (case unLoc hs_inst_ty of
1415 HsForAllTy _ _ _ (L _ (HsPredTy pred)) -> ppr pred
1416 HsPredTy pred -> ppr pred
1417 _ -> ppr hs_inst_ty) -- Don't expect this
1418 instDeclCtxt2 :: Type -> SDoc
1419 instDeclCtxt2 dfun_ty
1420 = inst_decl_ctxt (ppr (mkClassPred cls tys))
1422 (_,_,cls,tys) = tcSplitDFunTy dfun_ty
1424 inst_decl_ctxt :: SDoc -> SDoc
1425 inst_decl_ctxt doc = ptext (sLit "In the instance declaration for") <+> quotes doc
1427 atInstCtxt :: Name -> SDoc
1428 atInstCtxt name = ptext (sLit "In the associated type instance for") <+>
1431 mustBeVarArgErr :: Type -> SDoc
1432 mustBeVarArgErr ty =
1433 sep [ ptext (sLit "Arguments that do not correspond to a class parameter") <+>
1434 ptext (sLit "must be variables")
1435 , ptext (sLit "Instead of a variable, found") <+> ppr ty
1438 wrongATArgErr :: Type -> Type -> SDoc
1439 wrongATArgErr ty instTy =
1440 sep [ ptext (sLit "Type indexes must match class instance head")
1441 , ptext (sLit "Found") <+> quotes (ppr ty)
1442 <+> ptext (sLit "but expected") <+> quotes (ppr instTy)
1445 tooManyParmsErr :: Located Name -> SDoc
1446 tooManyParmsErr tc_name
1447 = ptext (sLit "Family instance has too many parameters:") <+>
1448 quotes (ppr tc_name)
1450 tooFewParmsErr :: Arity -> SDoc
1451 tooFewParmsErr arity
1452 = ptext (sLit "Family instance has too few parameters; expected") <+>
1455 wrongNumberOfParmsErr :: Arity -> SDoc
1456 wrongNumberOfParmsErr exp_arity
1457 = ptext (sLit "Number of parameters must match family declaration; expected")
1460 badBootFamInstDeclErr :: SDoc
1461 badBootFamInstDeclErr
1462 = ptext (sLit "Illegal family instance in hs-boot file")
1464 notFamily :: TyCon -> SDoc
1466 = vcat [ ptext (sLit "Illegal family instance for") <+> quotes (ppr tycon)
1467 , nest 2 $ parens (ppr tycon <+> ptext (sLit "is not an indexed type family"))]
1469 wrongKindOfFamily :: TyCon -> SDoc
1470 wrongKindOfFamily family
1471 = ptext (sLit "Wrong category of family instance; declaration was for a")
1474 kindOfFamily | isSynTyCon family = ptext (sLit "type synonym")
1475 | isAlgTyCon family = ptext (sLit "data type")
1476 | otherwise = pprPanic "wrongKindOfFamily" (ppr family)