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