2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[TcDeriv]{Deriving}
6 Handles @deriving@ clauses on @data@ declarations.
9 module TcDeriv ( tcDeriving ) where
11 #include "HsVersions.h"
13 import HsSyn ( HsBinds(..), MonoBinds(..), TyClDecl(..),
14 collectLocatedMonoBinders )
15 import RdrHsSyn ( RdrNameMonoBinds )
16 import RnHsSyn ( RenamedHsBinds, RenamedMonoBinds, RenamedTyClDecl, RenamedHsPred )
17 import CmdLineOpts ( DynFlag(..), DynFlags )
20 import TcEnv ( tcSetInstEnv, newDFunName, InstInfo(..), pprInstInfo,
21 tcLookupClass, tcLookupTyCon, tcExtendTyVarEnv
23 import TcGenDeriv -- Deriv stuff
24 import InstEnv ( InstEnv, simpleDFunClassTyCon, extendInstEnv )
25 import TcMonoType ( tcHsPred )
26 import TcSimplify ( tcSimplifyThetas )
28 import RnBinds ( rnMethodBinds, rnTopMonoBinds )
29 import RnEnv ( bindLocatedLocalsRn )
30 import RnMonad ( renameDerivedCode, thenRn, mapRn, returnRn )
31 import HscTypes ( DFunId, PersistentRenamerState )
33 import BasicTypes ( Fixity, NewOrData(..) )
34 import Class ( className, classKey, classTyVars, Class )
35 import ErrUtils ( dumpIfSet_dyn, Message )
36 import MkId ( mkDictFunId )
37 import DataCon ( dataConRepArgTys, isNullaryDataCon, isExistentialDataCon )
38 import PrelInfo ( needsDataDeclCtxtClassKeys )
39 import Maybes ( maybeToBool, catMaybes )
40 import Module ( Module )
41 import Name ( Name, getSrcLoc, nameUnique )
42 import RdrName ( RdrName )
44 import TyCon ( tyConTyVars, tyConDataCons, tyConArity, newTyConRep,
45 tyConTheta, maybeTyConSingleCon, isDataTyCon,
46 isEnumerationTyCon, TyCon
48 import TcType ( TcType, ThetaType, mkTyVarTys, mkTyConApp, getClassPredTys_maybe,
49 isUnLiftedType, mkClassPred, tyVarsOfTypes, tcSplitFunTys,
50 tcSplitTyConApp_maybe, tcEqTypes )
51 import Var ( TyVar, tyVarKind )
52 import VarSet ( mkVarSet, subVarSet )
54 import Util ( zipWithEqual, sortLt )
55 import ListSetOps ( removeDups, assoc )
57 import Maybe ( isJust )
59 import FastString ( FastString )
62 %************************************************************************
64 \subsection[TcDeriv-intro]{Introduction to how we do deriving}
66 %************************************************************************
70 data T a b = C1 (Foo a) (Bar b)
75 [NOTE: See end of these comments for what to do with
76 data (C a, D b) => T a b = ...
79 We want to come up with an instance declaration of the form
81 instance (Ping a, Pong b, ...) => Eq (T a b) where
84 It is pretty easy, albeit tedious, to fill in the code "...". The
85 trick is to figure out what the context for the instance decl is,
86 namely @Ping@, @Pong@ and friends.
88 Let's call the context reqd for the T instance of class C at types
89 (a,b, ...) C (T a b). Thus:
91 Eq (T a b) = (Ping a, Pong b, ...)
93 Now we can get a (recursive) equation from the @data@ decl:
95 Eq (T a b) = Eq (Foo a) u Eq (Bar b) -- From C1
96 u Eq (T b a) u Eq Int -- From C2
97 u Eq (T a a) -- From C3
99 Foo and Bar may have explicit instances for @Eq@, in which case we can
100 just substitute for them. Alternatively, either or both may have
101 their @Eq@ instances given by @deriving@ clauses, in which case they
102 form part of the system of equations.
104 Now all we need do is simplify and solve the equations, iterating to
105 find the least fixpoint. Notice that the order of the arguments can
106 switch around, as here in the recursive calls to T.
108 Let's suppose Eq (Foo a) = Eq a, and Eq (Bar b) = Ping b.
112 Eq (T a b) = {} -- The empty set
115 Eq (T a b) = Eq (Foo a) u Eq (Bar b) -- From C1
116 u Eq (T b a) u Eq Int -- From C2
117 u Eq (T a a) -- From C3
119 After simplification:
120 = Eq a u Ping b u {} u {} u {}
125 Eq (T a b) = Eq (Foo a) u Eq (Bar b) -- From C1
126 u Eq (T b a) u Eq Int -- From C2
127 u Eq (T a a) -- From C3
129 After simplification:
134 = Eq a u Ping b u Eq b u Ping a
136 The next iteration gives the same result, so this is the fixpoint. We
137 need to make a canonical form of the RHS to ensure convergence. We do
138 this by simplifying the RHS to a form in which
140 - the classes constrain only tyvars
141 - the list is sorted by tyvar (major key) and then class (minor key)
142 - no duplicates, of course
144 So, here are the synonyms for the ``equation'' structures:
147 type DerivEqn = (Name, Class, TyCon, [TyVar], DerivRhs)
148 -- The Name is the name for the DFun we'll build
149 -- The tyvars bind all the variables in the RHS
151 type DerivRhs = ThetaType
152 type DerivSoln = DerivRhs
156 A note about contexts on data decls
157 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
160 data (RealFloat a) => Complex a = !a :+ !a deriving( Read )
162 We will need an instance decl like:
164 instance (Read a, RealFloat a) => Read (Complex a) where
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
171 But this ain't true for Show, Eq, Ord, etc, since they don't construct
172 a Complex; they only take them apart.
174 Our approach: identify the offending classes, and add the data type
175 context to the instance decl. The "offending classes" are
180 %************************************************************************
182 \subsection[TcDeriv-driver]{Top-level function for \tr{derivings}}
184 %************************************************************************
187 tcDeriving :: PersistentRenamerState
188 -> Module -- name of module under scrutiny
189 -> InstEnv -- What we already know about instances
190 -> (Name -> Maybe Fixity) -- used in deriving Show and Read
191 -> [RenamedTyClDecl] -- All type constructors
192 -> TcM ([InstInfo], -- The generated "instance decls".
193 RenamedHsBinds) -- Extra generated bindings
195 tcDeriving prs mod inst_env get_fixity tycl_decls
196 = recoverTc (returnTc ([], EmptyBinds)) $
197 getDOptsTc `thenNF_Tc` \ dflags ->
199 -- Fish the "deriving"-related information out of the TcEnv
200 -- and make the necessary "equations".
201 makeDerivEqns tycl_decls `thenTc` \ (ordinary_eqns, newtype_inst_info) ->
203 -- Add the newtype-derived instances to the inst env
204 -- before tacking the "ordinary" ones
205 inst_env1 = extend_inst_env dflags inst_env
206 (map iDFunId newtype_inst_info)
208 deriveOrdinaryStuff mod prs inst_env1 get_fixity
209 ordinary_eqns `thenTc` \ (ordinary_inst_info, binds) ->
211 inst_info = newtype_inst_info ++ ordinary_inst_info
214 ioToTc (dumpIfSet_dyn dflags Opt_D_dump_deriv "Derived instances"
215 (ddump_deriving inst_info binds)) `thenTc_`
217 returnTc (inst_info, binds)
220 ddump_deriving :: [InstInfo] -> RenamedHsBinds -> SDoc
221 ddump_deriving inst_infos extra_binds
222 = vcat (map pprInstInfo inst_infos) $$ ppr extra_binds
225 -----------------------------------------
226 deriveOrdinaryStuff mod prs inst_env_in get_fixity [] -- Short cut
227 = returnTc ([], EmptyBinds)
229 deriveOrdinaryStuff mod prs inst_env_in get_fixity eqns
230 = -- Take the equation list and solve it, to deliver a list of
231 -- solutions, a.k.a. the contexts for the instance decls
232 -- required for the corresponding equations.
233 solveDerivEqns inst_env_in eqns `thenTc` \ new_dfuns ->
235 -- Now augment the InstInfos, adding in the rather boring
236 -- actual-code-to-do-the-methods binds. We may also need to
237 -- generate extra not-one-inst-decl-specific binds, notably
238 -- "con2tag" and/or "tag2con" functions. We do these
240 gen_taggery_Names new_dfuns `thenTc` \ nm_alist_etc ->
242 tcGetEnv `thenNF_Tc` \ env ->
243 getDOptsTc `thenNF_Tc` \ dflags ->
245 extra_mbind_list = map gen_tag_n_con_monobind nm_alist_etc
246 extra_mbinds = foldr AndMonoBinds EmptyMonoBinds extra_mbind_list
247 method_binds_s = map (gen_bind get_fixity) new_dfuns
248 mbinders = collectLocatedMonoBinders extra_mbinds
250 -- Rename to get RenamedBinds.
251 -- The only tricky bit is that the extra_binds must scope over the
252 -- method bindings for the instances.
253 (rn_method_binds_s, rn_extra_binds)
254 = renameDerivedCode dflags mod prs (
255 bindLocatedLocalsRn (ptext (SLIT("deriving"))) mbinders $ \ _ ->
256 rnTopMonoBinds extra_mbinds [] `thenRn` \ (rn_extra_binds, _) ->
257 mapRn rn_meths method_binds_s `thenRn` \ rn_method_binds_s ->
258 returnRn (rn_method_binds_s, rn_extra_binds)
260 new_inst_infos = zipWith gen_inst_info new_dfuns rn_method_binds_s
262 returnTc (new_inst_infos, rn_extra_binds)
265 -- Make a Real dfun instead of the dummy one we have so far
266 gen_inst_info :: DFunId -> RenamedMonoBinds -> InstInfo
267 gen_inst_info dfun binds
268 = InstInfo { iDFunId = dfun, iBinds = binds, iPrags = [] }
270 rn_meths (cls, meths) = rnMethodBinds cls [] meths `thenRn` \ (meths', _) ->
271 returnRn meths' -- Ignore the free vars returned
275 %************************************************************************
277 \subsection[TcDeriv-eqns]{Forming the equations}
279 %************************************************************************
281 @makeDerivEqns@ fishes around to find the info about needed derived
282 instances. Complicating factors:
285 We can only derive @Enum@ if the data type is an enumeration
286 type (all nullary data constructors).
289 We can only derive @Ix@ if the data type is an enumeration {\em
290 or} has just one data constructor (e.g., tuples).
293 [See Appendix~E in the Haskell~1.2 report.] This code here deals w/
297 makeDerivEqns :: [RenamedTyClDecl]
298 -> TcM ([DerivEqn], -- Ordinary derivings
299 [InstInfo]) -- Special newtype derivings
301 makeDerivEqns tycl_decls
302 = mapAndUnzipTc mk_eqn derive_these `thenTc` \ (maybe_ordinaries, maybe_newtypes) ->
303 returnTc (catMaybes maybe_ordinaries, catMaybes maybe_newtypes)
305 ------------------------------------------------------------------
306 derive_these :: [(NewOrData, Name, RenamedHsPred)]
307 -- Find the (nd, TyCon, Pred) pairs that must be `derived'
308 -- NB: only source-language decls have deriving, no imported ones do
309 derive_these = [ (nd, tycon, pred)
310 | TyData {tcdND = nd, tcdName = tycon, tcdDerivs = Just preds} <- tycl_decls,
313 ------------------------------------------------------------------
314 mk_eqn :: (NewOrData, Name, RenamedHsPred) -> NF_TcM (Maybe DerivEqn, Maybe InstInfo)
315 -- We swizzle the tyvars and datacons out of the tycon
316 -- to make the rest of the equation
318 mk_eqn (new_or_data, tycon_name, pred)
319 = tcLookupTyCon tycon_name `thenNF_Tc` \ tycon ->
320 tcAddSrcLoc (getSrcLoc tycon) $
321 tcAddErrCtxt (derivCtxt tycon) $
322 tcExtendTyVarEnv (tyConTyVars tycon) $ -- Deriving preds may (now) mention
323 -- the type variables for the type constructor
324 tcHsPred pred `thenTc` \ pred' ->
325 case getClassPredTys_maybe pred' of
326 Nothing -> bale_out (malformedPredErr tycon pred)
327 Just (clas, tys) -> mk_eqn_help new_or_data tycon clas tys
329 ------------------------------------------------------------------
330 mk_eqn_help DataType tycon clas tys
331 | Just err <- chk_out clas tycon tys
332 = bale_out (derivingThingErr clas tys tycon tyvars err)
334 = new_dfun_name clas tycon `thenNF_Tc` \ dfun_name ->
335 returnNF_Tc (Just (dfun_name, clas, tycon, tyvars, constraints), Nothing)
337 tyvars = tyConTyVars tycon
338 data_cons = tyConDataCons tycon
339 constraints = extra_constraints ++
340 [ mkClassPred clas [arg_ty]
341 | data_con <- tyConDataCons tycon,
342 arg_ty <- dataConRepArgTys data_con,
343 -- Use the same type variables
344 -- as the type constructor,
345 -- hence no need to instantiate
346 not (isUnLiftedType arg_ty) -- No constraints for unlifted types?
350 -- "extra_constraints": see notes above about contexts on data decls
351 extra_constraints | offensive_class = tyConTheta tycon
354 offensive_class = classKey clas `elem` needsDataDeclCtxtClassKeys
357 mk_eqn_help NewType tycon clas tys
358 = doptsTc Opt_GlasgowExts `thenTc` \ gla_exts ->
359 if can_derive_via_isomorphism && (gla_exts || standard_instance) then
360 -- Go ahead and use the isomorphism
361 new_dfun_name clas tycon `thenNF_Tc` \ dfun_name ->
362 returnTc (Nothing, Just (NewTypeDerived (mk_dfun dfun_name)))
364 if standard_instance then
365 mk_eqn_help DataType tycon clas [] -- Go via bale-out route
367 bale_out cant_derive_err
369 -- Here is the plan for newtype derivings. We see
370 -- newtype T a1...an = T (t ak...an) deriving (C1...Cm)
371 -- where aj...an do not occur free in t, and the Ci are *partial applications* of
372 -- classes with the last parameter missing
374 -- We generate the instances
375 -- instance Ci (t ak...aj) => Ci (T a1...aj)
376 -- where T a1...aj is the partial application of the LHS of the correct kind
378 -- Running example: newtype T s a = MkT (ST s a) deriving( Monad )
380 kind = tyVarKind (last (classTyVars clas))
381 -- Kind of the thing we want to instance
382 -- e.g. argument kind of Monad, *->*
384 (arg_kinds, _) = tcSplitFunTys kind
385 n_args_to_drop = length arg_kinds
386 -- Want to drop 1 arg from (T s a) and (ST s a)
387 -- to get instance Monad (ST s) => Monad (T s)
389 (tyvars, rep_ty) = newTyConRep tycon
390 maybe_rep_app = tcSplitTyConApp_maybe rep_ty
391 Just (rep_tc, rep_ty_args) = maybe_rep_app
393 n_tyvars_to_keep = tyConArity tycon - n_args_to_drop
394 tyvars_to_drop = drop n_tyvars_to_keep tyvars
395 tyvars_to_keep = take n_tyvars_to_keep tyvars
397 n_args_to_keep = tyConArity rep_tc - n_args_to_drop
398 args_to_drop = drop n_args_to_keep rep_ty_args
399 args_to_keep = take n_args_to_keep rep_ty_args
401 ctxt_pred = mkClassPred clas (tys ++ [mkTyConApp rep_tc args_to_keep])
403 mk_dfun dfun_name = mkDictFunId dfun_name clas tyvars
404 (tys ++ [mkTyConApp tycon (mkTyVarTys tyvars_to_keep)] )
407 -- We can only do this newtype deriving thing if:
408 standard_instance = null tys && classKey clas `elem` derivableClassKeys
410 can_derive_via_isomorphism
411 = not (clas `hasKey` readClassKey) -- Never derive Read,Show this way
412 && not (clas `hasKey` showClassKey)
413 && n_tyvars_to_keep >= 0 -- Well kinded;
414 -- eg not: newtype T = T Int deriving( Monad )
415 && isJust maybe_rep_app -- The rep type is a type constructor app
416 && n_args_to_keep >= 0 -- Well kinded:
417 -- eg not: newtype T a = T Int deriving( Monad )
418 && eta_ok -- Eta reduction works
420 -- Check that eta reduction is OK
421 -- (a) the dropped-off args are identical
422 -- (b) the remaining type args mention
423 -- only the remaining type variables
424 eta_ok = (args_to_drop `tcEqTypes` mkTyVarTys tyvars_to_drop)
425 && (tyVarsOfTypes args_to_keep `subVarSet` mkVarSet tyvars_to_keep)
427 cant_derive_err = derivingThingErr clas tys tycon tyvars_to_keep
428 SLIT("too hard for cunning newtype deriving")
431 bale_out err = addErrTc err `thenNF_Tc_` returnNF_Tc (Nothing, Nothing)
433 ------------------------------------------------------------------
434 chk_out :: Class -> TyCon -> [TcType] -> Maybe FastString
435 chk_out clas tycon tys
436 | not (null tys) = Just non_std_why
437 | not (getUnique clas `elem` derivableClassKeys) = Just non_std_why
438 | clas `hasKey` enumClassKey && not is_enumeration = Just nullary_why
439 | clas `hasKey` boundedClassKey && not is_enumeration_or_single = Just single_nullary_why
440 | clas `hasKey` ixClassKey && not is_enumeration_or_single = Just single_nullary_why
441 | null data_cons = Just no_cons_why
442 | any isExistentialDataCon data_cons = Just existential_why
443 | otherwise = Nothing
445 data_cons = tyConDataCons tycon
446 is_enumeration = isEnumerationTyCon tycon
447 is_single_con = maybeToBool (maybeTyConSingleCon tycon)
448 is_enumeration_or_single = is_enumeration || is_single_con
450 single_nullary_why = SLIT("one constructor data type or type with all nullary constructors expected")
451 nullary_why = SLIT("data type with all nullary constructors expected")
452 no_cons_why = SLIT("type has no data constructors")
453 non_std_why = SLIT("not a derivable class")
454 existential_why = SLIT("it has existentially-quantified constructor(s)")
456 new_dfun_name clas tycon -- Just a simple wrapper
457 = newDFunName clas [mkTyConApp tycon []] (getSrcLoc tycon)
458 -- The type passed to newDFunName is only used to generate
459 -- a suitable string; hence the empty type arg list
462 %************************************************************************
464 \subsection[TcDeriv-fixpoint]{Finding the fixed point of \tr{deriving} equations}
466 %************************************************************************
468 A ``solution'' (to one of the equations) is a list of (k,TyVarTy tv)
469 terms, which is the final correct RHS for the corresponding original
473 Each (k,TyVarTy tv) in a solution constrains only a type
477 The (k,TyVarTy tv) pairs in a solution are canonically
478 ordered by sorting on type varible, tv, (major key) and then class, k,
483 solveDerivEqns :: InstEnv
485 -> TcM [DFunId] -- Solns in same order as eqns.
486 -- This bunch is Absolutely minimal...
488 solveDerivEqns inst_env_in orig_eqns
489 = iterateDeriv initial_solutions
491 -- The initial solutions for the equations claim that each
492 -- instance has an empty context; this solution is certainly
493 -- in canonical form.
494 initial_solutions :: [DerivSoln]
495 initial_solutions = [ [] | _ <- orig_eqns ]
497 ------------------------------------------------------------------
498 -- iterateDeriv calculates the next batch of solutions,
499 -- compares it with the current one; finishes if they are the
500 -- same, otherwise recurses with the new solutions.
501 -- It fails if any iteration fails
502 iterateDeriv :: [DerivSoln] ->TcM [DFunId]
503 iterateDeriv current_solns
504 = checkNoErrsTc (iterateOnce current_solns)
505 `thenTc` \ (new_dfuns, new_solns) ->
506 if (current_solns == new_solns) then
509 iterateDeriv new_solns
511 ------------------------------------------------------------------
512 iterateOnce current_solns
513 = -- Extend the inst info from the explicit instance decls
514 -- with the current set of solutions, giving a
515 getDOptsTc `thenNF_Tc` \ dflags ->
517 new_dfuns = zipWithEqual "add_solns" mk_deriv_dfun orig_eqns current_solns
518 inst_env = extend_inst_env dflags inst_env_in new_dfuns
519 -- the eqns and solns move "in lockstep"; we have the eqns
520 -- because we need the LHS info for addClassInstance.
523 tcSetInstEnv inst_env (
524 listTc [ tcAddSrcLoc (getSrcLoc tc) $
525 tcAddErrCtxt (derivCtxt tc) $
526 tcSimplifyThetas deriv_rhs
527 | (_, _,tc,_,deriv_rhs) <- orig_eqns ]
528 ) `thenTc` \ next_solns ->
530 -- Canonicalise the solutions, so they compare nicely
531 let canonicalised_next_solns = [ sortLt (<) next_soln | next_soln <- next_solns ]
533 returnTc (new_dfuns, canonicalised_next_solns)
537 extend_inst_env dflags inst_env new_dfuns
540 (new_inst_env, _errs) = extendInstEnv dflags inst_env new_dfuns
541 -- Ignore the errors about duplicate instances.
542 -- We don't want repeated error messages
543 -- They'll appear later, when we do the top-level extendInstEnvs
545 mk_deriv_dfun (dfun_name, clas, tycon, tyvars, _) theta
546 = mkDictFunId dfun_name clas tyvars
547 [mkTyConApp tycon (mkTyVarTys tyvars)]
551 %************************************************************************
553 \subsection[TcDeriv-normal-binds]{Bindings for the various classes}
555 %************************************************************************
557 After all the trouble to figure out the required context for the
558 derived instance declarations, all that's left is to chug along to
559 produce them. They will then be shoved into @tcInstDecls2@, which
560 will do all its usual business.
562 There are lots of possibilities for code to generate. Here are
563 various general remarks.
568 We want derived instances of @Eq@ and @Ord@ (both v common) to be
569 ``you-couldn't-do-better-by-hand'' efficient.
572 Deriving @Show@---also pretty common--- should also be reasonable good code.
575 Deriving for the other classes isn't that common or that big a deal.
582 Deriving @Ord@ is done mostly with the 1.3 @compare@ method.
585 Deriving @Eq@ also uses @compare@, if we're deriving @Ord@, too.
588 We {\em normally} generate code only for the non-defaulted methods;
589 there are some exceptions for @Eq@ and (especially) @Ord@...
592 Sometimes we use a @_con2tag_<tycon>@ function, which returns a data
593 constructor's numeric (@Int#@) tag. These are generated by
594 @gen_tag_n_con_binds@, and the heuristic for deciding if one of
595 these is around is given by @hasCon2TagFun@.
597 The examples under the different sections below will make this
601 Much less often (really just for deriving @Ix@), we use a
602 @_tag2con_<tycon>@ function. See the examples.
605 We use the renamer!!! Reason: we're supposed to be
606 producing @RenamedMonoBinds@ for the methods, but that means
607 producing correctly-uniquified code on the fly. This is entirely
608 possible (the @TcM@ monad has a @UniqueSupply@), but it is painful.
609 So, instead, we produce @RdrNameMonoBinds@ then heave 'em through
610 the renamer. What a great hack!
614 -- Generate the method bindings for the required instance
615 -- (paired with class name, as we need that when renaming
617 gen_bind :: (Name -> Maybe Fixity) -> DFunId -> (Name, RdrNameMonoBinds)
618 gen_bind get_fixity dfun
621 cls_nm = className clas
622 (clas, tycon) = simpleDFunClassTyCon dfun
624 binds = assoc "gen_bind:bad derived class" gen_list
625 (nameUnique cls_nm) tycon
627 gen_list = [(eqClassKey, gen_Eq_binds)
628 ,(ordClassKey, gen_Ord_binds)
629 ,(enumClassKey, gen_Enum_binds)
630 ,(boundedClassKey, gen_Bounded_binds)
631 ,(ixClassKey, gen_Ix_binds)
632 ,(showClassKey, gen_Show_binds get_fixity)
633 ,(readClassKey, gen_Read_binds get_fixity)
638 %************************************************************************
640 \subsection[TcDeriv-taggery-Names]{What con2tag/tag2con functions are available?}
642 %************************************************************************
647 con2tag_Foo :: Foo ... -> Int#
648 tag2con_Foo :: Int -> Foo ... -- easier if Int, not Int#
649 maxtag_Foo :: Int -- ditto (NB: not unlifted)
652 We have a @con2tag@ function for a tycon if:
655 We're deriving @Eq@ and the tycon has nullary data constructors.
658 Or: we're deriving @Ord@ (unless single-constructor), @Enum@, @Ix@
662 We have a @tag2con@ function for a tycon if:
665 We're deriving @Enum@, or @Ix@ (enum type only???)
668 If we have a @tag2con@ function, we also generate a @maxtag@ constant.
671 gen_taggery_Names :: [DFunId]
672 -> TcM [(RdrName, -- for an assoc list
673 TyCon, -- related tycon
676 gen_taggery_Names dfuns
677 = foldlTc do_con2tag [] tycons_of_interest `thenTc` \ names_so_far ->
678 foldlTc do_tag2con names_so_far tycons_of_interest
680 all_CTs = map simpleDFunClassTyCon dfuns
681 all_tycons = map snd all_CTs
682 (tycons_of_interest, _) = removeDups compare all_tycons
684 do_con2tag acc_Names tycon
685 | isDataTyCon tycon &&
686 ((we_are_deriving eqClassKey tycon
687 && any isNullaryDataCon (tyConDataCons tycon))
688 || (we_are_deriving ordClassKey tycon
689 && not (maybeToBool (maybeTyConSingleCon tycon)))
690 || (we_are_deriving enumClassKey tycon)
691 || (we_are_deriving ixClassKey tycon))
693 = returnTc ((con2tag_RDR tycon, tycon, GenCon2Tag)
698 do_tag2con acc_Names tycon
699 | isDataTyCon tycon &&
700 (we_are_deriving enumClassKey tycon ||
701 we_are_deriving ixClassKey tycon
702 && isEnumerationTyCon tycon)
703 = returnTc ( (tag2con_RDR tycon, tycon, GenTag2Con)
704 : (maxtag_RDR tycon, tycon, GenMaxTag)
709 we_are_deriving clas_key tycon
710 = is_in_eqns clas_key tycon all_CTs
712 is_in_eqns clas_key tycon [] = False
713 is_in_eqns clas_key tycon ((c,t):cts)
714 = (clas_key == classKey c && tycon == t)
715 || is_in_eqns clas_key tycon cts
719 derivingThingErr clas tys tycon tyvars why
720 = sep [hsep [ptext SLIT("Can't make a derived instance of"), quotes (ppr pred)],
723 pred = mkClassPred clas (tys ++ [mkTyConApp tycon (mkTyVarTys tyvars)])
725 malformedPredErr tycon pred = ptext SLIT("Illegal deriving item") <+> ppr pred
728 = ptext SLIT("When deriving classes for") <+> quotes (ppr tycon)