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(..),
15 import RdrHsSyn ( RdrNameMonoBinds )
16 import RnHsSyn ( RenamedHsBinds, RenamedMonoBinds, RenamedTyClDecl, RenamedHsPred )
17 import CmdLineOpts ( DynFlag(..) )
20 import TcEnv ( tcGetInstEnv, tcSetInstEnv, newDFunName, InstInfo(..), pprInstInfo,
21 pprInstInfoDetails, tcLookupTyCon, tcExtendTyVarEnv
23 import TcGenDeriv -- Deriv stuff
24 import InstEnv ( InstEnv, simpleDFunClassTyCon, extendInstEnv )
25 import TcMonoType ( tcHsPred )
26 import TcSimplify ( tcSimplifyDeriv )
28 import RnBinds ( rnMethodBinds, rnTopMonoBinds )
29 import RnEnv ( bindLocalsFVRn )
30 import TcRnMonad ( thenM, returnM, mapAndUnzipM )
31 import HscTypes ( DFunId )
33 import BasicTypes ( NewOrData(..) )
34 import Class ( className, classKey, classTyVars, Class )
35 import ErrUtils ( dumpIfSet_dyn )
36 import MkId ( mkDictFunId )
37 import DataCon ( dataConRepArgTys, isNullaryDataCon, isExistentialDataCon )
38 import Maybes ( maybeToBool, catMaybes )
39 import Name ( Name, getSrcLoc, nameUnique )
41 import RdrName ( RdrName )
43 import TyCon ( tyConTyVars, tyConDataCons, tyConArity, newTyConRep,
44 tyConTheta, maybeTyConSingleCon, isDataTyCon,
45 isEnumerationTyCon, isRecursiveTyCon, TyCon
47 import TcType ( TcType, ThetaType, mkTyVarTys, mkTyConApp, getClassPredTys_maybe,
48 isUnLiftedType, mkClassPred, tyVarsOfTypes, tcSplitFunTys,
49 tcSplitTyConApp_maybe, tcEqTypes )
50 import Var ( TyVar, tyVarKind )
51 import VarSet ( mkVarSet, subVarSet )
53 import Util ( zipWithEqual, sortLt, notNull )
54 import ListSetOps ( removeDups, assoc )
56 import Maybe ( isJust )
59 %************************************************************************
61 \subsection[TcDeriv-intro]{Introduction to how we do deriving}
63 %************************************************************************
67 data T a b = C1 (Foo a) (Bar b)
72 [NOTE: See end of these comments for what to do with
73 data (C a, D b) => T a b = ...
76 We want to come up with an instance declaration of the form
78 instance (Ping a, Pong b, ...) => Eq (T a b) where
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.
85 Let's call the context reqd for the T instance of class C at types
86 (a,b, ...) C (T a b). Thus:
88 Eq (T a b) = (Ping a, Pong b, ...)
90 Now we can get a (recursive) equation from the @data@ decl:
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
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.
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.
105 Let's suppose Eq (Foo a) = Eq a, and Eq (Bar b) = Ping b.
109 Eq (T a b) = {} -- The empty set
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
116 After simplification:
117 = Eq a u Ping b u {} u {} u {}
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
126 After simplification:
131 = Eq a u Ping b u Eq b u Ping a
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
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
141 So, here are the synonyms for the ``equation'' structures:
144 type DerivEqn = (Name, Class, TyCon, [TyVar], DerivRhs)
145 -- The Name is the name for the DFun we'll build
146 -- The tyvars bind all the variables in the RHS
148 pprDerivEqn (n,c,tc,tvs,rhs)
149 = parens (hsep [ppr n, ppr c, ppr tc, ppr tvs] <+> equals <+> ppr 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
179 FURTHER NOTE ADDED March 2002. In fact, Haskell98 now requires that
180 pattern matching against a constructor from a data type with a context
181 gives rise to the constraints for that context -- or at least the thinned
182 version. So now all classes are "offending".
186 %************************************************************************
188 \subsection[TcDeriv-driver]{Top-level function for \tr{derivings}}
190 %************************************************************************
193 tcDeriving :: [RenamedTyClDecl] -- All type constructors
194 -> TcM ([InstInfo], -- The generated "instance decls".
195 RenamedHsBinds, -- Extra generated bindings
196 FreeVars) -- These are free in the generated bindings
198 tcDeriving tycl_decls
199 = recoverM (returnM ([], EmptyBinds, emptyFVs)) $
200 getDOpts `thenM` \ dflags ->
201 tcGetInstEnv `thenM` \ inst_env ->
203 -- Fish the "deriving"-related information out of the TcEnv
204 -- and make the necessary "equations".
205 makeDerivEqns tycl_decls `thenM` \ (ordinary_eqns, newtype_inst_info) ->
207 -- Add the newtype-derived instances to the inst env
208 -- before tacking the "ordinary" ones
209 inst_env1 = extend_inst_env dflags inst_env
210 (map iDFunId newtype_inst_info)
212 deriveOrdinaryStuff inst_env1 ordinary_eqns `thenM` \ (ordinary_inst_info, binds, fvs) ->
214 inst_info = newtype_inst_info ++ ordinary_inst_info
217 ioToTcRn (dumpIfSet_dyn dflags Opt_D_dump_deriv "Derived instances"
218 (ddump_deriving inst_info binds)) `thenM_`
220 returnM (inst_info, binds, fvs)
223 ddump_deriving :: [InstInfo] -> RenamedHsBinds -> SDoc
224 ddump_deriving inst_infos extra_binds
225 = vcat (map ppr_info inst_infos) $$ ppr extra_binds
227 ppr_info inst_info = pprInstInfo inst_info $$
228 nest 4 (pprInstInfoDetails inst_info)
229 -- pprInstInfo doesn't print much: only the type
231 -----------------------------------------
232 deriveOrdinaryStuff inst_env_in [] -- Short cut
233 = returnM ([], EmptyBinds, emptyFVs)
235 deriveOrdinaryStuff inst_env_in eqns
236 = -- Take the equation list and solve it, to deliver a list of
237 -- solutions, a.k.a. the contexts for the instance decls
238 -- required for the corresponding equations.
239 solveDerivEqns inst_env_in eqns `thenM` \ new_dfuns ->
241 -- Now augment the InstInfos, adding in the rather boring
242 -- actual-code-to-do-the-methods binds. We may also need to
243 -- generate extra not-one-inst-decl-specific binds, notably
244 -- "con2tag" and/or "tag2con" functions. We do these
246 gen_taggery_Names new_dfuns `thenM` \ nm_alist_etc ->
249 extra_mbind_list = map gen_tag_n_con_monobind nm_alist_etc
250 extra_mbinds = foldr AndMonoBinds EmptyMonoBinds extra_mbind_list
251 mbinders = collectMonoBinders extra_mbinds
253 mappM gen_bind new_dfuns `thenM` \ method_binds_s ->
255 traceTc (text "tcDeriv" <+> ppr method_binds_s) `thenM_`
256 getModule `thenM` \ this_mod ->
257 initRn (InterfaceMode this_mod) (
258 -- Rename to get RenamedBinds.
259 -- The only tricky bit is that the extra_binds must scope
260 -- over the method bindings for the instances.
261 bindLocalsFVRn (ptext (SLIT("deriving"))) mbinders $ \ _ ->
262 rnTopMonoBinds extra_mbinds [] `thenM` \ (rn_extra_binds, fvs) ->
263 mapAndUnzipM rn_meths method_binds_s `thenM` \ (rn_method_binds_s, fvs_s) ->
264 returnM ((rn_method_binds_s, rn_extra_binds),
265 fvs `plusFV` plusFVs fvs_s)
266 ) `thenM` \ ((rn_method_binds_s, rn_extra_binds), fvs) ->
268 new_inst_infos = zipWith gen_inst_info new_dfuns rn_method_binds_s
270 returnM (new_inst_infos, rn_extra_binds, fvs)
273 -- Make a Real dfun instead of the dummy one we have so far
274 gen_inst_info :: DFunId -> RenamedMonoBinds -> InstInfo
275 gen_inst_info dfun binds
276 = InstInfo { iDFunId = dfun, iBinds = binds, iPrags = [] }
278 rn_meths (cls, meths) = rnMethodBinds cls [] meths
282 %************************************************************************
284 \subsection[TcDeriv-eqns]{Forming the equations}
286 %************************************************************************
288 @makeDerivEqns@ fishes around to find the info about needed derived
289 instances. Complicating factors:
292 We can only derive @Enum@ if the data type is an enumeration
293 type (all nullary data constructors).
296 We can only derive @Ix@ if the data type is an enumeration {\em
297 or} has just one data constructor (e.g., tuples).
300 [See Appendix~E in the Haskell~1.2 report.] This code here deals w/
304 makeDerivEqns :: [RenamedTyClDecl]
305 -> TcM ([DerivEqn], -- Ordinary derivings
306 [InstInfo]) -- Special newtype derivings
308 makeDerivEqns tycl_decls
309 = mapAndUnzipM mk_eqn derive_these `thenM` \ (maybe_ordinaries, maybe_newtypes) ->
310 returnM (catMaybes maybe_ordinaries, catMaybes maybe_newtypes)
312 ------------------------------------------------------------------
313 derive_these :: [(NewOrData, Name, RenamedHsPred)]
314 -- Find the (nd, TyCon, Pred) pairs that must be `derived'
315 -- NB: only source-language decls have deriving, no imported ones do
316 derive_these = [ (nd, tycon, pred)
317 | TyData {tcdND = nd, tcdName = tycon, tcdDerivs = Just preds} <- tycl_decls,
320 ------------------------------------------------------------------
321 mk_eqn :: (NewOrData, Name, RenamedHsPred) -> TcM (Maybe DerivEqn, Maybe InstInfo)
322 -- We swizzle the tyvars and datacons out of the tycon
323 -- to make the rest of the equation
325 mk_eqn (new_or_data, tycon_name, pred)
326 = tcLookupTyCon tycon_name `thenM` \ tycon ->
327 addSrcLoc (getSrcLoc tycon) $
328 addErrCtxt (derivCtxt Nothing tycon) $
329 tcExtendTyVarEnv (tyConTyVars tycon) $ -- Deriving preds may (now) mention
330 -- the type variables for the type constructor
331 tcHsPred pred `thenM` \ pred' ->
332 case getClassPredTys_maybe pred' of
333 Nothing -> bale_out (malformedPredErr tycon pred)
334 Just (clas, tys) -> mk_eqn_help new_or_data tycon clas tys
336 ------------------------------------------------------------------
337 mk_eqn_help DataType tycon clas tys
338 | Just err <- chk_out clas tycon tys
339 = bale_out (derivingThingErr clas tys tycon tyvars err)
341 = new_dfun_name clas tycon `thenM` \ dfun_name ->
342 returnM (Just (dfun_name, clas, tycon, tyvars, constraints), Nothing)
344 tyvars = tyConTyVars tycon
345 data_cons = tyConDataCons tycon
346 constraints = extra_constraints ++
347 [ mkClassPred clas [arg_ty]
348 | data_con <- tyConDataCons tycon,
349 arg_ty <- dataConRepArgTys data_con,
350 -- Use the same type variables
351 -- as the type constructor,
352 -- hence no need to instantiate
353 not (isUnLiftedType arg_ty) -- No constraints for unlifted types?
356 -- "extra_constraints": see notes above about contexts on data decls
357 extra_constraints = tyConTheta tycon
359 -- | offensive_class = tyConTheta tycon
361 -- offensive_class = classKey clas `elem` PrelInfo.needsDataDeclCtxtClassKeys
364 mk_eqn_help NewType tycon clas tys
365 = doptM Opt_GlasgowExts `thenM` \ gla_exts ->
366 if can_derive_via_isomorphism && (gla_exts || standard_instance) then
367 -- Go ahead and use the isomorphism
368 new_dfun_name clas tycon `thenM` \ dfun_name ->
369 returnM (Nothing, Just (NewTypeDerived (mk_dfun dfun_name)))
371 if standard_instance then
372 mk_eqn_help DataType tycon clas [] -- Go via bale-out route
374 bale_out cant_derive_err
376 -- Here is the plan for newtype derivings. We see
377 -- newtype T a1...an = T (t ak...an) deriving (C1...Cm)
378 -- where aj...an do not occur free in t, and the Ci are *partial applications* of
379 -- classes with the last parameter missing
381 -- We generate the instances
382 -- instance Ci (t ak...aj) => Ci (T a1...aj)
383 -- where T a1...aj is the partial application of the LHS of the correct kind
385 -- Running example: newtype T s a = MkT (ST s a) deriving( Monad )
387 kind = tyVarKind (last (classTyVars clas))
388 -- Kind of the thing we want to instance
389 -- e.g. argument kind of Monad, *->*
391 (arg_kinds, _) = tcSplitFunTys kind
392 n_args_to_drop = length arg_kinds
393 -- Want to drop 1 arg from (T s a) and (ST s a)
394 -- to get instance Monad (ST s) => Monad (T s)
396 (tyvars, rep_ty) = newTyConRep tycon
397 maybe_rep_app = tcSplitTyConApp_maybe rep_ty
398 Just (rep_tc, rep_ty_args) = maybe_rep_app
400 n_tyvars_to_keep = tyConArity tycon - n_args_to_drop
401 tyvars_to_drop = drop n_tyvars_to_keep tyvars
402 tyvars_to_keep = take n_tyvars_to_keep tyvars
404 n_args_to_keep = tyConArity rep_tc - n_args_to_drop
405 args_to_drop = drop n_args_to_keep rep_ty_args
406 args_to_keep = take n_args_to_keep rep_ty_args
408 ctxt_pred = mkClassPred clas (tys ++ [mkTyConApp rep_tc args_to_keep])
410 mk_dfun dfun_name = mkDictFunId dfun_name clas tyvars
411 (tys ++ [mkTyConApp tycon (mkTyVarTys tyvars_to_keep)] )
414 -- We can only do this newtype deriving thing if:
415 standard_instance = null tys && classKey clas `elem` derivableClassKeys
417 can_derive_via_isomorphism
418 = not (clas `hasKey` readClassKey) -- Never derive Read,Show this way
419 && not (clas `hasKey` showClassKey)
420 && n_tyvars_to_keep >= 0 -- Well kinded;
421 -- eg not: newtype T = T Int deriving( Monad )
422 && isJust maybe_rep_app -- The rep type is a type constructor app
423 && n_args_to_keep >= 0 -- Well kinded:
424 -- eg not: newtype T a = T Int deriving( Monad )
425 && eta_ok -- Eta reduction works
426 && not (isRecursiveTyCon tycon) -- Does not work for recursive tycons:
427 -- newtype A = MkA [A]
429 -- instance Eq [A] => Eq A !!
431 -- Check that eta reduction is OK
432 -- (a) the dropped-off args are identical
433 -- (b) the remaining type args mention
434 -- only the remaining type variables
435 eta_ok = (args_to_drop `tcEqTypes` mkTyVarTys tyvars_to_drop)
436 && (tyVarsOfTypes args_to_keep `subVarSet` mkVarSet tyvars_to_keep)
438 cant_derive_err = derivingThingErr clas tys tycon tyvars_to_keep
439 (ptext SLIT("too hard for cunning newtype deriving"))
441 bale_out err = addErrTc err `thenM_` returnM (Nothing, Nothing)
443 ------------------------------------------------------------------
444 chk_out :: Class -> TyCon -> [TcType] -> Maybe SDoc
445 chk_out clas tycon tys
446 | notNull tys = Just non_std_why
447 | not (getUnique clas `elem` derivableClassKeys) = Just non_std_why
448 | clas `hasKey` enumClassKey && not is_enumeration = Just nullary_why
449 | clas `hasKey` boundedClassKey && not is_enumeration_or_single = Just single_nullary_why
450 | clas `hasKey` ixClassKey && not is_enumeration_or_single = Just single_nullary_why
451 | null data_cons = Just no_cons_why
452 | any isExistentialDataCon data_cons = Just existential_why
453 | otherwise = Nothing
455 data_cons = tyConDataCons tycon
456 is_enumeration = isEnumerationTyCon tycon
457 is_single_con = maybeToBool (maybeTyConSingleCon tycon)
458 is_enumeration_or_single = is_enumeration || is_single_con
460 single_nullary_why = ptext SLIT("one constructor data type or type with all nullary constructors expected")
461 nullary_why = ptext SLIT("data type with all nullary constructors expected")
462 no_cons_why = ptext SLIT("type has no data constructors")
463 non_std_why = ptext SLIT("not a derivable class")
464 existential_why = ptext SLIT("it has existentially-quantified constructor(s)")
466 new_dfun_name clas tycon -- Just a simple wrapper
467 = newDFunName clas [mkTyConApp tycon []] (getSrcLoc tycon)
468 -- The type passed to newDFunName is only used to generate
469 -- a suitable string; hence the empty type arg list
472 %************************************************************************
474 \subsection[TcDeriv-fixpoint]{Finding the fixed point of \tr{deriving} equations}
476 %************************************************************************
478 A ``solution'' (to one of the equations) is a list of (k,TyVarTy tv)
479 terms, which is the final correct RHS for the corresponding original
483 Each (k,TyVarTy tv) in a solution constrains only a type
487 The (k,TyVarTy tv) pairs in a solution are canonically
488 ordered by sorting on type varible, tv, (major key) and then class, k,
493 solveDerivEqns :: InstEnv
495 -> TcM [DFunId] -- Solns in same order as eqns.
496 -- This bunch is Absolutely minimal...
498 solveDerivEqns inst_env_in orig_eqns
499 = iterateDeriv 1 initial_solutions
501 -- The initial solutions for the equations claim that each
502 -- instance has an empty context; this solution is certainly
503 -- in canonical form.
504 initial_solutions :: [DerivSoln]
505 initial_solutions = [ [] | _ <- orig_eqns ]
507 ------------------------------------------------------------------
508 -- iterateDeriv calculates the next batch of solutions,
509 -- compares it with the current one; finishes if they are the
510 -- same, otherwise recurses with the new solutions.
511 -- It fails if any iteration fails
512 iterateDeriv :: Int -> [DerivSoln] ->TcM [DFunId]
513 iterateDeriv n current_solns
514 | n > 20 -- Looks as if we are in an infinite loop
515 -- This can happen if we have -fallow-undecidable-instances
516 -- (See TcSimplify.tcSimplifyDeriv.)
517 = pprPanic "solveDerivEqns: probable loop"
518 (vcat (map pprDerivEqn orig_eqns) $$ ppr current_solns)
520 = getDOpts `thenM` \ dflags ->
522 dfuns = zipWithEqual "add_solns" mk_deriv_dfun orig_eqns current_solns
523 inst_env = extend_inst_env dflags inst_env_in dfuns
526 -- Extend the inst info from the explicit instance decls
527 -- with the current set of solutions, and simplify each RHS
528 tcSetInstEnv inst_env $
529 mappM gen_soln orig_eqns
530 ) `thenM` \ new_solns ->
531 if (current_solns == new_solns) then
534 iterateDeriv (n+1) new_solns
536 ------------------------------------------------------------------
538 gen_soln (_, clas, tc,tyvars,deriv_rhs)
539 = addSrcLoc (getSrcLoc tc) $
540 addErrCtxt (derivCtxt (Just clas) tc) $
541 tcSimplifyDeriv tyvars deriv_rhs `thenM` \ theta ->
542 returnM (sortLt (<) theta) -- Canonicalise before returning the soluction
546 extend_inst_env dflags inst_env new_dfuns
549 (new_inst_env, _errs) = extendInstEnv dflags inst_env new_dfuns
550 -- Ignore the errors about duplicate instances.
551 -- We don't want repeated error messages
552 -- They'll appear later, when we do the top-level extendInstEnvs
554 mk_deriv_dfun (dfun_name, clas, tycon, tyvars, _) theta
555 = mkDictFunId dfun_name clas tyvars
556 [mkTyConApp tycon (mkTyVarTys tyvars)]
560 %************************************************************************
562 \subsection[TcDeriv-normal-binds]{Bindings for the various classes}
564 %************************************************************************
566 After all the trouble to figure out the required context for the
567 derived instance declarations, all that's left is to chug along to
568 produce them. They will then be shoved into @tcInstDecls2@, which
569 will do all its usual business.
571 There are lots of possibilities for code to generate. Here are
572 various general remarks.
577 We want derived instances of @Eq@ and @Ord@ (both v common) to be
578 ``you-couldn't-do-better-by-hand'' efficient.
581 Deriving @Show@---also pretty common--- should also be reasonable good code.
584 Deriving for the other classes isn't that common or that big a deal.
591 Deriving @Ord@ is done mostly with the 1.3 @compare@ method.
594 Deriving @Eq@ also uses @compare@, if we're deriving @Ord@, too.
597 We {\em normally} generate code only for the non-defaulted methods;
598 there are some exceptions for @Eq@ and (especially) @Ord@...
601 Sometimes we use a @_con2tag_<tycon>@ function, which returns a data
602 constructor's numeric (@Int#@) tag. These are generated by
603 @gen_tag_n_con_binds@, and the heuristic for deciding if one of
604 these is around is given by @hasCon2TagFun@.
606 The examples under the different sections below will make this
610 Much less often (really just for deriving @Ix@), we use a
611 @_tag2con_<tycon>@ function. See the examples.
614 We use the renamer!!! Reason: we're supposed to be
615 producing @RenamedMonoBinds@ for the methods, but that means
616 producing correctly-uniquified code on the fly. This is entirely
617 possible (the @TcM@ monad has a @UniqueSupply@), but it is painful.
618 So, instead, we produce @RdrNameMonoBinds@ then heave 'em through
619 the renamer. What a great hack!
623 -- Generate the method bindings for the required instance
624 -- (paired with class name, as we need that when renaming
626 gen_bind :: DFunId -> TcM (Name, RdrNameMonoBinds)
628 = getFixityEnv `thenM` \ fix_env ->
629 returnM (cls_nm, gen_binds_fn fix_env cls_nm tycon)
631 cls_nm = className clas
632 (clas, tycon) = simpleDFunClassTyCon dfun
634 gen_binds_fn fix_env cls_nm
635 = assoc "gen_bind:bad derived class"
636 gen_list (nameUnique cls_nm)
638 gen_list = [(eqClassKey, gen_Eq_binds)
639 ,(ordClassKey, gen_Ord_binds)
640 ,(enumClassKey, gen_Enum_binds)
641 ,(boundedClassKey, gen_Bounded_binds)
642 ,(ixClassKey, gen_Ix_binds)
643 ,(showClassKey, gen_Show_binds fix_env)
644 ,(readClassKey, gen_Read_binds fix_env)
649 %************************************************************************
651 \subsection[TcDeriv-taggery-Names]{What con2tag/tag2con functions are available?}
653 %************************************************************************
658 con2tag_Foo :: Foo ... -> Int#
659 tag2con_Foo :: Int -> Foo ... -- easier if Int, not Int#
660 maxtag_Foo :: Int -- ditto (NB: not unlifted)
663 We have a @con2tag@ function for a tycon if:
666 We're deriving @Eq@ and the tycon has nullary data constructors.
669 Or: we're deriving @Ord@ (unless single-constructor), @Enum@, @Ix@
673 We have a @tag2con@ function for a tycon if:
676 We're deriving @Enum@, or @Ix@ (enum type only???)
679 If we have a @tag2con@ function, we also generate a @maxtag@ constant.
682 gen_taggery_Names :: [DFunId]
683 -> TcM [(RdrName, -- for an assoc list
684 TyCon, -- related tycon
687 gen_taggery_Names dfuns
688 = foldlM do_con2tag [] tycons_of_interest `thenM` \ names_so_far ->
689 foldlM do_tag2con names_so_far tycons_of_interest
691 all_CTs = map simpleDFunClassTyCon dfuns
692 all_tycons = map snd all_CTs
693 (tycons_of_interest, _) = removeDups compare all_tycons
695 do_con2tag acc_Names tycon
696 | isDataTyCon tycon &&
697 ((we_are_deriving eqClassKey tycon
698 && any isNullaryDataCon (tyConDataCons tycon))
699 || (we_are_deriving ordClassKey tycon
700 && not (maybeToBool (maybeTyConSingleCon tycon)))
701 || (we_are_deriving enumClassKey tycon)
702 || (we_are_deriving ixClassKey tycon))
704 = returnM ((con2tag_RDR tycon, tycon, GenCon2Tag)
709 do_tag2con acc_Names tycon
710 | isDataTyCon tycon &&
711 (we_are_deriving enumClassKey tycon ||
712 we_are_deriving ixClassKey tycon
713 && isEnumerationTyCon tycon)
714 = returnM ( (tag2con_RDR tycon, tycon, GenTag2Con)
715 : (maxtag_RDR tycon, tycon, GenMaxTag)
720 we_are_deriving clas_key tycon
721 = is_in_eqns clas_key tycon all_CTs
723 is_in_eqns clas_key tycon [] = False
724 is_in_eqns clas_key tycon ((c,t):cts)
725 = (clas_key == classKey c && tycon == t)
726 || is_in_eqns clas_key tycon cts
730 derivingThingErr clas tys tycon tyvars why
731 = sep [hsep [ptext SLIT("Can't make a derived instance of"), quotes (ppr pred)],
734 pred = mkClassPred clas (tys ++ [mkTyConApp tycon (mkTyVarTys tyvars)])
736 malformedPredErr tycon pred = ptext SLIT("Illegal deriving item") <+> ppr pred
738 derivCtxt :: Maybe Class -> TyCon -> SDoc
739 derivCtxt maybe_cls tycon
740 = ptext SLIT("When deriving") <+> cls <+> ptext SLIT("for type") <+> quotes (ppr tycon)
742 cls = case maybe_cls of
743 Nothing -> ptext SLIT("instances")
744 Just c -> ptext SLIT("the") <+> quotes (ppr c) <+> ptext SLIT("instance")