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