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