[project @ 2003-10-09 11:58:39 by simonpj]
[ghc-hetmet.git] / ghc / compiler / typecheck / TcInstDcls.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[TcInstDecls]{Typechecking instance declarations}
5
6 \begin{code}
7 module TcInstDcls ( tcInstDecls1, tcInstDecls2 ) where
8
9 #include "HsVersions.h"
10
11 import HsSyn            ( InstDecl(..), HsType(..),
12                           MonoBinds(..), HsExpr(..),  HsLit(..), Sig(..), 
13                           andMonoBindList, collectMonoBinders, 
14                           isClassDecl 
15                         )
16 import RnHsSyn          ( RenamedHsBinds, RenamedInstDecl, RenamedTyClDecl )
17 import TcHsSyn          ( TcMonoBinds, mkHsConApp )
18 import TcBinds          ( tcSpecSigs )
19 import TcClassDcl       ( tcMethodBind, mkMethodBind, badMethodErr, 
20                           tcClassDecl2, getGenericInstances )
21 import TcRnMonad       
22 import TcMType          ( tcInstType, checkValidTheta, checkValidInstHead, instTypeErr, 
23                           checkAmbiguity, SourceTyCtxt(..) )
24 import TcType           ( mkClassPred, tcSplitForAllTys, tyVarsOfType,
25                           tcSplitSigmaTy, getClassPredTys, tcSplitPredTy_maybe, mkTyVarTys,
26                           TyVarDetails(..), tcSplitDFunTy
27                         )
28 import Inst             ( InstOrigin(..), tcInstClassOp, newDicts, instToId, 
29                           showLIE, tcExtendLocalInstEnv )
30 import TcDeriv          ( tcDeriving )
31 import TcEnv            ( tcExtendGlobalValEnv, tcExtendTyVarEnv2,
32                           InstInfo(..), InstBindings(..), 
33                           newDFunName, tcExtendLocalValEnv
34                         )
35 import PprType          ( pprClassPred )
36 import TcHsType         ( kcHsSigType, tcHsKindedType )
37 import TcUnify          ( checkSigTyVars )
38 import TcSimplify       ( tcSimplifyCheck, tcSimplifyTop )
39 import Subst            ( mkTyVarSubst, substTheta, substTy )
40 import DataCon          ( classDataCon )
41 import Class            ( classBigSig )
42 import Var              ( idName, idType )
43 import NameSet          
44 import MkId             ( mkDictFunId, rUNTIME_ERROR_ID )
45 import FunDeps          ( checkInstFDs )
46 import Name             ( getSrcLoc )
47 import NameSet          ( unitNameSet, emptyNameSet, nameSetToList )
48 import UnicodeUtil      ( stringToUtf8 )
49 import Maybe            ( catMaybes )
50 import ListSetOps       ( minusList )
51 import Outputable
52 import FastString
53 \end{code}
54
55 Typechecking instance declarations is done in two passes. The first
56 pass, made by @tcInstDecls1@, collects information to be used in the
57 second pass.
58
59 This pre-processed info includes the as-yet-unprocessed bindings
60 inside the instance declaration.  These are type-checked in the second
61 pass, when the class-instance envs and GVE contain all the info from
62 all the instance and value decls.  Indeed that's the reason we need
63 two passes over the instance decls.
64
65
66 Here is the overall algorithm.
67 Assume that we have an instance declaration
68
69     instance c => k (t tvs) where b
70
71 \begin{enumerate}
72 \item
73 $LIE_c$ is the LIE for the context of class $c$
74 \item
75 $betas_bar$ is the free variables in the class method type, excluding the
76    class variable
77 \item
78 $LIE_cop$ is the LIE constraining a particular class method
79 \item
80 $tau_cop$ is the tau type of a class method
81 \item
82 $LIE_i$ is the LIE for the context of instance $i$
83 \item
84 $X$ is the instance constructor tycon
85 \item
86 $gammas_bar$ is the set of type variables of the instance
87 \item
88 $LIE_iop$ is the LIE for a particular class method instance
89 \item
90 $tau_iop$ is the tau type for this instance of a class method
91 \item
92 $alpha$ is the class variable
93 \item
94 $LIE_cop' = LIE_cop [X gammas_bar / alpha, fresh betas_bar]$
95 \item
96 $tau_cop' = tau_cop [X gammas_bar / alpha, fresh betas_bar]$
97 \end{enumerate}
98
99 ToDo: Update the list above with names actually in the code.
100
101 \begin{enumerate}
102 \item
103 First, make the LIEs for the class and instance contexts, which means
104 instantiate $thetaC [X inst_tyvars / alpha ]$, yielding LIElistC' and LIEC',
105 and make LIElistI and LIEI.
106 \item
107 Then process each method in turn.
108 \item
109 order the instance methods according to the ordering of the class methods
110 \item
111 express LIEC' in terms of LIEI, yielding $dbinds_super$ or an error
112 \item
113 Create final dictionary function from bindings generated already
114 \begin{pseudocode}
115 df = lambda inst_tyvars
116        lambda LIEI
117          let Bop1
118              Bop2
119              ...
120              Bopn
121          and dbinds_super
122               in <op1,op2,...,opn,sd1,...,sdm>
123 \end{pseudocode}
124 Here, Bop1 \ldots Bopn bind the methods op1 \ldots opn,
125 and $dbinds_super$ bind the superclass dictionaries sd1 \ldots sdm.
126 \end{enumerate}
127
128
129 %************************************************************************
130 %*                                                                      *
131 \subsection{Extracting instance decls}
132 %*                                                                      *
133 %************************************************************************
134
135 Gather up the instance declarations from their various sources
136
137 \begin{code}
138 tcInstDecls1    -- Deal with both source-code and imported instance decls
139    :: [RenamedTyClDecl]         -- For deriving stuff
140    -> [RenamedInstDecl]         -- Source code instance decls
141    -> TcM (TcGblEnv,            -- The full inst env
142            [InstInfo],          -- Source-code instance decls to process; 
143                                 -- contains all dfuns for this module
144            RenamedHsBinds)      -- Supporting bindings for derived instances
145
146 tcInstDecls1 tycl_decls inst_decls
147   = checkNoErrs $
148         -- Stop if addInstInfos etc discovers any errors
149         -- (they recover, so that we get more than one error each round)
150
151         -- (1) Do the ordinary instance declarations
152     mappM tcLocalInstDecl1 inst_decls    `thenM` \ local_inst_infos ->
153
154     let
155         local_inst_info = catMaybes local_inst_infos
156         clas_decls      = filter isClassDecl tycl_decls
157     in
158         -- (2) Instances from generic class declarations
159     getGenericInstances clas_decls              `thenM` \ generic_inst_info -> 
160
161         -- Next, construct the instance environment so far, consisting of
162         --      a) imported instance decls (from this module)
163         --      b) local instance decls
164         --      c) generic instances
165     addInsts local_inst_info    $
166     addInsts generic_inst_info  $
167
168         -- (3) Compute instances from "deriving" clauses; 
169         -- This stuff computes a context for the derived instance decl, so it
170         -- needs to know about all the instances possible; hence inst_env4
171     tcDeriving tycl_decls       `thenM` \ (deriv_inst_info, deriv_binds) ->
172     addInsts deriv_inst_info    $
173
174     getGblEnv                   `thenM` \ gbl_env ->
175     returnM (gbl_env, 
176              generic_inst_info ++ deriv_inst_info ++ local_inst_info,
177              deriv_binds)
178
179 addInsts :: [InstInfo] -> TcM a -> TcM a
180 addInsts infos thing_inside
181   = tcExtendLocalInstEnv (map iDFunId infos) thing_inside
182 \end{code} 
183
184 \begin{code}
185 tcLocalInstDecl1 :: RenamedInstDecl 
186                  -> TcM (Maybe InstInfo)        -- Nothing if there was an error
187         -- A source-file instance declaration
188         -- Type-check all the stuff before the "where"
189         --
190         -- We check for respectable instance type, and context
191         -- but only do this for non-imported instance decls.
192         -- Imported ones should have been checked already, and may indeed
193         -- contain something illegal in normal Haskell, notably
194         --      instance CCallable [Char] 
195 tcLocalInstDecl1 decl@(InstDecl poly_ty binds uprags src_loc)
196   =     -- Prime error recovery, set source location
197     recoverM (returnM Nothing)          $
198     addSrcLoc src_loc                   $
199     addErrCtxt (instDeclCtxt1 poly_ty)  $
200
201         -- Typecheck the instance type itself.  We can't use 
202         -- tcHsSigType, because it's not a valid user type.
203     kcHsSigType poly_ty                 `thenM` \ kinded_ty ->
204     tcHsKindedType kinded_ty            `thenM` \ poly_ty' ->
205     let
206         (tyvars, theta, tau) = tcSplitSigmaTy poly_ty'
207     in
208     checkValidTheta InstThetaCtxt theta                 `thenM_`
209     checkAmbiguity tyvars theta (tyVarsOfType tau)      `thenM_`
210     checkValidInstHead tau                              `thenM` \ (clas,inst_tys) ->
211     checkTc (checkInstFDs theta clas inst_tys)
212             (instTypeErr (pprClassPred clas inst_tys) msg)      `thenM_`
213     newDFunName clas inst_tys src_loc                           `thenM` \ dfun_name ->
214     returnM (Just (InstInfo { iDFunId = mkDictFunId dfun_name tyvars theta clas inst_tys,
215                               iBinds = VanillaInst binds uprags }))
216   where
217     msg  = parens (ptext SLIT("the instance types do not agree with the functional dependencies of the class"))
218 \end{code}
219
220
221 %************************************************************************
222 %*                                                                      *
223 \subsection{Type-checking instance declarations, pass 2}
224 %*                                                                      *
225 %************************************************************************
226
227 \begin{code}
228 tcInstDecls2 :: [RenamedTyClDecl] -> [InstInfo] 
229              -> TcM (TcLclEnv, TcMonoBinds)
230 -- (a) From each class declaration, 
231 --      generate any default-method bindings
232 -- (b) From each instance decl
233 --      generate the dfun binding
234
235 tcInstDecls2 tycl_decls inst_decls
236   = do  {       -- (a) Default methods from class decls
237           (dm_binds_s, dm_ids_s) <- mapAndUnzipM tcClassDecl2 $
238                                     filter isClassDecl tycl_decls
239         ; tcExtendLocalValEnv (concat dm_ids_s)         $ do 
240     
241                 -- (b) instance declarations
242         ; inst_binds_s <- mappM tcInstDecl2 inst_decls
243
244                 -- Done
245         ; tcl_env <- getLclEnv
246         ; returnM (tcl_env, andMonoBindList dm_binds_s  `AndMonoBinds`
247                             andMonoBindList inst_binds_s) }
248 \end{code}
249
250 ======= New documentation starts here (Sept 92)  ==============
251
252 The main purpose of @tcInstDecl2@ is to return a @HsBinds@ which defines
253 the dictionary function for this instance declaration.  For example
254 \begin{verbatim}
255         instance Foo a => Foo [a] where
256                 op1 x = ...
257                 op2 y = ...
258 \end{verbatim}
259 might generate something like
260 \begin{verbatim}
261         dfun.Foo.List dFoo_a = let op1 x = ...
262                                    op2 y = ...
263                                in
264                                    Dict [op1, op2]
265 \end{verbatim}
266
267 HOWEVER, if the instance decl has no context, then it returns a
268 bigger @HsBinds@ with declarations for each method.  For example
269 \begin{verbatim}
270         instance Foo [a] where
271                 op1 x = ...
272                 op2 y = ...
273 \end{verbatim}
274 might produce
275 \begin{verbatim}
276         dfun.Foo.List a = Dict [Foo.op1.List a, Foo.op2.List a]
277         const.Foo.op1.List a x = ...
278         const.Foo.op2.List a y = ...
279 \end{verbatim}
280 This group may be mutually recursive, because (for example) there may
281 be no method supplied for op2 in which case we'll get
282 \begin{verbatim}
283         const.Foo.op2.List a = default.Foo.op2 (dfun.Foo.List a)
284 \end{verbatim}
285 that is, the default method applied to the dictionary at this type.
286
287 What we actually produce in either case is:
288
289         AbsBinds [a] [dfun_theta_dicts]
290                  [(dfun.Foo.List, d)] ++ (maybe) [(const.Foo.op1.List, op1), ...]
291                  { d = (sd1,sd2, ..., op1, op2, ...)
292                    op1 = ...
293                    op2 = ...
294                  }
295
296 The "maybe" says that we only ask AbsBinds to make global constant methods
297 if the dfun_theta is empty.
298
299                 
300 For an instance declaration, say,
301
302         instance (C1 a, C2 b) => C (T a b) where
303                 ...
304
305 where the {\em immediate} superclasses of C are D1, D2, we build a dictionary
306 function whose type is
307
308         (C1 a, C2 b, D1 (T a b), D2 (T a b)) => C (T a b)
309
310 Notice that we pass it the superclass dictionaries at the instance type; this
311 is the ``Mark Jones optimisation''.  The stuff before the "=>" here
312 is the @dfun_theta@ below.
313
314 First comes the easy case of a non-local instance decl.
315
316
317 \begin{code}
318 tcInstDecl2 :: InstInfo -> TcM TcMonoBinds
319
320 tcInstDecl2 (InstInfo { iDFunId = dfun_id, iBinds = binds })
321   =      -- Prime error recovery
322     recoverM (returnM EmptyMonoBinds)           $
323     addSrcLoc (getSrcLoc dfun_id)               $
324     addErrCtxt (instDeclCtxt2 (idType dfun_id)) $
325     let
326         inst_ty          = idType dfun_id
327         (inst_tyvars, _) = tcSplitForAllTys inst_ty
328                 -- The tyvars of the instance decl scope over the 'where' part
329                 -- Those tyvars are inside the dfun_id's type, which is a bit
330                 -- bizarre, but OK so long as you realise it!
331     in
332
333         -- Instantiate the instance decl with tc-style type variables
334     tcInstType InstTv inst_ty           `thenM` \ (inst_tyvars', dfun_theta', inst_head') ->
335     let
336         Just pred         = tcSplitPredTy_maybe inst_head'
337         (clas, inst_tys') = getClassPredTys pred
338         (class_tyvars, sc_theta, _, op_items) = classBigSig clas
339
340         -- Instantiate the super-class context with inst_tys
341         sc_theta' = substTheta (mkTyVarSubst class_tyvars inst_tys') sc_theta
342         origin    = InstanceDeclOrigin
343     in
344          -- Create dictionary Ids from the specified instance contexts.
345     newDicts origin sc_theta'           `thenM` \ sc_dicts ->
346     newDicts origin dfun_theta'         `thenM` \ dfun_arg_dicts ->
347     newDicts origin [pred]              `thenM` \ [this_dict] ->
348                 -- Default-method Ids may be mentioned in synthesised RHSs,
349                 -- but they'll already be in the environment.
350
351         ------------------
352         -- Typecheck the methods
353     let         -- These insts are in scope; quite a few, eh?
354         avail_insts = [this_dict] ++ dfun_arg_dicts ++ sc_dicts
355     in
356     tcMethods clas inst_tyvars inst_tyvars' 
357               dfun_theta' inst_tys' avail_insts 
358               op_items binds            `thenM` \ (meth_ids, meth_binds) ->
359
360         -- Figure out bindings for the superclass context
361     tcSuperClasses inst_tyvars' dfun_arg_dicts sc_dicts 
362                 `thenM` \ (zonked_inst_tyvars, sc_binds_inner, sc_binds_outer) ->
363
364         -- Deal with 'SPECIALISE instance' pragmas by making them
365         -- look like SPECIALISE pragmas for the dfun
366     let
367         uprags = case binds of
368                        VanillaInst _ uprags -> uprags
369                        other                -> []
370         spec_prags = [ SpecSig (idName dfun_id) ty loc
371                      | SpecInstSig ty loc <- uprags ]
372         xtve = inst_tyvars `zip` inst_tyvars'
373     in
374     tcExtendGlobalValEnv [dfun_id] (
375         tcExtendTyVarEnv2 xtve          $
376         tcSpecSigs spec_prags
377     )                                   `thenM` \ prag_binds ->
378
379         -- Create the result bindings
380     let
381         dict_constr   = classDataCon clas
382         scs_and_meths = map instToId sc_dicts ++ meth_ids
383         this_dict_id  = instToId this_dict
384         inlines       | null dfun_arg_dicts = emptyNameSet
385                       | otherwise           = unitNameSet (idName dfun_id)
386                 -- Always inline the dfun; this is an experimental decision
387                 -- because it makes a big performance difference sometimes.
388                 -- Often it means we can do the method selection, and then
389                 -- inline the method as well.  Marcin's idea; see comments below.
390                 --
391                 -- BUT: don't inline it if it's a constant dictionary;
392                 -- we'll get all the benefit without inlining, and we get
393                 -- a **lot** of code duplication if we inline it
394                 --
395                 --      See Note [Inline dfuns] below
396
397         dict_rhs
398           | null scs_and_meths
399           =     -- Blatant special case for CCallable, CReturnable
400                 -- If the dictionary is empty then we should never
401                 -- select anything from it, so we make its RHS just
402                 -- emit an error message.  This in turn means that we don't
403                 -- mention the constructor, which doesn't exist for CCallable, CReturnable
404                 -- Hardly beautiful, but only three extra lines.
405             HsApp (TyApp (HsVar rUNTIME_ERROR_ID) [idType this_dict_id])
406                   (HsLit (HsStringPrim (mkFastString (stringToUtf8 msg))))
407
408           | otherwise   -- The common case
409           = mkHsConApp dict_constr inst_tys' (map HsVar scs_and_meths)
410                 -- We don't produce a binding for the dict_constr; instead we
411                 -- rely on the simplifier to unfold this saturated application
412                 -- We do this rather than generate an HsCon directly, because
413                 -- it means that the special cases (e.g. dictionary with only one
414                 -- member) are dealt with by the common MkId.mkDataConWrapId code rather
415                 -- than needing to be repeated here.
416
417           where
418             msg = "Compiler error: bad dictionary " ++ showSDoc (ppr clas)
419
420         dict_bind  = VarMonoBind this_dict_id dict_rhs
421         all_binds  = sc_binds_inner `AndMonoBinds` meth_binds `AndMonoBinds` dict_bind
422
423         main_bind = AbsBinds
424                          zonked_inst_tyvars
425                          (map instToId dfun_arg_dicts)
426                          [(inst_tyvars', dfun_id, this_dict_id)] 
427                          inlines all_binds
428     in
429     showLIE (text "instance")           `thenM_`
430     returnM (main_bind `AndMonoBinds` prag_binds `AndMonoBinds` sc_binds_outer)
431
432
433 tcMethods clas inst_tyvars inst_tyvars' dfun_theta' inst_tys' 
434           avail_insts op_items (VanillaInst monobinds uprags)
435   =     -- Check that all the method bindings come from this class
436     let
437         sel_names = [idName sel_id | (sel_id, _) <- op_items]
438         bad_bndrs = collectMonoBinders monobinds `minusList` sel_names
439     in
440     mappM (addErrTc . badMethodErr clas) bad_bndrs      `thenM_`
441
442         -- Make the method bindings
443     let
444         mk_method_bind = mkMethodBind InstanceDeclOrigin clas inst_tys' monobinds
445     in
446     mapAndUnzipM mk_method_bind op_items        `thenM` \ (meth_insts, meth_infos) ->
447
448         -- And type check them
449         -- It's really worth making meth_insts available to the tcMethodBind
450         -- Consider     instance Monad (ST s) where
451         --                {-# INLINE (>>) #-}
452         --                (>>) = ...(>>=)...
453         -- If we don't include meth_insts, we end up with bindings like this:
454         --      rec { dict = MkD then bind ...
455         --            then = inline_me (... (GHC.Base.>>= dict) ...)
456         --            bind = ... }
457         -- The trouble is that (a) 'then' and 'dict' are mutually recursive, 
458         -- and (b) the inline_me prevents us inlining the >>= selector, which
459         -- would unravel the loop.  Result: (>>) ends up as a loop breaker, and
460         -- is not inlined across modules. Rather ironic since this does not
461         -- happen without the INLINE pragma!  
462         --
463         -- Solution: make meth_insts available, so that 'then' refers directly
464         --           to the local 'bind' rather than going via the dictionary.
465         --
466         -- BUT WATCH OUT!  If the method type mentions the class variable, then
467         -- this optimisation is not right.  Consider
468         --      class C a where
469         --        op :: Eq a => a
470         --
471         --      instance C Int where
472         --        op = op
473         -- The occurrence of 'op' on the rhs gives rise to a constraint
474         --      op at Int
475         -- The trouble is that the 'meth_inst' for op, which is 'available', also
476         -- looks like 'op at Int'.  But they are not the same.
477     let
478         all_insts      = avail_insts ++ catMaybes meth_insts
479         xtve           = inst_tyvars `zip` inst_tyvars'
480         tc_method_bind = tcMethodBind xtve inst_tyvars' dfun_theta' all_insts uprags 
481     in
482     mapM tc_method_bind meth_infos              `thenM` \ meth_binds_s ->
483    
484     returnM ([meth_id | (_,meth_id,_) <- meth_infos], 
485              andMonoBindList meth_binds_s)
486
487
488 -- Derived newtype instances
489 tcMethods clas inst_tyvars inst_tyvars' dfun_theta' inst_tys' 
490           avail_insts op_items (NewTypeDerived rep_tys)
491   = getInstLoc InstanceDeclOrigin               `thenM` \ inst_loc ->
492     mapAndUnzip3M (do_one inst_loc) op_items    `thenM` \ (meth_ids, meth_binds, rhs_insts) ->
493     
494     tcSimplifyCheck
495          (ptext SLIT("newtype derived instance"))
496          inst_tyvars' avail_insts rhs_insts     `thenM` \ lie_binds ->
497
498         -- I don't think we have to do the checkSigTyVars thing
499
500     returnM (meth_ids, lie_binds `AndMonoBinds` andMonoBindList meth_binds)
501
502   where
503     do_one inst_loc (sel_id, _)
504         = -- The binding is like "op @ NewTy = op @ RepTy"
505                 -- Make the *binder*, like in mkMethodBind
506           tcInstClassOp inst_loc sel_id inst_tys'       `thenM` \ meth_inst ->
507
508                 -- Make the *occurrence on the rhs*
509           tcInstClassOp inst_loc sel_id rep_tys'        `thenM` \ rhs_inst ->
510           let
511              meth_id = instToId meth_inst
512           in
513           return (meth_id, VarMonoBind meth_id (HsVar (instToId rhs_inst)), rhs_inst)
514
515         -- Instantiate rep_tys with the relevant type variables
516     rep_tys' = map (substTy subst) rep_tys
517     subst    = mkTyVarSubst inst_tyvars (mkTyVarTys inst_tyvars')
518 \end{code}
519
520 Note: [Superclass loops]
521 ~~~~~~~~~~~~~~~~~~~~~~~~~
522 We have to be very, very careful when generating superclasses, lest we
523 accidentally build a loop. Here's an example:
524
525   class S a
526
527   class S a => C a where { opc :: a -> a }
528   class S b => D b where { opd :: b -> b }
529   
530   instance C Int where
531      opc = opd
532   
533   instance D Int where
534      opd = opc
535
536 From (instance C Int) we get the constraint set {ds1:S Int, dd:D Int}
537 Simplifying, we may well get:
538         $dfCInt = :C ds1 (opd dd)
539         dd  = $dfDInt
540         ds1 = $p1 dd
541 Notice that we spot that we can extract ds1 from dd.  
542
543 Alas!  Alack! We can do the same for (instance D Int):
544
545         $dfDInt = :D ds2 (opc dc)
546         dc  = $dfCInt
547         ds2 = $p1 dc
548
549 And now we've defined the superclass in terms of itself.
550
551
552 Solution: treat the superclass context separately, and simplify it
553 all the way down to nothing on its own.  Don't toss any 'free' parts
554 out to be simplified together with other bits of context.
555 Hence the tcSimplifyTop below.
556
557 At a more basic level, don't include this_dict in the context wrt
558 which we simplify sc_dicts, else sc_dicts get bound by just selecting
559 from this_dict!!
560
561 \begin{code}
562 tcSuperClasses inst_tyvars' dfun_arg_dicts sc_dicts
563   = addErrCtxt superClassCtxt   $
564     getLIE (tcSimplifyCheck doc inst_tyvars'
565                             dfun_arg_dicts
566                             sc_dicts)           `thenM` \ (sc_binds1, sc_lie) ->
567
568         -- It's possible that the superclass stuff might have done unification
569     checkSigTyVars inst_tyvars'         `thenM` \ zonked_inst_tyvars ->
570
571         -- We must simplify this all the way down 
572         -- lest we build superclass loops
573         -- See Note [Superclass loops] above
574     tcSimplifyTop sc_lie                `thenM` \ sc_binds2 ->
575
576     returnM (zonked_inst_tyvars, sc_binds1, sc_binds2)
577
578   where
579     doc = ptext SLIT("instance declaration superclass context")
580 \end{code}
581
582
583                 ------------------------------
584         [Inline dfuns] Inlining dfuns unconditionally
585                 ------------------------------
586
587 The code above unconditionally inlines dict funs.  Here's why.
588 Consider this program:
589
590     test :: Int -> Int -> Bool
591     test x y = (x,y) == (y,x) || test y x
592     -- Recursive to avoid making it inline.
593
594 This needs the (Eq (Int,Int)) instance.  If we inline that dfun
595 the code we end up with is good:
596
597     Test.$wtest =
598         \r -> case ==# [ww ww1] of wild {
599                 PrelBase.False -> Test.$wtest ww1 ww;
600                 PrelBase.True ->
601                   case ==# [ww1 ww] of wild1 {
602                     PrelBase.False -> Test.$wtest ww1 ww;
603                     PrelBase.True -> PrelBase.True [];
604                   };
605             };
606     Test.test = \r [w w1]
607             case w of w2 {
608               PrelBase.I# ww ->
609                   case w1 of w3 { PrelBase.I# ww1 -> Test.$wtest ww ww1; };
610             };
611
612 If we don't inline the dfun, the code is not nearly as good:
613
614     (==) = case PrelTup.$fEq(,) PrelBase.$fEqInt PrelBase.$fEqInt of tpl {
615               PrelBase.:DEq tpl1 tpl2 -> tpl2;
616             };
617     
618     Test.$wtest =
619         \r [ww ww1]
620             let { y = PrelBase.I#! [ww1]; } in
621             let { x = PrelBase.I#! [ww]; } in
622             let { sat_slx = PrelTup.(,)! [y x]; } in
623             let { sat_sly = PrelTup.(,)! [x y];
624             } in
625               case == sat_sly sat_slx of wild {
626                 PrelBase.False -> Test.$wtest ww1 ww;
627                 PrelBase.True -> PrelBase.True [];
628               };
629     
630     Test.test =
631         \r [w w1]
632             case w of w2 {
633               PrelBase.I# ww ->
634                   case w1 of w3 { PrelBase.I# ww1 -> Test.$wtest ww ww1; };
635             };
636
637 Why doesn't GHC inline $fEq?  Because it looks big:
638
639     PrelTup.zdfEqZ1T{-rcX-}
640         = \ @ a{-reT-} :: * @ b{-reS-} :: *
641             zddEq{-rf6-} _Ks :: {PrelBase.Eq{-23-} a{-reT-}}
642             zddEq1{-rf7-} _Ks :: {PrelBase.Eq{-23-} b{-reS-}} ->
643             let {
644               zeze{-rf0-} _Kl :: (b{-reS-} -> b{-reS-} -> PrelBase.Bool{-3c-})
645               zeze{-rf0-} = PrelBase.zeze{-01L-}@ b{-reS-} zddEq1{-rf7-} } in
646             let {
647               zeze1{-rf3-} _Kl :: (a{-reT-} -> a{-reT-} -> PrelBase.Bool{-3c-})
648               zeze1{-rf3-} = PrelBase.zeze{-01L-} @ a{-reT-} zddEq{-rf6-} } in
649             let {
650               zeze2{-reN-} :: ((a{-reT-}, b{-reS-}) -> (a{-reT-}, b{-reS-})-> PrelBase.Bool{-3c-})
651               zeze2{-reN-} = \ ds{-rf5-} _Ks :: (a{-reT-}, b{-reS-})
652                                ds1{-rf4-} _Ks :: (a{-reT-}, b{-reS-}) ->
653                              case ds{-rf5-}
654                              of wild{-reW-} _Kd { (a1{-rf2-} _Ks, a2{-reZ-} _Ks) ->
655                              case ds1{-rf4-}
656                              of wild1{-reX-} _Kd { (b1{-rf1-} _Ks, b2{-reY-} _Ks) ->
657                              PrelBase.zaza{-r4e-}
658                                (zeze1{-rf3-} a1{-rf2-} b1{-rf1-})
659                                (zeze{-rf0-} a2{-reZ-} b2{-reY-})
660                              }
661                              } } in     
662             let {
663               a1{-reR-} :: ((a{-reT-}, b{-reS-})-> (a{-reT-}, b{-reS-})-> PrelBase.Bool{-3c-})
664               a1{-reR-} = \ a2{-reV-} _Ks :: (a{-reT-}, b{-reS-})
665                             b1{-reU-} _Ks :: (a{-reT-}, b{-reS-}) ->
666                           PrelBase.not{-r6I-} (zeze2{-reN-} a2{-reV-} b1{-reU-})
667             } in
668               PrelBase.zdwZCDEq{-r8J-} @ (a{-reT-}, b{-reS-}) a1{-reR-} zeze2{-reN-})
669
670 and it's not as bad as it seems, because it's further dramatically
671 simplified: only zeze2 is extracted and its body is simplified.
672
673
674 %************************************************************************
675 %*                                                                      *
676 \subsection{Error messages}
677 %*                                                                      *
678 %************************************************************************
679
680 \begin{code}
681 instDeclCtxt1 hs_inst_ty 
682   = inst_decl_ctxt (case hs_inst_ty of
683                         HsForAllTy _ _ (HsPredTy pred) -> ppr pred
684                         HsPredTy pred                  -> ppr pred
685                         other                          -> ppr hs_inst_ty)       -- Don't expect this
686 instDeclCtxt2 dfun_ty
687   = inst_decl_ctxt (ppr (mkClassPred cls tys))
688   where
689     (_,_,cls,tys) = tcSplitDFunTy dfun_ty
690
691 inst_decl_ctxt doc = ptext SLIT("In the instance declaration for") <+> quotes doc
692
693 superClassCtxt = ptext SLIT("When checking the super-classes of an instance declaration")
694 \end{code}