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