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