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 CoreUtils ( mkPiTypes )
37 import PrelNames ( inlineIdName )
55 #include "HsVersions.h"
58 Typechecking instance declarations is done in two passes. The first
59 pass, made by @tcInstDecls1@, collects information to be used in the
62 This pre-processed info includes the as-yet-unprocessed bindings
63 inside the instance declaration. These are type-checked in the second
64 pass, when the class-instance envs and GVE contain all the info from
65 all the instance and value decls. Indeed that's the reason we need
66 two passes over the instance decls.
69 Note [How instance declarations are translated]
70 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
71 Here is how we translation instance declarations into Core
75 op1, op2 :: Ix b => a -> b -> b
79 {-# INLINE [2] op1 #-}
83 op1,op2 :: forall a. C a => forall b. Ix b => a -> b -> b
87 -- Default methods get the 'self' dictionary as argument
88 -- so they can call other methods at the same type
89 -- Default methods get the same type as their method selector
90 $dmop2 :: forall a. C a => forall b. Ix b => a -> b -> b
91 $dmop2 = /\a. \(d:C a). /\b. \(d2: Ix b). <dm-rhs>
92 -- NB: type variables 'a' and 'b' are *both* in scope in <dm-rhs>
93 -- Note [Tricky type variable scoping]
95 -- A top-level definition for each instance method
96 -- Here op1_i, op2_i are the "instance method Ids"
97 -- The INLINE pragma comes from the user pragma
98 {-# INLINE [2] op1_i #-} -- From the instance decl bindings
99 op1_i, op2_i :: forall a. C a => forall b. Ix b => [a] -> b -> b
100 op1_i = /\a. \(d:C a).
103 -- Note [Subtle interaction of recursion and overlap]
105 local_op1 :: forall b. Ix b => [a] -> b -> b
107 -- Source code; run the type checker on this
108 -- NB: Type variable 'a' (but not 'b') is in scope in <rhs>
109 -- Note [Tricky type variable scoping]
113 op2_i = /\a \d:C a. $dmop2 [a] (df_i a d)
115 -- The dictionary function itself
116 {-# NOINLINE CONLIKE df_i #-} -- Never inline dictionary functions
117 df_i :: forall a. C a -> C [a]
118 df_i = /\a. \d:C a. MkC (op1_i a d) (op2_i a d)
119 -- But see Note [Default methods in instances]
120 -- We can't apply the type checker to the default-method call
122 -- Use a RULE to short-circuit applications of the class ops
123 {-# RULE "op1@C[a]" forall a, d:C a.
124 op1 [a] (df_i d) = op1_i a d #-}
126 Note [Instances and loop breakers]
127 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
128 * Note that df_i may be mutually recursive with both op1_i and op2_i.
129 It's crucial that df_i is not chosen as the loop breaker, even
130 though op1_i has a (user-specified) INLINE pragma.
132 * Instead the idea is to inline df_i into op1_i, which may then select
133 methods from the MkC record, and thereby break the recursion with
134 df_i, leaving a *self*-recurisve op1_i. (If op1_i doesn't call op at
135 the same type, it won't mention df_i, so there won't be recursion in
138 * If op1_i is marked INLINE by the user there's a danger that we won't
139 inline df_i in it, and that in turn means that (since it'll be a
140 loop-breaker because df_i isn't), op1_i will ironically never be
141 inlined. But this is OK: the recursion breaking happens by way of
142 a RULE (the magic ClassOp rule above), and RULES work inside InlineRule
143 unfoldings. See Note [RULEs enabled in SimplGently] in SimplUtils
145 Note [ClassOp/DFun selection]
146 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
147 One thing we see a lot is stuff like
149 where 'op2' is a ClassOp and 'df' is DFun. Now, we could inline *both*
150 'op2' and 'df' to get
151 case (MkD ($cop1 d1 d2) ($cop2 d1 d2) ... of
152 MkD _ op2 _ _ _ -> op2
153 And that will reduce to ($cop2 d1 d2) which is what we wanted.
155 But it's tricky to make this work in practice, because it requires us to
156 inline both 'op2' and 'df'. But neither is keen to inline without having
157 seen the other's result; and it's very easy to get code bloat (from the
158 big intermediate) if you inline a bit too much.
160 Instead we use a cunning trick.
161 * We arrange that 'df' and 'op2' NEVER inline.
163 * We arrange that 'df' is ALWAYS defined in the sylised form
164 df d1 d2 = MkD ($cop1 d1 d2) ($cop2 d1 d2) ...
166 * We give 'df' a magical unfolding (DFunUnfolding [$cop1, $cop2, ..])
167 that lists its methods.
169 * We make CoreUnfold.exprIsConApp_maybe spot a DFunUnfolding and return
170 a suitable constructor application -- inlining df "on the fly" as it
173 * We give the ClassOp 'op2' a BuiltinRule that extracts the right piece
174 iff its argument satisfies exprIsConApp_maybe. This is done in
177 * We make 'df' CONLIKE, so that shared uses stil match; eg
179 in ...(op2 d)...(op1 d)...
181 Note [Single-method classes]
182 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
183 If the class has just one method (or, more accurately, just one elemen
184 of {superclasses + methods}), then we want a different strategy.
186 class C a where op :: a -> a
187 instance C a => C [a] where op = <blah>
189 We translate the class decl into a newtype, which just gives
192 axiom Co:C a :: C a ~ (a->a)
194 op :: forall a. C a -> (a -> a)
195 op a d = d |> (Co:C a)
197 df :: forall a. C a => C [a]
199 df = $cop_list |> (forall a. C a -> (sym (Co:C a))
201 $cop_list :: forall a. C a => a -> a
204 So the ClassOp is just a cast; and so is the dictionary function.
205 (The latter doesn't even have any lambdas.) We can inline both freely.
206 No need for fancy BuiltIn rules. Indeed the BuiltinRule stuff does
207 not work well for newtypes because it uses exprIsConApp_maybe.
209 The INLINE on df is vital, else $cop_list occurs just once and is inlined,
210 which is a disaster if $cop_list *itself* has an INLINE pragma.
212 Notice, also, that we go to the trouble of generating a complicated cast,
214 df = /\a. \d. MkD ($cop_list a d)
215 where the MkD "constructor" willl expand to a suitable cast:
216 df = /\a. \d. ($cop_list a d) |> (...)
217 Reason: suppose $cop_list has an INLINE pragma. We want to avoid the
218 nasty possibility that we eta-expand df, to get
219 df = (/\a \d \x. $cop_list a d x) |> (...)
220 and now $cop_list may get inlined into the df, rather than at
221 the actual call site. Of course, eta reduction may get there first,
222 but it seems less fragile to generate the Right Thing in the first place.
226 Note [Subtle interaction of recursion and overlap]
227 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
229 class C a where { op1,op2 :: a -> a }
230 instance C a => C [a] where
231 op1 x = op2 x ++ op2 x
233 intance C [Int] where
236 When type-checking the C [a] instance, we need a C [a] dictionary (for
237 the call of op2). If we look up in the instance environment, we find
238 an overlap. And in *general* the right thing is to complain (see Note
239 [Overlapping instances] in InstEnv). But in *this* case it's wrong to
240 complain, because we just want to delegate to the op2 of this same
243 Why is this justified? Because we generate a (C [a]) constraint in
244 a context in which 'a' cannot be instantiated to anything that matches
245 other overlapping instances, or else we would not be excecuting this
246 version of op1 in the first place.
248 It might even be a bit disguised:
250 nullFail :: C [a] => [a] -> [a]
251 nullFail x = op2 x ++ op2 x
253 instance C a => C [a] where
256 Precisely this is used in package 'regex-base', module Context.hs.
257 See the overlapping instances for RegexContext, and the fact that they
258 call 'nullFail' just like the example above. The DoCon package also
259 does the same thing; it shows up in module Fraction.hs
261 Conclusion: when typechecking the methods in a C [a] instance, we want
262 to have C [a] available. That is why we have the strange local
263 definition for 'this' in the definition of op1_i in the example above.
264 We can typecheck the defintion of local_op1, and when doing tcSimplifyCheck
265 we supply 'this' as a given dictionary. Only needed, though, if there
266 are some type variables involved; otherwise there can be no overlap and
269 Note [Tricky type variable scoping]
270 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
273 op1, op2 :: Ix b => a -> b -> b
276 instance C a => C [a]
277 {-# INLINE [2] op1 #-}
280 note that 'a' and 'b' are *both* in scope in <dm-rhs>, but only 'a' is
281 in scope in <rhs>. In particular, we must make sure that 'b' is in
282 scope when typechecking <dm-rhs>. This is achieved by subFunTys,
283 which brings appropriate tyvars into scope. This happens for both
284 <dm-rhs> and for <rhs>, but that doesn't matter: the *renamer* will have
285 complained if 'b' is mentioned in <rhs>.
289 %************************************************************************
291 \subsection{Extracting instance decls}
293 %************************************************************************
295 Gather up the instance declarations from their various sources
298 tcInstDecls1 -- Deal with both source-code and imported instance decls
299 :: [LTyClDecl Name] -- For deriving stuff
300 -> [LInstDecl Name] -- Source code instance decls
301 -> [LDerivDecl Name] -- Source code stand-alone deriving decls
302 -> TcM (TcGblEnv, -- The full inst env
303 [InstInfo Name], -- Source-code instance decls to process;
304 -- contains all dfuns for this module
305 HsValBinds Name) -- Supporting bindings for derived instances
307 tcInstDecls1 tycl_decls inst_decls deriv_decls
309 do { -- Stop if addInstInfos etc discovers any errors
310 -- (they recover, so that we get more than one error each
313 -- (1) Do class and family instance declarations
314 ; let { idxty_decls = filter (isFamInstDecl . unLoc) tycl_decls }
315 ; local_info_tycons <- mapAndRecoverM tcLocalInstDecl1 inst_decls
316 ; idx_tycons <- mapAndRecoverM tcIdxTyInstDeclTL idxty_decls
319 at_tycons_s) = unzip local_info_tycons
320 ; at_idx_tycons = concat at_tycons_s ++ idx_tycons
321 ; clas_decls = filter (isClassDecl.unLoc) tycl_decls
322 ; implicit_things = concatMap implicitTyThings at_idx_tycons
323 ; aux_binds = mkAuxBinds at_idx_tycons
326 -- (2) Add the tycons of indexed types and their implicit
327 -- tythings to the global environment
328 ; tcExtendGlobalEnv (at_idx_tycons ++ implicit_things) $ do {
330 -- (3) Instances from generic class declarations
331 ; generic_inst_info <- getGenericInstances clas_decls
333 -- Next, construct the instance environment so far, consisting
335 -- a) local instance decls
336 -- b) generic instances
337 -- c) local family instance decls
338 ; addInsts local_info $
339 addInsts generic_inst_info $
340 addFamInsts at_idx_tycons $ do {
342 -- (4) Compute instances from "deriving" clauses;
343 -- This stuff computes a context for the derived instance
344 -- decl, so it needs to know about all the instances possible
345 -- NB: class instance declarations can contain derivings as
346 -- part of associated data type declarations
347 failIfErrsM -- If the addInsts stuff gave any errors, don't
348 -- try the deriving stuff, becuase that may give
350 ; (deriv_inst_info, deriv_binds, deriv_dus)
351 <- tcDeriving tycl_decls inst_decls deriv_decls
352 ; gbl_env <- addInsts deriv_inst_info getGblEnv
353 ; return ( addTcgDUs gbl_env deriv_dus,
354 generic_inst_info ++ deriv_inst_info ++ local_info,
355 aux_binds `plusHsValBinds` deriv_binds)
358 -- Make sure that toplevel type instance are not for associated types.
359 -- !!!TODO: Need to perform this check for the TyThing of type functions,
361 tcIdxTyInstDeclTL ldecl@(L loc decl) =
362 do { tything <- tcFamInstDecl ldecl
364 when (isAssocFamily tything) $
365 addErr $ assocInClassErr (tcdName decl)
368 isAssocFamily (ATyCon tycon) =
369 case tyConFamInst_maybe tycon of
370 Nothing -> panic "isAssocFamily: no family?!?"
371 Just (fam, _) -> isTyConAssoc fam
372 isAssocFamily _ = panic "isAssocFamily: no tycon?!?"
374 assocInClassErr :: Name -> SDoc
375 assocInClassErr name =
376 ptext (sLit "Associated type") <+> quotes (ppr name) <+>
377 ptext (sLit "must be inside a class instance")
379 addInsts :: [InstInfo Name] -> TcM a -> TcM a
380 addInsts infos thing_inside
381 = tcExtendLocalInstEnv (map iSpec infos) thing_inside
383 addFamInsts :: [TyThing] -> TcM a -> TcM a
384 addFamInsts tycons thing_inside
385 = tcExtendLocalFamInstEnv (map mkLocalFamInstTyThing tycons) thing_inside
387 mkLocalFamInstTyThing (ATyCon tycon) = mkLocalFamInst tycon
388 mkLocalFamInstTyThing tything = pprPanic "TcInstDcls.addFamInsts"
393 tcLocalInstDecl1 :: LInstDecl Name
394 -> TcM (InstInfo Name, [TyThing])
395 -- A source-file instance declaration
396 -- Type-check all the stuff before the "where"
398 -- We check for respectable instance type, and context
399 tcLocalInstDecl1 (L loc (InstDecl poly_ty binds uprags ats))
401 addErrCtxt (instDeclCtxt1 poly_ty) $
403 do { is_boot <- tcIsHsBoot
404 ; checkTc (not is_boot || (isEmptyLHsBinds binds && null uprags))
407 ; (tyvars, theta, tau) <- tcHsInstHead poly_ty
409 -- Now, check the validity of the instance.
410 ; (clas, inst_tys) <- checkValidInstHead tau
411 ; checkValidInstance tyvars theta clas inst_tys
413 -- Next, process any associated types.
414 ; idx_tycons <- recoverM (return []) $
415 do { idx_tycons <- checkNoErrs $ mapAndRecoverM tcFamInstDecl ats
416 ; checkValidAndMissingATs clas (tyvars, inst_tys)
418 ; return idx_tycons }
420 -- Finally, construct the Core representation of the instance.
421 -- (This no longer includes the associated types.)
422 ; dfun_name <- newDFunName clas inst_tys (getLoc poly_ty)
423 -- Dfun location is that of instance *header*
424 ; overlap_flag <- getOverlapFlag
425 ; let (eq_theta,dict_theta) = partition isEqPred theta
426 theta' = eq_theta ++ dict_theta
427 dfun = mkDictFunId dfun_name tyvars theta' clas inst_tys
428 ispec = mkLocalInstance dfun overlap_flag
430 ; return (InstInfo { iSpec = ispec,
431 iBinds = VanillaInst binds uprags False },
435 -- We pass in the source form and the type checked form of the ATs. We
436 -- really need the source form only to be able to produce more informative
438 checkValidAndMissingATs :: Class
439 -> ([TyVar], [TcType]) -- instance types
440 -> [(LTyClDecl Name, -- source form of AT
441 TyThing)] -- Core form of AT
443 checkValidAndMissingATs clas inst_tys ats
444 = do { -- Issue a warning for each class AT that is not defined in this
446 ; let class_ats = map tyConName (classATs clas)
447 defined_ats = listToNameSet . map (tcdName.unLoc.fst) $ ats
448 omitted = filterOut (`elemNameSet` defined_ats) class_ats
449 ; warn <- doptM Opt_WarnMissingMethods
450 ; mapM_ (warnTc warn . omittedATWarn) omitted
452 -- Ensure that all AT indexes that correspond to class parameters
453 -- coincide with the types in the instance head. All remaining
454 -- AT arguments must be variables. Also raise an error for any
455 -- type instances that are not associated with this class.
456 ; mapM_ (checkIndexes clas inst_tys) ats
459 checkIndexes clas inst_tys (hsAT, ATyCon tycon)
460 -- !!!TODO: check that this does the Right Thing for indexed synonyms, too!
461 = checkIndexes' clas inst_tys hsAT
463 snd . fromJust . tyConFamInst_maybe $ tycon)
464 checkIndexes _ _ _ = panic "checkIndexes"
466 checkIndexes' clas (instTvs, instTys) hsAT (atTvs, atTys)
467 = let atName = tcdName . unLoc $ hsAT
469 setSrcSpan (getLoc hsAT) $
470 addErrCtxt (atInstCtxt atName) $
471 case find ((atName ==) . tyConName) (classATs clas) of
472 Nothing -> addErrTc $ badATErr clas atName -- not in this class
474 case assocTyConArgPoss_maybe atycon of
475 Nothing -> panic "checkIndexes': AT has no args poss?!?"
478 -- The following is tricky! We need to deal with three
479 -- complications: (1) The AT possibly only uses a subset of
480 -- the class parameters as indexes and those it uses may be in
481 -- a different order; (2) the AT may have extra arguments,
482 -- which must be type variables; and (3) variables in AT and
483 -- instance head will be different `Name's even if their
484 -- source lexemes are identical.
486 -- e.g. class C a b c where
487 -- data D b a :: * -> * -- NB (1) b a, omits c
488 -- instance C [x] Bool Char where
489 -- data D Bool [x] v = MkD x [v] -- NB (2) v
490 -- -- NB (3) the x in 'instance C...' have differnt
491 -- -- Names to x's in 'data D...'
493 -- Re (1), `poss' contains a permutation vector to extract the
494 -- class parameters in the right order.
496 -- Re (2), we wrap the (permuted) class parameters in a Maybe
497 -- type and use Nothing for any extra AT arguments. (First
498 -- equation of `checkIndex' below.)
500 -- Re (3), we replace any type variable in the AT parameters
501 -- that has the same source lexeme as some variable in the
502 -- instance types with the instance type variable sharing its
505 let relevantInstTys = map (instTys !!) poss
506 instArgs = map Just relevantInstTys ++
507 repeat Nothing -- extra arguments
508 renaming = substSameTyVar atTvs instTvs
510 zipWithM_ checkIndex (substTys renaming atTys) instArgs
512 checkIndex ty Nothing
513 | isTyVarTy ty = return ()
514 | otherwise = addErrTc $ mustBeVarArgErr ty
515 checkIndex ty (Just instTy)
516 | ty `tcEqType` instTy = return ()
517 | otherwise = addErrTc $ wrongATArgErr ty instTy
519 listToNameSet = addListToNameSet emptyNameSet
521 substSameTyVar [] _ = emptyTvSubst
522 substSameTyVar (tv:tvs) replacingTvs =
523 let replacement = case find (tv `sameLexeme`) replacingTvs of
524 Nothing -> mkTyVarTy tv
525 Just rtv -> mkTyVarTy rtv
527 tv1 `sameLexeme` tv2 =
528 nameOccName (tyVarName tv1) == nameOccName (tyVarName tv2)
530 extendTvSubst (substSameTyVar tvs replacingTvs) tv replacement
534 %************************************************************************
536 Type-checking instance declarations, pass 2
538 %************************************************************************
541 tcInstDecls2 :: [LTyClDecl Name] -> [InstInfo Name]
542 -> TcM (LHsBinds Id, TcLclEnv)
543 -- (a) From each class declaration,
544 -- generate any default-method bindings
545 -- (b) From each instance decl
546 -- generate the dfun binding
548 tcInstDecls2 tycl_decls inst_decls
549 = do { -- (a) Default methods from class decls
550 let class_decls = filter (isClassDecl . unLoc) tycl_decls
551 ; (dm_ids_s, dm_binds_s) <- mapAndUnzipM tcClassDecl2 class_decls
553 ; tcExtendIdEnv (concat dm_ids_s) $ do
555 -- (b) instance declarations
556 { inst_binds_s <- mapM tcInstDecl2 inst_decls
559 ; let binds = unionManyBags dm_binds_s `unionBags`
560 unionManyBags inst_binds_s
561 ; tcl_env <- getLclEnv -- Default method Ids in here
562 ; return (binds, tcl_env) } }
564 tcInstDecl2 :: InstInfo Name -> TcM (LHsBinds Id)
565 tcInstDecl2 (InstInfo { iSpec = ispec, iBinds = ibinds })
566 = recoverM (return emptyLHsBinds) $
568 addErrCtxt (instDeclCtxt2 (idType dfun_id)) $
569 tc_inst_decl2 dfun_id ibinds
571 dfun_id = instanceDFunId ispec
572 loc = getSrcSpan dfun_id
577 tc_inst_decl2 :: Id -> InstBindings Name -> TcM (LHsBinds Id)
578 -- Returns a binding for the dfun
580 ------------------------
581 -- Derived newtype instances; surprisingly tricky!
583 -- class Show a => Foo a b where ...
584 -- newtype N a = MkN (Tree [a]) deriving( Foo Int )
586 -- The newtype gives an FC axiom looking like
587 -- axiom CoN a :: N a ~ Tree [a]
588 -- (see Note [Newtype coercions] in TyCon for this unusual form of axiom)
590 -- So all need is to generate a binding looking like:
591 -- dfunFooT :: forall a. (Foo Int (Tree [a], Show (N a)) => Foo Int (N a)
592 -- dfunFooT = /\a. \(ds:Show (N a)) (df:Foo (Tree [a])).
593 -- case df `cast` (Foo Int (sym (CoN a))) of
594 -- Foo _ op1 .. opn -> Foo ds op1 .. opn
596 -- If there are no superclasses, matters are simpler, because we don't need the case
597 -- see Note [Newtype deriving superclasses] in TcDeriv.lhs
599 tc_inst_decl2 dfun_id (NewTypeDerived coi)
600 = do { let rigid_info = InstSkol
601 origin = SigOrigin rigid_info
602 inst_ty = idType dfun_id
603 inst_tvs = fst (tcSplitForAllTys inst_ty)
604 ; (inst_tvs', theta, inst_head_ty) <- tcSkolSigType rigid_info inst_ty
605 -- inst_head_ty is a PredType
607 ; let (cls, cls_inst_tys) = tcSplitDFunHead inst_head_ty
608 (class_tyvars, sc_theta, _, _) = classBigSig cls
609 cls_tycon = classTyCon cls
610 sc_theta' = substTheta (zipOpenTvSubst class_tyvars cls_inst_tys) sc_theta
611 Just (initial_cls_inst_tys, last_ty) = snocView cls_inst_tys
615 IdCo -> (last_ty, idHsWrapper)
616 ACo co -> (snd (coercionKind co'), WpCast (mk_full_coercion co'))
618 co' = substTyWith inst_tvs (mkTyVarTys inst_tvs') co
619 -- NB: the free variable of coi are bound by the
620 -- universally quantified variables of the dfun_id
621 -- This is weird, and maybe we should make NewTypeDerived
622 -- carry a type-variable list too; but it works fine
624 -----------------------
626 -- The inst_head looks like (C s1 .. sm (T a1 .. ak))
627 -- But we want the coercion (C s1 .. sm (sym (CoT a1 .. ak)))
628 -- with kind (C s1 .. sm (T a1 .. ak) ~ C s1 .. sm <rep_ty>)
629 -- where rep_ty is the (eta-reduced) type rep of T
630 -- So we just replace T with CoT, and insert a 'sym'
631 -- NB: we know that k will be >= arity of CoT, because the latter fully eta-reduced
633 mk_full_coercion co = mkTyConApp cls_tycon
634 (initial_cls_inst_tys ++ [mkSymCoercion co])
635 -- Full coercion : (Foo Int (Tree [a]) ~ Foo Int (N a)
637 rep_pred = mkClassPred cls (initial_cls_inst_tys ++ [rep_ty])
638 -- In our example, rep_pred is (Foo Int (Tree [a]))
640 ; sc_loc <- getInstLoc InstScOrigin
641 ; sc_dicts <- newDictBndrs sc_loc sc_theta'
642 ; inst_loc <- getInstLoc origin
643 ; dfun_dicts <- newDictBndrs inst_loc theta
644 ; rep_dict <- newDictBndr inst_loc rep_pred
645 ; this_dict <- newDictBndr inst_loc (mkClassPred cls cls_inst_tys)
647 -- Figure out bindings for the superclass context from dfun_dicts
648 -- Don't include this_dict in the 'givens', else
649 -- sc_dicts get bound by just selecting from this_dict!!
650 ; sc_binds <- addErrCtxt superClassCtxt $
651 tcSimplifySuperClasses inst_loc this_dict dfun_dicts
654 -- It's possible that the superclass stuff might unified something
655 -- in the envt with one of the clas_tyvars
656 ; checkSigTyVars inst_tvs'
658 ; let coerced_rep_dict = wrapId wrapper (instToId rep_dict)
660 ; body <- make_body cls_tycon cls_inst_tys sc_dicts coerced_rep_dict
661 ; let dict_bind = mkVarBind (instToId this_dict) (noLoc body)
663 ; return (unitBag $ noLoc $
664 AbsBinds inst_tvs' (map instToVar dfun_dicts)
665 [(inst_tvs', dfun_id, instToId this_dict, [])]
666 (dict_bind `consBag` sc_binds)) }
668 -----------------------
669 -- (make_body C tys scs coreced_rep_dict)
671 -- (case coerced_rep_dict of { C _ ops -> C scs ops })
672 -- But if there are no superclasses, it returns just coerced_rep_dict
673 -- See Note [Newtype deriving superclasses] in TcDeriv.lhs
675 make_body cls_tycon cls_inst_tys sc_dicts coerced_rep_dict
676 | null sc_dicts -- Case (a)
677 = return coerced_rep_dict
678 | otherwise -- Case (b)
679 = do { op_ids <- newSysLocalIds (fsLit "op") op_tys
680 ; dummy_sc_dict_ids <- newSysLocalIds (fsLit "sc") (map idType sc_dict_ids)
681 ; let the_pat = ConPatOut { pat_con = noLoc cls_data_con, pat_tvs = [],
682 pat_dicts = dummy_sc_dict_ids,
683 pat_binds = emptyLHsBinds,
684 pat_args = PrefixCon (map nlVarPat op_ids),
686 the_match = mkSimpleMatch [noLoc the_pat] the_rhs
687 the_rhs = mkHsConApp cls_data_con cls_inst_tys $
688 map HsVar (sc_dict_ids ++ op_ids)
690 -- Warning: this HsCase scrutinises a value with a PredTy, which is
691 -- never otherwise seen in Haskell source code. It'd be
692 -- nicer to generate Core directly!
693 ; return (HsCase (noLoc coerced_rep_dict) $
694 MatchGroup [the_match] (mkFunTy pat_ty pat_ty)) }
696 sc_dict_ids = map instToId sc_dicts
697 pat_ty = mkTyConApp cls_tycon cls_inst_tys
698 cls_data_con = head (tyConDataCons cls_tycon)
699 cls_arg_tys = dataConInstArgTys cls_data_con cls_inst_tys
700 op_tys = dropList sc_dict_ids cls_arg_tys
702 ------------------------
703 -- Ordinary instances
705 tc_inst_decl2 dfun_id (VanillaInst monobinds uprags standalone_deriv)
706 = do { let rigid_info = InstSkol
707 inst_ty = idType dfun_id
708 loc = getSrcSpan dfun_id
710 -- Instantiate the instance decl with skolem constants
711 ; (inst_tyvars', dfun_theta', inst_head') <- tcSkolSigType rigid_info inst_ty
712 -- These inst_tyvars' scope over the 'where' part
713 -- Those tyvars are inside the dfun_id's type, which is a bit
714 -- bizarre, but OK so long as you realise it!
716 (clas, inst_tys') = tcSplitDFunHead inst_head'
717 (class_tyvars, sc_theta, sc_sels, op_items) = classBigSig clas
719 -- Instantiate the super-class context with inst_tys
720 sc_theta' = substTheta (zipOpenTvSubst class_tyvars inst_tys') sc_theta
721 origin = SigOrigin rigid_info
723 -- Create dictionary Ids from the specified instance contexts.
724 ; inst_loc <- getInstLoc origin
725 ; dfun_dicts <- newDictBndrs inst_loc dfun_theta' -- Includes equalities
726 ; this_dict <- newDictBndr inst_loc (mkClassPred clas inst_tys')
727 -- Default-method Ids may be mentioned in synthesised RHSs,
728 -- but they'll already be in the environment.
731 -- Cook up a binding for "this = df d1 .. dn",
732 -- to use in each method binding
733 -- Need to clone the dict in case it is floated out, and
734 -- then clashes with its friends
735 ; cloned_this <- cloneDict this_dict
736 ; let cloned_this_bind = mkVarBind (instToId cloned_this) $
737 L loc $ wrapId app_wrapper dfun_id
738 app_wrapper = mkWpApps dfun_lam_vars <.> mkWpTyApps (mkTyVarTys inst_tyvars')
739 dfun_lam_vars = map instToVar dfun_dicts -- Includes equalities
741 | null inst_tyvars' && null dfun_theta' = (this_dict, emptyBag)
742 | otherwise = (cloned_this, unitBag cloned_this_bind)
744 -- Deal with 'SPECIALISE instance' pragmas
745 -- See Note [SPECIALISE instance pragmas]
746 ; let spec_inst_sigs = filter isSpecInstLSig uprags
747 -- The filter removes the pragmas for methods
748 ; spec_inst_prags <- mapM (wrapLocM (tcSpecInst dfun_id)) spec_inst_sigs
750 -- Typecheck the methods
751 ; let prag_fn = mkPragFun uprags
752 tc_meth = tcInstanceMethod loc standalone_deriv
756 prag_fn spec_inst_prags monobinds
758 ; (meth_ids, meth_binds) <- tcExtendTyVarEnv inst_tyvars' $
759 mapAndUnzipM tc_meth op_items
761 -- Figure out bindings for the superclass context
762 ; sc_loc <- getInstLoc InstScOrigin
763 ; sc_dicts <- newDictOccs sc_loc sc_theta' -- These are wanted
764 ; let tc_sc = tcSuperClass inst_loc inst_tyvars' dfun_dicts nested_this_pair
765 ; (sc_ids, sc_binds) <- mapAndUnzipM tc_sc (sc_sels `zip` sc_dicts)
767 -- It's possible that the superclass stuff might unified
768 -- something in the envt with one of the inst_tyvars'
769 ; checkSigTyVars inst_tyvars'
771 -- Create the result bindings
772 ; let this_dict_id = instToId this_dict
773 arg_ids = sc_ids ++ meth_ids
774 arg_binds = listToBag meth_binds `unionBags`
777 ; showLIE (text "instance")
778 ; case newTyConCo_maybe (classTyCon clas) of
779 Nothing -- A multi-method class
780 -> return (unitBag (L loc data_bind) `unionBags` arg_binds)
782 data_dfun_id = dfun_id -- Do not inline; instead give it a magic DFunFunfolding
783 -- See Note [ClassOp/DFun selection]
784 `setIdUnfolding` mkDFunUnfolding dict_constr arg_ids
785 `setInlinePragma` dfunInlinePragma
787 data_bind = AbsBinds inst_tyvars' dfun_lam_vars
788 [(inst_tyvars', data_dfun_id, this_dict_id, spec_inst_prags)]
791 dict_bind = mkVarBind this_dict_id dict_rhs
792 dict_rhs = foldl mk_app inst_constr arg_ids
793 dict_constr = classDataCon clas
794 inst_constr = L loc $ wrapId (mkWpTyApps inst_tys')
795 (dataConWrapId dict_constr)
796 -- We don't produce a binding for the dict_constr; instead we
797 -- rely on the simplifier to unfold this saturated application
798 -- We do this rather than generate an HsCon directly, because
799 -- it means that the special cases (e.g. dictionary with only one
800 -- member) are dealt with by the common MkId.mkDataConWrapId code rather
801 -- than needing to be repeated here.
803 mk_app :: LHsExpr Id -> Id -> LHsExpr Id
804 mk_app fun arg_id = L loc (HsApp fun (L loc (wrapId arg_wrapper arg_id)))
805 arg_wrapper = mkWpApps dfun_lam_vars <.> mkWpTyApps (mkTyVarTys inst_tyvars')
807 Just the_nt_co -- (Just co) for a single-method class
808 -> return (unitBag (L loc nt_bind) `unionBags` arg_binds)
810 nt_dfun_id = dfun_id -- Just let the dfun inline; see Note [Single-method classes]
811 `setInlinePragma` alwaysInlinePragma
813 local_nt_dfun = setIdType this_dict_id inst_ty -- A bit of a hack, but convenient
815 nt_bind = AbsBinds [] []
816 [([], nt_dfun_id, local_nt_dfun, spec_inst_prags)]
817 (unitBag (mkVarBind local_nt_dfun (L loc (wrapId nt_cast the_meth_id))))
819 the_meth_id = ASSERT( length arg_ids == 1 ) head arg_ids
820 nt_cast = WpCast $ mkPiTypes (inst_tyvars' ++ dfun_lam_vars) $
821 mkSymCoercion (mkTyConApp the_nt_co inst_tys')
825 ------------------------------
826 tcSuperClass :: InstLoc -> [TyVar] -> [Inst]
827 -> (Inst, LHsBinds Id)
828 -> (Id, Inst) -> TcM (Id, LHsBind Id)
829 -- Build a top level decl like
830 -- sc_op = /\a \d. let this = ... in
833 -- The "this" part is just-in-case (discarded if not used)
834 -- See Note [Recursive superclasses]
835 tcSuperClass inst_loc tyvars dicts (this_dict, this_bind)
837 = addErrCtxt superClassCtxt $
838 do { sc_binds <- tcSimplifySuperClasses inst_loc
839 this_dict dicts [sc_dict]
840 -- Don't include this_dict in the 'givens', else
841 -- sc_dicts get bound by just selecting from this_dict!!
844 ; let sc_op_ty = mkSigmaTy tyvars (map dictPred dicts)
845 (mkPredTy (dictPred sc_dict))
846 sc_op_name = mkDerivedInternalName mkClassOpAuxOcc uniq
848 sc_op_id = mkLocalId sc_op_name sc_op_ty
849 sc_id = instToVar sc_dict
850 sc_op_bind = AbsBinds tyvars
851 (map instToVar dicts)
852 [(tyvars, sc_op_id, sc_id, [])]
853 (this_bind `unionBags` sc_binds)
855 ; return (sc_op_id, noLoc sc_op_bind) }
858 Note [Recursive superclasses]
859 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
860 See Trac #1470 for why we would *like* to add "this_dict" to the
861 available instances here. But we can't do so because then the superclases
862 get satisfied by selection from this_dict, and that leads to an immediate
863 loop. What we need is to add this_dict to Avails without adding its
864 superclasses, and we currently have no way to do that.
866 Note [SPECIALISE instance pragmas]
867 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
870 instance (Ix a, Ix b) => Ix (a,b) where
871 {-# SPECIALISE instance Ix (Int,Int) #-}
874 We do *not* want to make a specialised version of the dictionary
875 function. Rather, we want specialised versions of each method.
876 Thus we should generate something like this:
878 $dfIx :: (Ix a, Ix x) => Ix (a,b)
879 {- DFUN [$crange, ...] -}
880 $dfIx da db = Ix ($crange da db) (...other methods...)
882 $dfIxPair :: (Ix a, Ix x) => Ix (a,b)
883 {- DFUN [$crangePair, ...] -}
884 $dfIxPair = Ix ($crangePair da db) (...other methods...)
886 $crange :: (Ix a, Ix b) -> ((a,b),(a,b)) -> [(a,b)]
887 {-# SPECIALISE $crange :: ((Int,Int),(Int,Int)) -> [(Int,Int)] #-}
888 $crange da db = <blah>
890 {-# RULE range ($dfIx da db) = $crange da db #-}
894 * The RULE is unaffected by the specialisation. We don't want to
895 specialise $dfIx, because then it would need a specialised RULE
896 which is a pain. The single RULE works fine at all specialisations.
897 See Note [How instance declarations are translated] above
899 * Instead, we want to specialise the *method*, $crange
901 In practice, rather than faking up a SPECIALISE pragama for each
902 method (which is painful, since we'd have to figure out its
903 specialised type), we call tcSpecPrag *as if* were going to specialise
904 $dfIx -- you can see that in the call to tcSpecInst. That generates a
905 SpecPrag which, as it turns out, can be used unchanged for each method.
906 The "it turns out" bit is delicate, but it works fine!
909 tcSpecInst :: Id -> Sig Name -> TcM SpecPrag
910 tcSpecInst dfun_id prag@(SpecInstSig hs_ty)
911 = addErrCtxt (spec_ctxt prag) $
912 do { let name = idName dfun_id
913 ; (tyvars, theta, tau) <- tcHsInstHead hs_ty
914 ; let spec_ty = mkSigmaTy tyvars theta tau
915 ; co_fn <- tcSubExp (SpecPragOrigin name) (idType dfun_id) spec_ty
916 ; return (SpecPrag co_fn defaultInlinePragma) }
918 spec_ctxt prag = hang (ptext (sLit "In the SPECIALISE pragma")) 2 (ppr prag)
920 tcSpecInst _ _ = panic "tcSpecInst"
923 %************************************************************************
925 Type-checking an instance method
927 %************************************************************************
930 - Make the method bindings, as a [(NonRec, HsBinds)], one per method
931 - Remembering to use fresh Name (the instance method Name) as the binder
932 - Bring the instance method Ids into scope, for the benefit of tcInstSig
933 - Use sig_fn mapping instance method Name -> instance tyvars
935 - Use tcValBinds to do the checking
938 tcInstanceMethod :: SrcSpan -> Bool -> Class -> [TcTyVar] -> [Inst]
940 -> (Inst, LHsBinds Id) -- "This" and its binding
941 -> TcPragFun -- Local prags
942 -> [LSpecPrag] -- Arising from 'SPECLALISE instance'
945 -> TcM (Id, LHsBind Id)
946 -- The returned inst_meth_ids all have types starting
947 -- forall tvs. theta => ...
949 tcInstanceMethod loc standalone_deriv clas tyvars dfun_dicts inst_tys
950 (this_dict, this_dict_bind)
951 prag_fn spec_inst_prags binds_in (sel_id, dm_info)
952 = do { uniq <- newUnique
953 ; let meth_name = mkDerivedInternalName mkClassOpAuxOcc uniq sel_name
954 ; local_meth_name <- newLocalName sel_name
955 -- Base the local_meth_name on the selector name, becuase
956 -- type errors from tcInstanceMethodBody come from here
958 ; let local_meth_ty = instantiateMethod clas sel_id inst_tys
959 meth_ty = mkSigmaTy tyvars (map dictPred dfun_dicts) local_meth_ty
960 meth_id = mkLocalId meth_name meth_ty
961 local_meth_id = mkLocalId local_meth_name local_meth_ty
965 = add_meth_ctxt rn_bind $
966 do { (meth_id1, spec_prags) <- tcPrags NonRecursive False True
967 meth_id (prag_fn sel_name)
968 ; tcInstanceMethodBody (instLoc this_dict)
970 ([this_dict], this_dict_bind)
971 meth_id1 local_meth_id
973 (spec_inst_prags ++ spec_prags)
977 tc_default :: DefMeth -> TcM (Id, LHsBind Id)
978 -- The user didn't supply a method binding, so we have to make
979 -- up a default binding, in a way depending on the default-method info
981 tc_default NoDefMeth -- No default method at all
982 = do { warnMissingMethod sel_id
983 ; return (meth_id, mkVarBind meth_id $
984 mkLHsWrap lam_wrapper error_rhs) }
986 tc_default GenDefMeth -- Derivable type classes stuff
987 = do { meth_bind <- mkGenericDefMethBind clas inst_tys sel_id local_meth_name
988 ; tc_body meth_bind }
990 tc_default DefMeth -- An polymorphic default method
991 = do { -- Build the typechecked version directly,
992 -- without calling typecheck_method;
993 -- see Note [Default methods in instances]
994 -- Generate /\as.\ds. let this = df as ds
995 -- in $dm inst_tys this
996 -- The 'let' is necessary only because HsSyn doesn't allow
997 -- you to apply a function to a dictionary *expression*.
998 dm_name <- lookupGlobalOccRn (mkDefMethRdrName sel_name)
999 -- Might not be imported, but will be an OrigName
1000 ; dm_id <- tcLookupId dm_name
1001 ; inline_id <- tcLookupId inlineIdName
1002 ; let dm_inline_prag = idInlinePragma dm_id
1003 dm_app = HsWrap (WpApp (instToId this_dict) <.> mkWpTyApps inst_tys) $
1005 rhs | isInlinePragma dm_inline_prag -- See Note [INLINE and default methods]
1006 = HsApp (L loc (HsWrap (WpTyApp local_meth_ty) (HsVar inline_id)))
1008 | otherwise = dm_app
1010 meth_bind = L loc $ VarBind { var_id = local_meth_id
1011 , var_rhs = L loc rhs
1012 , var_inline = False }
1013 meth_id1 = meth_id `setInlinePragma` dm_inline_prag
1014 -- Copy the inline pragma (if any) from the default
1015 -- method to this version. Note [INLINE and default methods]
1017 bind = AbsBinds { abs_tvs = tyvars, abs_dicts = dfun_lam_vars
1018 , abs_exports = [( tyvars, meth_id1
1019 , local_meth_id, spec_inst_prags)]
1020 , abs_binds = this_dict_bind `unionBags` unitBag meth_bind }
1021 -- Default methods in an instance declaration can't have their own
1022 -- INLINE or SPECIALISE pragmas. It'd be possible to allow them, but
1023 -- currently they are rejected with
1024 -- "INLINE pragma lacks an accompanying binding"
1026 ; return (meth_id1, L loc bind) }
1028 ; case findMethodBind sel_name local_meth_name binds_in of
1029 Just user_bind -> tc_body user_bind -- User-supplied method binding
1030 Nothing -> tc_default dm_info -- None supplied
1033 sel_name = idName sel_id
1035 meth_sig_fn _ = Just [] -- The 'Just' says "yes, there's a type sig"
1036 -- But there are no scoped type variables from local_method_id
1037 -- Only the ones from the instance decl itself, which are already
1038 -- in scope. Example:
1039 -- class C a where { op :: forall b. Eq b => ... }
1040 -- instance C [c] where { op = <rhs> }
1041 -- In <rhs>, 'c' is scope but 'b' is not!
1043 error_rhs = L loc $ HsApp error_fun error_msg
1044 error_fun = L loc $ wrapId (WpTyApp meth_tau) nO_METHOD_BINDING_ERROR_ID
1045 error_msg = L loc (HsLit (HsStringPrim (mkFastString error_string)))
1046 meth_tau = funResultTy (applyTys (idType sel_id) inst_tys)
1047 error_string = showSDoc (hcat [ppr loc, text "|", ppr sel_id ])
1049 dfun_lam_vars = map instToVar dfun_dicts
1050 lam_wrapper = mkWpTyLams tyvars <.> mkWpLams dfun_lam_vars
1052 -- For instance decls that come from standalone deriving clauses
1053 -- we want to print out the full source code if there's an error
1054 -- because otherwise the user won't see the code at all
1055 add_meth_ctxt rn_bind thing
1056 | standalone_deriv = addLandmarkErrCtxt (derivBindCtxt clas inst_tys rn_bind) thing
1059 wrapId :: HsWrapper -> id -> HsExpr id
1060 wrapId wrapper id = mkHsWrap wrapper (HsVar id)
1062 derivBindCtxt :: Class -> [Type ] -> LHsBind Name -> SDoc
1063 derivBindCtxt clas tys bind
1064 = vcat [ ptext (sLit "When typechecking a standalone-derived method for")
1065 <+> quotes (pprClassPred clas tys) <> colon
1066 , nest 2 $ pprSetDepth AllTheWay $ ppr bind ]
1068 warnMissingMethod :: Id -> TcM ()
1069 warnMissingMethod sel_id
1070 = do { warn <- doptM Opt_WarnMissingMethods
1071 ; warnTc (warn -- Warn only if -fwarn-missing-methods
1072 && not (startsWithUnderscore (getOccName sel_id)))
1073 -- Don't warn about _foo methods
1074 (ptext (sLit "No explicit method nor default method for")
1075 <+> quotes (ppr sel_id)) }
1078 Note [Export helper functions]
1079 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1080 We arrange to export the "helper functions" of an instance declaration,
1081 so that they are not subject to preInlineUnconditionally, even if their
1082 RHS is trivial. Reason: they are mentioned in the DFunUnfolding of
1083 the dict fun as Ids, not as CoreExprs, so we can't substitute a
1084 non-variable for them.
1086 We could change this by making DFunUnfoldings have CoreExprs, but it
1087 seems a bit simpler this way.
1089 Note [Default methods in instances]
1090 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1097 instance Baz Int Int
1099 From the class decl we get
1101 $dmfoo :: forall v x. Baz v x => x -> x
1104 Notice that the type is ambiguous. That's fine, though. The instance decl generates
1106 $dBazIntInt = MkBaz fooIntInt
1107 fooIntInt = $dmfoo Int Int $dBazIntInt
1109 BUT this does mean we must generate the dictionary translation of
1110 fooIntInt directly, rather than generating source-code and
1111 type-checking it. That was the bug in Trac #1061. In any case it's
1112 less work to generate the translated version!
1114 Note [INLINE and default methods]
1115 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1116 We *copy* any INLINE pragma from the default method to the instance.
1119 op1, op2 :: Bool -> a -> a
1122 op1 b x = op2 (not b) x
1124 instance Foo Int where
1129 {-# INLINE $dmop1 #-}
1130 $dmop1 d b x = op2 d (not b) x
1132 $fFooInt = MkD $cop1 $cop2
1134 {-# INLINE $cop1 #-}
1135 $cop1 = inline $dmop1 $fFooInt
1140 a) We copy $dmop1's inline pragma to $cop1. Otherwise
1141 we'll just inline the former in the latter and stop, which
1142 isn't what the user expected
1144 b) We use the magic 'inline' Id to ensure that $dmop1 really is
1145 inlined in $cop1, even though
1146 (i) the latter itself has an INLINE pragma
1147 (ii) $dmop1 is not saturated
1148 That is important to allow the mutual recursion between $fooInt and
1152 %************************************************************************
1154 \subsection{Error messages}
1156 %************************************************************************
1159 instDeclCtxt1 :: LHsType Name -> SDoc
1160 instDeclCtxt1 hs_inst_ty
1161 = inst_decl_ctxt (case unLoc hs_inst_ty of
1162 HsForAllTy _ _ _ (L _ (HsPredTy pred)) -> ppr pred
1163 HsPredTy pred -> ppr pred
1164 _ -> ppr hs_inst_ty) -- Don't expect this
1165 instDeclCtxt2 :: Type -> SDoc
1166 instDeclCtxt2 dfun_ty
1167 = inst_decl_ctxt (ppr (mkClassPred cls tys))
1169 (_,cls,tys) = tcSplitDFunTy dfun_ty
1171 inst_decl_ctxt :: SDoc -> SDoc
1172 inst_decl_ctxt doc = ptext (sLit "In the instance declaration for") <+> quotes doc
1174 superClassCtxt :: SDoc
1175 superClassCtxt = ptext (sLit "When checking the super-classes of an instance declaration")
1177 atInstCtxt :: Name -> SDoc
1178 atInstCtxt name = ptext (sLit "In the associated type instance for") <+>
1181 mustBeVarArgErr :: Type -> SDoc
1182 mustBeVarArgErr ty =
1183 sep [ ptext (sLit "Arguments that do not correspond to a class parameter") <+>
1184 ptext (sLit "must be variables")
1185 , ptext (sLit "Instead of a variable, found") <+> ppr ty
1188 wrongATArgErr :: Type -> Type -> SDoc
1189 wrongATArgErr ty instTy =
1190 sep [ ptext (sLit "Type indexes must match class instance head")
1191 , ptext (sLit "Found") <+> quotes (ppr ty)
1192 <+> ptext (sLit "but expected") <+> quotes (ppr instTy)