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