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
24 import RnEnv ( lookupGlobalOccRn )
25 import RnSource ( addTcgDUs )
35 import CoreUnfold ( mkDFunUnfolding )
36 import PrelNames ( inlineIdName )
54 #include "HsVersions.h"
57 Typechecking instance declarations is done in two passes. The first
58 pass, made by @tcInstDecls1@, collects information to be used in the
61 This pre-processed info includes the as-yet-unprocessed bindings
62 inside the instance declaration. These are type-checked in the second
63 pass, when the class-instance envs and GVE contain all the info from
64 all the instance and value decls. Indeed that's the reason we need
65 two passes over the instance decls.
68 Note [How instance declarations are translated]
69 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
70 Here is how we translation instance declarations into Core
74 op1, op2 :: Ix b => a -> b -> b
78 {-# INLINE [2] op1 #-}
82 op1,op2 :: forall a. C a => forall b. Ix b => a -> b -> b
86 -- Default methods get the 'self' dictionary as argument
87 -- so they can call other methods at the same type
88 -- Default methods get the same type as their method selector
89 $dmop2 :: forall a. C a => forall b. Ix b => a -> b -> b
90 $dmop2 = /\a. \(d:C a). /\b. \(d2: Ix b). <dm-rhs>
91 -- NB: type variables 'a' and 'b' are *both* in scope in <dm-rhs>
92 -- Note [Tricky type variable scoping]
94 -- A top-level definition for each instance method
95 -- Here op1_i, op2_i are the "instance method Ids"
96 -- The INLINE pragma comes from the user pragma
97 {-# INLINE [2] op1_i #-} -- From the instance decl bindings
98 op1_i, op2_i :: forall a. C a => forall b. Ix b => [a] -> b -> b
99 op1_i = /\a. \(d:C a).
102 -- Note [Subtle interaction of recursion and overlap]
104 local_op1 :: forall b. Ix b => [a] -> b -> b
106 -- Source code; run the type checker on this
107 -- NB: Type variable 'a' (but not 'b') is in scope in <rhs>
108 -- Note [Tricky type variable scoping]
112 op2_i = /\a \d:C a. $dmop2 [a] (df_i a d)
114 -- The dictionary function itself
115 {-# NOINLINE CONLIKE df_i #-} -- Never inline dictionary functions
116 df_i :: forall a. C a -> C [a]
117 df_i = /\a. \d:C a. MkC (op1_i a d) (op2_i a d)
118 -- But see Note [Default methods in instances]
119 -- We can't apply the type checker to the default-method call
121 -- Use a RULE to short-circuit applications of the class ops
122 {-# RULE "op1@C[a]" forall a, d:C a.
123 op1 [a] (df_i d) = op1_i a d #-}
125 Note [Instances and loop breakers]
126 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
127 * Note that df_i may be mutually recursive with both op1_i and op2_i.
128 It's crucial that df_i is not chosen as the loop breaker, even
129 though op1_i has a (user-specified) INLINE pragma.
131 * Instead the idea is to inline df_i into op1_i, which may then select
132 methods from the MkC record, and thereby break the recursion with
133 df_i, leaving a *self*-recurisve op1_i. (If op1_i doesn't call op at
134 the same type, it won't mention df_i, so there won't be recursion in
137 * If op1_i is marked INLINE by the user there's a danger that we won't
138 inline df_i in it, and that in turn means that (since it'll be a
139 loop-breaker because df_i isn't), op1_i will ironically never be
140 inlined. But this is OK: the recursion breaking happens by way of
141 a RULE (the magic ClassOp rule above), and RULES work inside InlineRule
142 unfoldings. See Note [RULEs enabled in SimplGently] in SimplUtils
144 Note [ClassOp/DFun selection]
145 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
146 One thing we see a lot is stuff like
148 where 'op2' is a ClassOp and 'df' is DFun. Now, we could inline *both*
149 'op2' and 'df' to get
150 case (MkD ($cop1 d1 d2) ($cop2 d1 d2) ... of
151 MkD _ op2 _ _ _ -> op2
152 And that will reduce to ($cop2 d1 d2) which is what we wanted.
154 But it's tricky to make this work in practice, because it requires us to
155 inline both 'op2' and 'df'. But neither is keen to inline without having
156 seen the other's result; and it's very easy to get code bloat (from the
157 big intermediate) if you inline a bit too much.
159 Instead we use a cunning trick.
160 * We arrange that 'df' and 'op2' NEVER inline.
162 * We arrange that 'df' is ALWAYS defined in the sylised form
163 df d1 d2 = MkD ($cop1 d1 d2) ($cop2 d1 d2) ...
165 * We give 'df' a magical unfolding (DFunUnfolding [$cop1, $cop2, ..])
166 that lists its methods.
168 * We make CoreUnfold.exprIsConApp_maybe spot a DFunUnfolding and return
169 a suitable constructor application -- inlining df "on the fly" as it
172 * We give the ClassOp 'op2' a BuiltinRule that extracts the right piece
173 iff its argument satisfies exprIsConApp_maybe. This is done in
176 * We make 'df' CONLIKE, so that shared uses stil match; eg
178 in ...(op2 d)...(op1 d)...
180 Note [Single-method classes]
181 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
182 If the class has just one method (or, more accurately, just one elemen
183 of {superclasses + methods}), then we want a different strategy.
185 class C a where op :: a -> a
186 instance C a => C [a] where op = <blah>
188 We translate the class decl into a newtype, which just gives
191 axiom Co:C a :: C a ~ (a->a)
193 op :: forall a. C a -> (a -> a)
194 op a d = d |> (Co:C a)
196 df :: forall a. C a => C [a]
198 df = $cop_list |> (forall a. C a -> (sym (Co:C a))
200 $cop_list :: forall a. C a => a -> a
203 So the ClassOp is just a cast; and so is the dictionary function.
204 (The latter doesn't even have any lambdas.) We can inline both freely.
205 No need for fancy BuiltIn rules. Indeed the BuiltinRule stuff does
206 not work well for newtypes because it uses exprIsConApp_maybe.
209 Note [Subtle interaction of recursion and overlap]
210 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
212 class C a where { op1,op2 :: a -> a }
213 instance C a => C [a] where
214 op1 x = op2 x ++ op2 x
216 intance C [Int] where
219 When type-checking the C [a] instance, we need a C [a] dictionary (for
220 the call of op2). If we look up in the instance environment, we find
221 an overlap. And in *general* the right thing is to complain (see Note
222 [Overlapping instances] in InstEnv). But in *this* case it's wrong to
223 complain, because we just want to delegate to the op2 of this same
226 Why is this justified? Because we generate a (C [a]) constraint in
227 a context in which 'a' cannot be instantiated to anything that matches
228 other overlapping instances, or else we would not be excecuting this
229 version of op1 in the first place.
231 It might even be a bit disguised:
233 nullFail :: C [a] => [a] -> [a]
234 nullFail x = op2 x ++ op2 x
236 instance C a => C [a] where
239 Precisely this is used in package 'regex-base', module Context.hs.
240 See the overlapping instances for RegexContext, and the fact that they
241 call 'nullFail' just like the example above. The DoCon package also
242 does the same thing; it shows up in module Fraction.hs
244 Conclusion: when typechecking the methods in a C [a] instance, we want
245 to have C [a] available. That is why we have the strange local
246 definition for 'this' in the definition of op1_i in the example above.
247 We can typecheck the defintion of local_op1, and when doing tcSimplifyCheck
248 we supply 'this' as a given dictionary. Only needed, though, if there
249 are some type variables involved; otherwise there can be no overlap and
252 Note [Tricky type variable scoping]
253 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
256 op1, op2 :: Ix b => a -> b -> b
259 instance C a => C [a]
260 {-# INLINE [2] op1 #-}
263 note that 'a' and 'b' are *both* in scope in <dm-rhs>, but only 'a' is
264 in scope in <rhs>. In particular, we must make sure that 'b' is in
265 scope when typechecking <dm-rhs>. This is achieved by subFunTys,
266 which brings appropriate tyvars into scope. This happens for both
267 <dm-rhs> and for <rhs>, but that doesn't matter: the *renamer* will have
268 complained if 'b' is mentioned in <rhs>.
272 %************************************************************************
274 \subsection{Extracting instance decls}
276 %************************************************************************
278 Gather up the instance declarations from their various sources
281 tcInstDecls1 -- Deal with both source-code and imported instance decls
282 :: [LTyClDecl Name] -- For deriving stuff
283 -> [LInstDecl Name] -- Source code instance decls
284 -> [LDerivDecl Name] -- Source code stand-alone deriving decls
285 -> TcM (TcGblEnv, -- The full inst env
286 [InstInfo Name], -- Source-code instance decls to process;
287 -- contains all dfuns for this module
288 HsValBinds Name) -- Supporting bindings for derived instances
290 tcInstDecls1 tycl_decls inst_decls deriv_decls
292 do { -- Stop if addInstInfos etc discovers any errors
293 -- (they recover, so that we get more than one error each
296 -- (1) Do class and family instance declarations
297 ; let { idxty_decls = filter (isFamInstDecl . unLoc) tycl_decls }
298 ; local_info_tycons <- mapAndRecoverM tcLocalInstDecl1 inst_decls
299 ; idx_tycons <- mapAndRecoverM tcIdxTyInstDeclTL idxty_decls
302 at_tycons_s) = unzip local_info_tycons
303 ; at_idx_tycons = concat at_tycons_s ++ idx_tycons
304 ; clas_decls = filter (isClassDecl.unLoc) tycl_decls
305 ; implicit_things = concatMap implicitTyThings at_idx_tycons
306 ; aux_binds = mkAuxBinds at_idx_tycons
309 -- (2) Add the tycons of indexed types and their implicit
310 -- tythings to the global environment
311 ; tcExtendGlobalEnv (at_idx_tycons ++ implicit_things) $ do {
313 -- (3) Instances from generic class declarations
314 ; generic_inst_info <- getGenericInstances clas_decls
316 -- Next, construct the instance environment so far, consisting
318 -- a) local instance decls
319 -- b) generic instances
320 -- c) local family instance decls
321 ; addInsts local_info $
322 addInsts generic_inst_info $
323 addFamInsts at_idx_tycons $ do {
325 -- (4) Compute instances from "deriving" clauses;
326 -- This stuff computes a context for the derived instance
327 -- decl, so it needs to know about all the instances possible
328 -- NB: class instance declarations can contain derivings as
329 -- part of associated data type declarations
330 failIfErrsM -- If the addInsts stuff gave any errors, don't
331 -- try the deriving stuff, becuase that may give
333 ; (deriv_inst_info, deriv_binds, deriv_dus)
334 <- tcDeriving tycl_decls inst_decls deriv_decls
335 ; gbl_env <- addInsts deriv_inst_info getGblEnv
336 ; return ( addTcgDUs gbl_env deriv_dus,
337 generic_inst_info ++ deriv_inst_info ++ local_info,
338 aux_binds `plusHsValBinds` deriv_binds)
341 -- Make sure that toplevel type instance are not for associated types.
342 -- !!!TODO: Need to perform this check for the TyThing of type functions,
344 tcIdxTyInstDeclTL ldecl@(L loc decl) =
345 do { tything <- tcFamInstDecl ldecl
347 when (isAssocFamily tything) $
348 addErr $ assocInClassErr (tcdName decl)
351 isAssocFamily (ATyCon tycon) =
352 case tyConFamInst_maybe tycon of
353 Nothing -> panic "isAssocFamily: no family?!?"
354 Just (fam, _) -> isTyConAssoc fam
355 isAssocFamily _ = panic "isAssocFamily: no tycon?!?"
357 assocInClassErr :: Name -> SDoc
358 assocInClassErr name =
359 ptext (sLit "Associated type") <+> quotes (ppr name) <+>
360 ptext (sLit "must be inside a class instance")
362 addInsts :: [InstInfo Name] -> TcM a -> TcM a
363 addInsts infos thing_inside
364 = tcExtendLocalInstEnv (map iSpec infos) thing_inside
366 addFamInsts :: [TyThing] -> TcM a -> TcM a
367 addFamInsts tycons thing_inside
368 = tcExtendLocalFamInstEnv (map mkLocalFamInstTyThing tycons) thing_inside
370 mkLocalFamInstTyThing (ATyCon tycon) = mkLocalFamInst tycon
371 mkLocalFamInstTyThing tything = pprPanic "TcInstDcls.addFamInsts"
376 tcLocalInstDecl1 :: LInstDecl Name
377 -> TcM (InstInfo Name, [TyThing])
378 -- A source-file instance declaration
379 -- Type-check all the stuff before the "where"
381 -- We check for respectable instance type, and context
382 tcLocalInstDecl1 (L loc (InstDecl poly_ty binds uprags ats))
384 addErrCtxt (instDeclCtxt1 poly_ty) $
386 do { is_boot <- tcIsHsBoot
387 ; checkTc (not is_boot || (isEmptyLHsBinds binds && null uprags))
390 ; (tyvars, theta, tau) <- tcHsInstHead poly_ty
392 -- Now, check the validity of the instance.
393 ; (clas, inst_tys) <- checkValidInstHead tau
394 ; checkValidInstance tyvars theta clas inst_tys
396 -- Next, process any associated types.
397 ; idx_tycons <- recoverM (return []) $
398 do { idx_tycons <- checkNoErrs $ mapAndRecoverM tcFamInstDecl ats
399 ; checkValidAndMissingATs clas (tyvars, inst_tys)
401 ; return idx_tycons }
403 -- Finally, construct the Core representation of the instance.
404 -- (This no longer includes the associated types.)
405 ; dfun_name <- newDFunName clas inst_tys (getLoc poly_ty)
406 -- Dfun location is that of instance *header*
407 ; overlap_flag <- getOverlapFlag
408 ; let (eq_theta,dict_theta) = partition isEqPred theta
409 theta' = eq_theta ++ dict_theta
410 dfun = mkDictFunId dfun_name tyvars theta' clas inst_tys
411 ispec = mkLocalInstance dfun overlap_flag
413 ; return (InstInfo { iSpec = ispec,
414 iBinds = VanillaInst binds uprags False },
418 -- We pass in the source form and the type checked form of the ATs. We
419 -- really need the source form only to be able to produce more informative
421 checkValidAndMissingATs :: Class
422 -> ([TyVar], [TcType]) -- instance types
423 -> [(LTyClDecl Name, -- source form of AT
424 TyThing)] -- Core form of AT
426 checkValidAndMissingATs clas inst_tys ats
427 = do { -- Issue a warning for each class AT that is not defined in this
429 ; let class_ats = map tyConName (classATs clas)
430 defined_ats = listToNameSet . map (tcdName.unLoc.fst) $ ats
431 omitted = filterOut (`elemNameSet` defined_ats) class_ats
432 ; warn <- doptM Opt_WarnMissingMethods
433 ; mapM_ (warnTc warn . omittedATWarn) omitted
435 -- Ensure that all AT indexes that correspond to class parameters
436 -- coincide with the types in the instance head. All remaining
437 -- AT arguments must be variables. Also raise an error for any
438 -- type instances that are not associated with this class.
439 ; mapM_ (checkIndexes clas inst_tys) ats
442 checkIndexes clas inst_tys (hsAT, ATyCon tycon)
443 -- !!!TODO: check that this does the Right Thing for indexed synonyms, too!
444 = checkIndexes' clas inst_tys hsAT
446 snd . fromJust . tyConFamInst_maybe $ tycon)
447 checkIndexes _ _ _ = panic "checkIndexes"
449 checkIndexes' clas (instTvs, instTys) hsAT (atTvs, atTys)
450 = let atName = tcdName . unLoc $ hsAT
452 setSrcSpan (getLoc hsAT) $
453 addErrCtxt (atInstCtxt atName) $
454 case find ((atName ==) . tyConName) (classATs clas) of
455 Nothing -> addErrTc $ badATErr clas atName -- not in this class
457 case assocTyConArgPoss_maybe atycon of
458 Nothing -> panic "checkIndexes': AT has no args poss?!?"
461 -- The following is tricky! We need to deal with three
462 -- complications: (1) The AT possibly only uses a subset of
463 -- the class parameters as indexes and those it uses may be in
464 -- a different order; (2) the AT may have extra arguments,
465 -- which must be type variables; and (3) variables in AT and
466 -- instance head will be different `Name's even if their
467 -- source lexemes are identical.
469 -- e.g. class C a b c where
470 -- data D b a :: * -> * -- NB (1) b a, omits c
471 -- instance C [x] Bool Char where
472 -- data D Bool [x] v = MkD x [v] -- NB (2) v
473 -- -- NB (3) the x in 'instance C...' have differnt
474 -- -- Names to x's in 'data D...'
476 -- Re (1), `poss' contains a permutation vector to extract the
477 -- class parameters in the right order.
479 -- Re (2), we wrap the (permuted) class parameters in a Maybe
480 -- type and use Nothing for any extra AT arguments. (First
481 -- equation of `checkIndex' below.)
483 -- Re (3), we replace any type variable in the AT parameters
484 -- that has the same source lexeme as some variable in the
485 -- instance types with the instance type variable sharing its
488 let relevantInstTys = map (instTys !!) poss
489 instArgs = map Just relevantInstTys ++
490 repeat Nothing -- extra arguments
491 renaming = substSameTyVar atTvs instTvs
493 zipWithM_ checkIndex (substTys renaming atTys) instArgs
495 checkIndex ty Nothing
496 | isTyVarTy ty = return ()
497 | otherwise = addErrTc $ mustBeVarArgErr ty
498 checkIndex ty (Just instTy)
499 | ty `tcEqType` instTy = return ()
500 | otherwise = addErrTc $ wrongATArgErr ty instTy
502 listToNameSet = addListToNameSet emptyNameSet
504 substSameTyVar [] _ = emptyTvSubst
505 substSameTyVar (tv:tvs) replacingTvs =
506 let replacement = case find (tv `sameLexeme`) replacingTvs of
507 Nothing -> mkTyVarTy tv
508 Just rtv -> mkTyVarTy rtv
510 tv1 `sameLexeme` tv2 =
511 nameOccName (tyVarName tv1) == nameOccName (tyVarName tv2)
513 extendTvSubst (substSameTyVar tvs replacingTvs) tv replacement
517 %************************************************************************
519 Type-checking instance declarations, pass 2
521 %************************************************************************
524 tcInstDecls2 :: [LTyClDecl Name] -> [InstInfo Name]
525 -> TcM (LHsBinds Id, TcLclEnv)
526 -- (a) From each class declaration,
527 -- generate any default-method bindings
528 -- (b) From each instance decl
529 -- generate the dfun binding
531 tcInstDecls2 tycl_decls inst_decls
532 = do { -- (a) Default methods from class decls
533 let class_decls = filter (isClassDecl . unLoc) tycl_decls
534 ; (dm_ids_s, dm_binds_s) <- mapAndUnzipM tcClassDecl2 class_decls
536 ; tcExtendIdEnv (concat dm_ids_s) $ do
538 -- (b) instance declarations
539 { inst_binds_s <- mapM tcInstDecl2 inst_decls
542 ; let binds = unionManyBags dm_binds_s `unionBags`
543 unionManyBags inst_binds_s
544 ; tcl_env <- getLclEnv -- Default method Ids in here
545 ; return (binds, tcl_env) } }
547 tcInstDecl2 :: InstInfo Name -> TcM (LHsBinds Id)
548 tcInstDecl2 (InstInfo { iSpec = ispec, iBinds = ibinds })
549 = recoverM (return emptyLHsBinds) $
551 addErrCtxt (instDeclCtxt2 (idType dfun_id)) $
552 tc_inst_decl2 dfun_id ibinds
554 dfun_id = instanceDFunId ispec
555 loc = getSrcSpan dfun_id
560 tc_inst_decl2 :: Id -> InstBindings Name -> TcM (LHsBinds Id)
561 -- Returns a binding for the dfun
563 ------------------------
564 -- Derived newtype instances; surprisingly tricky!
566 -- class Show a => Foo a b where ...
567 -- newtype N a = MkN (Tree [a]) deriving( Foo Int )
569 -- The newtype gives an FC axiom looking like
570 -- axiom CoN a :: N a ~ Tree [a]
571 -- (see Note [Newtype coercions] in TyCon for this unusual form of axiom)
573 -- So all need is to generate a binding looking like:
574 -- dfunFooT :: forall a. (Foo Int (Tree [a], Show (N a)) => Foo Int (N a)
575 -- dfunFooT = /\a. \(ds:Show (N a)) (df:Foo (Tree [a])).
576 -- case df `cast` (Foo Int (sym (CoN a))) of
577 -- Foo _ op1 .. opn -> Foo ds op1 .. opn
579 -- If there are no superclasses, matters are simpler, because we don't need the case
580 -- see Note [Newtype deriving superclasses] in TcDeriv.lhs
582 tc_inst_decl2 dfun_id (NewTypeDerived coi)
583 = do { let rigid_info = InstSkol
584 origin = SigOrigin rigid_info
585 inst_ty = idType dfun_id
586 inst_tvs = fst (tcSplitForAllTys inst_ty)
587 ; (inst_tvs', theta, inst_head_ty) <- tcSkolSigType rigid_info inst_ty
588 -- inst_head_ty is a PredType
590 ; let (cls, cls_inst_tys) = tcSplitDFunHead inst_head_ty
591 (class_tyvars, sc_theta, _, _) = classBigSig cls
592 cls_tycon = classTyCon cls
593 sc_theta' = substTheta (zipOpenTvSubst class_tyvars cls_inst_tys) sc_theta
594 Just (initial_cls_inst_tys, last_ty) = snocView cls_inst_tys
598 IdCo -> (last_ty, idHsWrapper)
599 ACo co -> (snd (coercionKind co'), WpCast (mk_full_coercion co'))
601 co' = substTyWith inst_tvs (mkTyVarTys inst_tvs') co
602 -- NB: the free variable of coi are bound by the
603 -- universally quantified variables of the dfun_id
604 -- This is weird, and maybe we should make NewTypeDerived
605 -- carry a type-variable list too; but it works fine
607 -----------------------
609 -- The inst_head looks like (C s1 .. sm (T a1 .. ak))
610 -- But we want the coercion (C s1 .. sm (sym (CoT a1 .. ak)))
611 -- with kind (C s1 .. sm (T a1 .. ak) ~ C s1 .. sm <rep_ty>)
612 -- where rep_ty is the (eta-reduced) type rep of T
613 -- So we just replace T with CoT, and insert a 'sym'
614 -- NB: we know that k will be >= arity of CoT, because the latter fully eta-reduced
616 mk_full_coercion co = mkTyConApp cls_tycon
617 (initial_cls_inst_tys ++ [mkSymCoercion co])
618 -- Full coercion : (Foo Int (Tree [a]) ~ Foo Int (N a)
620 rep_pred = mkClassPred cls (initial_cls_inst_tys ++ [rep_ty])
621 -- In our example, rep_pred is (Foo Int (Tree [a]))
623 ; sc_loc <- getInstLoc InstScOrigin
624 ; sc_dicts <- newDictBndrs sc_loc sc_theta'
625 ; inst_loc <- getInstLoc origin
626 ; dfun_dicts <- newDictBndrs inst_loc theta
627 ; rep_dict <- newDictBndr inst_loc rep_pred
628 ; this_dict <- newDictBndr inst_loc (mkClassPred cls cls_inst_tys)
630 -- Figure out bindings for the superclass context from dfun_dicts
631 -- Don't include this_dict in the 'givens', else
632 -- sc_dicts get bound by just selecting from this_dict!!
633 ; sc_binds <- addErrCtxt superClassCtxt $
634 tcSimplifySuperClasses inst_loc this_dict dfun_dicts
637 -- It's possible that the superclass stuff might unified something
638 -- in the envt with one of the clas_tyvars
639 ; checkSigTyVars inst_tvs'
641 ; let coerced_rep_dict = wrapId wrapper (instToId rep_dict)
643 ; body <- make_body cls_tycon cls_inst_tys sc_dicts coerced_rep_dict
644 ; let dict_bind = mkVarBind (instToId this_dict) (noLoc body)
646 ; return (unitBag $ noLoc $
647 AbsBinds inst_tvs' (map instToVar dfun_dicts)
648 [(inst_tvs', dfun_id, instToId this_dict, [])]
649 (dict_bind `consBag` sc_binds)) }
651 -----------------------
652 -- (make_body C tys scs coreced_rep_dict)
654 -- (case coerced_rep_dict of { C _ ops -> C scs ops })
655 -- But if there are no superclasses, it returns just coerced_rep_dict
656 -- See Note [Newtype deriving superclasses] in TcDeriv.lhs
658 make_body cls_tycon cls_inst_tys sc_dicts coerced_rep_dict
659 | null sc_dicts -- Case (a)
660 = return coerced_rep_dict
661 | otherwise -- Case (b)
662 = do { op_ids <- newSysLocalIds (fsLit "op") op_tys
663 ; dummy_sc_dict_ids <- newSysLocalIds (fsLit "sc") (map idType sc_dict_ids)
664 ; let the_pat = ConPatOut { pat_con = noLoc cls_data_con, pat_tvs = [],
665 pat_dicts = dummy_sc_dict_ids,
666 pat_binds = emptyLHsBinds,
667 pat_args = PrefixCon (map nlVarPat op_ids),
669 the_match = mkSimpleMatch [noLoc the_pat] the_rhs
670 the_rhs = mkHsConApp cls_data_con cls_inst_tys $
671 map HsVar (sc_dict_ids ++ op_ids)
673 -- Warning: this HsCase scrutinises a value with a PredTy, which is
674 -- never otherwise seen in Haskell source code. It'd be
675 -- nicer to generate Core directly!
676 ; return (HsCase (noLoc coerced_rep_dict) $
677 MatchGroup [the_match] (mkFunTy pat_ty pat_ty)) }
679 sc_dict_ids = map instToId sc_dicts
680 pat_ty = mkTyConApp cls_tycon cls_inst_tys
681 cls_data_con = head (tyConDataCons cls_tycon)
682 cls_arg_tys = dataConInstArgTys cls_data_con cls_inst_tys
683 op_tys = dropList sc_dict_ids cls_arg_tys
685 ------------------------
686 -- Ordinary instances
688 tc_inst_decl2 dfun_id (VanillaInst monobinds uprags standalone_deriv)
689 = do { let rigid_info = InstSkol
690 inst_ty = idType dfun_id
691 loc = getSrcSpan dfun_id
693 -- Instantiate the instance decl with skolem constants
694 ; (inst_tyvars', dfun_theta', inst_head') <- tcSkolSigType rigid_info inst_ty
695 -- These inst_tyvars' scope over the 'where' part
696 -- Those tyvars are inside the dfun_id's type, which is a bit
697 -- bizarre, but OK so long as you realise it!
699 (clas, inst_tys') = tcSplitDFunHead inst_head'
700 (class_tyvars, sc_theta, sc_sels, op_items) = classBigSig clas
702 -- Instantiate the super-class context with inst_tys
703 sc_theta' = substTheta (zipOpenTvSubst class_tyvars inst_tys') sc_theta
704 origin = SigOrigin rigid_info
706 -- Create dictionary Ids from the specified instance contexts.
707 ; inst_loc <- getInstLoc origin
708 ; dfun_dicts <- newDictBndrs inst_loc dfun_theta' -- Includes equalities
709 ; this_dict <- newDictBndr inst_loc (mkClassPred clas inst_tys')
710 -- Default-method Ids may be mentioned in synthesised RHSs,
711 -- but they'll already be in the environment.
714 -- Cook up a binding for "this = df d1 .. dn",
715 -- to use in each method binding
716 -- Need to clone the dict in case it is floated out, and
717 -- then clashes with its friends
718 ; cloned_this <- cloneDict this_dict
719 ; let cloned_this_bind = mkVarBind (instToId cloned_this) $
720 L loc $ wrapId app_wrapper dfun_id
721 app_wrapper = mkWpApps dfun_lam_vars <.> mkWpTyApps (mkTyVarTys inst_tyvars')
722 dfun_lam_vars = map instToVar dfun_dicts -- Includes equalities
724 | null inst_tyvars' && null dfun_theta' = (this_dict, emptyBag)
725 | otherwise = (cloned_this, unitBag cloned_this_bind)
727 -- Deal with 'SPECIALISE instance' pragmas
728 -- See Note [SPECIALISE instance pragmas]
729 ; let spec_inst_sigs = filter isSpecInstLSig uprags
730 -- The filter removes the pragmas for methods
731 ; spec_inst_prags <- mapM (wrapLocM (tcSpecInst dfun_id)) spec_inst_sigs
733 -- Typecheck the methods
734 ; let prag_fn = mkPragFun uprags
735 tc_meth = tcInstanceMethod loc standalone_deriv
739 prag_fn spec_inst_prags monobinds
741 ; (meth_ids, meth_binds) <- tcExtendTyVarEnv inst_tyvars' $
742 mapAndUnzipM tc_meth op_items
744 -- Figure out bindings for the superclass context
745 ; sc_loc <- getInstLoc InstScOrigin
746 ; sc_dicts <- newDictOccs sc_loc sc_theta' -- These are wanted
747 ; let tc_sc = tcSuperClass inst_loc inst_tyvars' dfun_dicts nested_this_pair
748 ; (sc_ids, sc_binds) <- mapAndUnzipM tc_sc (sc_sels `zip` sc_dicts)
750 -- It's possible that the superclass stuff might unified
751 -- something in the envt with one of the inst_tyvars'
752 ; checkSigTyVars inst_tyvars'
754 -- Create the result bindings
755 ; let dict_constr = classDataCon clas
756 this_dict_id = instToId this_dict
757 dict_bind = mkVarBind this_dict_id dict_rhs
758 dict_rhs = foldl mk_app inst_constr (sc_ids ++ meth_ids)
759 inst_constr = L loc $ wrapId (mkWpTyApps inst_tys')
760 (dataConWrapId dict_constr)
761 -- We don't produce a binding for the dict_constr; instead we
762 -- rely on the simplifier to unfold this saturated application
763 -- We do this rather than generate an HsCon directly, because
764 -- it means that the special cases (e.g. dictionary with only one
765 -- member) are dealt with by the common MkId.mkDataConWrapId code rather
766 -- than needing to be repeated here.
768 mk_app :: LHsExpr Id -> Id -> LHsExpr Id
769 mk_app fun arg_id = L loc (HsApp fun (L loc (wrapId arg_wrapper arg_id)))
770 arg_wrapper = mkWpApps dfun_lam_vars <.> mkWpTyApps (mkTyVarTys inst_tyvars')
772 dfun_id_w_fun | isNewTyCon (classTyCon clas)
773 = dfun_id -- Just let the dfun inline; see Note [Single-method classes]
775 = dfun_id -- Do not inline; instead give it a magic DFunFunfolding
776 -- See Note [ClassOp/DFun selection]
777 `setIdUnfolding` mkDFunUnfolding dict_constr (sc_ids ++ meth_ids)
778 `setInlinePragma` dfunInlinePragma
780 main_bind = noLoc $ AbsBinds
783 [(inst_tyvars', dfun_id_w_fun, this_dict_id, spec_inst_prags)]
786 ; showLIE (text "instance")
787 ; return (unitBag main_bind `unionBags`
788 listToBag meth_binds `unionBags`
789 listToBag sc_binds) }
792 ------------------------------
793 tcSuperClass :: InstLoc -> [TyVar] -> [Inst]
794 -> (Inst, LHsBinds Id)
795 -> (Id, Inst) -> TcM (Id, LHsBind Id)
796 -- Build a top level decl like
797 -- sc_op = /\a \d. let this = ... in
800 -- The "this" part is just-in-case (discarded if not used)
801 -- See Note [Recursive superclasses]
802 tcSuperClass inst_loc tyvars dicts (this_dict, this_bind)
804 = addErrCtxt superClassCtxt $
805 do { sc_binds <- tcSimplifySuperClasses inst_loc
806 this_dict dicts [sc_dict]
807 -- Don't include this_dict in the 'givens', else
808 -- sc_dicts get bound by just selecting from this_dict!!
811 ; let sc_op_ty = mkSigmaTy tyvars (map dictPred dicts)
812 (mkPredTy (dictPred sc_dict))
813 sc_op_name = mkDerivedInternalName mkClassOpAuxOcc uniq
815 sc_op_id = mkLocalId sc_op_name sc_op_ty
816 sc_id = instToVar sc_dict
817 sc_op_bind = AbsBinds tyvars
818 (map instToVar dicts)
819 [(tyvars, sc_op_id, sc_id, [])]
820 (this_bind `unionBags` sc_binds)
822 ; return (sc_op_id, noLoc sc_op_bind) }
825 Note [Recursive superclasses]
826 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
827 See Trac #1470 for why we would *like* to add "this_dict" to the
828 available instances here. But we can't do so because then the superclases
829 get satisfied by selection from this_dict, and that leads to an immediate
830 loop. What we need is to add this_dict to Avails without adding its
831 superclasses, and we currently have no way to do that.
833 Note [SPECIALISE instance pragmas]
834 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
837 instance (Ix a, Ix b) => Ix (a,b) where
838 {-# SPECIALISE instance Ix (Int,Int) #-}
841 We do *not* want to make a specialised version of the dictionary
842 function. Rather, we want specialised versions of each method.
843 Thus we should generate something like this:
845 $dfIx :: (Ix a, Ix x) => Ix (a,b)
846 {- DFUN [$crange, ...] -}
847 $dfIx da db = Ix ($crange da db) (...other methods...)
849 $dfIxPair :: (Ix a, Ix x) => Ix (a,b)
850 {- DFUN [$crangePair, ...] -}
851 $dfIxPair = Ix ($crangePair da db) (...other methods...)
853 $crange :: (Ix a, Ix b) -> ((a,b),(a,b)) -> [(a,b)]
854 {-# SPECIALISE $crange :: ((Int,Int),(Int,Int)) -> [(Int,Int)] #-}
855 $crange da db = <blah>
857 {-# RULE range ($dfIx da db) = $crange da db #-}
861 * The RULE is unaffected by the specialisation. We don't want to
862 specialise $dfIx, because then it would need a specialised RULE
863 which is a pain. The single RULE works fine at all specialisations.
864 See Note [How instance declarations are translated] above
866 * Instead, we want to specialise the *method*, $crange
868 In practice, rather than faking up a SPECIALISE pragama for each
869 method (which is painful, since we'd have to figure out its
870 specialised type), we call tcSpecPrag *as if* were going to specialise
871 $dfIx -- you can see that in the call to tcSpecInst. That generates a
872 SpecPrag which, as it turns out, can be used unchanged for each method.
873 The "it turns out" bit is delicate, but it works fine!
876 tcSpecInst :: Id -> Sig Name -> TcM SpecPrag
877 tcSpecInst dfun_id prag@(SpecInstSig hs_ty)
878 = addErrCtxt (spec_ctxt prag) $
879 do { let name = idName dfun_id
880 ; (tyvars, theta, tau) <- tcHsInstHead hs_ty
881 ; let spec_ty = mkSigmaTy tyvars theta tau
882 ; co_fn <- tcSubExp (SpecPragOrigin name) (idType dfun_id) spec_ty
883 ; return (SpecPrag co_fn defaultInlinePragma) }
885 spec_ctxt prag = hang (ptext (sLit "In the SPECIALISE pragma")) 2 (ppr prag)
887 tcSpecInst _ _ = panic "tcSpecInst"
890 %************************************************************************
892 Type-checking an instance method
894 %************************************************************************
897 - Make the method bindings, as a [(NonRec, HsBinds)], one per method
898 - Remembering to use fresh Name (the instance method Name) as the binder
899 - Bring the instance method Ids into scope, for the benefit of tcInstSig
900 - Use sig_fn mapping instance method Name -> instance tyvars
902 - Use tcValBinds to do the checking
905 tcInstanceMethod :: SrcSpan -> Bool -> Class -> [TcTyVar] -> [Inst]
907 -> (Inst, LHsBinds Id) -- "This" and its binding
908 -> TcPragFun -- Local prags
909 -> [LSpecPrag] -- Arising from 'SPECLALISE instance'
912 -> TcM (Id, LHsBind Id)
913 -- The returned inst_meth_ids all have types starting
914 -- forall tvs. theta => ...
916 tcInstanceMethod loc standalone_deriv clas tyvars dfun_dicts inst_tys
917 (this_dict, this_dict_bind)
918 prag_fn spec_inst_prags binds_in (sel_id, dm_info)
919 = do { uniq <- newUnique
920 ; let meth_name = mkDerivedInternalName mkClassOpAuxOcc uniq sel_name
921 ; local_meth_name <- newLocalName sel_name
922 -- Base the local_meth_name on the selector name, becuase
923 -- type errors from tcInstanceMethodBody come from here
925 ; let local_meth_ty = instantiateMethod clas sel_id inst_tys
926 meth_ty = mkSigmaTy tyvars (map dictPred dfun_dicts) local_meth_ty
927 meth_id = mkLocalId meth_name meth_ty
928 local_meth_id = mkLocalId local_meth_name local_meth_ty
932 = add_meth_ctxt rn_bind $
933 do { (meth_id1, spec_prags) <- tcPrags NonRecursive False True
934 meth_id (prag_fn sel_name)
935 ; tcInstanceMethodBody (instLoc this_dict)
937 ([this_dict], this_dict_bind)
938 meth_id1 local_meth_id
940 (spec_inst_prags ++ spec_prags)
944 tc_default :: DefMeth -> TcM (Id, LHsBind Id)
945 -- The user didn't supply a method binding, so we have to make
946 -- up a default binding, in a way depending on the default-method info
948 tc_default NoDefMeth -- No default method at all
949 = do { warnMissingMethod sel_id
950 ; return (meth_id, mkVarBind meth_id $
951 mkLHsWrap lam_wrapper error_rhs) }
953 tc_default GenDefMeth -- Derivable type classes stuff
954 = do { meth_bind <- mkGenericDefMethBind clas inst_tys sel_id local_meth_name
955 ; tc_body meth_bind }
957 tc_default DefMeth -- An polymorphic default method
958 = do { -- Build the typechecked version directly,
959 -- without calling typecheck_method;
960 -- see Note [Default methods in instances]
961 -- Generate /\as.\ds. let this = df as ds
962 -- in $dm inst_tys this
963 -- The 'let' is necessary only because HsSyn doesn't allow
964 -- you to apply a function to a dictionary *expression*.
965 dm_name <- lookupGlobalOccRn (mkDefMethRdrName sel_name)
966 -- Might not be imported, but will be an OrigName
967 ; dm_id <- tcLookupId dm_name
968 ; inline_id <- tcLookupId inlineIdName
969 ; let dm_inline_prag = idInlinePragma dm_id
970 dm_app = HsWrap (WpApp (instToId this_dict) <.> mkWpTyApps inst_tys) $
972 rhs | isInlinePragma dm_inline_prag -- See Note [INLINE and default methods]
973 = HsApp (L loc (HsWrap (WpTyApp local_meth_ty) (HsVar inline_id)))
977 meth_bind = L loc $ VarBind { var_id = local_meth_id
978 , var_rhs = L loc rhs
979 , var_inline = False }
980 meth_id1 = meth_id `setInlinePragma` dm_inline_prag
981 -- Copy the inline pragma (if any) from the default
982 -- method to this version. Note [INLINE and default methods]
984 bind = AbsBinds { abs_tvs = tyvars, abs_dicts = dfun_lam_vars
985 , abs_exports = [( tyvars, meth_id1
986 , local_meth_id, spec_inst_prags)]
987 , abs_binds = this_dict_bind `unionBags` unitBag meth_bind }
988 -- Default methods in an instance declaration can't have their own
989 -- INLINE or SPECIALISE pragmas. It'd be possible to allow them, but
990 -- currently they are rejected with
991 -- "INLINE pragma lacks an accompanying binding"
993 ; return (meth_id1, L loc bind) }
995 ; case findMethodBind sel_name local_meth_name binds_in of
996 Just user_bind -> tc_body user_bind -- User-supplied method binding
997 Nothing -> tc_default dm_info -- None supplied
1000 sel_name = idName sel_id
1002 meth_sig_fn _ = Just [] -- The 'Just' says "yes, there's a type sig"
1003 -- But there are no scoped type variables from local_method_id
1004 -- Only the ones from the instance decl itself, which are already
1005 -- in scope. Example:
1006 -- class C a where { op :: forall b. Eq b => ... }
1007 -- instance C [c] where { op = <rhs> }
1008 -- In <rhs>, 'c' is scope but 'b' is not!
1010 error_rhs = L loc $ HsApp error_fun error_msg
1011 error_fun = L loc $ wrapId (WpTyApp meth_tau) nO_METHOD_BINDING_ERROR_ID
1012 error_msg = L loc (HsLit (HsStringPrim (mkFastString error_string)))
1013 meth_tau = funResultTy (applyTys (idType sel_id) inst_tys)
1014 error_string = showSDoc (hcat [ppr loc, text "|", ppr sel_id ])
1016 dfun_lam_vars = map instToVar dfun_dicts
1017 lam_wrapper = mkWpTyLams tyvars <.> mkWpLams dfun_lam_vars
1019 -- For instance decls that come from standalone deriving clauses
1020 -- we want to print out the full source code if there's an error
1021 -- because otherwise the user won't see the code at all
1022 add_meth_ctxt rn_bind thing
1023 | standalone_deriv = addLandmarkErrCtxt (derivBindCtxt clas inst_tys rn_bind) thing
1026 wrapId :: HsWrapper -> id -> HsExpr id
1027 wrapId wrapper id = mkHsWrap wrapper (HsVar id)
1029 derivBindCtxt :: Class -> [Type ] -> LHsBind Name -> SDoc
1030 derivBindCtxt clas tys bind
1031 = vcat [ ptext (sLit "When typechecking a standalone-derived method for")
1032 <+> quotes (pprClassPred clas tys) <> colon
1033 , nest 2 $ pprSetDepth AllTheWay $ ppr bind ]
1035 warnMissingMethod :: Id -> TcM ()
1036 warnMissingMethod sel_id
1037 = do { warn <- doptM Opt_WarnMissingMethods
1038 ; warnTc (warn -- Warn only if -fwarn-missing-methods
1039 && not (startsWithUnderscore (getOccName sel_id)))
1040 -- Don't warn about _foo methods
1041 (ptext (sLit "No explicit method nor default method for")
1042 <+> quotes (ppr sel_id)) }
1045 Note [Export helper functions]
1046 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1047 We arrange to export the "helper functions" of an instance declaration,
1048 so that they are not subject to preInlineUnconditionally, even if their
1049 RHS is trivial. Reason: they are mentioned in the DFunUnfolding of
1050 the dict fun as Ids, not as CoreExprs, so we can't substitute a
1051 non-variable for them.
1053 We could change this by making DFunUnfoldings have CoreExprs, but it
1054 seems a bit simpler this way.
1056 Note [Default methods in instances]
1057 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1064 instance Baz Int Int
1066 From the class decl we get
1068 $dmfoo :: forall v x. Baz v x => x -> x
1071 Notice that the type is ambiguous. That's fine, though. The instance decl generates
1073 $dBazIntInt = MkBaz fooIntInt
1074 fooIntInt = $dmfoo Int Int $dBazIntInt
1076 BUT this does mean we must generate the dictionary translation of
1077 fooIntInt directly, rather than generating source-code and
1078 type-checking it. That was the bug in Trac #1061. In any case it's
1079 less work to generate the translated version!
1081 Note [INLINE and default methods]
1082 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1083 We *copy* any INLINE pragma from the default method to the instance.
1086 op1, op2 :: Bool -> a -> a
1089 op1 b x = op2 (not b) x
1091 instance Foo Int where
1096 {-# INLINE $dmop1 #-}
1097 $dmop1 d b x = op2 d (not b) x
1099 $fFooInt = MkD $cop1 $cop2
1101 {-# INLINE $cop1 #-}
1102 $cop1 = inline $dmop1 $fFooInt
1107 a) We copy $dmop1's inline pragma to $cop1. Otherwise
1108 we'll just inline the former in the latter and stop, which
1109 isn't what the user expected
1111 b) We use the magic 'inline' Id to ensure that $dmop1 really is
1112 inlined in $cop1, even though the latter itself has an INLINE pragma
1113 That is important to allow the mutual recursion between $fooInt and
1116 This is all regrettably delicate.
1119 %************************************************************************
1121 \subsection{Error messages}
1123 %************************************************************************
1126 instDeclCtxt1 :: LHsType Name -> SDoc
1127 instDeclCtxt1 hs_inst_ty
1128 = inst_decl_ctxt (case unLoc hs_inst_ty of
1129 HsForAllTy _ _ _ (L _ (HsPredTy pred)) -> ppr pred
1130 HsPredTy pred -> ppr pred
1131 _ -> ppr hs_inst_ty) -- Don't expect this
1132 instDeclCtxt2 :: Type -> SDoc
1133 instDeclCtxt2 dfun_ty
1134 = inst_decl_ctxt (ppr (mkClassPred cls tys))
1136 (_,cls,tys) = tcSplitDFunTy dfun_ty
1138 inst_decl_ctxt :: SDoc -> SDoc
1139 inst_decl_ctxt doc = ptext (sLit "In the instance declaration for") <+> quotes doc
1141 superClassCtxt :: SDoc
1142 superClassCtxt = ptext (sLit "When checking the super-classes of an instance declaration")
1144 atInstCtxt :: Name -> SDoc
1145 atInstCtxt name = ptext (sLit "In the associated type instance for") <+>
1148 mustBeVarArgErr :: Type -> SDoc
1149 mustBeVarArgErr ty =
1150 sep [ ptext (sLit "Arguments that do not correspond to a class parameter") <+>
1151 ptext (sLit "must be variables")
1152 , ptext (sLit "Instead of a variable, found") <+> ppr ty
1155 wrongATArgErr :: Type -> Type -> SDoc
1156 wrongATArgErr ty instTy =
1157 sep [ ptext (sLit "Type indexes must match class instance head")
1158 , ptext (sLit "Found") <+> quotes (ppr ty)
1159 <+> ptext (sLit "but expected") <+> quotes (ppr instTy)