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