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