Remove old, redundant note
[ghc-hetmet.git] / compiler / typecheck / TcInstDcls.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 %
5
6 TcInstDecls: Typechecking instance declarations
7
8 \begin{code}
9 module TcInstDcls ( tcInstDecls1, tcInstDecls2 ) where
10
11 import HsSyn
12 import TcBinds
13 import TcTyClsDecls
14 import TcClassDcl
15 import TcRnMonad
16 import TcMType
17 import TcType
18 import Inst
19 import InstEnv
20 import FamInst
21 import FamInstEnv
22 import TcDeriv
23 import TcEnv
24 import RnEnv    ( lookupGlobalOccRn )
25 import RnSource ( addTcgDUs )
26 import TcHsType
27 import TcUnify
28 import TcSimplify
29 import Type
30 import Coercion
31 import TyCon
32 import DataCon
33 import Class
34 import Var
35 import CoreUnfold ( mkDFunUnfolding )
36 import PrelNames  ( inlineIdName )
37 import Id
38 import MkId
39 import Name
40 import NameSet
41 import DynFlags
42 import SrcLoc
43 import Util
44 import Outputable
45 import Bag
46 import BasicTypes
47 import HscTypes
48 import FastString
49
50 import Data.Maybe
51 import Control.Monad
52 import Data.List
53
54 #include "HsVersions.h"
55 \end{code}
56
57 Typechecking instance declarations is done in two passes. The first
58 pass, made by @tcInstDecls1@, collects information to be used in the
59 second pass.
60
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.
66
67
68 Note [How instance declarations are translated]
69 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
70 Here is how we translation instance declarations into Core
71
72 Running example:
73         class C a where
74            op1, op2 :: Ix b => a -> b -> b
75            op2 = <dm-rhs>
76
77         instance C a => C [a]
78            {-# INLINE [2] op1 #-}
79            op1 = <rhs>
80 ===>
81         -- Method selectors
82         op1,op2 :: forall a. C a => forall b. Ix b => a -> b -> b
83         op1 = ...
84         op2 = ...
85
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]
93
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). 
100                let this :: C [a]
101                    this = df_i a d
102                      -- Note [Subtle interaction of recursion and overlap]
103
104                    local_op1 :: forall b. Ix b => [a] -> b -> b
105                    local_op1 = <rhs>
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]
109
110                in local_op1 a d
111
112         op2_i = /\a \d:C a. $dmop2 [a] (df_i a d) 
113
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
120
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 #-}
124
125 * We want to inline the dictionary function itself as vigorously as we
126   possibly can, so that we expose that dictionary constructor to
127   selectors as much as poss.  We don't actually inline it; rather, we
128   use a Builtin RULE for the ClassOps (see MkId.mkDictSelId) to short
129   circuit such applications.  But the RULE only applies if it can "see"
130   the dfun's DFunUnfolding. 
131
132 * Note that df_i may be mutually recursive with both op1_i and op2_i.
133   It's crucial that df_i is not chosen as the loop breaker, even 
134   though op1_i has a (user-specified) INLINE pragma.
135
136 * Instead the idea is to inline df_i into op1_i, which may then select
137   methods from the MkC record, and thereby break the recursion with
138   df_i, leaving a *self*-recurisve op1_i.  (If op1_i doesn't call op at
139   the same type, it won't mention df_i, so there won't be recursion in
140   the first place.)  
141
142 * If op1_i is marked INLINE by the user there's a danger that we won't
143   inline df_i in it, and that in turn means that (since it'll be a
144   loop-breaker because df_i isn't), op1_i will ironically never be 
145   inlined.  But this is OK: the recursion breaking happens by way of
146   a RULE (the magic ClassOp rule above), and RULES work inside InlineRule
147   unfoldings. See Note [RULEs enabled in SimplGently] in SimplUtils
148
149
150 Note [Subtle interaction of recursion and overlap]
151 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
152 Consider this
153   class C a where { op1,op2 :: a -> a }
154   instance C a => C [a] where
155     op1 x = op2 x ++ op2 x
156     op2 x = ...
157   intance C [Int] where
158     ...
159
160 When type-checking the C [a] instance, we need a C [a] dictionary (for
161 the call of op2).  If we look up in the instance environment, we find
162 an overlap.  And in *general* the right thing is to complain (see Note
163 [Overlapping instances] in InstEnv).  But in *this* case it's wrong to
164 complain, because we just want to delegate to the op2 of this same
165 instance.  
166
167 Why is this justified?  Because we generate a (C [a]) constraint in 
168 a context in which 'a' cannot be instantiated to anything that matches
169 other overlapping instances, or else we would not be excecuting this
170 version of op1 in the first place.
171
172 It might even be a bit disguised:
173
174   nullFail :: C [a] => [a] -> [a]
175   nullFail x = op2 x ++ op2 x
176
177   instance C a => C [a] where
178     op1 x = nullFail x
179
180 Precisely this is used in package 'regex-base', module Context.hs.
181 See the overlapping instances for RegexContext, and the fact that they
182 call 'nullFail' just like the example above.  The DoCon package also
183 does the same thing; it shows up in module Fraction.hs
184
185 Conclusion: when typechecking the methods in a C [a] instance, we want
186 to have C [a] available.  That is why we have the strange local
187 definition for 'this' in the definition of op1_i in the example above.
188 We can typecheck the defintion of local_op1, and when doing tcSimplifyCheck
189 we supply 'this' as a given dictionary.  Only needed, though, if there
190 are some type variables involved; otherwise there can be no overlap and
191 none of this arises.
192
193 Note [Tricky type variable scoping]
194 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
195 In our example
196         class C a where
197            op1, op2 :: Ix b => a -> b -> b
198            op2 = <dm-rhs>
199
200         instance C a => C [a]
201            {-# INLINE [2] op1 #-}
202            op1 = <rhs>
203
204 note that 'a' and 'b' are *both* in scope in <dm-rhs>, but only 'a' is
205 in scope in <rhs>.  In particular, we must make sure that 'b' is in
206 scope when typechecking <dm-rhs>.  This is achieved by subFunTys,
207 which brings appropriate tyvars into scope. This happens for both
208 <dm-rhs> and for <rhs>, but that doesn't matter: the *renamer* will have
209 complained if 'b' is mentioned in <rhs>.
210
211
212
213 %************************************************************************
214 %*                                                                      *
215 \subsection{Extracting instance decls}
216 %*                                                                      *
217 %************************************************************************
218
219 Gather up the instance declarations from their various sources
220
221 \begin{code}
222 tcInstDecls1    -- Deal with both source-code and imported instance decls
223    :: [LTyClDecl Name]          -- For deriving stuff
224    -> [LInstDecl Name]          -- Source code instance decls
225    -> [LDerivDecl Name]         -- Source code stand-alone deriving decls
226    -> TcM (TcGblEnv,            -- The full inst env
227            [InstInfo Name],     -- Source-code instance decls to process;
228                                 -- contains all dfuns for this module
229            HsValBinds Name)     -- Supporting bindings for derived instances
230
231 tcInstDecls1 tycl_decls inst_decls deriv_decls
232   = checkNoErrs $
233     do {        -- Stop if addInstInfos etc discovers any errors
234                 -- (they recover, so that we get more than one error each
235                 -- round)
236
237                 -- (1) Do class and family instance declarations
238        ; let { idxty_decls = filter (isFamInstDecl . unLoc) tycl_decls }
239        ; local_info_tycons <- mapAndRecoverM tcLocalInstDecl1  inst_decls
240        ; idx_tycons        <- mapAndRecoverM tcIdxTyInstDeclTL idxty_decls
241
242        ; let { (local_info,
243                 at_tycons_s)   = unzip local_info_tycons
244              ; at_idx_tycons   = concat at_tycons_s ++ idx_tycons
245              ; clas_decls      = filter (isClassDecl.unLoc) tycl_decls
246              ; implicit_things = concatMap implicitTyThings at_idx_tycons
247              ; aux_binds       = mkAuxBinds at_idx_tycons
248              }
249
250                 -- (2) Add the tycons of indexed types and their implicit
251                 --     tythings to the global environment
252        ; tcExtendGlobalEnv (at_idx_tycons ++ implicit_things) $ do {
253
254                 -- (3) Instances from generic class declarations
255        ; generic_inst_info <- getGenericInstances clas_decls
256
257                 -- Next, construct the instance environment so far, consisting
258                 -- of
259                 --   a) local instance decls
260                 --   b) generic instances
261                 --   c) local family instance decls
262        ; addInsts local_info         $
263          addInsts generic_inst_info  $
264          addFamInsts at_idx_tycons   $ do {
265
266                 -- (4) Compute instances from "deriving" clauses;
267                 -- This stuff computes a context for the derived instance
268                 -- decl, so it needs to know about all the instances possible
269                 -- NB: class instance declarations can contain derivings as
270                 --     part of associated data type declarations
271          failIfErrsM            -- If the addInsts stuff gave any errors, don't
272                                 -- try the deriving stuff, becuase that may give
273                                 -- more errors still
274        ; (deriv_inst_info, deriv_binds, deriv_dus) 
275               <- tcDeriving tycl_decls inst_decls deriv_decls
276        ; gbl_env <- addInsts deriv_inst_info getGblEnv
277        ; return ( addTcgDUs gbl_env deriv_dus,
278                   generic_inst_info ++ deriv_inst_info ++ local_info,
279                   aux_binds `plusHsValBinds` deriv_binds)
280     }}}
281   where
282     -- Make sure that toplevel type instance are not for associated types.
283     -- !!!TODO: Need to perform this check for the TyThing of type functions,
284     --          too.
285     tcIdxTyInstDeclTL ldecl@(L loc decl) =
286       do { tything <- tcFamInstDecl ldecl
287          ; setSrcSpan loc $
288              when (isAssocFamily tything) $
289                addErr $ assocInClassErr (tcdName decl)
290          ; return tything
291          }
292     isAssocFamily (ATyCon tycon) =
293       case tyConFamInst_maybe tycon of
294         Nothing       -> panic "isAssocFamily: no family?!?"
295         Just (fam, _) -> isTyConAssoc fam
296     isAssocFamily _ = panic "isAssocFamily: no tycon?!?"
297
298 assocInClassErr :: Name -> SDoc
299 assocInClassErr name =
300   ptext (sLit "Associated type") <+> quotes (ppr name) <+>
301   ptext (sLit "must be inside a class instance")
302
303 addInsts :: [InstInfo Name] -> TcM a -> TcM a
304 addInsts infos thing_inside
305   = tcExtendLocalInstEnv (map iSpec infos) thing_inside
306
307 addFamInsts :: [TyThing] -> TcM a -> TcM a
308 addFamInsts tycons thing_inside
309   = tcExtendLocalFamInstEnv (map mkLocalFamInstTyThing tycons) thing_inside
310   where
311     mkLocalFamInstTyThing (ATyCon tycon) = mkLocalFamInst tycon
312     mkLocalFamInstTyThing tything        = pprPanic "TcInstDcls.addFamInsts"
313                                                     (ppr tything)
314 \end{code}
315
316 \begin{code}
317 tcLocalInstDecl1 :: LInstDecl Name
318                  -> TcM (InstInfo Name, [TyThing])
319         -- A source-file instance declaration
320         -- Type-check all the stuff before the "where"
321         --
322         -- We check for respectable instance type, and context
323 tcLocalInstDecl1 (L loc (InstDecl poly_ty binds uprags ats))
324   = setSrcSpan loc                      $
325     addErrCtxt (instDeclCtxt1 poly_ty)  $
326
327     do  { is_boot <- tcIsHsBoot
328         ; checkTc (not is_boot || (isEmptyLHsBinds binds && null uprags))
329                   badBootDeclErr
330
331         ; (tyvars, theta, tau) <- tcHsInstHead poly_ty
332
333         -- Now, check the validity of the instance.
334         ; (clas, inst_tys) <- checkValidInstHead tau
335         ; checkValidInstance tyvars theta clas inst_tys
336
337         -- Next, process any associated types.
338         ; idx_tycons <- recoverM (return []) $
339                      do { idx_tycons <- checkNoErrs $ mapAndRecoverM tcFamInstDecl ats
340                         ; checkValidAndMissingATs clas (tyvars, inst_tys)
341                                                   (zip ats idx_tycons)
342                         ; return idx_tycons }
343
344         -- Finally, construct the Core representation of the instance.
345         -- (This no longer includes the associated types.)
346         ; dfun_name <- newDFunName clas inst_tys (getLoc poly_ty)
347                 -- Dfun location is that of instance *header*
348         ; overlap_flag <- getOverlapFlag
349         ; let (eq_theta,dict_theta) = partition isEqPred theta
350               theta'         = eq_theta ++ dict_theta
351               dfun           = mkDictFunId dfun_name tyvars theta' clas inst_tys
352               ispec          = mkLocalInstance dfun overlap_flag
353
354         ; return (InstInfo { iSpec  = ispec,
355                              iBinds = VanillaInst binds uprags False },
356                   idx_tycons)
357         }
358   where
359     -- We pass in the source form and the type checked form of the ATs.  We
360     -- really need the source form only to be able to produce more informative
361     -- error messages.
362     checkValidAndMissingATs :: Class
363                             -> ([TyVar], [TcType])     -- instance types
364                             -> [(LTyClDecl Name,       -- source form of AT
365                                  TyThing)]             -- Core form of AT
366                             -> TcM ()
367     checkValidAndMissingATs clas inst_tys ats
368       = do { -- Issue a warning for each class AT that is not defined in this
369              -- instance.
370            ; let class_ats   = map tyConName (classATs clas)
371                  defined_ats = listToNameSet . map (tcdName.unLoc.fst)  $ ats
372                  omitted     = filterOut (`elemNameSet` defined_ats) class_ats
373            ; warn <- doptM Opt_WarnMissingMethods
374            ; mapM_ (warnTc warn . omittedATWarn) omitted
375
376              -- Ensure that all AT indexes that correspond to class parameters
377              -- coincide with the types in the instance head.  All remaining
378              -- AT arguments must be variables.  Also raise an error for any
379              -- type instances that are not associated with this class.
380            ; mapM_ (checkIndexes clas inst_tys) ats
381            }
382
383     checkIndexes clas inst_tys (hsAT, ATyCon tycon)
384 -- !!!TODO: check that this does the Right Thing for indexed synonyms, too!
385       = checkIndexes' clas inst_tys hsAT
386                       (tyConTyVars tycon,
387                        snd . fromJust . tyConFamInst_maybe $ tycon)
388     checkIndexes _ _ _ = panic "checkIndexes"
389
390     checkIndexes' clas (instTvs, instTys) hsAT (atTvs, atTys)
391       = let atName = tcdName . unLoc $ hsAT
392         in
393         setSrcSpan (getLoc hsAT)       $
394         addErrCtxt (atInstCtxt atName) $
395         case find ((atName ==) . tyConName) (classATs clas) of
396           Nothing     -> addErrTc $ badATErr clas atName  -- not in this class
397           Just atycon ->
398             case assocTyConArgPoss_maybe atycon of
399               Nothing   -> panic "checkIndexes': AT has no args poss?!?"
400               Just poss ->
401
402                 -- The following is tricky!  We need to deal with three
403                 -- complications: (1) The AT possibly only uses a subset of
404                 -- the class parameters as indexes and those it uses may be in
405                 -- a different order; (2) the AT may have extra arguments,
406                 -- which must be type variables; and (3) variables in AT and
407                 -- instance head will be different `Name's even if their
408                 -- source lexemes are identical.
409                 --
410                 -- e.g.    class C a b c where 
411                 --           data D b a :: * -> *           -- NB (1) b a, omits c
412                 --         instance C [x] Bool Char where 
413                 --           data D Bool [x] v = MkD x [v]  -- NB (2) v
414                 --                -- NB (3) the x in 'instance C...' have differnt
415                 --                --        Names to x's in 'data D...'
416                 --
417                 -- Re (1), `poss' contains a permutation vector to extract the
418                 -- class parameters in the right order.
419                 --
420                 -- Re (2), we wrap the (permuted) class parameters in a Maybe
421                 -- type and use Nothing for any extra AT arguments.  (First
422                 -- equation of `checkIndex' below.)
423                 --
424                 -- Re (3), we replace any type variable in the AT parameters
425                 -- that has the same source lexeme as some variable in the
426                 -- instance types with the instance type variable sharing its
427                 -- source lexeme.
428                 --
429                 let relevantInstTys = map (instTys !!) poss
430                     instArgs        = map Just relevantInstTys ++
431                                       repeat Nothing  -- extra arguments
432                     renaming        = substSameTyVar atTvs instTvs
433                 in
434                 zipWithM_ checkIndex (substTys renaming atTys) instArgs
435
436     checkIndex ty Nothing
437       | isTyVarTy ty         = return ()
438       | otherwise            = addErrTc $ mustBeVarArgErr ty
439     checkIndex ty (Just instTy)
440       | ty `tcEqType` instTy = return ()
441       | otherwise            = addErrTc $ wrongATArgErr ty instTy
442
443     listToNameSet = addListToNameSet emptyNameSet
444
445     substSameTyVar []       _            = emptyTvSubst
446     substSameTyVar (tv:tvs) replacingTvs =
447       let replacement = case find (tv `sameLexeme`) replacingTvs of
448                         Nothing  -> mkTyVarTy tv
449                         Just rtv -> mkTyVarTy rtv
450           --
451           tv1 `sameLexeme` tv2 =
452             nameOccName (tyVarName tv1) == nameOccName (tyVarName tv2)
453       in
454       extendTvSubst (substSameTyVar tvs replacingTvs) tv replacement
455 \end{code}
456
457
458 %************************************************************************
459 %*                                                                      *
460       Type-checking instance declarations, pass 2
461 %*                                                                      *
462 %************************************************************************
463
464 \begin{code}
465 tcInstDecls2 :: [LTyClDecl Name] -> [InstInfo Name]
466              -> TcM (LHsBinds Id, TcLclEnv)
467 -- (a) From each class declaration,
468 --      generate any default-method bindings
469 -- (b) From each instance decl
470 --      generate the dfun binding
471
472 tcInstDecls2 tycl_decls inst_decls
473   = do  { -- (a) Default methods from class decls
474           let class_decls = filter (isClassDecl . unLoc) tycl_decls
475         ; (dm_ids_s, dm_binds_s) <- mapAndUnzipM tcClassDecl2 class_decls
476                                     
477         ; tcExtendIdEnv (concat dm_ids_s) $ do 
478
479           -- (b) instance declarations
480         { inst_binds_s <- mapM tcInstDecl2 inst_decls
481
482           -- Done
483         ; let binds = unionManyBags dm_binds_s `unionBags`
484                       unionManyBags inst_binds_s
485         ; tcl_env <- getLclEnv -- Default method Ids in here
486         ; return (binds, tcl_env) } }
487
488 tcInstDecl2 :: InstInfo Name -> TcM (LHsBinds Id)
489 tcInstDecl2 (InstInfo { iSpec = ispec, iBinds = ibinds })
490   = recoverM (return emptyLHsBinds)             $
491     setSrcSpan loc                              $
492     addErrCtxt (instDeclCtxt2 (idType dfun_id)) $ 
493     tc_inst_decl2 dfun_id ibinds
494  where
495     dfun_id = instanceDFunId ispec
496     loc     = getSrcSpan dfun_id
497 \end{code}
498
499
500 \begin{code}
501 tc_inst_decl2 :: Id -> InstBindings Name -> TcM (LHsBinds Id)
502 -- Returns a binding for the dfun
503
504 ------------------------
505 -- Derived newtype instances; surprisingly tricky!
506 --
507 --      class Show a => Foo a b where ...
508 --      newtype N a = MkN (Tree [a]) deriving( Foo Int )
509 --
510 -- The newtype gives an FC axiom looking like
511 --      axiom CoN a ::  N a ~ Tree [a]
512 --   (see Note [Newtype coercions] in TyCon for this unusual form of axiom)
513 --
514 -- So all need is to generate a binding looking like:
515 --      dfunFooT :: forall a. (Foo Int (Tree [a], Show (N a)) => Foo Int (N a)
516 --      dfunFooT = /\a. \(ds:Show (N a)) (df:Foo (Tree [a])).
517 --                case df `cast` (Foo Int (sym (CoN a))) of
518 --                   Foo _ op1 .. opn -> Foo ds op1 .. opn
519 --
520 -- If there are no superclasses, matters are simpler, because we don't need the case
521 -- see Note [Newtype deriving superclasses] in TcDeriv.lhs
522
523 tc_inst_decl2 dfun_id (NewTypeDerived coi)
524   = do  { let rigid_info = InstSkol
525               origin     = SigOrigin rigid_info
526               inst_ty    = idType dfun_id
527               inst_tvs   = fst (tcSplitForAllTys inst_ty)
528         ; (inst_tvs', theta, inst_head_ty) <- tcSkolSigType rigid_info inst_ty
529                 -- inst_head_ty is a PredType
530
531         ; let (cls, cls_inst_tys) = tcSplitDFunHead inst_head_ty
532               (class_tyvars, sc_theta, _, _) = classBigSig cls
533               cls_tycon = classTyCon cls
534               sc_theta' = substTheta (zipOpenTvSubst class_tyvars cls_inst_tys) sc_theta
535               Just (initial_cls_inst_tys, last_ty) = snocView cls_inst_tys
536
537               (rep_ty, wrapper) 
538                  = case coi of
539                      IdCo   -> (last_ty, idHsWrapper)
540                      ACo co -> (snd (coercionKind co'), WpCast (mk_full_coercion co'))
541                             where
542                                co' = substTyWith inst_tvs (mkTyVarTys inst_tvs') co
543                                 -- NB: the free variable of coi are bound by the
544                                 -- universally quantified variables of the dfun_id
545                                 -- This is weird, and maybe we should make NewTypeDerived
546                                 -- carry a type-variable list too; but it works fine
547
548                  -----------------------
549                  --        mk_full_coercion
550                  -- The inst_head looks like (C s1 .. sm (T a1 .. ak))
551                  -- But we want the coercion (C s1 .. sm (sym (CoT a1 .. ak)))
552                  --        with kind (C s1 .. sm (T a1 .. ak)  ~  C s1 .. sm <rep_ty>)
553                  --        where rep_ty is the (eta-reduced) type rep of T
554                  -- So we just replace T with CoT, and insert a 'sym'
555                  -- NB: we know that k will be >= arity of CoT, because the latter fully eta-reduced
556
557               mk_full_coercion co = mkTyConApp cls_tycon 
558                                          (initial_cls_inst_tys ++ [mkSymCoercion co])
559                  -- Full coercion : (Foo Int (Tree [a]) ~ Foo Int (N a)
560
561               rep_pred = mkClassPred cls (initial_cls_inst_tys ++ [rep_ty])
562                  -- In our example, rep_pred is (Foo Int (Tree [a]))
563
564         ; sc_loc     <- getInstLoc InstScOrigin
565         ; sc_dicts   <- newDictBndrs sc_loc sc_theta'
566         ; inst_loc   <- getInstLoc origin
567         ; dfun_dicts <- newDictBndrs inst_loc theta
568         ; rep_dict   <- newDictBndr inst_loc rep_pred
569         ; this_dict  <- newDictBndr inst_loc (mkClassPred cls cls_inst_tys)
570
571         -- Figure out bindings for the superclass context from dfun_dicts
572         -- Don't include this_dict in the 'givens', else
573         -- sc_dicts get bound by just selecting from this_dict!!
574         ; sc_binds <- addErrCtxt superClassCtxt $
575                       tcSimplifySuperClasses inst_loc this_dict dfun_dicts 
576                                              (rep_dict:sc_dicts)
577
578         -- It's possible that the superclass stuff might unified something
579         -- in the envt with one of the clas_tyvars
580         ; checkSigTyVars inst_tvs'
581
582         ; let coerced_rep_dict = wrapId wrapper (instToId rep_dict)
583
584         ; body <- make_body cls_tycon cls_inst_tys sc_dicts coerced_rep_dict
585         ; let dict_bind = mkVarBind (instToId this_dict) (noLoc body)
586
587         ; return (unitBag $ noLoc $
588                   AbsBinds inst_tvs' (map instToVar dfun_dicts)
589                             [(inst_tvs', dfun_id, instToId this_dict, [])]
590                             (dict_bind `consBag` sc_binds)) }
591   where
592       -----------------------
593       --     (make_body C tys scs coreced_rep_dict)
594       --                returns
595       --     (case coerced_rep_dict of { C _ ops -> C scs ops })
596       -- But if there are no superclasses, it returns just coerced_rep_dict
597       -- See Note [Newtype deriving superclasses] in TcDeriv.lhs
598
599     make_body cls_tycon cls_inst_tys sc_dicts coerced_rep_dict
600         | null sc_dicts         -- Case (a)
601         = return coerced_rep_dict
602         | otherwise             -- Case (b)
603         = do { op_ids            <- newSysLocalIds (fsLit "op") op_tys
604              ; dummy_sc_dict_ids <- newSysLocalIds (fsLit "sc") (map idType sc_dict_ids)
605              ; let the_pat = ConPatOut { pat_con = noLoc cls_data_con, pat_tvs = [],
606                                          pat_dicts = dummy_sc_dict_ids,
607                                          pat_binds = emptyLHsBinds,
608                                          pat_args = PrefixCon (map nlVarPat op_ids),
609                                          pat_ty = pat_ty}
610                    the_match = mkSimpleMatch [noLoc the_pat] the_rhs
611                    the_rhs = mkHsConApp cls_data_con cls_inst_tys $
612                              map HsVar (sc_dict_ids ++ op_ids)
613
614                 -- Warning: this HsCase scrutinises a value with a PredTy, which is
615                 --          never otherwise seen in Haskell source code. It'd be
616                 --          nicer to generate Core directly!
617              ; return (HsCase (noLoc coerced_rep_dict) $
618                        MatchGroup [the_match] (mkFunTy pat_ty pat_ty)) }
619         where
620           sc_dict_ids  = map instToId sc_dicts
621           pat_ty       = mkTyConApp cls_tycon cls_inst_tys
622           cls_data_con = head (tyConDataCons cls_tycon)
623           cls_arg_tys  = dataConInstArgTys cls_data_con cls_inst_tys
624           op_tys       = dropList sc_dict_ids cls_arg_tys
625
626 ------------------------
627 -- Ordinary instances
628
629 tc_inst_decl2 dfun_id (VanillaInst monobinds uprags standalone_deriv)
630   = do { let rigid_info = InstSkol
631              inst_ty    = idType dfun_id
632              loc        = getSrcSpan dfun_id
633
634         -- Instantiate the instance decl with skolem constants
635        ; (inst_tyvars', dfun_theta', inst_head') <- tcSkolSigType rigid_info inst_ty
636                 -- These inst_tyvars' scope over the 'where' part
637                 -- Those tyvars are inside the dfun_id's type, which is a bit
638                 -- bizarre, but OK so long as you realise it!
639        ; let
640             (clas, inst_tys') = tcSplitDFunHead inst_head'
641             (class_tyvars, sc_theta, sc_sels, op_items) = classBigSig clas
642
643              -- Instantiate the super-class context with inst_tys
644             sc_theta' = substTheta (zipOpenTvSubst class_tyvars inst_tys') sc_theta
645             origin    = SigOrigin rigid_info
646
647          -- Create dictionary Ids from the specified instance contexts.
648        ; inst_loc   <- getInstLoc origin
649        ; dfun_dicts <- newDictBndrs inst_loc dfun_theta'        -- Includes equalities
650        ; this_dict  <- newDictBndr inst_loc (mkClassPred clas inst_tys')
651                 -- Default-method Ids may be mentioned in synthesised RHSs,
652                 -- but they'll already be in the environment.
653
654        
655         -- Cook up a binding for "this = df d1 .. dn",
656         -- to use in each method binding
657         -- Need to clone the dict in case it is floated out, and
658         -- then clashes with its friends
659        ; cloned_this <- cloneDict this_dict
660        ; let cloned_this_bind = mkVarBind (instToId cloned_this) $ 
661                                 L loc $ wrapId app_wrapper dfun_id
662              app_wrapper = mkWpApps dfun_lam_vars <.> mkWpTyApps (mkTyVarTys inst_tyvars')
663              dfun_lam_vars = map instToVar dfun_dicts   -- Includes equalities
664              nested_this_pair 
665                 | null inst_tyvars' && null dfun_theta' = (this_dict, emptyBag)
666                 | otherwise = (cloned_this, unitBag cloned_this_bind)
667
668        -- Deal with 'SPECIALISE instance' pragmas
669        -- See Note [SPECIALISE instance pragmas]
670        ; let spec_inst_sigs = filter isSpecInstLSig uprags
671              -- The filter removes the pragmas for methods
672        ; spec_inst_prags <- mapM (wrapLocM (tcSpecInst dfun_id)) spec_inst_sigs
673
674         -- Typecheck the methods
675        ; let prag_fn = mkPragFun uprags 
676              tc_meth = tcInstanceMethod loc standalone_deriv
677                                         clas inst_tyvars'
678                                         dfun_dicts inst_tys'
679                                         nested_this_pair 
680                                         prag_fn spec_inst_prags monobinds
681
682        ; (meth_ids, meth_binds) <- tcExtendTyVarEnv inst_tyvars' $
683                                    mapAndUnzipM tc_meth op_items 
684
685          -- Figure out bindings for the superclass context
686        ; sc_loc   <- getInstLoc InstScOrigin
687        ; sc_dicts <- newDictOccs sc_loc sc_theta'               -- These are wanted
688        ; let tc_sc = tcSuperClass inst_loc inst_tyvars' dfun_dicts nested_this_pair
689        ; (sc_ids, sc_binds) <- mapAndUnzipM tc_sc (sc_sels `zip` sc_dicts)
690
691         -- It's possible that the superclass stuff might unified
692         -- something in the envt with one of the inst_tyvars'
693        ; checkSigTyVars inst_tyvars'
694
695        -- Create the result bindings
696        ; let dict_constr   = classDataCon clas
697              this_dict_id  = instToId this_dict
698              dict_bind     = mkVarBind this_dict_id dict_rhs
699              dict_rhs      = foldl mk_app inst_constr (sc_ids ++ meth_ids)
700              inst_constr   = L loc $ wrapId (mkWpTyApps inst_tys')
701                                             (dataConWrapId dict_constr)
702                      -- We don't produce a binding for the dict_constr; instead we
703                      -- rely on the simplifier to unfold this saturated application
704                      -- We do this rather than generate an HsCon directly, because
705                      -- it means that the special cases (e.g. dictionary with only one
706                      -- member) are dealt with by the common MkId.mkDataConWrapId code rather
707                      -- than needing to be repeated here.
708
709              mk_app :: LHsExpr Id -> Id -> LHsExpr Id
710              mk_app fun arg_id = L loc (HsApp fun (L loc (wrapId arg_wrapper arg_id)))
711              arg_wrapper = mkWpApps dfun_lam_vars <.> mkWpTyApps (mkTyVarTys inst_tyvars')
712
713              dfun_id_w_fun = dfun_id 
714                              `setIdUnfolding` mkDFunUnfolding dict_constr (sc_ids ++ meth_ids)
715                              `setInlinePragma` dfunInlinePragma
716
717              main_bind = noLoc $ AbsBinds
718                                  inst_tyvars'
719                                  dfun_lam_vars
720                                  [(inst_tyvars', dfun_id_w_fun, this_dict_id, spec_inst_prags)]
721                                  (unitBag dict_bind)
722
723        ; showLIE (text "instance")
724        ; return (unitBag main_bind    `unionBags` 
725                  listToBag meth_binds `unionBags` 
726                  listToBag sc_binds) }
727
728
729 ------------------------------
730 tcSuperClass :: InstLoc -> [TyVar] -> [Inst]
731              -> (Inst, LHsBinds Id)
732              -> (Id, Inst) -> TcM (Id, LHsBind Id)
733 -- Build a top level decl like
734 --      sc_op = /\a \d. let this = ... in 
735 --                      let sc = ... in
736 --                      sc
737 -- The "this" part is just-in-case (discarded if not used)
738 -- See Note [Recursive superclasses]
739 tcSuperClass inst_loc tyvars dicts (this_dict, this_bind)
740              (sc_sel, sc_dict)
741   = addErrCtxt superClassCtxt $
742     do { sc_binds <- tcSimplifySuperClasses inst_loc 
743                                 this_dict dicts [sc_dict]
744          -- Don't include this_dict in the 'givens', else
745          -- sc_dicts get bound by just selecting  from this_dict!!
746
747        ; uniq <- newUnique
748        ; let sc_op_ty = mkSigmaTy tyvars (map dictPred dicts) 
749                                   (mkPredTy (dictPred sc_dict))
750              sc_op_name = mkDerivedInternalName mkClassOpAuxOcc uniq
751                                                 (getName sc_sel)
752              sc_op_id   = mkLocalId sc_op_name sc_op_ty
753              sc_id      = instToVar sc_dict
754              sc_op_bind = AbsBinds tyvars 
755                              (map instToVar dicts) 
756                              [(tyvars, sc_op_id, sc_id, [])]
757                              (this_bind `unionBags` sc_binds)
758
759        ; return (sc_op_id, noLoc sc_op_bind) }
760 \end{code}
761
762 Note [Recursive superclasses]
763 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
764 See Trac #1470 for why we would *like* to add "this_dict" to the 
765 available instances here.  But we can't do so because then the superclases
766 get satisfied by selection from this_dict, and that leads to an immediate
767 loop.  What we need is to add this_dict to Avails without adding its 
768 superclasses, and we currently have no way to do that.
769
770 Note [SPECIALISE instance pragmas]
771 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
772 Consider
773
774    instance (Ix a, Ix b) => Ix (a,b) where
775      {-# SPECIALISE instance Ix (Int,Int) #-}
776      range (x,y) = ...
777
778 We do *not* want to make a specialised version of the dictionary
779 function.  Rather, we want specialised versions of each method.
780 Thus we should generate something like this:
781
782   $dfIx :: (Ix a, Ix x) => Ix (a,b)
783   {- DFUN [$crange, ...] -}
784   $dfIx da db = Ix ($crange da db) (...other methods...)
785
786   $dfIxPair :: (Ix a, Ix x) => Ix (a,b)
787   {- DFUN [$crangePair, ...] -}
788   $dfIxPair = Ix ($crangePair da db) (...other methods...)
789
790   $crange :: (Ix a, Ix b) -> ((a,b),(a,b)) -> [(a,b)]
791   {-# SPECIALISE $crange :: ((Int,Int),(Int,Int)) -> [(Int,Int)] #-}
792   $crange da db = <blah>
793
794   {-# RULE  range ($dfIx da db) = $crange da db #-}
795
796 Note that  
797
798   * The RULE is unaffected by the specialisation.  We don't want to
799     specialise $dfIx, because then it would need a specialised RULE
800     which is a pain.  The single RULE works fine at all specialisations.
801     See Note [How instance declarations are translated] above
802
803   * Instead, we want to specialise the *method*, $crange
804
805 In practice, rather than faking up a SPECIALISE pragama for each
806 method (which is painful, since we'd have to figure out its
807 specialised type), we call tcSpecPrag *as if* were going to specialise
808 $dfIx -- you can see that in the call to tcSpecInst.  That generates a
809 SpecPrag which, as it turns out, can be used unchanged for each method.
810 The "it turns out" bit is delicate, but it works fine!
811
812 \begin{code}
813 tcSpecInst :: Id -> Sig Name -> TcM SpecPrag
814 tcSpecInst dfun_id prag@(SpecInstSig hs_ty) 
815   = addErrCtxt (spec_ctxt prag) $
816     do  { let name = idName dfun_id
817         ; (tyvars, theta, tau) <- tcHsInstHead hs_ty    
818         ; let spec_ty = mkSigmaTy tyvars theta tau
819         ; co_fn <- tcSubExp (SpecPragOrigin name) (idType dfun_id) spec_ty
820         ; return (SpecPrag co_fn defaultInlinePragma) }
821   where
822     spec_ctxt prag = hang (ptext (sLit "In the SPECIALISE pragma")) 2 (ppr prag)
823
824 tcSpecInst _  _ = panic "tcSpecInst"
825 \end{code}
826
827 %************************************************************************
828 %*                                                                      *
829       Type-checking an instance method
830 %*                                                                      *
831 %************************************************************************
832
833 tcInstanceMethod
834 - Make the method bindings, as a [(NonRec, HsBinds)], one per method
835 - Remembering to use fresh Name (the instance method Name) as the binder
836 - Bring the instance method Ids into scope, for the benefit of tcInstSig
837 - Use sig_fn mapping instance method Name -> instance tyvars
838 - Ditto prag_fn
839 - Use tcValBinds to do the checking
840
841 \begin{code}
842 tcInstanceMethod :: SrcSpan -> Bool -> Class -> [TcTyVar] -> [Inst]
843                  -> [TcType]
844                  -> (Inst, LHsBinds Id)  -- "This" and its binding
845                  -> TcPragFun            -- Local prags
846                  -> [LSpecPrag]          -- Arising from 'SPECLALISE instance'
847                  -> LHsBinds Name 
848                  -> (Id, DefMeth)
849                  -> TcM (Id, LHsBind Id)
850         -- The returned inst_meth_ids all have types starting
851         --      forall tvs. theta => ...
852
853 tcInstanceMethod loc standalone_deriv clas tyvars dfun_dicts inst_tys 
854                  (this_dict, this_dict_bind)
855                  prag_fn spec_inst_prags binds_in (sel_id, dm_info)
856   = do  { uniq <- newUnique
857         ; let meth_name = mkDerivedInternalName mkClassOpAuxOcc uniq sel_name
858         ; local_meth_name <- newLocalName sel_name
859           -- Base the local_meth_name on the selector name, becuase
860           -- type errors from tcInstanceMethodBody come from here
861
862         ; let local_meth_ty = instantiateMethod clas sel_id inst_tys
863               meth_ty = mkSigmaTy tyvars (map dictPred dfun_dicts) local_meth_ty
864               meth_id       = mkLocalId meth_name meth_ty
865               local_meth_id = mkLocalId local_meth_name local_meth_ty
866
867             --------------
868               tc_body rn_bind 
869                 = add_meth_ctxt rn_bind $
870                   do { (meth_id1, spec_prags) <- tcPrags NonRecursive False True 
871                                                     meth_id (prag_fn sel_name)
872                      ; tcInstanceMethodBody (instLoc this_dict)
873                                     tyvars dfun_dicts
874                                     ([this_dict], this_dict_bind)
875                                     meth_id1 local_meth_id
876                                     meth_sig_fn 
877                                     (spec_inst_prags ++ spec_prags) 
878                                     rn_bind }
879
880             --------------
881               tc_default :: DefMeth -> TcM (Id, LHsBind Id)
882                 -- The user didn't supply a method binding, so we have to make 
883                 -- up a default binding, in a way depending on the default-method info
884
885               tc_default NoDefMeth          -- No default method at all
886                 = do { warnMissingMethod sel_id
887                      ; return (meth_id, mkVarBind meth_id $ 
888                                         mkLHsWrap lam_wrapper error_rhs) }
889               
890               tc_default GenDefMeth    -- Derivable type classes stuff
891                 = do { meth_bind <- mkGenericDefMethBind clas inst_tys sel_id local_meth_name
892                      ; tc_body meth_bind }
893                   
894               tc_default DefMeth        -- An polymorphic default method
895                 = do {   -- Build the typechecked version directly, 
896                          -- without calling typecheck_method; 
897                          -- see Note [Default methods in instances]
898                          -- Generate   /\as.\ds. let this = df as ds 
899                          --                      in $dm inst_tys this
900                          -- The 'let' is necessary only because HsSyn doesn't allow
901                          -- you to apply a function to a dictionary *expression*.
902                        dm_name <- lookupGlobalOccRn (mkDefMethRdrName sel_name)
903                                         -- Might not be imported, but will be an OrigName
904                      ; dm_id <- tcLookupId dm_name
905                      ; inline_id <- tcLookupId inlineIdName
906                      ; let dm_inline_prag = idInlinePragma dm_id
907                            dm_app = HsWrap (WpApp (instToId this_dict) <.> mkWpTyApps inst_tys) $
908                                     HsVar dm_id 
909                            rhs | isInlinePragma dm_inline_prag  -- See Note [INLINE and default methods]
910                                = HsApp (L loc (HsWrap (WpTyApp local_meth_ty) (HsVar inline_id)))
911                                        (L loc dm_app)
912                                | otherwise = dm_app
913
914                            meth_bind = L loc $ VarBind { var_id = local_meth_id
915                                                        , var_rhs = L loc rhs 
916                                                        , var_inline = False }
917                            meth_id1 = meth_id `setInlinePragma` dm_inline_prag
918                                     -- Copy the inline pragma (if any) from the default
919                                     -- method to this version. Note [INLINE and default methods]
920                                     
921                            bind = AbsBinds { abs_tvs = tyvars, abs_dicts =  dfun_lam_vars
922                                            , abs_exports = [( tyvars, meth_id1
923                                                             , local_meth_id, spec_inst_prags)]
924                                            , abs_binds = this_dict_bind `unionBags` unitBag meth_bind }
925                      -- Default methods in an instance declaration can't have their own 
926                      -- INLINE or SPECIALISE pragmas. It'd be possible to allow them, but
927                      -- currently they are rejected with 
928                      --           "INLINE pragma lacks an accompanying binding"
929
930                      ; return (meth_id1, L loc bind) } 
931
932         ; case findMethodBind sel_name local_meth_name binds_in of
933             Just user_bind -> tc_body user_bind    -- User-supplied method binding
934             Nothing        -> tc_default dm_info   -- None supplied
935         }
936   where
937     sel_name = idName sel_id
938
939     meth_sig_fn _ = Just []     -- The 'Just' says "yes, there's a type sig"
940         -- But there are no scoped type variables from local_method_id
941         -- Only the ones from the instance decl itself, which are already
942         -- in scope.  Example:
943         --      class C a where { op :: forall b. Eq b => ... }
944         --      instance C [c] where { op = <rhs> }
945         -- In <rhs>, 'c' is scope but 'b' is not!
946
947     error_rhs    = L loc $ HsApp error_fun error_msg
948     error_fun    = L loc $ wrapId (WpTyApp meth_tau) nO_METHOD_BINDING_ERROR_ID
949     error_msg    = L loc (HsLit (HsStringPrim (mkFastString error_string)))
950     meth_tau     = funResultTy (applyTys (idType sel_id) inst_tys)
951     error_string = showSDoc (hcat [ppr loc, text "|", ppr sel_id ])
952
953     dfun_lam_vars = map instToVar dfun_dicts
954     lam_wrapper   = mkWpTyLams tyvars <.> mkWpLams dfun_lam_vars
955
956         -- For instance decls that come from standalone deriving clauses
957         -- we want to print out the full source code if there's an error
958         -- because otherwise the user won't see the code at all
959     add_meth_ctxt rn_bind thing 
960       | standalone_deriv = addLandmarkErrCtxt (derivBindCtxt clas inst_tys rn_bind) thing
961       | otherwise        = thing
962
963 wrapId :: HsWrapper -> id -> HsExpr id
964 wrapId wrapper id = mkHsWrap wrapper (HsVar id)
965
966 derivBindCtxt :: Class -> [Type ] -> LHsBind Name -> SDoc
967 derivBindCtxt clas tys bind
968    = vcat [ ptext (sLit "When typechecking a standalone-derived method for")
969             <+> quotes (pprClassPred clas tys) <> colon
970           , nest 2 $ pprSetDepth AllTheWay $ ppr bind ]
971
972 warnMissingMethod :: Id -> TcM ()
973 warnMissingMethod sel_id
974   = do { warn <- doptM Opt_WarnMissingMethods           
975        ; warnTc (warn  -- Warn only if -fwarn-missing-methods
976                  && not (startsWithUnderscore (getOccName sel_id)))
977                                         -- Don't warn about _foo methods
978                 (ptext (sLit "No explicit method nor default method for")
979                  <+> quotes (ppr sel_id)) }
980 \end{code}
981
982 Note [Export helper functions]
983 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
984 We arrange to export the "helper functions" of an instance declaration,
985 so that they are not subject to preInlineUnconditionally, even if their
986 RHS is trivial.  Reason: they are mentioned in the DFunUnfolding of
987 the dict fun as Ids, not as CoreExprs, so we can't substitute a 
988 non-variable for them.
989
990 We could change this by making DFunUnfoldings have CoreExprs, but it
991 seems a bit simpler this way.
992
993 Note [Default methods in instances]
994 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
995 Consider this
996
997    class Baz v x where
998       foo :: x -> x
999       foo y = <blah>
1000
1001    instance Baz Int Int
1002
1003 From the class decl we get
1004
1005    $dmfoo :: forall v x. Baz v x => x -> x
1006    $dmfoo y = <blah>
1007
1008 Notice that the type is ambiguous.  That's fine, though. The instance decl generates
1009
1010    $dBazIntInt = MkBaz fooIntInt
1011    fooIntInt = $dmfoo Int Int $dBazIntInt
1012
1013 BUT this does mean we must generate the dictionary translation of
1014 fooIntInt directly, rather than generating source-code and
1015 type-checking it.  That was the bug in Trac #1061. In any case it's
1016 less work to generate the translated version!
1017
1018 Note [INLINE and default methods]
1019 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1020 We *copy* any INLINE pragma from the default method to the instance.
1021 Example:
1022   class Foo a where
1023     op1, op2 :: Bool -> a -> a
1024
1025     {-# INLINE op1 #-}
1026     op1 b x = op2 (not b) x
1027
1028   instance Foo Int where
1029     op2 b x = <blah>
1030
1031 Then we generate:
1032
1033   {-# INLINE $dmop1 #-}
1034   $dmop1 d b x = op2 d (not b) x
1035
1036   $fFooInt = MkD $cop1 $cop2
1037
1038   {-# INLINE $cop1 #-}
1039   $cop1 = inline $dmop1 $fFooInt
1040
1041   $cop2 = <blah>
1042
1043 Note carefully:
1044   a) We copy $dmop1's inline pragma to $cop1.  Otherwise 
1045      we'll just inline the former in the latter and stop, which 
1046      isn't what the user expected
1047
1048   b) We use the magic 'inline' Id to ensure that $dmop1 really is
1049      inlined in $cop1, even though the latter itself has an INLINE pragma
1050      That is important to allow the mutual recursion between $fooInt and
1051      $cop1 to be broken
1052
1053 This is all regrettably delicate.
1054
1055
1056 %************************************************************************
1057 %*                                                                      *
1058 \subsection{Error messages}
1059 %*                                                                      *
1060 %************************************************************************
1061
1062 \begin{code}
1063 instDeclCtxt1 :: LHsType Name -> SDoc
1064 instDeclCtxt1 hs_inst_ty
1065   = inst_decl_ctxt (case unLoc hs_inst_ty of
1066                         HsForAllTy _ _ _ (L _ (HsPredTy pred)) -> ppr pred
1067                         HsPredTy pred                    -> ppr pred
1068                         _                                -> ppr hs_inst_ty)     -- Don't expect this
1069 instDeclCtxt2 :: Type -> SDoc
1070 instDeclCtxt2 dfun_ty
1071   = inst_decl_ctxt (ppr (mkClassPred cls tys))
1072   where
1073     (_,cls,tys) = tcSplitDFunTy dfun_ty
1074
1075 inst_decl_ctxt :: SDoc -> SDoc
1076 inst_decl_ctxt doc = ptext (sLit "In the instance declaration for") <+> quotes doc
1077
1078 superClassCtxt :: SDoc
1079 superClassCtxt = ptext (sLit "When checking the super-classes of an instance declaration")
1080
1081 atInstCtxt :: Name -> SDoc
1082 atInstCtxt name = ptext (sLit "In the associated type instance for") <+>
1083                   quotes (ppr name)
1084
1085 mustBeVarArgErr :: Type -> SDoc
1086 mustBeVarArgErr ty =
1087   sep [ ptext (sLit "Arguments that do not correspond to a class parameter") <+>
1088         ptext (sLit "must be variables")
1089       , ptext (sLit "Instead of a variable, found") <+> ppr ty
1090       ]
1091
1092 wrongATArgErr :: Type -> Type -> SDoc
1093 wrongATArgErr ty instTy =
1094   sep [ ptext (sLit "Type indexes must match class instance head")
1095       , ptext (sLit "Found") <+> quotes (ppr ty)
1096         <+> ptext (sLit "but expected") <+> quotes (ppr instTy)
1097       ]
1098 \end{code}