[project @ 2000-10-13 14:14:31 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      ( 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, instInfoClass, simpleInstInfoTyCon, buildInstanceEnv )
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 = (Class, TyCon, [TyVar], DerivRhs)
145                          -- The tyvars bind all the variables in the RHS
146                          -- NEW: it's convenient to re-use InstInfo
147                          -- We'll "panic" out some fields...
148
149 type DerivRhs = [(Class, [TauType])]    -- Same as a ThetaType!
150
151 type DerivSoln = DerivRhs
152 \end{code}
153
154
155 A note about contexts on data decls
156 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
157 Consider
158
159         data (RealFloat a) => Complex a = !a :+ !a deriving( Read )
160
161 We will need an instance decl like:
162
163         instance (Read a, RealFloat a) => Read (Complex a) where
164           ...
165
166 The RealFloat in the context is because the read method for Complex is bound
167 to construct a Complex, and doing that requires that the argument type is
168 in RealFloat. 
169
170 But this ain't true for Show, Eq, Ord, etc, since they don't construct
171 a Complex; they only take them apart.
172
173 Our approach: identify the offending classes, and add the data type
174 context to the instance decl.  The "offending classes" are
175
176         Read, Enum?
177
178
179 %************************************************************************
180 %*                                                                      *
181 \subsection[TcDeriv-driver]{Top-level function for \tr{derivings}}
182 %*                                                                      *
183 %************************************************************************
184
185 \begin{code}
186 tcDeriving  :: PersistentRenamerState
187             -> Module                   -- name of module under scrutiny
188             -> Bag InstInfo             -- What we already know about instances
189             -> TcM (Bag InstInfo,       -- The generated "instance decls".
190                       RenamedHsBinds)   -- Extra generated bindings
191
192 tcDeriving prs mod inst_decl_infos_in
193   = recoverTc (returnTc (emptyBag, EmptyBinds)) $
194
195         -- Fish the "deriving"-related information out of the TcEnv
196         -- and make the necessary "equations".
197     makeDerivEqns                               `thenTc` \ eqns ->
198     if null eqns then
199         returnTc (emptyBag, EmptyBinds)
200     else
201
202         -- Take the equation list and solve it, to deliver a list of
203         -- solutions, a.k.a. the contexts for the instance decls
204         -- required for the corresponding equations.
205     solveDerivEqns inst_decl_infos_in eqns      `thenTc` \ new_inst_infos ->
206
207         -- Now augment the InstInfos, adding in the rather boring
208         -- actual-code-to-do-the-methods binds.  We may also need to
209         -- generate extra not-one-inst-decl-specific binds, notably
210         -- "con2tag" and/or "tag2con" functions.  We do these
211         -- separately.
212
213     gen_taggery_Names new_inst_infos            `thenTc` \ nm_alist_etc ->
214
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 (tcGST env)) new_inst_infos
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_inst_infos `zip` rn_method_binds_s)     `thenNF_Tc` \ really_new_inst_infos ->
235
236     ioToTc (dumpIfSet opt_D_dump_deriv "Derived instances" 
237                       (ddump_deriving really_new_inst_infos rn_extra_binds))    `thenTc_`
238
239     returnTc (listToBag really_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         -- Paste the dfun id and method binds into the InstInfo
247     gen_inst_info (InstInfo clas tyvars tys@(ty:_) inst_decl_theta _ _ locn _, meth_binds)
248       = newDFunName mod clas tys locn   `thenNF_Tc` \ dfun_name ->
249         let
250             dfun_id = mkDictFunId dfun_name clas tyvars tys inst_decl_theta
251         in
252         returnNF_Tc (InstInfo clas tyvars tys inst_decl_theta
253                               dfun_id meth_binds locn [])
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 :: TcM [DerivEqn]
283
284 makeDerivEqns
285   = tcGetEnv                        `thenNF_Tc` \ env ->
286     let
287         local_data_tycons = filter (\tc -> isLocallyDefined tc && isAlgTyCon tc)
288                                    (getEnvTyCons env)
289
290         think_about_deriving = need_deriving local_data_tycons
291         (derive_these, _)    = removeDups cmp_deriv think_about_deriving
292     in
293     if null local_data_tycons then
294         returnTc []     -- Bale out now
295     else
296     mapTc mk_eqn derive_these `thenTc`  \ maybe_eqns ->
297     returnTc (catMaybes maybe_eqns)
298   where
299     ------------------------------------------------------------------
300     need_deriving :: [TyCon] -> [(Class, TyCon)]
301         -- find the tycons that have `deriving' clauses;
302
303     need_deriving tycons_to_consider
304       = foldr (\ tycon acc -> [(clas,tycon) | clas <- tyConDerivings tycon] ++ acc)
305               []
306               tycons_to_consider
307
308     ------------------------------------------------------------------
309     cmp_deriv :: (Class, TyCon) -> (Class, TyCon) -> Ordering
310     cmp_deriv (c1, t1) (c2, t2)
311       = (c1 `compare` c2) `thenCmp` (t1 `compare` t2)
312
313     ------------------------------------------------------------------
314     mk_eqn :: (Class, TyCon) -> NF_TcM (Maybe DerivEqn)
315         -- we swizzle the tyvars and datacons out of the tycon
316         -- to make the rest of the equation
317
318     mk_eqn (clas, tycon)
319       = case chk_out clas tycon of
320            Just err ->  addErrTc err    `thenNF_Tc_` 
321                         returnNF_Tc Nothing
322            Nothing  ->  returnNF_Tc (Just (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
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 :: Bag InstInfo
387                -> [DerivEqn]
388                -> TcM [InstInfo]        -- Solns in same order as eqns.
389                                         -- This bunch is Absolutely minimal...
390
391 solveDerivEqns inst_decl_infos_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 [InstInfo]
406     iterateDeriv current_solns
407       = checkNoErrsTc (iterateOnce current_solns)       `thenTc` \ (new_inst_infos, new_solns) ->
408         if (current_solns == new_solns) then
409             returnTc new_inst_infos
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_decl_infos_in orig_eqns current_solns
419                                 `thenNF_Tc` \ (new_inst_infos, inst_env) ->
420
421             -- Simplify each RHS
422
423         tcSetInstEnv inst_env (
424           listTc [ tcAddErrCtxt (derivCtxt tc) $
425                    tcSimplifyThetas deriv_rhs
426                  | (_,tc,_,deriv_rhs) <- orig_eqns ]  
427         )                                               `thenTc` \ next_solns ->
428
429             -- Canonicalise the solutions, so they compare nicely
430         let canonicalised_next_solns
431               = [ sortLt (<) next_soln | next_soln <- next_solns ]
432         in
433         returnTc (new_inst_infos, canonicalised_next_solns)
434 \end{code}
435
436 \begin{code}
437 add_solns :: Bag InstInfo                       -- The global, non-derived ones
438           -> [DerivEqn] -> [DerivSoln]
439           -> NF_TcM ([InstInfo],                -- The new, derived ones
440                        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 inst_infos_in eqns solns
445
446   = discardErrsTc (buildInstanceEnv all_inst_infos)     `thenNF_Tc` \ inst_env ->
447         -- We do the discard-errs so that we don't get repeated error messages
448         -- about duplicate instances.
449         -- They'll appear later, when we do the top-level buildInstanceEnv.
450
451     returnNF_Tc (new_inst_infos, inst_env)
452   where
453     new_inst_infos = zipWithEqual "add_solns" mk_deriv_inst_info eqns solns
454
455     all_inst_infos = inst_infos_in `unionBags` listToBag new_inst_infos
456
457     mk_deriv_inst_info (clas, tycon, tyvars, _) theta
458       = InstInfo clas tyvars [mkTyConApp tycon (mkTyVarTys tyvars)]
459                  theta'
460                  dummy_dfun_id
461                  (my_panic "binds") (getSrcLoc tycon)
462                  (my_panic "upragmas")
463       where
464         dummy_dfun_id
465           = mkVanillaId (getName tycon) dummy_dfun_ty
466                 -- The name is getSrcLoc'd in an error message 
467
468         theta' = classesToPreds theta
469         dummy_dfun_ty = mkSigmaTy tyvars theta' voidTy
470                 -- All we need from the dfun is its "theta" part, used during
471                 -- equation simplification (tcSimplifyThetas).  The final
472                 -- dfun_id will have the superclass dictionaries as arguments too,
473                 -- but that'll be added after the equations are solved.  For now,
474                 -- it's enough just to make a dummy dfun with the simple theta part.
475                 -- 
476                 -- The part after the theta is dummied here as voidTy; actually it's
477                 --      (C (T a b)), but it doesn't seem worth constructing it.
478                 -- We can't leave it as a panic because to get the theta part we
479                 -- have to run down the type!
480
481         my_panic str = panic "add_soln" -- pprPanic ("add_soln:"++str) (hsep [char ':', ppr clas, ppr tycon])
482 \end{code}
483
484 %************************************************************************
485 %*                                                                      *
486 \subsection[TcDeriv-normal-binds]{Bindings for the various classes}
487 %*                                                                      *
488 %************************************************************************
489
490 After all the trouble to figure out the required context for the
491 derived instance declarations, all that's left is to chug along to
492 produce them.  They will then be shoved into @tcInstDecls2@, which
493 will do all its usual business.
494
495 There are lots of possibilities for code to generate.  Here are
496 various general remarks.
497
498 PRINCIPLES:
499 \begin{itemize}
500 \item
501 We want derived instances of @Eq@ and @Ord@ (both v common) to be
502 ``you-couldn't-do-better-by-hand'' efficient.
503
504 \item
505 Deriving @Show@---also pretty common--- should also be reasonable good code.
506
507 \item
508 Deriving for the other classes isn't that common or that big a deal.
509 \end{itemize}
510
511 PRAGMATICS:
512
513 \begin{itemize}
514 \item
515 Deriving @Ord@ is done mostly with the 1.3 @compare@ method.
516
517 \item
518 Deriving @Eq@ also uses @compare@, if we're deriving @Ord@, too.
519
520 \item
521 We {\em normally} generate code only for the non-defaulted methods;
522 there are some exceptions for @Eq@ and (especially) @Ord@...
523
524 \item
525 Sometimes we use a @_con2tag_<tycon>@ function, which returns a data
526 constructor's numeric (@Int#@) tag.  These are generated by
527 @gen_tag_n_con_binds@, and the heuristic for deciding if one of
528 these is around is given by @hasCon2TagFun@.
529
530 The examples under the different sections below will make this
531 clearer.
532
533 \item
534 Much less often (really just for deriving @Ix@), we use a
535 @_tag2con_<tycon>@ function.  See the examples.
536
537 \item
538 We use the renamer!!!  Reason: we're supposed to be
539 producing @RenamedMonoBinds@ for the methods, but that means
540 producing correctly-uniquified code on the fly.  This is entirely
541 possible (the @TcM@ monad has a @UniqueSupply@), but it is painful.
542 So, instead, we produce @RdrNameMonoBinds@ then heave 'em through
543 the renamer.  What a great hack!
544 \end{itemize}
545
546 \begin{code}
547 -- Generate the method bindings for the required instance
548 -- (paired with class name, as we need that when generating dict
549 --  names.)
550 gen_bind :: GlobalSymbolTable -> InstInfo -> RdrNameMonoBinds
551 gen_bind fixities inst
552   | not (isLocallyDefined tycon) = EmptyMonoBinds
553   | clas `hasKey` showClassKey   = gen_Show_binds fixities tycon
554   | clas `hasKey` readClassKey   = gen_Read_binds fixities tycon
555   | otherwise
556   = assoc "gen_bind:bad derived class"
557            [(eqClassKey,      gen_Eq_binds)
558            ,(ordClassKey,     gen_Ord_binds)
559            ,(enumClassKey,    gen_Enum_binds)
560            ,(boundedClassKey, gen_Bounded_binds)
561            ,(ixClassKey,      gen_Ix_binds)
562            ]
563            (classKey clas)
564            tycon
565   where
566       clas  = instInfoClass inst
567       tycon = simpleInstInfoTyCon inst
568 \end{code}
569
570
571 %************************************************************************
572 %*                                                                      *
573 \subsection[TcDeriv-taggery-Names]{What con2tag/tag2con functions are available?}
574 %*                                                                      *
575 %************************************************************************
576
577
578 data Foo ... = ...
579
580 con2tag_Foo :: Foo ... -> Int#
581 tag2con_Foo :: Int -> Foo ...   -- easier if Int, not Int#
582 maxtag_Foo  :: Int              -- ditto (NB: not unboxed)
583
584
585 We have a @con2tag@ function for a tycon if:
586 \begin{itemize}
587 \item
588 We're deriving @Eq@ and the tycon has nullary data constructors.
589
590 \item
591 Or: we're deriving @Ord@ (unless single-constructor), @Enum@, @Ix@
592 (enum type only????)
593 \end{itemize}
594
595 We have a @tag2con@ function for a tycon if:
596 \begin{itemize}
597 \item
598 We're deriving @Enum@, or @Ix@ (enum type only???)
599 \end{itemize}
600
601 If we have a @tag2con@ function, we also generate a @maxtag@ constant.
602
603 \begin{code}
604 gen_taggery_Names :: [InstInfo]
605                   -> TcM [(RdrName,     -- for an assoc list
606                              TyCon,     -- related tycon
607                              TagThingWanted)]
608
609 gen_taggery_Names inst_infos
610   = --pprTrace "gen_taggery:\n" (vcat [hsep [ppr c, ppr t] | (c,t) <- all_CTs]) $
611     foldlTc do_con2tag []           tycons_of_interest `thenTc` \ names_so_far ->
612     foldlTc do_tag2con names_so_far tycons_of_interest
613   where
614     all_CTs = [ (instInfoClass info, simpleInstInfoTyCon info) | info <- inst_infos ]
615                     
616     all_tycons              = map snd all_CTs
617     (tycons_of_interest, _) = removeDups compare all_tycons
618     
619     do_con2tag acc_Names tycon
620       | isDataTyCon tycon &&
621         ((we_are_deriving eqClassKey tycon
622             && any isNullaryDataCon (tyConDataCons tycon))
623          || (we_are_deriving ordClassKey  tycon
624             && not (maybeToBool (maybeTyConSingleCon tycon)))
625          || (we_are_deriving enumClassKey tycon)
626          || (we_are_deriving ixClassKey   tycon))
627         
628       = returnTc ((con2tag_RDR tycon, tycon, GenCon2Tag)
629                    : acc_Names)
630       | otherwise
631       = returnTc acc_Names
632
633     do_tag2con acc_Names tycon
634       | isDataTyCon tycon &&
635          (we_are_deriving enumClassKey tycon ||
636           we_are_deriving ixClassKey   tycon
637           && isEnumerationTyCon tycon)
638       = returnTc ( (tag2con_RDR tycon, tycon, GenTag2Con)
639                  : (maxtag_RDR  tycon, tycon, GenMaxTag)
640                  : acc_Names)
641       | otherwise
642       = returnTc acc_Names
643
644     we_are_deriving clas_key tycon
645       = is_in_eqns clas_key tycon all_CTs
646       where
647         is_in_eqns clas_key tycon [] = False
648         is_in_eqns clas_key tycon ((c,t):cts)
649           =  (clas_key == classKey c && tycon == t)
650           || is_in_eqns clas_key tycon cts
651
652 \end{code}
653
654 \begin{code}
655 derivingThingErr :: Class -> TyCon -> FAST_STRING -> Message
656
657 derivingThingErr clas tycon why
658   = sep [hsep [ptext SLIT("Can't make a derived instance of"), quotes (ppr clas)],
659          hsep [ptext SLIT("for the type"), quotes (ppr tycon)],
660          parens (ptext why)]
661
662 existentialErr clas tycon
663   = sep [ptext SLIT("Can't derive any instances for type") <+> quotes (ppr tycon),
664          ptext SLIT("because it has existentially-quantified constructor(s)")]
665
666 derivCtxt tycon
667   = ptext SLIT("When deriving classes for") <+> quotes (ppr tycon)
668 \end{code}