9c15b24ed1fe1390620828bda44243e1c36477b7
[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(..), collectLocatedMonoBinders )
14 import RdrHsSyn         ( RdrNameMonoBinds )
15 import RnHsSyn          ( RenamedHsBinds, RenamedMonoBinds )
16 import CmdLineOpts      ( DynFlag(..), DynFlags )
17
18 import TcMonad
19 import TcEnv            ( TcEnv, tcSetInstEnv, getTcGST, newDFunName )
20 import TcGenDeriv       -- Deriv stuff
21 import InstEnv          ( InstInfo(..), InstEnv, 
22                           pprInstInfo, simpleDFunClassTyCon, extendInstEnv )
23 import TcSimplify       ( tcSimplifyThetas )
24
25 import RnBinds          ( rnMethodBinds, rnTopMonoBinds )
26 import RnEnv            ( bindLocatedLocalsRn )
27 import RnMonad          ( --RnNameSupply, 
28                           renameSourceCode, thenRn, mapRn, returnRn )
29 import HscTypes         ( DFunId, GlobalSymbolTable, PersistentRenamerState )
30
31 import Bag              ( Bag, emptyBag, unionBags, listToBag )
32 import Class            ( classKey, Class )
33 import ErrUtils         ( dumpIfSet_dyn, Message )
34 import MkId             ( mkDictFunId )
35 import Id               ( mkVanillaId, idType )
36 import DataCon          ( dataConArgTys, isNullaryDataCon, isExistentialDataCon )
37 import PrelInfo         ( needsDataDeclCtxtClassKeys )
38 import Maybes           ( maybeToBool, catMaybes )
39 import Module           ( Module )
40 import Name             ( Name, isLocallyDefined, getSrcLoc, NamedThing(..) )
41 import RdrName          ( RdrName )
42 --import RnMonad                ( FixityEnv )
43
44 import TyCon            ( tyConTyVars, tyConDataCons, tyConDerivings,
45                           tyConTheta, maybeTyConSingleCon, isDataTyCon,
46                           isEnumerationTyCon, isAlgTyCon, TyCon
47                         )
48 import Type             ( TauType, PredType(..), mkTyVarTys, mkTyConApp,
49                           mkSigmaTy, splitSigmaTy, splitDictTy, mkDictTy, 
50                           isUnboxedType, splitAlgTyConApp, classesToPreds
51                         )
52 import TysWiredIn       ( voidTy )
53 import Var              ( TyVar )
54 import PrelNames
55 import Bag              ( bagToList )
56 import Util             ( zipWithEqual, sortLt, thenCmp )
57 import ListSetOps       ( removeDups,  assoc )
58 import Outputable
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 type DerivRhs = [(Class, [TauType])]    -- Same as a ThetaType!
151                 --[PredType]   -- ... | Class Class [Type==TauType]
152
153 type DerivSoln = DerivRhs
154 \end{code}
155
156
157 A note about contexts on data decls
158 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
159 Consider
160
161         data (RealFloat a) => Complex a = !a :+ !a deriving( Read )
162
163 We will need an instance decl like:
164
165         instance (Read a, RealFloat a) => Read (Complex a) where
166           ...
167
168 The RealFloat in the context is because the read method for Complex is bound
169 to construct a Complex, and doing that requires that the argument type is
170 in RealFloat. 
171
172 But this ain't true for Show, Eq, Ord, etc, since they don't construct
173 a Complex; they only take them apart.
174
175 Our approach: identify the offending classes, and add the data type
176 context to the instance decl.  The "offending classes" are
177
178         Read, Enum?
179
180
181 %************************************************************************
182 %*                                                                      *
183 \subsection[TcDeriv-driver]{Top-level function for \tr{derivings}}
184 %*                                                                      *
185 %************************************************************************
186
187 \begin{code}
188 tcDeriving  :: PersistentRenamerState
189             -> Module                   -- name of module under scrutiny
190             -> InstEnv                  -- What we already know about instances
191             -> (Name -> Maybe Fixity)   -- used in deriving Show and Read
192             -> [TyCon]                  -- "local_tycons" ???
193             -> TcM ([InstInfo],         -- The generated "instance decls".
194                     RenamedHsBinds)     -- Extra generated bindings
195
196 tcDeriving prs mod inst_env_in get_fixity local_tycons
197   = recoverTc (returnTc ([], EmptyBinds)) $
198
199         -- Fish the "deriving"-related information out of the TcEnv
200         -- and make the necessary "equations".
201     makeDerivEqns mod local_tycons              `thenTc` \ eqns ->
202     if null eqns then
203         returnTc ([], EmptyBinds)
204     else
205
206         -- Take the equation list and solve it, to deliver a list of
207         -- solutions, a.k.a. the contexts for the instance decls
208         -- required for the corresponding equations.
209     solveDerivEqns inst_env_in eqns             `thenTc` \ new_dfuns ->
210
211         -- Now augment the InstInfos, adding in the rather boring
212         -- actual-code-to-do-the-methods binds.  We may also need to
213         -- generate extra not-one-inst-decl-specific binds, notably
214         -- "con2tag" and/or "tag2con" functions.  We do these
215         -- separately.
216
217     gen_taggery_Names new_dfuns                 `thenTc` \ nm_alist_etc ->
218
219     tcGetEnv                                    `thenNF_Tc` \ env ->
220     getDOptsTc                                  `thenTc` \ dflags ->
221     let
222         extra_mbind_list = map gen_tag_n_con_monobind nm_alist_etc
223         extra_mbinds     = foldr AndMonoBinds EmptyMonoBinds extra_mbind_list
224         method_binds_s   = map (gen_bind get_fixity) new_dfuns
225         mbinders         = collectLocatedMonoBinders extra_mbinds
226         
227         -- Rename to get RenamedBinds.
228         -- The only tricky bit is that the extra_binds must scope over the
229         -- method bindings for the instances.
230         (rn_method_binds_s, rn_extra_binds)
231                 = renameSourceCode dflags mod prs (
232                         bindLocatedLocalsRn (ptext (SLIT("deriving"))) mbinders $ \ _ ->
233                         rnTopMonoBinds extra_mbinds []          `thenRn` \ (rn_extra_binds, _) ->
234                         mapRn rn_meths method_binds_s           `thenRn` \ rn_method_binds_s ->
235                         returnRn (rn_method_binds_s, rn_extra_binds)
236                   )
237
238         new_inst_infos = map gen_inst_info (new_dfuns `zip` rn_method_binds_s)
239     in
240
241     ioToTc (dumpIfSet_dyn dflags Opt_D_dump_deriv "Derived instances" 
242               (ddump_deriving new_inst_infos rn_extra_binds))   `thenTc_`
243
244     returnTc (new_inst_infos, rn_extra_binds)
245   where
246     ddump_deriving :: [InstInfo] -> RenamedHsBinds -> SDoc
247     ddump_deriving inst_infos extra_binds
248       = vcat (map pprInstInfo inst_infos) $$ ppr extra_binds
249       where
250
251         -- Make a Real dfun instead of the dummy one we have so far
252     gen_inst_info :: (DFunId, RenamedMonoBinds) -> InstInfo
253     gen_inst_info (dfun, binds)
254       = InstInfo { iLocal = True,
255                    iClass = clas, iTyVars = tyvars, 
256                    iTys = tys, iTheta = theta, 
257                    iDFunId = dfun, 
258                    iBinds = binds,
259                    iLoc = getSrcLoc dfun, iPrags = [] }
260         where
261          (tyvars, theta, tau) = splitSigmaTy (idType dfun)
262          (clas, tys)          = splitDictTy tau
263
264     rn_meths meths = rnMethodBinds [] meths `thenRn` \ (meths', _) -> returnRn meths'
265         -- Ignore the free vars returned
266 \end{code}
267
268
269 %************************************************************************
270 %*                                                                      *
271 \subsection[TcDeriv-eqns]{Forming the equations}
272 %*                                                                      *
273 %************************************************************************
274
275 @makeDerivEqns@ fishes around to find the info about needed derived
276 instances.  Complicating factors:
277 \begin{itemize}
278 \item
279 We can only derive @Enum@ if the data type is an enumeration
280 type (all nullary data constructors).
281
282 \item
283 We can only derive @Ix@ if the data type is an enumeration {\em
284 or} has just one data constructor (e.g., tuples).
285 \end{itemize}
286
287 [See Appendix~E in the Haskell~1.2 report.] This code here deals w/
288 all those.
289
290 \begin{code}
291 makeDerivEqns :: Module -> [TyCon] -> TcM [DerivEqn]
292
293 makeDerivEqns this_mod local_tycons
294   = let
295         think_about_deriving = need_deriving local_tycons
296         (derive_these, _)    = removeDups cmp_deriv think_about_deriving
297     in
298     if null local_tycons then
299         returnTc []     -- Bale out now
300     else
301     mapTc mk_eqn derive_these `thenTc`  \ maybe_eqns ->
302     returnTc (catMaybes maybe_eqns)
303   where
304     ------------------------------------------------------------------
305     need_deriving :: [TyCon] -> [(Class, TyCon)]
306         -- find the tycons that have `deriving' clauses;
307
308     need_deriving tycons_to_consider
309       = foldr (\ tycon acc -> [(clas,tycon) | clas <- tyConDerivings tycon] ++ acc)
310               []
311               tycons_to_consider
312
313     ------------------------------------------------------------------
314     cmp_deriv :: (Class, TyCon) -> (Class, TyCon) -> Ordering
315     cmp_deriv (c1, t1) (c2, t2)
316       = (c1 `compare` c2) `thenCmp` (t1 `compare` t2)
317
318     ------------------------------------------------------------------
319     mk_eqn :: (Class, TyCon) -> NF_TcM (Maybe DerivEqn)
320         -- we swizzle the tyvars and datacons out of the tycon
321         -- to make the rest of the equation
322
323     mk_eqn (clas, tycon)
324       = case chk_out clas tycon of
325            Just err ->  addErrTc err                            `thenNF_Tc_` 
326                         returnNF_Tc Nothing
327            Nothing  ->  newDFunName this_mod clas tyvar_tys locn `thenNF_Tc` \ dfun_name ->
328                         returnNF_Tc (Just (dfun_name, clas, tycon, tyvars, constraints))
329       where
330         clas_key  = classKey clas
331         tyvars    = tyConTyVars tycon   -- ToDo: Do we need new tyvars ???
332         tyvar_tys = mkTyVarTys tyvars
333         data_cons = tyConDataCons tycon
334         locn      = getSrcLoc tycon
335
336         constraints = extra_constraints ++ concat (map mk_constraints data_cons)
337
338         -- "extra_constraints": see notes above about contexts on data decls
339         extra_constraints
340           | offensive_class = tyConTheta tycon
341           | otherwise       = []
342            where
343             offensive_class = clas_key `elem` needsDataDeclCtxtClassKeys
344
345         mk_constraints data_con
346            = [ (clas, [arg_ty])
347              | arg_ty <- instd_arg_tys,
348                not (isUnboxedType arg_ty)       -- No constraints for unboxed types?
349              ]
350            where
351              instd_arg_tys  = dataConArgTys data_con tyvar_tys
352
353     ------------------------------------------------------------------
354     chk_out :: Class -> TyCon -> Maybe Message
355     chk_out clas tycon
356         | clas `hasKey` enumClassKey    && not is_enumeration         = bog_out nullary_why
357         | clas `hasKey` boundedClassKey && not is_enumeration_or_single = bog_out single_nullary_why
358         | clas `hasKey` ixClassKey      && not is_enumeration_or_single = bog_out single_nullary_why
359         | any isExistentialDataCon (tyConDataCons tycon)              = Just (existentialErr clas tycon)
360         | otherwise                                                   = Nothing
361         where
362             is_enumeration = isEnumerationTyCon tycon
363             is_single_con  = maybeToBool (maybeTyConSingleCon tycon)
364             is_enumeration_or_single = is_enumeration || is_single_con
365
366             single_nullary_why = SLIT("one constructor data type or type with all nullary constructors expected")
367             nullary_why        = SLIT("data type with all nullary constructors expected")
368
369             bog_out why = Just (derivingThingErr clas tycon why)
370 \end{code}
371
372 %************************************************************************
373 %*                                                                      *
374 \subsection[TcDeriv-fixpoint]{Finding the fixed point of \tr{deriving} equations}
375 %*                                                                      *
376 %************************************************************************
377
378 A ``solution'' (to one of the equations) is a list of (k,TyVarTy tv)
379 terms, which is the final correct RHS for the corresponding original
380 equation.
381 \begin{itemize}
382 \item
383 Each (k,TyVarTy tv) in a solution constrains only a type
384 variable, tv.
385
386 \item
387 The (k,TyVarTy tv) pairs in a solution are canonically
388 ordered by sorting on type varible, tv, (major key) and then class, k,
389 (minor key)
390 \end{itemize}
391
392 \begin{code}
393 solveDerivEqns :: InstEnv
394                -> [DerivEqn]
395                -> TcM [DFunId]  -- Solns in same order as eqns.
396                                 -- This bunch is Absolutely minimal...
397
398 solveDerivEqns inst_env_in orig_eqns
399   = iterateDeriv initial_solutions
400   where
401         -- The initial solutions for the equations claim that each
402         -- instance has an empty context; this solution is certainly
403         -- in canonical form.
404     initial_solutions :: [DerivSoln]
405     initial_solutions = [ [] | _ <- orig_eqns ]
406
407     ------------------------------------------------------------------
408         -- iterateDeriv calculates the next batch of solutions,
409         -- compares it with the current one; finishes if they are the
410         -- same, otherwise recurses with the new solutions.
411         -- It fails if any iteration fails
412     iterateDeriv :: [DerivSoln] ->TcM [DFunId]
413     iterateDeriv current_solns
414       = checkNoErrsTc (iterateOnce current_solns)
415                                                 `thenTc` \ (new_dfuns, new_solns) ->
416         if (current_solns == new_solns) then
417             returnTc new_dfuns
418         else
419             iterateDeriv new_solns
420
421     ------------------------------------------------------------------
422     iterateOnce current_solns
423       =     -- Extend the inst info from the explicit instance decls
424             -- with the current set of solutions, giving a
425         getDOptsTc                              `thenTc` \ dflags ->
426         let (new_dfuns, inst_env) =
427                 add_solns dflags inst_env_in orig_eqns current_solns
428         in
429             -- Simplify each RHS
430         tcSetInstEnv inst_env (
431           listTc [ tcAddErrCtxt (derivCtxt tc) $
432                    tcSimplifyThetas deriv_rhs
433                  | (_, _,tc,_,deriv_rhs) <- orig_eqns ]  
434         )                                       `thenTc` \ next_solns ->
435
436             -- Canonicalise the solutions, so they compare nicely
437         let canonicalised_next_solns = [ sortLt (<) next_soln | next_soln <- next_solns ]
438         in
439         returnTc (new_dfuns, canonicalised_next_solns)
440 \end{code}
441
442 \begin{code}
443 add_solns :: DynFlags
444           -> InstEnv                            -- The global, non-derived ones
445           -> [DerivEqn] -> [DerivSoln]
446           -> ([DFunId], InstEnv)
447     -- the eqns and solns move "in lockstep"; we have the eqns
448     -- because we need the LHS info for addClassInstance.
449
450 add_solns dflags inst_env_in eqns solns
451   = (new_dfuns, inst_env)
452     where
453       new_dfuns     = zipWithEqual "add_solns" mk_deriv_dfun eqns solns
454       (inst_env, _) = extendInstEnv dflags inst_env_in new_dfuns
455         -- Ignore the errors about duplicate instances.
456         -- We don't want repeated error messages
457         -- They'll appear later, when we do the top-level extendInstEnvs
458
459       mk_deriv_dfun (dfun_name, clas, tycon, tyvars, _) theta
460         = mkDictFunId dfun_name clas tyvars [mkTyConApp tycon (mkTyVarTys tyvars)] 
461                       (map pair2PredType theta)
462
463       pair2PredType (clas, tautypes) = Class clas tautypes
464 \end{code}
465
466 %************************************************************************
467 %*                                                                      *
468 \subsection[TcDeriv-normal-binds]{Bindings for the various classes}
469 %*                                                                      *
470 %************************************************************************
471
472 After all the trouble to figure out the required context for the
473 derived instance declarations, all that's left is to chug along to
474 produce them.  They will then be shoved into @tcInstDecls2@, which
475 will do all its usual business.
476
477 There are lots of possibilities for code to generate.  Here are
478 various general remarks.
479
480 PRINCIPLES:
481 \begin{itemize}
482 \item
483 We want derived instances of @Eq@ and @Ord@ (both v common) to be
484 ``you-couldn't-do-better-by-hand'' efficient.
485
486 \item
487 Deriving @Show@---also pretty common--- should also be reasonable good code.
488
489 \item
490 Deriving for the other classes isn't that common or that big a deal.
491 \end{itemize}
492
493 PRAGMATICS:
494
495 \begin{itemize}
496 \item
497 Deriving @Ord@ is done mostly with the 1.3 @compare@ method.
498
499 \item
500 Deriving @Eq@ also uses @compare@, if we're deriving @Ord@, too.
501
502 \item
503 We {\em normally} generate code only for the non-defaulted methods;
504 there are some exceptions for @Eq@ and (especially) @Ord@...
505
506 \item
507 Sometimes we use a @_con2tag_<tycon>@ function, which returns a data
508 constructor's numeric (@Int#@) tag.  These are generated by
509 @gen_tag_n_con_binds@, and the heuristic for deciding if one of
510 these is around is given by @hasCon2TagFun@.
511
512 The examples under the different sections below will make this
513 clearer.
514
515 \item
516 Much less often (really just for deriving @Ix@), we use a
517 @_tag2con_<tycon>@ function.  See the examples.
518
519 \item
520 We use the renamer!!!  Reason: we're supposed to be
521 producing @RenamedMonoBinds@ for the methods, but that means
522 producing correctly-uniquified code on the fly.  This is entirely
523 possible (the @TcM@ monad has a @UniqueSupply@), but it is painful.
524 So, instead, we produce @RdrNameMonoBinds@ then heave 'em through
525 the renamer.  What a great hack!
526 \end{itemize}
527
528 \begin{code}
529 -- Generate the method bindings for the required instance
530 -- (paired with class name, as we need that when generating dict
531 --  names.)
532 gen_bind :: (Name -> Maybe Fixity) -> DFunId -> RdrNameMonoBinds
533 gen_bind get_fixity dfun
534   | not (isLocallyDefined tycon) = EmptyMonoBinds
535   | clas `hasKey` showClassKey   = gen_Show_binds get_fixity tycon
536   | clas `hasKey` readClassKey   = gen_Read_binds get_fixity tycon
537   | otherwise
538   = assoc "gen_bind:bad derived class"
539            [(eqClassKey,      gen_Eq_binds)
540            ,(ordClassKey,     gen_Ord_binds)
541            ,(enumClassKey,    gen_Enum_binds)
542            ,(boundedClassKey, gen_Bounded_binds)
543            ,(ixClassKey,      gen_Ix_binds)
544            ]
545            (classKey clas)
546            tycon
547   where
548     (clas, tycon) = simpleDFunClassTyCon dfun
549 \end{code}
550
551
552 %************************************************************************
553 %*                                                                      *
554 \subsection[TcDeriv-taggery-Names]{What con2tag/tag2con functions are available?}
555 %*                                                                      *
556 %************************************************************************
557
558
559 data Foo ... = ...
560
561 con2tag_Foo :: Foo ... -> Int#
562 tag2con_Foo :: Int -> Foo ...   -- easier if Int, not Int#
563 maxtag_Foo  :: Int              -- ditto (NB: not unboxed)
564
565
566 We have a @con2tag@ function for a tycon if:
567 \begin{itemize}
568 \item
569 We're deriving @Eq@ and the tycon has nullary data constructors.
570
571 \item
572 Or: we're deriving @Ord@ (unless single-constructor), @Enum@, @Ix@
573 (enum type only????)
574 \end{itemize}
575
576 We have a @tag2con@ function for a tycon if:
577 \begin{itemize}
578 \item
579 We're deriving @Enum@, or @Ix@ (enum type only???)
580 \end{itemize}
581
582 If we have a @tag2con@ function, we also generate a @maxtag@ constant.
583
584 \begin{code}
585 gen_taggery_Names :: [DFunId]
586                   -> TcM [(RdrName,     -- for an assoc list
587                            TyCon,       -- related tycon
588                            TagThingWanted)]
589
590 gen_taggery_Names dfuns
591   = foldlTc do_con2tag []           tycons_of_interest `thenTc` \ names_so_far ->
592     foldlTc do_tag2con names_so_far tycons_of_interest
593   where
594     all_CTs = map simpleDFunClassTyCon dfuns
595     all_tycons              = map snd all_CTs
596     (tycons_of_interest, _) = removeDups compare all_tycons
597     
598     do_con2tag acc_Names tycon
599       | isDataTyCon tycon &&
600         ((we_are_deriving eqClassKey tycon
601             && any isNullaryDataCon (tyConDataCons tycon))
602          || (we_are_deriving ordClassKey  tycon
603             && not (maybeToBool (maybeTyConSingleCon tycon)))
604          || (we_are_deriving enumClassKey tycon)
605          || (we_are_deriving ixClassKey   tycon))
606         
607       = returnTc ((con2tag_RDR tycon, tycon, GenCon2Tag)
608                    : acc_Names)
609       | otherwise
610       = returnTc acc_Names
611
612     do_tag2con acc_Names tycon
613       | isDataTyCon tycon &&
614          (we_are_deriving enumClassKey tycon ||
615           we_are_deriving ixClassKey   tycon
616           && isEnumerationTyCon tycon)
617       = returnTc ( (tag2con_RDR tycon, tycon, GenTag2Con)
618                  : (maxtag_RDR  tycon, tycon, GenMaxTag)
619                  : acc_Names)
620       | otherwise
621       = returnTc acc_Names
622
623     we_are_deriving clas_key tycon
624       = is_in_eqns clas_key tycon all_CTs
625       where
626         is_in_eqns clas_key tycon [] = False
627         is_in_eqns clas_key tycon ((c,t):cts)
628           =  (clas_key == classKey c && tycon == t)
629           || is_in_eqns clas_key tycon cts
630 \end{code}
631
632 \begin{code}
633 derivingThingErr :: Class -> TyCon -> FAST_STRING -> Message
634
635 derivingThingErr clas tycon why
636   = sep [hsep [ptext SLIT("Can't make a derived instance of"), quotes (ppr clas)],
637          hsep [ptext SLIT("for the type"), quotes (ppr tycon)],
638          parens (ptext why)]
639
640 existentialErr clas tycon
641   = sep [ptext SLIT("Can't derive any instances for type") <+> quotes (ppr tycon),
642          ptext SLIT("because it has existentially-quantified constructor(s)")]
643
644 derivCtxt tycon
645   = ptext SLIT("When deriving classes for") <+> quotes (ppr tycon)
646 \end{code}