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