[project @ 2002-01-18 07:02:59 by sof]
[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, tcAddDeclCtxt ) where
8
9 #include "HsVersions.h"
10
11
12 import CmdLineOpts      ( DynFlag(..) )
13
14 import HsSyn            ( HsDecl(..), InstDecl(..), TyClDecl(..), HsType(..),
15                           MonoBinds(..), HsExpr(..),  HsLit(..), Sig(..), HsTyVarBndr(..),
16                           andMonoBindList, collectMonoBinders, 
17                           isClassDecl, isIfaceInstDecl, toHsType
18                         )
19 import RnHsSyn          ( RenamedHsBinds, RenamedInstDecl, RenamedHsDecl, 
20                           RenamedMonoBinds, RenamedTyClDecl, RenamedHsType, 
21                           extractHsTyVars, maybeGenericMatch
22                         )
23 import TcHsSyn          ( TcMonoBinds, mkHsConApp )
24 import TcBinds          ( tcSpecSigs )
25 import TcClassDcl       ( tcMethodBind, badMethodErr )
26 import TcMonad       
27 import TcMType          ( tcInstSigType, checkValidTheta, checkValidInstHead, instTypeErr, 
28                           UserTypeCtxt(..), SourceTyCtxt(..) )
29 import TcType           ( mkClassPred, mkTyVarTy, mkTyVarTys, tcSplitForAllTys,
30                           tcSplitSigmaTy, getClassPredTys, tcSplitPredTy_maybe,
31                           TyVarDetails(..)
32                         )
33 import Inst             ( InstOrigin(..), newDicts, instToId,
34                           LIE, mkLIE, emptyLIE, plusLIE, plusLIEs )
35 import TcDeriv          ( tcDeriving )
36 import TcEnv            ( TcEnv, tcExtendGlobalValEnv, isHomePackageThing,
37                           tcExtendTyVarEnvForMeths, tcLookupId, tcLookupClass,
38                           InstInfo(..), pprInstInfo, simpleInstInfoTyCon, 
39                           simpleInstInfoTy, newDFunName
40                         )
41 import InstEnv          ( InstEnv, extendInstEnv )
42 import PprType          ( pprClassPred )
43 import TcMonoType       ( tcHsTyVars, kcHsSigType, tcHsType, tcHsSigType )
44 import TcUnify          ( checkSigTyVars )
45 import TcSimplify       ( tcSimplifyCheck )
46 import HscTypes         ( HomeSymbolTable, DFunId,
47                           ModDetails(..), PackageInstEnv, PersistentRenamerState
48                         )
49 import Subst            ( substTy, substTheta )
50 import DataCon          ( classDataCon )
51 import Class            ( Class, classBigSig )
52 import Var              ( idName, idType )
53 import VarSet           ( emptyVarSet )
54 import Id               ( setIdLocalExported )
55 import MkId             ( mkDictFunId, unsafeCoerceId, eRROR_ID )
56 import FunDeps          ( checkInstFDs )
57 import Generics         ( validGenericInstanceType )
58 import Module           ( Module, foldModuleEnv )
59 import Name             ( getSrcLoc )
60 import NameSet          ( unitNameSet, emptyNameSet, nameSetToList )
61 import TyCon            ( TyCon )
62 import Subst            ( mkTopTyVarSubst, substTheta )
63 import TysWiredIn       ( genericTyCons )
64 import Name             ( Name )
65 import SrcLoc           ( SrcLoc )
66 import Unique           ( Uniquable(..) )
67 import Util             ( lengthExceeds, isSingleton )
68 import BasicTypes       ( NewOrData(..), Fixity )
69 import ErrUtils         ( dumpIfSet_dyn )
70 import ListSetOps       ( Assoc, emptyAssoc, plusAssoc_C, mapAssoc, 
71                           assocElts, extendAssoc_C, equivClassesByUniq, minusList
72                         )
73 import Maybe            ( catMaybes )
74 import List             ( partition )
75 import Outputable
76 \end{code}
77
78 Typechecking instance declarations is done in two passes. The first
79 pass, made by @tcInstDecls1@, collects information to be used in the
80 second pass.
81
82 This pre-processed info includes the as-yet-unprocessed bindings
83 inside the instance declaration.  These are type-checked in the second
84 pass, when the class-instance envs and GVE contain all the info from
85 all the instance and value decls.  Indeed that's the reason we need
86 two passes over the instance decls.
87
88
89 Here is the overall algorithm.
90 Assume that we have an instance declaration
91
92     instance c => k (t tvs) where b
93
94 \begin{enumerate}
95 \item
96 $LIE_c$ is the LIE for the context of class $c$
97 \item
98 $betas_bar$ is the free variables in the class method type, excluding the
99    class variable
100 \item
101 $LIE_cop$ is the LIE constraining a particular class method
102 \item
103 $tau_cop$ is the tau type of a class method
104 \item
105 $LIE_i$ is the LIE for the context of instance $i$
106 \item
107 $X$ is the instance constructor tycon
108 \item
109 $gammas_bar$ is the set of type variables of the instance
110 \item
111 $LIE_iop$ is the LIE for a particular class method instance
112 \item
113 $tau_iop$ is the tau type for this instance of a class method
114 \item
115 $alpha$ is the class variable
116 \item
117 $LIE_cop' = LIE_cop [X gammas_bar / alpha, fresh betas_bar]$
118 \item
119 $tau_cop' = tau_cop [X gammas_bar / alpha, fresh betas_bar]$
120 \end{enumerate}
121
122 ToDo: Update the list above with names actually in the code.
123
124 \begin{enumerate}
125 \item
126 First, make the LIEs for the class and instance contexts, which means
127 instantiate $thetaC [X inst_tyvars / alpha ]$, yielding LIElistC' and LIEC',
128 and make LIElistI and LIEI.
129 \item
130 Then process each method in turn.
131 \item
132 order the instance methods according to the ordering of the class methods
133 \item
134 express LIEC' in terms of LIEI, yielding $dbinds_super$ or an error
135 \item
136 Create final dictionary function from bindings generated already
137 \begin{pseudocode}
138 df = lambda inst_tyvars
139        lambda LIEI
140          let Bop1
141              Bop2
142              ...
143              Bopn
144          and dbinds_super
145               in <op1,op2,...,opn,sd1,...,sdm>
146 \end{pseudocode}
147 Here, Bop1 \ldots Bopn bind the methods op1 \ldots opn,
148 and $dbinds_super$ bind the superclass dictionaries sd1 \ldots sdm.
149 \end{enumerate}
150
151
152 %************************************************************************
153 %*                                                                      *
154 \subsection{Extracting instance decls}
155 %*                                                                      *
156 %************************************************************************
157
158 Gather up the instance declarations from their various sources
159
160 \begin{code}
161 tcInstDecls1 :: PackageInstEnv
162              -> PersistentRenamerState  
163              -> HomeSymbolTable         -- Contains instances
164              -> TcEnv                   -- Contains IdInfo for dfun ids
165              -> (Name -> Maybe Fixity)  -- for deriving Show and Read
166              -> Module                  -- Module for deriving
167              -> [RenamedHsDecl]
168              -> TcM (PackageInstEnv, InstEnv, [InstInfo], RenamedHsBinds)
169
170 tcInstDecls1 inst_env0 prs hst unf_env get_fixity this_mod decls
171   = let
172         inst_decls = [inst_decl | InstD inst_decl <- decls]     
173         tycl_decls = [decl      | TyClD decl <- decls]
174         clas_decls = filter isClassDecl tycl_decls
175         (iface_inst_ds, local_inst_ds) = partition isIfaceInstDecl inst_decls
176     in
177         -- (1) Do the ordinary instance declarations
178     mapNF_Tc tcLocalInstDecl1 local_inst_ds             `thenNF_Tc` \ local_inst_infos ->
179     mapNF_Tc tcImportedInstDecl1 iface_inst_ds          `thenNF_Tc` \ iface_dfuns ->
180
181         -- (2) Instances from generic class declarations
182     getGenericInstances clas_decls              `thenTc` \ generic_inst_info -> 
183
184         -- Next, construct the instance environment so far, consisting of
185         --      a) cached non-home-package InstEnv (gotten from pcs)    inst_env0
186         --      b) imported instance decls (not in the home package)    inst_env1
187         --      c) imported instance decls (from this module)           inst_env2
188         --      c) other modules in this package (gotten from hst)      inst_env3
189         --      d) local instance decls                                 inst_env4
190         --      e) generic instances                                    inst_env5
191         -- The result of (b) replaces the cached InstEnv in the PCS
192         --
193         -- Note that iface_dfuns may contain not only insts that we demand-loaded
194         -- from package interface files, but also instances from the current module
195         -- in the case where we are loading this module's interface file in GHCi,
196         -- so we partition the iface_dfuns into package instances and local instances
197         -- below so that we don't end up with home package instances in the PCS.
198         --
199         -- There can't be any instance declarations from the home
200         -- package other than from the current module (with the
201         -- compilation manager) because they are loaded explicitly by
202         -- the compilation manager.  The partition is really only
203         -- necessary when we're under control of the compilation
204         -- manager.
205     let
206         local_inst_info = catMaybes local_inst_infos
207         (local_iface_dfuns, pkg_iface_dfuns) = partition isHomePackageThing iface_dfuns
208         hst_dfuns       = foldModuleEnv ((++) . md_insts) [] hst
209     in 
210
211 --    pprTrace "tcInstDecls" (vcat [ppr imported_dfuns, ppr hst_dfuns]) $
212
213     addInstDFuns inst_env0 pkg_iface_dfuns      `thenNF_Tc` \ inst_env1 ->
214     addInstDFuns inst_env1 hst_dfuns            `thenNF_Tc` \ inst_env2 ->
215     addInstDFuns inst_env2 local_iface_dfuns    `thenNF_Tc` \ inst_env3 ->
216     addInstInfos inst_env3 local_inst_info      `thenNF_Tc` \ inst_env4 ->
217     addInstInfos inst_env4 generic_inst_info    `thenNF_Tc` \ inst_env5 ->
218
219         -- (3) Compute instances from "deriving" clauses; 
220         --     note that we only do derivings for things in this module; 
221         --     we ignore deriving decls from interfaces!
222         -- This stuff computes a context for the derived instance decl, so it
223         -- needs to know about all the instances possible; hence inst_env4
224     tcDeriving prs this_mod inst_env4 get_fixity tycl_decls
225                                         `thenTc` \ (deriv_inst_info, deriv_binds) ->
226     addInstInfos inst_env4 deriv_inst_info              `thenNF_Tc` \ final_inst_env ->
227
228     returnTc (inst_env1, 
229               final_inst_env, 
230               generic_inst_info ++ deriv_inst_info ++ local_inst_info,
231               deriv_binds)
232
233 addInstInfos :: InstEnv -> [InstInfo] -> NF_TcM InstEnv
234 addInstInfos inst_env infos = addInstDFuns inst_env (map iDFunId infos)
235
236 addInstDFuns :: InstEnv -> [DFunId] -> NF_TcM InstEnv
237 addInstDFuns inst_env dfuns
238   = getDOptsTc                          `thenNF_Tc` \ dflags ->
239     let
240         (inst_env', errs) = extendInstEnv dflags inst_env dfuns
241     in
242     addErrsTc errs                      `thenNF_Tc_` 
243     traceTc (text "Adding instances:" <+> vcat (map pp dfuns))  `thenTc_`
244     returnTc inst_env'
245   where
246     pp dfun = ppr dfun <+> dcolon <+> ppr (idType dfun)
247 \end{code} 
248
249 \begin{code}
250 tcImportedInstDecl1 :: RenamedInstDecl -> NF_TcM DFunId
251         -- An interface-file instance declaration
252         -- Should be in scope by now, because we should
253         -- have sucked in its interface-file definition
254         -- So it will be replete with its unfolding etc
255 tcImportedInstDecl1 decl@(InstDecl poly_ty binds uprags (Just dfun_name) src_loc)
256   = tcLookupId dfun_name
257
258
259 tcLocalInstDecl1 :: RenamedInstDecl 
260                  -> NF_TcM (Maybe InstInfo)     -- Nothing if there was an error
261         -- A source-file instance declaration
262         -- Type-check all the stuff before the "where"
263         --
264         -- We check for respectable instance type, and context
265         -- but only do this for non-imported instance decls.
266         -- Imported ones should have been checked already, and may indeed
267         -- contain something illegal in normal Haskell, notably
268         --      instance CCallable [Char] 
269 tcLocalInstDecl1 decl@(InstDecl poly_ty binds uprags Nothing src_loc)
270   =     -- Prime error recovery, set source location
271     recoverNF_Tc (returnNF_Tc Nothing)  $
272     tcAddSrcLoc src_loc                 $
273     tcAddErrCtxt (instDeclCtxt poly_ty) $
274
275         -- Typecheck the instance type itself.  We can't use 
276         -- tcHsSigType, because it's not a valid user type.
277     kcHsSigType poly_ty                 `thenTc_`
278     tcHsType poly_ty                    `thenTc` \ poly_ty' ->
279     let
280         (tyvars, theta, tau) = tcSplitSigmaTy poly_ty'
281     in
282     checkValidTheta InstThetaCtxt theta         `thenTc_`
283     checkValidInstHead tau                      `thenTc` \ (clas,inst_tys) ->
284     checkTc (checkInstFDs theta clas inst_tys)
285             (instTypeErr (pprClassPred clas inst_tys) msg)      `thenTc_`
286     newDFunName clas inst_tys src_loc                           `thenNF_Tc` \ dfun_name ->
287     returnTc (Just (InstInfo { iDFunId = mkDictFunId dfun_name clas tyvars inst_tys theta,
288                                iBinds = binds, iPrags = uprags }))
289   where
290     msg  = parens (ptext SLIT("the instance types do not agree with the functional dependencies of the class"))
291 \end{code}
292
293
294 %************************************************************************
295 %*                                                                      *
296 \subsection{Extracting generic instance declaration from class declarations}
297 %*                                                                      *
298 %************************************************************************
299
300 @getGenericInstances@ extracts the generic instance declarations from a class
301 declaration.  For exmaple
302
303         class C a where
304           op :: a -> a
305         
306           op{ x+y } (Inl v)   = ...
307           op{ x+y } (Inr v)   = ...
308           op{ x*y } (v :*: w) = ...
309           op{ 1   } Unit      = ...
310
311 gives rise to the instance declarations
312
313         instance C (x+y) where
314           op (Inl v)   = ...
315           op (Inr v)   = ...
316         
317         instance C (x*y) where
318           op (v :*: w) = ...
319
320         instance C 1 where
321           op Unit      = ...
322
323
324 \begin{code}
325 getGenericInstances :: [RenamedTyClDecl] -> TcM [InstInfo] 
326 getGenericInstances class_decls
327   = mapTc get_generics class_decls              `thenTc` \ gen_inst_infos ->
328     let
329         gen_inst_info = concat gen_inst_infos
330     in
331     if null gen_inst_info then
332         returnTc []
333     else
334     getDOptsTc                                          `thenNF_Tc`  \ dflags ->
335     ioToTc (dumpIfSet_dyn dflags Opt_D_dump_deriv "Generic instances" 
336                       (vcat (map pprInstInfo gen_inst_info)))   
337                                                         `thenNF_Tc_`
338     returnTc gen_inst_info
339
340 get_generics decl@(ClassDecl {tcdMeths = Nothing})
341   = returnTc [] -- Imported class decls
342
343 get_generics decl@(ClassDecl {tcdName = class_name, tcdMeths = Just def_methods, tcdLoc = loc})
344   | null groups         
345   = returnTc [] -- The comon case: no generic default methods
346
347   | otherwise   -- A source class decl with generic default methods
348   = recoverNF_Tc (returnNF_Tc [])                               $
349     tcAddDeclCtxt decl                                          $
350     tcLookupClass class_name                                    `thenTc` \ clas ->
351
352         -- Make an InstInfo out of each group
353     mapTc (mkGenericInstance clas loc) groups           `thenTc` \ inst_infos ->
354
355         -- Check that there is only one InstInfo for each type constructor
356         -- The main way this can fail is if you write
357         --      f {| a+b |} ... = ...
358         --      f {| x+y |} ... = ...
359         -- Then at this point we'll have an InstInfo for each
360     let
361         tc_inst_infos :: [(TyCon, InstInfo)]
362         tc_inst_infos = [(simpleInstInfoTyCon i, i) | i <- inst_infos]
363
364         bad_groups = [group | group <- equivClassesByUniq get_uniq tc_inst_infos,
365                               group `lengthExceeds` 1]
366         get_uniq (tc,_) = getUnique tc
367     in
368     mapTc (addErrTc . dupGenericInsts) bad_groups       `thenTc_`
369
370         -- Check that there is an InstInfo for each generic type constructor
371     let
372         missing = genericTyCons `minusList` [tc | (tc,_) <- tc_inst_infos]
373     in
374     checkTc (null missing) (missingGenericInstances missing)    `thenTc_`
375
376     returnTc inst_infos
377
378   where
379         -- Group the declarations by type pattern
380         groups :: [(RenamedHsType, RenamedMonoBinds)]
381         groups = assocElts (getGenericBinds def_methods)
382
383
384 ---------------------------------
385 getGenericBinds :: RenamedMonoBinds -> Assoc RenamedHsType RenamedMonoBinds
386   -- Takes a group of method bindings, finds the generic ones, and returns
387   -- them in finite map indexed by the type parameter in the definition.
388
389 getGenericBinds EmptyMonoBinds    = emptyAssoc
390 getGenericBinds (AndMonoBinds m1 m2) 
391   = plusAssoc_C AndMonoBinds (getGenericBinds m1) (getGenericBinds m2)
392
393 getGenericBinds (FunMonoBind id infixop matches loc)
394   = mapAssoc wrap (foldl add emptyAssoc matches)
395         -- Using foldl not foldr is vital, else
396         -- we reverse the order of the bindings!
397   where
398     add env match = case maybeGenericMatch match of
399                       Nothing           -> env
400                       Just (ty, match') -> extendAssoc_C (++) env (ty, [match'])
401
402     wrap ms = FunMonoBind id infixop ms loc
403
404 ---------------------------------
405 mkGenericInstance :: Class -> SrcLoc
406                   -> (RenamedHsType, RenamedMonoBinds)
407                   -> TcM InstInfo
408
409 mkGenericInstance clas loc (hs_ty, binds)
410   -- Make a generic instance declaration
411   -- For example:       instance (C a, C b) => C (a+b) where { binds }
412
413   =     -- Extract the universally quantified type variables
414     let
415         sig_tvs = map UserTyVar (nameSetToList (extractHsTyVars hs_ty))
416     in
417     tcHsTyVars sig_tvs (kcHsSigType hs_ty)      $ \ tyvars ->
418
419         -- Type-check the instance type, and check its form
420     tcHsSigType GenPatCtxt hs_ty                `thenTc` \ inst_ty ->
421     checkTc (validGenericInstanceType inst_ty)
422             (badGenericInstanceType binds)      `thenTc_`
423
424         -- Make the dictionary function.
425     newDFunName clas [inst_ty] loc              `thenNF_Tc` \ dfun_name ->
426     let
427         inst_theta = [mkClassPred clas [mkTyVarTy tv] | tv <- tyvars]
428         dfun_id    = mkDictFunId dfun_name clas tyvars [inst_ty] inst_theta
429     in
430
431     returnTc (InstInfo { iDFunId = dfun_id, iBinds = binds, iPrags = [] })
432 \end{code}
433
434
435 %************************************************************************
436 %*                                                                      *
437 \subsection{Type-checking instance declarations, pass 2}
438 %*                                                                      *
439 %************************************************************************
440
441 \begin{code}
442 tcInstDecls2 :: [InstInfo]
443              -> NF_TcM (LIE, TcMonoBinds)
444
445 tcInstDecls2 inst_decls
446 --  = foldBag combine tcInstDecl2 (returnNF_Tc (emptyLIE, EmptyMonoBinds)) inst_decls
447   = foldr combine (returnNF_Tc (emptyLIE, EmptyMonoBinds)) 
448           (map tcInstDecl2 inst_decls)
449   where
450     combine tc1 tc2 = tc1       `thenNF_Tc` \ (lie1, binds1) ->
451                       tc2       `thenNF_Tc` \ (lie2, binds2) ->
452                       returnNF_Tc (lie1 `plusLIE` lie2,
453                                    binds1 `AndMonoBinds` binds2)
454 \end{code}
455
456 ======= New documentation starts here (Sept 92)  ==============
457
458 The main purpose of @tcInstDecl2@ is to return a @HsBinds@ which defines
459 the dictionary function for this instance declaration.  For example
460 \begin{verbatim}
461         instance Foo a => Foo [a] where
462                 op1 x = ...
463                 op2 y = ...
464 \end{verbatim}
465 might generate something like
466 \begin{verbatim}
467         dfun.Foo.List dFoo_a = let op1 x = ...
468                                    op2 y = ...
469                                in
470                                    Dict [op1, op2]
471 \end{verbatim}
472
473 HOWEVER, if the instance decl has no context, then it returns a
474 bigger @HsBinds@ with declarations for each method.  For example
475 \begin{verbatim}
476         instance Foo [a] where
477                 op1 x = ...
478                 op2 y = ...
479 \end{verbatim}
480 might produce
481 \begin{verbatim}
482         dfun.Foo.List a = Dict [Foo.op1.List a, Foo.op2.List a]
483         const.Foo.op1.List a x = ...
484         const.Foo.op2.List a y = ...
485 \end{verbatim}
486 This group may be mutually recursive, because (for example) there may
487 be no method supplied for op2 in which case we'll get
488 \begin{verbatim}
489         const.Foo.op2.List a = default.Foo.op2 (dfun.Foo.List a)
490 \end{verbatim}
491 that is, the default method applied to the dictionary at this type.
492
493 What we actually produce in either case is:
494
495         AbsBinds [a] [dfun_theta_dicts]
496                  [(dfun.Foo.List, d)] ++ (maybe) [(const.Foo.op1.List, op1), ...]
497                  { d = (sd1,sd2, ..., op1, op2, ...)
498                    op1 = ...
499                    op2 = ...
500                  }
501
502 The "maybe" says that we only ask AbsBinds to make global constant methods
503 if the dfun_theta is empty.
504
505                 
506 For an instance declaration, say,
507
508         instance (C1 a, C2 b) => C (T a b) where
509                 ...
510
511 where the {\em immediate} superclasses of C are D1, D2, we build a dictionary
512 function whose type is
513
514         (C1 a, C2 b, D1 (T a b), D2 (T a b)) => C (T a b)
515
516 Notice that we pass it the superclass dictionaries at the instance type; this
517 is the ``Mark Jones optimisation''.  The stuff before the "=>" here
518 is the @dfun_theta@ below.
519
520 First comes the easy case of a non-local instance decl.
521
522
523 \begin{code}
524 tcInstDecl2 :: InstInfo -> TcM (LIE, TcMonoBinds)
525
526 tcInstDecl2 (NewTypeDerived { iDFunId = dfun_id })
527   = tcInstSigType InstTv (idType dfun_id)       `thenNF_Tc` \ (inst_tyvars', dfun_theta', inst_head') ->
528     newDicts InstanceDeclOrigin dfun_theta'     `thenNF_Tc` \ rep_dicts ->
529     let
530         rep_dict_id = ASSERT( isSingleton rep_dicts )
531                       instToId (head rep_dicts)         -- Derived newtypes have just one dict arg
532
533         body = TyLam inst_tyvars'    $
534                DictLam [rep_dict_id] $
535                 (HsVar unsafeCoerceId `TyApp` [idType rep_dict_id, inst_head'])
536                           `HsApp` 
537                 (HsVar rep_dict_id)
538         -- You might wonder why we have the 'coerce'.  It's because the
539         -- type equality mechanism isn't clever enough; see comments with Type.eqType.
540         -- So Lint complains if we don't have this. 
541     in
542     returnTc (emptyLIE, VarMonoBind dfun_id body)
543
544 tcInstDecl2 (InstInfo { iDFunId = dfun_id, iBinds = monobinds, iPrags = uprags })
545   =      -- Prime error recovery
546     recoverNF_Tc (returnNF_Tc (emptyLIE, EmptyMonoBinds))       $
547     tcAddSrcLoc (getSrcLoc dfun_id)                             $
548     tcAddErrCtxt (instDeclCtxt (toHsType (idType dfun_id)))     $
549
550         -- Instantiate the instance decl with tc-style type variables
551     tcInstSigType InstTv (idType dfun_id)       `thenNF_Tc` \ (inst_tyvars', dfun_theta', inst_head') ->
552     let
553         Just pred         = tcSplitPredTy_maybe inst_head'
554         (clas, inst_tys') = getClassPredTys pred
555         (class_tyvars, sc_theta, _, op_items) = classBigSig clas
556
557         sel_names = [idName sel_id | (sel_id, _) <- op_items]
558
559         -- Instantiate the super-class context with inst_tys
560         sc_theta' = substTheta (mkTopTyVarSubst class_tyvars inst_tys') sc_theta
561
562         -- Find any definitions in monobinds that aren't from the class
563         bad_bndrs        = collectMonoBinders monobinds `minusList` sel_names
564         (inst_tyvars, _) = tcSplitForAllTys (idType dfun_id)
565         origin           = InstanceDeclOrigin
566     in
567          -- Check that all the method bindings come from this class
568     mapTc (addErrTc . badMethodErr clas) bad_bndrs              `thenNF_Tc_`
569
570          -- Create dictionary Ids from the specified instance contexts.
571     newDicts origin sc_theta'                    `thenNF_Tc` \ sc_dicts ->
572     newDicts origin dfun_theta'                  `thenNF_Tc` \ dfun_arg_dicts ->
573     newDicts origin [mkClassPred clas inst_tys'] `thenNF_Tc` \ [this_dict] ->
574
575     tcExtendTyVarEnvForMeths inst_tyvars inst_tyvars' (
576         -- The type variable from the dict fun actually scope 
577         -- over the bindings.  They were gotten from
578         -- the original instance declaration
579
580                 -- Default-method Ids may be mentioned in synthesised RHSs,
581                 -- but they'll already be in the environment.
582
583         mapAndUnzip3Tc (tcMethodBind clas origin inst_tyvars' inst_tys'
584                                      dfun_theta'
585                                      monobinds uprags True)
586                        op_items
587     )                   `thenTc` \ (method_binds_s, insts_needed_s, meth_insts) ->
588
589         -- Deal with SPECIALISE instance pragmas by making them
590         -- look like SPECIALISE pragmas for the dfun
591     let
592         dfun_prags = [SpecSig (idName dfun_id) ty loc | SpecInstSig ty loc <- uprags]
593     in
594     tcExtendGlobalValEnv [dfun_id] (
595         tcSpecSigs dfun_prags
596     )                                   `thenTc` \ (prag_binds, prag_lie) ->
597
598         -- Check the overloading constraints of the methods and superclasses
599     let
600                  -- These insts are in scope; quite a few, eh?
601         avail_insts = [this_dict] ++
602                       dfun_arg_dicts ++
603                       sc_dicts ++
604                       meth_insts
605
606         methods_lie    = plusLIEs insts_needed_s
607     in
608
609         -- Simplify the constraints from methods
610     tcAddErrCtxt methodCtxt (
611       tcSimplifyCheck
612                  (ptext SLIT("instance declaration context"))
613                  inst_tyvars'
614                  avail_insts
615                  methods_lie
616     )                                            `thenTc` \ (const_lie1, lie_binds1) ->
617     
618         -- Figure out bindings for the superclass context
619     tcAddErrCtxt superClassCtxt (
620       tcSimplifyCheck
621                  (ptext SLIT("instance declaration context"))
622                  inst_tyvars'
623                  dfun_arg_dicts         -- NB! Don't include this_dict here, else the sc_dicts
624                                         -- get bound by just selecting from this_dict!!
625                  (mkLIE sc_dicts)
626     )                                           `thenTc` \ (const_lie2, lie_binds2) ->
627
628     checkSigTyVars inst_tyvars' emptyVarSet     `thenNF_Tc` \ zonked_inst_tyvars ->
629
630         -- Create the result bindings
631     let
632         local_dfun_id = setIdLocalExported dfun_id
633                 -- Reason for setIdLocalExported: see notes with MkId.mkDictFunId
634
635         dict_constr   = classDataCon clas
636         scs_and_meths = map instToId (sc_dicts ++ meth_insts)
637         this_dict_id  = instToId this_dict
638         inlines       | null dfun_arg_dicts = emptyNameSet
639                       | otherwise           = unitNameSet (idName dfun_id)
640                 -- Always inline the dfun; this is an experimental decision
641                 -- because it makes a big performance difference sometimes.
642                 -- Often it means we can do the method selection, and then
643                 -- inline the method as well.  Marcin's idea; see comments below.
644                 --
645                 -- BUT: don't inline it if it's a constant dictionary;
646                 -- we'll get all the benefit without inlining, and we get
647                 -- a **lot** of code duplication if we inline it
648
649         dict_rhs
650           | null scs_and_meths
651           =     -- Blatant special case for CCallable, CReturnable
652                 -- If the dictionary is empty then we should never
653                 -- select anything from it, so we make its RHS just
654                 -- emit an error message.  This in turn means that we don't
655                 -- mention the constructor, which doesn't exist for CCallable, CReturnable
656                 -- Hardly beautiful, but only three extra lines.
657             HsApp (TyApp (HsVar eRROR_ID) [idType this_dict_id])
658                   (HsLit (HsString msg))
659
660           | otherwise   -- The common case
661           = mkHsConApp dict_constr inst_tys' (map HsVar scs_and_meths)
662                 -- We don't produce a binding for the dict_constr; instead we
663                 -- rely on the simplifier to unfold this saturated application
664                 -- We do this rather than generate an HsCon directly, because
665                 -- it means that the special cases (e.g. dictionary with only one
666                 -- member) are dealt with by the common MkId.mkDataConWrapId code rather
667                 -- than needing to be repeated here.
668
669           where
670             msg = _PK_ ("Compiler error: bad dictionary " ++ showSDoc (ppr clas))
671
672         dict_bind    = VarMonoBind this_dict_id dict_rhs
673         method_binds = andMonoBindList method_binds_s
674
675         main_bind
676           = AbsBinds
677                  zonked_inst_tyvars
678                  (map instToId dfun_arg_dicts)
679                  [(inst_tyvars', local_dfun_id, this_dict_id)] 
680                  inlines
681                  (lie_binds1    `AndMonoBinds` 
682                   lie_binds2    `AndMonoBinds`
683                   method_binds  `AndMonoBinds`
684                   dict_bind)
685     in
686     returnTc (const_lie1 `plusLIE` const_lie2 `plusLIE` prag_lie,
687               main_bind `AndMonoBinds` prag_binds)
688 \end{code}
689
690                 ------------------------------
691                 Inlining dfuns unconditionally
692                 ------------------------------
693
694 The code above unconditionally inlines dict funs.  Here's why.
695 Consider this program:
696
697     test :: Int -> Int -> Bool
698     test x y = (x,y) == (y,x) || test y x
699     -- Recursive to avoid making it inline.
700
701 This needs the (Eq (Int,Int)) instance.  If we inline that dfun
702 the code we end up with is good:
703
704     Test.$wtest =
705         \r -> case ==# [ww ww1] of wild {
706                 PrelBase.False -> Test.$wtest ww1 ww;
707                 PrelBase.True ->
708                   case ==# [ww1 ww] of wild1 {
709                     PrelBase.False -> Test.$wtest ww1 ww;
710                     PrelBase.True -> PrelBase.True [];
711                   };
712             };
713     Test.test = \r [w w1]
714             case w of w2 {
715               PrelBase.I# ww ->
716                   case w1 of w3 { PrelBase.I# ww1 -> Test.$wtest ww ww1; };
717             };
718
719 If we don't inline the dfun, the code is not nearly as good:
720
721     (==) = case PrelTup.$fEq(,) PrelBase.$fEqInt PrelBase.$fEqInt of tpl {
722               PrelBase.:DEq tpl1 tpl2 -> tpl2;
723             };
724     
725     Test.$wtest =
726         \r [ww ww1]
727             let { y = PrelBase.I#! [ww1]; } in
728             let { x = PrelBase.I#! [ww]; } in
729             let { sat_slx = PrelTup.(,)! [y x]; } in
730             let { sat_sly = PrelTup.(,)! [x y];
731             } in
732               case == sat_sly sat_slx of wild {
733                 PrelBase.False -> Test.$wtest ww1 ww;
734                 PrelBase.True -> PrelBase.True [];
735               };
736     
737     Test.test =
738         \r [w w1]
739             case w of w2 {
740               PrelBase.I# ww ->
741                   case w1 of w3 { PrelBase.I# ww1 -> Test.$wtest ww ww1; };
742             };
743
744 Why doesn't GHC inline $fEq?  Because it looks big:
745
746     PrelTup.zdfEqZ1T{-rcX-}
747         = \ @ a{-reT-} :: * @ b{-reS-} :: *
748             zddEq{-rf6-} _Ks :: {PrelBase.Eq{-23-} a{-reT-}}
749             zddEq1{-rf7-} _Ks :: {PrelBase.Eq{-23-} b{-reS-}} ->
750             let {
751               zeze{-rf0-} _Kl :: (b{-reS-} -> b{-reS-} -> PrelBase.Bool{-3c-})
752               zeze{-rf0-} = PrelBase.zeze{-01L-}@ b{-reS-} zddEq1{-rf7-} } in
753             let {
754               zeze1{-rf3-} _Kl :: (a{-reT-} -> a{-reT-} -> PrelBase.Bool{-3c-})
755               zeze1{-rf3-} = PrelBase.zeze{-01L-} @ a{-reT-} zddEq{-rf6-} } in
756             let {
757               zeze2{-reN-} :: ((a{-reT-}, b{-reS-}) -> (a{-reT-}, b{-reS-})-> PrelBase.Bool{-3c-})
758               zeze2{-reN-} = \ ds{-rf5-} _Ks :: (a{-reT-}, b{-reS-})
759                                ds1{-rf4-} _Ks :: (a{-reT-}, b{-reS-}) ->
760                              case ds{-rf5-}
761                              of wild{-reW-} _Kd { (a1{-rf2-} _Ks, a2{-reZ-} _Ks) ->
762                              case ds1{-rf4-}
763                              of wild1{-reX-} _Kd { (b1{-rf1-} _Ks, b2{-reY-} _Ks) ->
764                              PrelBase.zaza{-r4e-}
765                                (zeze1{-rf3-} a1{-rf2-} b1{-rf1-})
766                                (zeze{-rf0-} a2{-reZ-} b2{-reY-})
767                              }
768                              } } in     
769             let {
770               a1{-reR-} :: ((a{-reT-}, b{-reS-})-> (a{-reT-}, b{-reS-})-> PrelBase.Bool{-3c-})
771               a1{-reR-} = \ a2{-reV-} _Ks :: (a{-reT-}, b{-reS-})
772                             b1{-reU-} _Ks :: (a{-reT-}, b{-reS-}) ->
773                           PrelBase.not{-r6I-} (zeze2{-reN-} a2{-reV-} b1{-reU-})
774             } in
775               PrelBase.zdwZCDEq{-r8J-} @ (a{-reT-}, b{-reS-}) a1{-reR-} zeze2{-reN-})
776
777 and it's not as bad as it seems, because it's further dramatically
778 simplified: only zeze2 is extracted and its body is simplified.
779
780
781 %************************************************************************
782 %*                                                                      *
783 \subsection{Error messages}
784 %*                                                                      *
785 %************************************************************************
786
787 \begin{code}
788 tcAddDeclCtxt decl thing_inside
789   = tcAddSrcLoc (tcdLoc decl)   $
790     tcAddErrCtxt ctxt   $
791     thing_inside
792   where
793      thing = case decl of
794                 ClassDecl {}              -> "class"
795                 TySynonym {}              -> "type synonym"
796                 TyData {tcdND = NewType}  -> "newtype"
797                 TyData {tcdND = DataType} -> "data type"
798
799      ctxt = hsep [ptext SLIT("In the"), text thing, 
800                   ptext SLIT("declaration for"), quotes (ppr (tcdName decl))]
801
802 instDeclCtxt inst_ty = ptext SLIT("In the instance declaration for") <+> quotes doc
803                      where
804                         doc = case inst_ty of
805                                 HsForAllTy _ _ (HsPredTy pred) -> ppr pred
806                                 HsPredTy pred                  -> ppr pred
807                                 other                          -> ppr inst_ty   -- Don't expect this
808 \end{code}
809
810 \begin{code}
811 badGenericInstanceType binds
812   = vcat [ptext SLIT("Illegal type pattern in the generic bindings"),
813           nest 4 (ppr binds)]
814
815 missingGenericInstances missing
816   = ptext SLIT("Missing type patterns for") <+> pprQuotedList missing
817           
818 dupGenericInsts tc_inst_infos
819   = vcat [ptext SLIT("More than one type pattern for a single generic type constructor:"),
820           nest 4 (vcat (map ppr_inst_ty tc_inst_infos)),
821           ptext SLIT("All the type patterns for a generic type constructor must be identical")
822     ]
823   where 
824     ppr_inst_ty (tc,inst) = ppr (simpleInstInfoTy inst)
825
826 methodCtxt     = ptext SLIT("When checking the methods of an instance declaration")
827 superClassCtxt = ptext SLIT("When checking the super-classes of an instance declaration")
828 \end{code}