[project @ 2000-08-01 09:08:25 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(..), collectMonoBinders )
14 import RdrHsSyn         ( RdrNameMonoBinds )
15 import RnHsSyn          ( RenamedHsBinds, RenamedMonoBinds )
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(..), 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, pprBagOfErrors )
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,
39                           Name, NamedThing(..),
40                           OccName, nameOccName
41                         )
42 import RdrName          ( RdrName )
43 import RnMonad          ( FixityEnv )
44 import SrcLoc           ( mkGeneratedSrcLoc, SrcLoc )
45 import TyCon            ( tyConTyVars, tyConDataCons, tyConDerivings,
46                           tyConTheta, maybeTyConSingleCon, isDataTyCon,
47                           isEnumerationTyCon, isAlgTyCon, TyCon
48                         )
49 import Type             ( TauType, mkTyVarTys, mkTyConApp,
50                           mkSigmaTy, mkDictTy, isUnboxedType,
51                           splitAlgTyConApp, classesToPreds
52                         )
53 import TysWiredIn       ( voidTy )
54 import Var              ( TyVar )
55 import Unique           -- Keys stuff
56 import Bag              ( bagToList )
57 import Util             ( zipWithEqual, sortLt, removeDups,  assoc, thenCmp )
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 = (Class, TyCon, [TyVar], DerivRhs)
147                          -- The tyvars bind all the variables in the RHS
148                          -- NEW: it's convenient to re-use InstInfo
149                          -- We'll "panic" out some fields...
150
151 type DerivRhs = [(Class, [TauType])]    -- Same as a ThetaType!
152
153 type DerivSoln = DerivRhs
154 \end{code}
155
156
157 A note about contexts on data decls
158 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
159 Consider
160
161         data (RealFloat a) => Complex a = !a :+ !a deriving( Read )
162
163 We will need an instance decl like:
164
165         instance (Read a, RealFloat a) => Read (Complex a) where
166           ...
167
168 The RealFloat in the context is because the read method for Complex is bound
169 to construct a Complex, and doing that requires that the argument type is
170 in RealFloat. 
171
172 But this ain't true for Show, Eq, Ord, etc, since they don't construct
173 a Complex; they only take them apart.
174
175 Our approach: identify the offending classes, and add the data type
176 context to the instance decl.  The "offending classes" are
177
178         Read, Enum?
179
180
181 %************************************************************************
182 %*                                                                      *
183 \subsection[TcDeriv-driver]{Top-level function for \tr{derivings}}
184 %*                                                                      *
185 %************************************************************************
186
187 \begin{code}
188 tcDeriving  :: Module                   -- name of module under scrutiny
189             -> FixityEnv                -- for the deriving code (Show/Read.)
190             -> RnNameSupply             -- for "renaming" bits of generated code
191             -> Bag InstInfo             -- What we already know about instances
192             -> TcM s (Bag InstInfo,     -- The generated "instance decls".
193                       RenamedHsBinds)   -- Extra generated bindings
194
195 tcDeriving mod fixs rn_name_supply inst_decl_infos_in
196   = recoverTc (returnTc (emptyBag, EmptyBinds)) $
197
198         -- Fish the "deriving"-related information out of the TcEnv
199         -- and make the necessary "equations".
200     makeDerivEqns                               `thenTc` \ eqns ->
201     if null eqns then
202         returnTc (emptyBag, EmptyBinds)
203     else
204
205         -- Take the equation list and solve it, to deliver a list of
206         -- solutions, a.k.a. the contexts for the instance decls
207         -- required for the corresponding equations.
208     solveDerivEqns inst_decl_infos_in eqns      `thenTc` \ new_inst_infos ->
209
210         -- Now augment the InstInfos, adding in the rather boring
211         -- actual-code-to-do-the-methods binds.  We may also need to
212         -- generate extra not-one-inst-decl-specific binds, notably
213         -- "con2tag" and/or "tag2con" functions.  We do these
214         -- separately.
215
216     gen_taggery_Names new_inst_infos            `thenTc` \ nm_alist_etc ->
217
218
219     let
220         extra_mbind_list = map gen_tag_n_con_monobind nm_alist_etc
221         extra_mbinds     = foldr AndMonoBinds EmptyMonoBinds extra_mbind_list
222         method_binds_s   = map (gen_bind fixs) new_inst_infos
223         mbinders         = bagToList (collectMonoBinders extra_mbinds)
224         
225         -- Rename to get RenamedBinds.
226         -- The only tricky bit is that the extra_binds must scope over the
227         -- method bindings for the instances.
228         (rn_method_binds_s, rn_extra_binds)
229                 = renameSourceCode mod rn_name_supply (
230                         bindLocatedLocalsRn (ptext (SLIT("deriving"))) mbinders $ \ _ ->
231                         rnTopMonoBinds extra_mbinds []          `thenRn` \ (rn_extra_binds, _) ->
232                         mapRn rn_meths method_binds_s           `thenRn` \ rn_method_binds_s ->
233                         returnRn (rn_method_binds_s, rn_extra_binds)
234                   )
235     in
236     mapNF_Tc gen_inst_info (new_inst_infos `zip` rn_method_binds_s)     `thenNF_Tc` \ really_new_inst_infos ->
237
238     ioToTc (dumpIfSet opt_D_dump_deriv "Derived instances" 
239                       (ddump_deriving really_new_inst_infos rn_extra_binds))    `thenTc_`
240
241     returnTc (listToBag really_new_inst_infos, rn_extra_binds)
242   where
243     ddump_deriving :: [InstInfo] -> RenamedHsBinds -> SDoc
244     ddump_deriving inst_infos extra_binds
245       = vcat (map pp_info inst_infos) $$ ppr extra_binds
246       where
247         pp_info (InstInfo clas tvs [ty] inst_decl_theta _ mbinds _ _)
248           = ppr (mkSigmaTy tvs inst_decl_theta' (mkDictTy clas [ty]))
249             $$
250             ppr mbinds
251             where inst_decl_theta' = classesToPreds inst_decl_theta
252
253         -- Paste the dfun id and method binds into the InstInfo
254     gen_inst_info (InstInfo clas tyvars tys@(ty:_) inst_decl_theta _ _ locn _, meth_binds)
255       = newDFunName mod clas tys locn   `thenNF_Tc` \ dfun_name ->
256         let
257             dfun_id = mkDictFunId dfun_name clas tyvars tys inst_decl_theta
258         in
259         returnNF_Tc (InstInfo clas tyvars tys inst_decl_theta
260                               dfun_id meth_binds locn [])
261
262     rn_meths meths = rnMethodBinds meths `thenRn` \ (meths', _) -> returnRn meths'
263         -- Ignore the free vars returned
264 \end{code}
265
266
267 %************************************************************************
268 %*                                                                      *
269 \subsection[TcDeriv-eqns]{Forming the equations}
270 %*                                                                      *
271 %************************************************************************
272
273 @makeDerivEqns@ fishes around to find the info about needed derived
274 instances.  Complicating factors:
275 \begin{itemize}
276 \item
277 We can only derive @Enum@ if the data type is an enumeration
278 type (all nullary data constructors).
279
280 \item
281 We can only derive @Ix@ if the data type is an enumeration {\em
282 or} has just one data constructor (e.g., tuples).
283 \end{itemize}
284
285 [See Appendix~E in the Haskell~1.2 report.] This code here deals w/
286 all those.
287
288 \begin{code}
289 makeDerivEqns :: TcM s [DerivEqn]
290
291 makeDerivEqns
292   = tcGetEnv                        `thenNF_Tc` \ env ->
293     let
294         local_data_tycons = filter (\tc -> isLocallyDefined tc && isAlgTyCon tc)
295                                    (getEnvTyCons env)
296
297         think_about_deriving = need_deriving local_data_tycons
298         (derive_these, _)    = removeDups cmp_deriv think_about_deriving
299     in
300     if null local_data_tycons then
301         returnTc []     -- Bale out now
302     else
303     mapTc mk_eqn derive_these `thenTc`  \ maybe_eqns ->
304     returnTc (catMaybes maybe_eqns)
305   where
306     ------------------------------------------------------------------
307     need_deriving :: [TyCon] -> [(Class, TyCon)]
308         -- find the tycons that have `deriving' clauses;
309
310     need_deriving tycons_to_consider
311       = foldr (\ tycon acc -> [(clas,tycon) | clas <- tyConDerivings tycon] ++ acc)
312               []
313               tycons_to_consider
314
315     ------------------------------------------------------------------
316     cmp_deriv :: (Class, TyCon) -> (Class, TyCon) -> Ordering
317     cmp_deriv (c1, t1) (c2, t2)
318       = (c1 `compare` c2) `thenCmp` (t1 `compare` t2)
319
320     ------------------------------------------------------------------
321     mk_eqn :: (Class, TyCon) -> NF_TcM s (Maybe DerivEqn)
322         -- we swizzle the tyvars and datacons out of the tycon
323         -- to make the rest of the equation
324
325     mk_eqn (clas, tycon)
326       = case chk_out clas tycon of
327            Just err ->  addErrTc err    `thenNF_Tc_` 
328                         returnNF_Tc Nothing
329            Nothing  ->  returnNF_Tc (Just (clas, tycon, tyvars, constraints))
330       where
331         clas_key  = classKey clas
332         tyvars    = tyConTyVars tycon   -- ToDo: Do we need new tyvars ???
333         tyvar_tys = mkTyVarTys tyvars
334         data_cons = tyConDataCons tycon
335
336         constraints = extra_constraints ++ concat (map mk_constraints data_cons)
337
338         -- "extra_constraints": see notes above about contexts on data decls
339         extra_constraints
340           | offensive_class = tyConTheta tycon
341           | otherwise       = []
342            where
343             offensive_class = clas_key `elem` needsDataDeclCtxtClassKeys
344
345         mk_constraints data_con
346            = [ (clas, [arg_ty])
347              | arg_ty <- instd_arg_tys,
348                not (isUnboxedType arg_ty)       -- No constraints for unboxed types?
349              ]
350            where
351              instd_arg_tys  = dataConArgTys data_con tyvar_tys
352
353     ------------------------------------------------------------------
354     chk_out :: Class -> TyCon -> Maybe Message
355     chk_out clas tycon
356         | clas `hasKey` enumClassKey    && not is_enumeration         = bog_out nullary_why
357         | clas `hasKey` boundedClassKey && not is_enumeration_or_single = bog_out single_nullary_why
358         | clas `hasKey` ixClassKey      && not is_enumeration_or_single = bog_out single_nullary_why
359         | any isExistentialDataCon (tyConDataCons tycon)              = Just (existentialErr clas tycon)
360         | otherwise                                                   = Nothing
361         where
362             is_enumeration = isEnumerationTyCon tycon
363             is_single_con  = maybeToBool (maybeTyConSingleCon tycon)
364             is_enumeration_or_single = is_enumeration || is_single_con
365
366             single_nullary_why = SLIT("one constructor data type or type with all nullary constructors expected")
367             nullary_why        = SLIT("data type with all nullary constructors expected")
368
369             bog_out why = Just (derivingThingErr clas tycon why)
370 \end{code}
371
372 %************************************************************************
373 %*                                                                      *
374 \subsection[TcDeriv-fixpoint]{Finding the fixed point of \tr{deriving} equations}
375 %*                                                                      *
376 %************************************************************************
377
378 A ``solution'' (to one of the equations) is a list of (k,TyVarTy tv)
379 terms, which is the final correct RHS for the corresponding original
380 equation.
381 \begin{itemize}
382 \item
383 Each (k,TyVarTy tv) in a solution constrains only a type
384 variable, tv.
385
386 \item
387 The (k,TyVarTy tv) pairs in a solution are canonically
388 ordered by sorting on type varible, tv, (major key) and then class, k,
389 (minor key)
390 \end{itemize}
391
392 \begin{code}
393 solveDerivEqns :: Bag InstInfo
394                -> [DerivEqn]
395                -> TcM s [InstInfo]      -- Solns in same order as eqns.
396                                         -- This bunch is Absolutely minimal...
397
398 solveDerivEqns inst_decl_infos_in orig_eqns
399   = iterateDeriv initial_solutions
400   where
401         -- The initial solutions for the equations claim that each
402         -- instance has an empty context; this solution is certainly
403         -- in canonical form.
404     initial_solutions :: [DerivSoln]
405     initial_solutions = [ [] | _ <- orig_eqns ]
406
407     ------------------------------------------------------------------
408         -- iterateDeriv calculates the next batch of solutions,
409         -- compares it with the current one; finishes if they are the
410         -- same, otherwise recurses with the new solutions.
411         -- It fails if any iteration fails
412     iterateDeriv :: [DerivSoln] ->TcM s [InstInfo]
413     iterateDeriv current_solns
414       = checkNoErrsTc (iterateOnce current_solns)       `thenTc` \ (new_inst_infos, new_solns) ->
415         if (current_solns == new_solns) then
416             returnTc new_inst_infos
417         else
418             iterateDeriv new_solns
419
420     ------------------------------------------------------------------
421     iterateOnce current_solns
422       =     -- Extend the inst info from the explicit instance decls
423             -- with the current set of solutions, giving a
424
425         add_solns inst_decl_infos_in orig_eqns current_solns
426                                 `thenNF_Tc` \ (new_inst_infos, inst_env) ->
427
428             -- Simplify each RHS
429
430         tcSetInstEnv inst_env (
431           listTc [ tcAddErrCtxt (derivCtxt tc) $
432                    tcSimplifyThetas deriv_rhs
433                  | (_,tc,_,deriv_rhs) <- orig_eqns ]  
434         )                                               `thenTc` \ next_solns ->
435
436             -- Canonicalise the solutions, so they compare nicely
437         let canonicalised_next_solns
438               = [ sortLt (<) next_soln | next_soln <- next_solns ]
439         in
440         returnTc (new_inst_infos, canonicalised_next_solns)
441 \end{code}
442
443 \begin{code}
444 add_solns :: Bag InstInfo                       -- The global, non-derived ones
445           -> [DerivEqn] -> [DerivSoln]
446           -> NF_TcM s ([InstInfo],              -- The new, derived ones
447                        InstEnv)
448     -- the eqns and solns move "in lockstep"; we have the eqns
449     -- because we need the LHS info for addClassInstance.
450
451 add_solns inst_infos_in eqns solns
452
453   = discardErrsTc (buildInstanceEnv all_inst_infos)     `thenNF_Tc` \ inst_env ->
454         -- We do the discard-errs so that we don't get repeated error messages
455         -- about duplicate instances.
456         -- They'll appear later, when we do the top-level buildInstanceEnv.
457
458     returnNF_Tc (new_inst_infos, inst_env)
459   where
460     new_inst_infos = zipWithEqual "add_solns" mk_deriv_inst_info eqns solns
461
462     all_inst_infos = inst_infos_in `unionBags` listToBag new_inst_infos
463
464     mk_deriv_inst_info (clas, tycon, tyvars, _) theta
465       = InstInfo clas tyvars [mkTyConApp tycon (mkTyVarTys tyvars)]
466                  theta
467                  dummy_dfun_id
468                  (my_panic "binds") (getSrcLoc tycon)
469                  (my_panic "upragmas")
470       where
471         dummy_dfun_id
472           = mkVanillaId (getName tycon) dummy_dfun_ty
473                 -- The name is getSrcLoc'd in an error message 
474
475         theta' = classesToPreds theta
476         dummy_dfun_ty = mkSigmaTy tyvars theta' voidTy
477                 -- All we need from the dfun is its "theta" part, used during
478                 -- equation simplification (tcSimplifyThetas).  The final
479                 -- dfun_id will have the superclass dictionaries as arguments too,
480                 -- but that'll be added after the equations are solved.  For now,
481                 -- it's enough just to make a dummy dfun with the simple theta part.
482                 -- 
483                 -- The part after the theta is dummied here as voidTy; actually it's
484                 --      (C (T a b)), but it doesn't seem worth constructing it.
485                 -- We can't leave it as a panic because to get the theta part we
486                 -- have to run down the type!
487
488         my_panic str = panic "add_soln" -- pprPanic ("add_soln:"++str) (hsep [char ':', ppr clas, ppr tycon])
489 \end{code}
490
491 %************************************************************************
492 %*                                                                      *
493 \subsection[TcDeriv-normal-binds]{Bindings for the various classes}
494 %*                                                                      *
495 %************************************************************************
496
497 After all the trouble to figure out the required context for the
498 derived instance declarations, all that's left is to chug along to
499 produce them.  They will then be shoved into @tcInstDecls2@, which
500 will do all its usual business.
501
502 There are lots of possibilities for code to generate.  Here are
503 various general remarks.
504
505 PRINCIPLES:
506 \begin{itemize}
507 \item
508 We want derived instances of @Eq@ and @Ord@ (both v common) to be
509 ``you-couldn't-do-better-by-hand'' efficient.
510
511 \item
512 Deriving @Show@---also pretty common--- should also be reasonable good code.
513
514 \item
515 Deriving for the other classes isn't that common or that big a deal.
516 \end{itemize}
517
518 PRAGMATICS:
519
520 \begin{itemize}
521 \item
522 Deriving @Ord@ is done mostly with the 1.3 @compare@ method.
523
524 \item
525 Deriving @Eq@ also uses @compare@, if we're deriving @Ord@, too.
526
527 \item
528 We {\em normally} generate code only for the non-defaulted methods;
529 there are some exceptions for @Eq@ and (especially) @Ord@...
530
531 \item
532 Sometimes we use a @_con2tag_<tycon>@ function, which returns a data
533 constructor's numeric (@Int#@) tag.  These are generated by
534 @gen_tag_n_con_binds@, and the heuristic for deciding if one of
535 these is around is given by @hasCon2TagFun@.
536
537 The examples under the different sections below will make this
538 clearer.
539
540 \item
541 Much less often (really just for deriving @Ix@), we use a
542 @_tag2con_<tycon>@ function.  See the examples.
543
544 \item
545 We use the renamer!!!  Reason: we're supposed to be
546 producing @RenamedMonoBinds@ for the methods, but that means
547 producing correctly-uniquified code on the fly.  This is entirely
548 possible (the @TcM@ monad has a @UniqueSupply@), but it is painful.
549 So, instead, we produce @RdrNameMonoBinds@ then heave 'em through
550 the renamer.  What a great hack!
551 \end{itemize}
552
553 \begin{code}
554 -- Generate the method bindings for the required instance
555 -- (paired with class name, as we need that when generating dict
556 --  names.)
557 gen_bind :: FixityEnv -> InstInfo -> RdrNameMonoBinds
558 gen_bind fixities (InstInfo clas _ [ty] _ _ _ _ _)
559   | not from_here               = EmptyMonoBinds
560   | clas `hasKey` showClassKey  = gen_Show_binds fixities tycon
561   | clas `hasKey` readClassKey  = gen_Read_binds fixities tycon
562   | otherwise
563   = assoc "gen_bind:bad derived class"
564            [(eqClassKey,      gen_Eq_binds)
565            ,(ordClassKey,     gen_Ord_binds)
566            ,(enumClassKey,    gen_Enum_binds)
567            ,(boundedClassKey, gen_Bounded_binds)
568            ,(ixClassKey,      gen_Ix_binds)
569            ]
570            (classKey clas)
571            tycon
572   where
573       from_here   = isLocallyDefined tycon
574       (tycon,_,_) = splitAlgTyConApp ty 
575 \end{code}
576
577
578 %************************************************************************
579 %*                                                                      *
580 \subsection[TcDeriv-taggery-Names]{What con2tag/tag2con functions are available?}
581 %*                                                                      *
582 %************************************************************************
583
584
585 data Foo ... = ...
586
587 con2tag_Foo :: Foo ... -> Int#
588 tag2con_Foo :: Int -> Foo ...   -- easier if Int, not Int#
589 maxtag_Foo  :: Int              -- ditto (NB: not unboxed)
590
591
592 We have a @con2tag@ function for a tycon if:
593 \begin{itemize}
594 \item
595 We're deriving @Eq@ and the tycon has nullary data constructors.
596
597 \item
598 Or: we're deriving @Ord@ (unless single-constructor), @Enum@, @Ix@
599 (enum type only????)
600 \end{itemize}
601
602 We have a @tag2con@ function for a tycon if:
603 \begin{itemize}
604 \item
605 We're deriving @Enum@, or @Ix@ (enum type only???)
606 \end{itemize}
607
608 If we have a @tag2con@ function, we also generate a @maxtag@ constant.
609
610 \begin{code}
611 gen_taggery_Names :: [InstInfo]
612                   -> TcM s [(RdrName,   -- for an assoc list
613                              TyCon,     -- related tycon
614                              TagThingWanted)]
615
616 gen_taggery_Names inst_infos
617   = --pprTrace "gen_taggery:\n" (vcat [hsep [ppr c, ppr t] | (c,t) <- all_CTs]) $
618     foldlTc do_con2tag []           tycons_of_interest `thenTc` \ names_so_far ->
619     foldlTc do_tag2con names_so_far tycons_of_interest
620   where
621     all_CTs = [ (c, get_tycon ty) | (InstInfo c _ [ty] _ _ _ _ _) <- inst_infos ]
622                     
623     get_tycon ty = case splitAlgTyConApp ty of { (tc, _, _) -> tc }
624
625     all_tycons = map snd all_CTs
626     (tycons_of_interest, _) = removeDups compare all_tycons
627     
628     do_con2tag acc_Names tycon
629       | isDataTyCon tycon &&
630         ((we_are_deriving eqClassKey tycon
631             && any isNullaryDataCon (tyConDataCons tycon))
632          || (we_are_deriving ordClassKey  tycon
633             && not (maybeToBool (maybeTyConSingleCon tycon)))
634          || (we_are_deriving enumClassKey tycon)
635          || (we_are_deriving ixClassKey   tycon))
636         
637       = returnTc ((con2tag_RDR tycon, tycon, GenCon2Tag)
638                    : acc_Names)
639       | otherwise
640       = returnTc acc_Names
641
642     do_tag2con acc_Names tycon
643       | isDataTyCon tycon &&
644          (we_are_deriving enumClassKey tycon ||
645           we_are_deriving ixClassKey   tycon
646           && isEnumerationTyCon tycon)
647       = returnTc ( (tag2con_RDR tycon, tycon, GenTag2Con)
648                  : (maxtag_RDR  tycon, tycon, GenMaxTag)
649                  : acc_Names)
650       | otherwise
651       = returnTc acc_Names
652
653     we_are_deriving clas_key tycon
654       = is_in_eqns clas_key tycon all_CTs
655       where
656         is_in_eqns clas_key tycon [] = False
657         is_in_eqns clas_key tycon ((c,t):cts)
658           =  (clas_key == classKey c && tycon == t)
659           || is_in_eqns clas_key tycon cts
660
661 \end{code}
662
663 \begin{code}
664 derivingThingErr :: Class -> TyCon -> FAST_STRING -> Message
665
666 derivingThingErr clas tycon why
667   = sep [hsep [ptext SLIT("Can't make a derived instance of"), quotes (ppr clas)],
668          hsep [ptext SLIT("for the type"), quotes (ppr tycon)],
669          parens (ptext why)]
670
671 existentialErr clas tycon
672   = sep [ptext SLIT("Can't derive any instances for type") <+> quotes (ppr tycon),
673          ptext SLIT("because it has existentially-quantified constructor(s)")]
674
675 derivCtxt tycon
676   = ptext SLIT("When deriving classes for") <+> quotes (ppr tycon)
677 \end{code}