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