[project @ 2002-02-13 14:05:50 by simonpj]
[ghc-hetmet.git] / ghc / compiler / typecheck / TcDeriv.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[TcDeriv]{Deriving}
5
6 Handles @deriving@ clauses on @data@ declarations.
7
8 \begin{code}
9 module TcDeriv ( tcDeriving ) where
10
11 #include "HsVersions.h"
12
13 import HsSyn            ( HsBinds(..), MonoBinds(..), TyClDecl(..),
14                           collectLocatedMonoBinders )
15 import RdrHsSyn         ( RdrNameMonoBinds )
16 import RnHsSyn          ( RenamedHsBinds, RenamedMonoBinds, RenamedTyClDecl, RenamedHsPred )
17 import CmdLineOpts      ( DynFlag(..) )
18
19 import TcMonad
20 import TcEnv            ( tcSetInstEnv, newDFunName, InstInfo(..), pprInstInfo,
21                           tcLookupTyCon, tcExtendTyVarEnv
22                         )
23 import TcGenDeriv       -- Deriv stuff
24 import InstEnv          ( InstEnv, simpleDFunClassTyCon, extendInstEnv )
25 import TcMonoType       ( tcHsPred )
26 import TcSimplify       ( tcSimplifyDeriv )
27
28 import RnBinds          ( rnMethodBinds, rnTopMonoBinds )
29 import RnEnv            ( bindLocatedLocalsRn )
30 import RnMonad          ( renameDerivedCode, thenRn, mapRn, returnRn )
31 import HscTypes         ( DFunId, PersistentRenamerState, FixityEnv )
32
33 import BasicTypes       ( NewOrData(..) )
34 import Class            ( className, classKey, classTyVars, Class )
35 import ErrUtils         ( dumpIfSet_dyn )
36 import MkId             ( mkDictFunId )
37 import DataCon          ( dataConRepArgTys, isNullaryDataCon, isExistentialDataCon )
38 import PrelInfo         ( needsDataDeclCtxtClassKeys )
39 import Maybes           ( maybeToBool, catMaybes )
40 import Module           ( Module )
41 import Name             ( Name, getSrcLoc, nameUnique )
42 import RdrName          ( RdrName )
43
44 import TyCon            ( tyConTyVars, tyConDataCons, tyConArity, newTyConRep,
45                           tyConTheta, maybeTyConSingleCon, isDataTyCon,
46                           isEnumerationTyCon, TyCon
47                         )
48 import TcType           ( TcType, ThetaType, mkTyVarTys, mkTyConApp, getClassPredTys_maybe,
49                           isUnLiftedType, mkClassPred, tyVarsOfTypes, tcSplitFunTys, 
50                           tcSplitTyConApp_maybe, tcEqTypes )
51 import Var              ( TyVar, tyVarKind )
52 import VarSet           ( mkVarSet, subVarSet )
53 import PrelNames
54 import Util             ( zipWithEqual, sortLt )
55 import ListSetOps       ( removeDups,  assoc )
56 import Outputable
57 import Maybe            ( isJust )
58 import FastString       ( FastString )
59 \end{code}
60
61 %************************************************************************
62 %*                                                                      *
63 \subsection[TcDeriv-intro]{Introduction to how we do deriving}
64 %*                                                                      *
65 %************************************************************************
66
67 Consider
68
69         data T a b = C1 (Foo a) (Bar b)
70                    | C2 Int (T b a)
71                    | C3 (T a a)
72                    deriving (Eq)
73
74 [NOTE: See end of these comments for what to do with 
75         data (C a, D b) => T a b = ...
76 ]
77
78 We want to come up with an instance declaration of the form
79
80         instance (Ping a, Pong b, ...) => Eq (T a b) where
81                 x == y = ...
82
83 It is pretty easy, albeit tedious, to fill in the code "...".  The
84 trick is to figure out what the context for the instance decl is,
85 namely @Ping@, @Pong@ and friends.
86
87 Let's call the context reqd for the T instance of class C at types
88 (a,b, ...)  C (T a b).  Thus:
89
90         Eq (T a b) = (Ping a, Pong b, ...)
91
92 Now we can get a (recursive) equation from the @data@ decl:
93
94         Eq (T a b) = Eq (Foo a) u Eq (Bar b)    -- From C1
95                    u Eq (T b a) u Eq Int        -- From C2
96                    u Eq (T a a)                 -- From C3
97
98 Foo and Bar may have explicit instances for @Eq@, in which case we can
99 just substitute for them.  Alternatively, either or both may have
100 their @Eq@ instances given by @deriving@ clauses, in which case they
101 form part of the system of equations.
102
103 Now all we need do is simplify and solve the equations, iterating to
104 find the least fixpoint.  Notice that the order of the arguments can
105 switch around, as here in the recursive calls to T.
106
107 Let's suppose Eq (Foo a) = Eq a, and Eq (Bar b) = Ping b.
108
109 We start with:
110
111         Eq (T a b) = {}         -- The empty set
112
113 Next iteration:
114         Eq (T a b) = Eq (Foo a) u Eq (Bar b)    -- From C1
115                    u Eq (T b a) u Eq Int        -- From C2
116                    u Eq (T a a)                 -- From C3
117
118         After simplification:
119                    = Eq a u Ping b u {} u {} u {}
120                    = Eq a u Ping b
121
122 Next iteration:
123
124         Eq (T a b) = Eq (Foo a) u Eq (Bar b)    -- From C1
125                    u Eq (T b a) u Eq Int        -- From C2
126                    u Eq (T a a)                 -- From C3
127
128         After simplification:
129                    = Eq a u Ping b
130                    u (Eq b u Ping a)
131                    u (Eq a u Ping a)
132
133                    = Eq a u Ping b u Eq b u Ping a
134
135 The next iteration gives the same result, so this is the fixpoint.  We
136 need to make a canonical form of the RHS to ensure convergence.  We do
137 this by simplifying the RHS to a form in which
138
139         - the classes constrain only tyvars
140         - the list is sorted by tyvar (major key) and then class (minor key)
141         - no duplicates, of course
142
143 So, here are the synonyms for the ``equation'' structures:
144
145 \begin{code}
146 type DerivEqn = (Name, Class, TyCon, [TyVar], DerivRhs)
147                 -- The Name is the name for the DFun we'll build
148                 -- The tyvars bind all the variables in the RHS
149
150 pprDerivEqn (n,c,tc,tvs,rhs)
151   = parens (hsep [ppr n, ppr c, ppr tc, ppr tvs] <+> equals <+> ppr rhs)
152
153 type DerivRhs  = ThetaType
154 type DerivSoln = DerivRhs
155 \end{code}
156
157
158 A note about contexts on data decls
159 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
160 Consider
161
162         data (RealFloat a) => Complex a = !a :+ !a deriving( Read )
163
164 We will need an instance decl like:
165
166         instance (Read a, RealFloat a) => Read (Complex a) where
167           ...
168
169 The RealFloat in the context is because the read method for Complex is bound
170 to construct a Complex, and doing that requires that the argument type is
171 in RealFloat. 
172
173 But this ain't true for Show, Eq, Ord, etc, since they don't construct
174 a Complex; they only take them apart.
175
176 Our approach: identify the offending classes, and add the data type
177 context to the instance decl.  The "offending classes" are
178
179         Read, Enum?
180
181
182 %************************************************************************
183 %*                                                                      *
184 \subsection[TcDeriv-driver]{Top-level function for \tr{derivings}}
185 %*                                                                      *
186 %************************************************************************
187
188 \begin{code}
189 tcDeriving  :: PersistentRenamerState
190             -> Module                   -- name of module under scrutiny
191             -> InstEnv                  -- What we already know about instances
192             -> FixityEnv        -- used in deriving Show and Read
193             -> [RenamedTyClDecl]        -- All type constructors
194             -> TcM ([InstInfo],         -- The generated "instance decls".
195                     RenamedHsBinds)     -- Extra generated bindings
196
197 tcDeriving prs mod inst_env get_fixity tycl_decls
198   = recoverTc (returnTc ([], EmptyBinds)) $
199     getDOptsTc                            `thenNF_Tc` \ dflags ->
200
201         -- Fish the "deriving"-related information out of the TcEnv
202         -- and make the necessary "equations".
203     makeDerivEqns tycl_decls                            `thenTc` \ (ordinary_eqns, newtype_inst_info) ->
204     let
205         -- Add the newtype-derived instances to the inst env
206         -- before tacking the "ordinary" ones
207         inst_env1 = extend_inst_env dflags inst_env 
208                                     (map iDFunId newtype_inst_info)
209     in    
210     deriveOrdinaryStuff mod prs inst_env1 get_fixity 
211                         ordinary_eqns                   `thenTc` \ (ordinary_inst_info, binds) ->
212     let
213         inst_info  = newtype_inst_info ++ ordinary_inst_info
214     in
215
216     ioToTc (dumpIfSet_dyn dflags Opt_D_dump_deriv "Derived instances" 
217                           (ddump_deriving inst_info binds))     `thenTc_`
218
219     returnTc (inst_info, binds)
220
221   where
222     ddump_deriving :: [InstInfo] -> RenamedHsBinds -> SDoc
223     ddump_deriving inst_infos extra_binds
224       = vcat (map pprInstInfo inst_infos) $$ ppr extra_binds
225
226
227 -----------------------------------------
228 deriveOrdinaryStuff mod prs inst_env_in get_fixity []   -- Short cut
229   = returnTc ([], EmptyBinds)
230
231 deriveOrdinaryStuff mod prs inst_env_in get_fixity eqns
232   =     -- Take the equation list and solve it, to deliver a list of
233         -- solutions, a.k.a. the contexts for the instance decls
234         -- required for the corresponding equations.
235     solveDerivEqns inst_env_in eqns             `thenTc` \ new_dfuns ->
236
237         -- Now augment the InstInfos, adding in the rather boring
238         -- actual-code-to-do-the-methods binds.  We may also need to
239         -- generate extra not-one-inst-decl-specific binds, notably
240         -- "con2tag" and/or "tag2con" functions.  We do these
241         -- separately.
242     gen_taggery_Names new_dfuns                 `thenTc` \ nm_alist_etc ->
243
244     tcGetEnv                                    `thenNF_Tc` \ env ->
245     getDOptsTc                                  `thenNF_Tc` \ dflags ->
246     let
247         extra_mbind_list = map gen_tag_n_con_monobind nm_alist_etc
248         extra_mbinds     = foldr AndMonoBinds EmptyMonoBinds extra_mbind_list
249         method_binds_s   = map (gen_bind get_fixity) new_dfuns
250         mbinders         = collectLocatedMonoBinders extra_mbinds
251         
252         -- Rename to get RenamedBinds.
253         -- The only tricky bit is that the extra_binds must scope over the
254         -- method bindings for the instances.
255         (rn_method_binds_s, rn_extra_binds)
256                 = renameDerivedCode dflags mod prs (
257                         bindLocatedLocalsRn (ptext (SLIT("deriving"))) mbinders $ \ _ ->
258                         rnTopMonoBinds extra_mbinds []          `thenRn` \ (rn_extra_binds, _) ->
259                         mapRn rn_meths method_binds_s           `thenRn` \ rn_method_binds_s ->
260                         returnRn (rn_method_binds_s, rn_extra_binds)
261                   )
262         new_inst_infos = zipWith gen_inst_info new_dfuns rn_method_binds_s
263     in
264     returnTc (new_inst_infos, rn_extra_binds)
265
266   where
267         -- Make a Real dfun instead of the dummy one we have so far
268     gen_inst_info :: DFunId -> RenamedMonoBinds -> InstInfo
269     gen_inst_info dfun binds
270       = InstInfo { iDFunId = dfun, iBinds = binds, iPrags = [] }
271
272     rn_meths (cls, meths) = rnMethodBinds cls [] meths `thenRn` \ (meths', _) -> 
273                             returnRn meths'     -- Ignore the free vars returned
274 \end{code}
275
276
277 %************************************************************************
278 %*                                                                      *
279 \subsection[TcDeriv-eqns]{Forming the equations}
280 %*                                                                      *
281 %************************************************************************
282
283 @makeDerivEqns@ fishes around to find the info about needed derived
284 instances.  Complicating factors:
285 \begin{itemize}
286 \item
287 We can only derive @Enum@ if the data type is an enumeration
288 type (all nullary data constructors).
289
290 \item
291 We can only derive @Ix@ if the data type is an enumeration {\em
292 or} has just one data constructor (e.g., tuples).
293 \end{itemize}
294
295 [See Appendix~E in the Haskell~1.2 report.] This code here deals w/
296 all those.
297
298 \begin{code}
299 makeDerivEqns :: [RenamedTyClDecl] 
300               -> TcM ([DerivEqn],       -- Ordinary derivings
301                       [InstInfo])       -- Special newtype derivings
302
303 makeDerivEqns tycl_decls
304   = mapAndUnzipTc mk_eqn derive_these           `thenTc` \ (maybe_ordinaries, maybe_newtypes) ->
305     returnTc (catMaybes maybe_ordinaries, catMaybes maybe_newtypes)
306   where
307     ------------------------------------------------------------------
308     derive_these :: [(NewOrData, Name, RenamedHsPred)]
309         -- Find the (nd, TyCon, Pred) pairs that must be `derived'
310         -- NB: only source-language decls have deriving, no imported ones do
311     derive_these = [ (nd, tycon, pred) 
312                    | TyData {tcdND = nd, tcdName = tycon, tcdDerivs = Just preds} <- tycl_decls,
313                      pred <- preds ]
314
315     ------------------------------------------------------------------
316     mk_eqn :: (NewOrData, Name, RenamedHsPred) -> NF_TcM (Maybe DerivEqn, Maybe InstInfo)
317         -- We swizzle the tyvars and datacons out of the tycon
318         -- to make the rest of the equation
319
320     mk_eqn (new_or_data, tycon_name, pred)
321       = tcLookupTyCon tycon_name                `thenNF_Tc` \ tycon ->
322         tcAddSrcLoc (getSrcLoc tycon)           $
323         tcAddErrCtxt (derivCtxt Nothing tycon)  $
324         tcExtendTyVarEnv (tyConTyVars tycon)    $       -- Deriving preds may (now) mention
325                                                         -- the type variables for the type constructor
326         tcHsPred pred                           `thenTc` \ pred' ->
327         case getClassPredTys_maybe pred' of
328            Nothing          -> bale_out (malformedPredErr tycon pred)
329            Just (clas, tys) -> mk_eqn_help new_or_data tycon clas tys
330
331     ------------------------------------------------------------------
332     mk_eqn_help DataType tycon clas tys
333       | Just err <- chk_out clas tycon tys
334       = bale_out (derivingThingErr clas tys tycon tyvars err)
335       | otherwise 
336       = new_dfun_name clas tycon         `thenNF_Tc` \ dfun_name ->
337         returnNF_Tc (Just (dfun_name, clas, tycon, tyvars, constraints), Nothing)
338       where
339         tyvars    = tyConTyVars tycon
340         data_cons = tyConDataCons tycon
341         constraints = extra_constraints ++ 
342                       [ mkClassPred clas [arg_ty] 
343                       | data_con <- tyConDataCons tycon,
344                         arg_ty   <- dataConRepArgTys data_con,  
345                                 -- Use the same type variables
346                                 -- as the type constructor,
347                                 -- hence no need to instantiate
348                         not (isUnLiftedType arg_ty)     -- No constraints for unlifted types?
349                       ]
350
351         
352          -- "extra_constraints": see notes above about contexts on data decls
353         extra_constraints | offensive_class = tyConTheta tycon
354                           | otherwise       = []
355         
356         offensive_class = classKey clas `elem` needsDataDeclCtxtClassKeys
357
358
359     mk_eqn_help NewType tycon clas tys
360       = doptsTc Opt_GlasgowExts                 `thenTc` \ gla_exts ->
361         if can_derive_via_isomorphism && (gla_exts || standard_instance) then
362                 -- Go ahead and use the isomorphism
363            new_dfun_name clas tycon             `thenNF_Tc` \ dfun_name ->
364            returnTc (Nothing, Just (NewTypeDerived (mk_dfun dfun_name)))
365         else
366            if standard_instance then
367                 mk_eqn_help DataType tycon clas []      -- Go via bale-out route
368            else
369                 bale_out cant_derive_err
370       where
371         -- Here is the plan for newtype derivings.  We see
372         --        newtype T a1...an = T (t ak...an) deriving (C1...Cm)
373         -- where aj...an do not occur free in t, and the Ci are *partial applications* of
374         -- classes with the last parameter missing
375         --
376         -- We generate the instances
377         --       instance Ci (t ak...aj) => Ci (T a1...aj)
378         -- where T a1...aj is the partial application of the LHS of the correct kind
379         --
380         -- Running example: newtype T s a = MkT (ST s a) deriving( Monad )
381
382         kind = tyVarKind (last (classTyVars clas))
383                 -- Kind of the thing we want to instance
384                 --   e.g. argument kind of Monad, *->*
385
386         (arg_kinds, _) = tcSplitFunTys kind
387         n_args_to_drop = length arg_kinds       
388                 -- Want to drop 1 arg from (T s a) and (ST s a)
389                 -- to get       instance Monad (ST s) => Monad (T s)
390
391         (tyvars, rep_ty)           = newTyConRep tycon
392         maybe_rep_app              = tcSplitTyConApp_maybe rep_ty       
393         Just (rep_tc, rep_ty_args) = maybe_rep_app
394
395         n_tyvars_to_keep = tyConArity tycon  - n_args_to_drop
396         tyvars_to_drop   = drop n_tyvars_to_keep tyvars
397         tyvars_to_keep   = take n_tyvars_to_keep tyvars
398
399         n_args_to_keep = tyConArity rep_tc - n_args_to_drop
400         args_to_drop   = drop n_args_to_keep rep_ty_args
401         args_to_keep   = take n_args_to_keep rep_ty_args
402
403         ctxt_pred = mkClassPred clas (tys ++ [mkTyConApp rep_tc args_to_keep])
404
405         mk_dfun dfun_name = mkDictFunId dfun_name clas tyvars 
406                                                   (tys ++ [mkTyConApp tycon (mkTyVarTys tyvars_to_keep)] )
407                                                   [ctxt_pred]
408
409         -- We can only do this newtype deriving thing if:
410         standard_instance = null tys && classKey clas `elem` derivableClassKeys
411
412         can_derive_via_isomorphism
413            =  not (clas `hasKey` readClassKey)  -- Never derive Read,Show this way
414            && not (clas `hasKey` showClassKey)
415            && n_tyvars_to_keep >= 0             -- Well kinded; 
416                                                 -- eg not: newtype T = T Int deriving( Monad )
417            && isJust maybe_rep_app              -- The rep type is a type constructor app
418            && n_args_to_keep   >= 0             -- Well kinded: 
419                                                 -- eg not: newtype T a = T Int deriving( Monad )
420            && eta_ok                            -- Eta reduction works
421
422         -- Check that eta reduction is OK
423         --      (a) the dropped-off args are identical
424         --      (b) the remaining type args mention 
425         --          only the remaining type variables
426         eta_ok = (args_to_drop `tcEqTypes` mkTyVarTys tyvars_to_drop)
427               && (tyVarsOfTypes args_to_keep `subVarSet` mkVarSet tyvars_to_keep) 
428
429         cant_derive_err = derivingThingErr clas tys tycon tyvars_to_keep
430                                            SLIT("too hard for cunning newtype deriving")
431
432
433     bale_out err = addErrTc err `thenNF_Tc_` returnNF_Tc (Nothing, Nothing) 
434
435     ------------------------------------------------------------------
436     chk_out :: Class -> TyCon -> [TcType] -> Maybe FastString
437     chk_out clas tycon tys
438         | not (null tys)                                                = Just non_std_why
439         | not (getUnique clas `elem` derivableClassKeys)                = Just non_std_why
440         | clas `hasKey` enumClassKey    && not is_enumeration           = Just nullary_why
441         | clas `hasKey` boundedClassKey && not is_enumeration_or_single = Just single_nullary_why
442         | clas `hasKey` ixClassKey      && not is_enumeration_or_single = Just single_nullary_why
443         | null data_cons                                                = Just no_cons_why
444         | any isExistentialDataCon data_cons                            = Just existential_why     
445         | otherwise                                                     = Nothing
446         where
447             data_cons = tyConDataCons tycon
448             is_enumeration = isEnumerationTyCon tycon
449             is_single_con  = maybeToBool (maybeTyConSingleCon tycon)
450             is_enumeration_or_single = is_enumeration || is_single_con
451
452     single_nullary_why = SLIT("one constructor data type or type with all nullary constructors expected")
453     nullary_why        = SLIT("data type with all nullary constructors expected")
454     no_cons_why        = SLIT("type has no data constructors")
455     non_std_why        = SLIT("not a derivable class")
456     existential_why    = SLIT("it has existentially-quantified constructor(s)")
457
458 new_dfun_name clas tycon        -- Just a simple wrapper
459   = newDFunName clas [mkTyConApp tycon []] (getSrcLoc tycon)
460         -- The type passed to newDFunName is only used to generate
461         -- a suitable string; hence the empty type arg list
462 \end{code}
463
464 %************************************************************************
465 %*                                                                      *
466 \subsection[TcDeriv-fixpoint]{Finding the fixed point of \tr{deriving} equations}
467 %*                                                                      *
468 %************************************************************************
469
470 A ``solution'' (to one of the equations) is a list of (k,TyVarTy tv)
471 terms, which is the final correct RHS for the corresponding original
472 equation.
473 \begin{itemize}
474 \item
475 Each (k,TyVarTy tv) in a solution constrains only a type
476 variable, tv.
477
478 \item
479 The (k,TyVarTy tv) pairs in a solution are canonically
480 ordered by sorting on type varible, tv, (major key) and then class, k,
481 (minor key)
482 \end{itemize}
483
484 \begin{code}
485 solveDerivEqns :: InstEnv
486                -> [DerivEqn]
487                -> TcM [DFunId]  -- Solns in same order as eqns.
488                                 -- This bunch is Absolutely minimal...
489
490 solveDerivEqns inst_env_in orig_eqns
491   = iterateDeriv 1 initial_solutions
492   where
493         -- The initial solutions for the equations claim that each
494         -- instance has an empty context; this solution is certainly
495         -- in canonical form.
496     initial_solutions :: [DerivSoln]
497     initial_solutions = [ [] | _ <- orig_eqns ]
498
499     ------------------------------------------------------------------
500         -- iterateDeriv calculates the next batch of solutions,
501         -- compares it with the current one; finishes if they are the
502         -- same, otherwise recurses with the new solutions.
503         -- It fails if any iteration fails
504     iterateDeriv :: Int -> [DerivSoln] ->TcM [DFunId]
505     iterateDeriv n current_solns
506       | n > 20  -- Looks as if we are in an infinite loop
507                 -- This can happen if we have -fallow-undecidable-instances
508                 -- (See TcSimplify.tcSimplifyDeriv.)
509       = pprPanic "solveDerivEqns: probable loop" 
510                  (vcat (map pprDerivEqn orig_eqns) $$ ppr current_solns)
511       | otherwise
512       = getDOptsTc                              `thenNF_Tc` \ dflags ->
513         let 
514             dfuns    = zipWithEqual "add_solns" mk_deriv_dfun orig_eqns current_solns
515             inst_env = extend_inst_env dflags inst_env_in dfuns
516         in
517         checkNoErrsTc (
518                   -- Extend the inst info from the explicit instance decls
519                   -- with the current set of solutions, and simplify each RHS
520             tcSetInstEnv inst_env $
521             mapTc gen_soln orig_eqns
522         )                               `thenTc` \ new_solns ->
523         if (current_solns == new_solns) then
524             returnTc dfuns
525         else
526             iterateDeriv (n+1) new_solns
527
528     ------------------------------------------------------------------
529
530     gen_soln (_, clas, tc,tyvars,deriv_rhs)
531       = tcAddSrcLoc (getSrcLoc tc)              $
532         tcAddErrCtxt (derivCtxt (Just clas) tc) $
533         tcSimplifyDeriv tyvars deriv_rhs        `thenTc` \ theta ->
534         returnTc (sortLt (<) theta)     -- Canonicalise before returning the soluction
535 \end{code}
536
537 \begin{code}
538 extend_inst_env dflags inst_env new_dfuns
539   = new_inst_env
540   where
541     (new_inst_env, _errs) = extendInstEnv dflags inst_env new_dfuns
542         -- Ignore the errors about duplicate instances.
543         -- We don't want repeated error messages
544         -- They'll appear later, when we do the top-level extendInstEnvs
545
546 mk_deriv_dfun (dfun_name, clas, tycon, tyvars, _) theta
547   = mkDictFunId dfun_name clas tyvars 
548                 [mkTyConApp tycon (mkTyVarTys tyvars)] 
549                 theta
550 \end{code}
551
552 %************************************************************************
553 %*                                                                      *
554 \subsection[TcDeriv-normal-binds]{Bindings for the various classes}
555 %*                                                                      *
556 %************************************************************************
557
558 After all the trouble to figure out the required context for the
559 derived instance declarations, all that's left is to chug along to
560 produce them.  They will then be shoved into @tcInstDecls2@, which
561 will do all its usual business.
562
563 There are lots of possibilities for code to generate.  Here are
564 various general remarks.
565
566 PRINCIPLES:
567 \begin{itemize}
568 \item
569 We want derived instances of @Eq@ and @Ord@ (both v common) to be
570 ``you-couldn't-do-better-by-hand'' efficient.
571
572 \item
573 Deriving @Show@---also pretty common--- should also be reasonable good code.
574
575 \item
576 Deriving for the other classes isn't that common or that big a deal.
577 \end{itemize}
578
579 PRAGMATICS:
580
581 \begin{itemize}
582 \item
583 Deriving @Ord@ is done mostly with the 1.3 @compare@ method.
584
585 \item
586 Deriving @Eq@ also uses @compare@, if we're deriving @Ord@, too.
587
588 \item
589 We {\em normally} generate code only for the non-defaulted methods;
590 there are some exceptions for @Eq@ and (especially) @Ord@...
591
592 \item
593 Sometimes we use a @_con2tag_<tycon>@ function, which returns a data
594 constructor's numeric (@Int#@) tag.  These are generated by
595 @gen_tag_n_con_binds@, and the heuristic for deciding if one of
596 these is around is given by @hasCon2TagFun@.
597
598 The examples under the different sections below will make this
599 clearer.
600
601 \item
602 Much less often (really just for deriving @Ix@), we use a
603 @_tag2con_<tycon>@ function.  See the examples.
604
605 \item
606 We use the renamer!!!  Reason: we're supposed to be
607 producing @RenamedMonoBinds@ for the methods, but that means
608 producing correctly-uniquified code on the fly.  This is entirely
609 possible (the @TcM@ monad has a @UniqueSupply@), but it is painful.
610 So, instead, we produce @RdrNameMonoBinds@ then heave 'em through
611 the renamer.  What a great hack!
612 \end{itemize}
613
614 \begin{code}
615 -- Generate the method bindings for the required instance
616 -- (paired with class name, as we need that when renaming
617 --  the method binds)
618 gen_bind :: FixityEnv -> DFunId -> (Name, RdrNameMonoBinds)
619 gen_bind get_fixity dfun
620   = (cls_nm, binds)
621   where
622     cls_nm        = className clas
623     (clas, tycon) = simpleDFunClassTyCon dfun
624
625     binds = assoc "gen_bind:bad derived class" gen_list 
626                   (nameUnique cls_nm) tycon
627
628     gen_list = [(eqClassKey,      gen_Eq_binds)
629                ,(ordClassKey,     gen_Ord_binds)
630                ,(enumClassKey,    gen_Enum_binds)
631                ,(boundedClassKey, gen_Bounded_binds)
632                ,(ixClassKey,      gen_Ix_binds)
633                ,(showClassKey,    gen_Show_binds get_fixity)
634                ,(readClassKey,    gen_Read_binds get_fixity)
635                ]
636 \end{code}
637
638
639 %************************************************************************
640 %*                                                                      *
641 \subsection[TcDeriv-taggery-Names]{What con2tag/tag2con functions are available?}
642 %*                                                                      *
643 %************************************************************************
644
645
646 data Foo ... = ...
647
648 con2tag_Foo :: Foo ... -> Int#
649 tag2con_Foo :: Int -> Foo ...   -- easier if Int, not Int#
650 maxtag_Foo  :: Int              -- ditto (NB: not unlifted)
651
652
653 We have a @con2tag@ function for a tycon if:
654 \begin{itemize}
655 \item
656 We're deriving @Eq@ and the tycon has nullary data constructors.
657
658 \item
659 Or: we're deriving @Ord@ (unless single-constructor), @Enum@, @Ix@
660 (enum type only????)
661 \end{itemize}
662
663 We have a @tag2con@ function for a tycon if:
664 \begin{itemize}
665 \item
666 We're deriving @Enum@, or @Ix@ (enum type only???)
667 \end{itemize}
668
669 If we have a @tag2con@ function, we also generate a @maxtag@ constant.
670
671 \begin{code}
672 gen_taggery_Names :: [DFunId]
673                   -> TcM [(RdrName,     -- for an assoc list
674                            TyCon,       -- related tycon
675                            TagThingWanted)]
676
677 gen_taggery_Names dfuns
678   = foldlTc do_con2tag []           tycons_of_interest `thenTc` \ names_so_far ->
679     foldlTc do_tag2con names_so_far tycons_of_interest
680   where
681     all_CTs = map simpleDFunClassTyCon dfuns
682     all_tycons              = map snd all_CTs
683     (tycons_of_interest, _) = removeDups compare all_tycons
684     
685     do_con2tag acc_Names tycon
686       | isDataTyCon tycon &&
687         ((we_are_deriving eqClassKey tycon
688             && any isNullaryDataCon (tyConDataCons tycon))
689          || (we_are_deriving ordClassKey  tycon
690             && not (maybeToBool (maybeTyConSingleCon tycon)))
691          || (we_are_deriving enumClassKey tycon)
692          || (we_are_deriving ixClassKey   tycon))
693         
694       = returnTc ((con2tag_RDR tycon, tycon, GenCon2Tag)
695                    : acc_Names)
696       | otherwise
697       = returnTc acc_Names
698
699     do_tag2con acc_Names tycon
700       | isDataTyCon tycon &&
701          (we_are_deriving enumClassKey tycon ||
702           we_are_deriving ixClassKey   tycon
703           && isEnumerationTyCon tycon)
704       = returnTc ( (tag2con_RDR tycon, tycon, GenTag2Con)
705                  : (maxtag_RDR  tycon, tycon, GenMaxTag)
706                  : acc_Names)
707       | otherwise
708       = returnTc acc_Names
709
710     we_are_deriving clas_key tycon
711       = is_in_eqns clas_key tycon all_CTs
712       where
713         is_in_eqns clas_key tycon [] = False
714         is_in_eqns clas_key tycon ((c,t):cts)
715           =  (clas_key == classKey c && tycon == t)
716           || is_in_eqns clas_key tycon cts
717 \end{code}
718
719 \begin{code}
720 derivingThingErr clas tys tycon tyvars why
721   = sep [hsep [ptext SLIT("Can't make a derived instance of"), quotes (ppr pred)],
722          parens (ptext why)]
723   where
724     pred = mkClassPred clas (tys ++ [mkTyConApp tycon (mkTyVarTys tyvars)])
725
726 malformedPredErr tycon pred = ptext SLIT("Illegal deriving item") <+> ppr pred
727
728 derivCtxt :: Maybe Class -> TyCon -> SDoc
729 derivCtxt maybe_cls tycon
730   = ptext SLIT("When deriving") <+> cls <+> ptext SLIT("for type") <+> quotes (ppr tycon)
731   where
732     cls = case maybe_cls of
733             Nothing -> ptext SLIT("instances")
734             Just c  -> ptext SLIT("the") <+> quotes (ppr c) <+> ptext SLIT("instance")
735 \end{code}
736