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(..) )
20 import TcEnv ( tcSetInstEnv, newDFunName, InstInfo(..), pprInstInfo,
21 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 ( bindLocatedLocalsRn )
30 import RnMonad ( renameDerivedCode, thenRn, mapRn, returnRn )
31 import HscTypes ( DFunId, PersistentRenamerState, FixityEnv )
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 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 )
58 import FastString ( FastString )
61 %************************************************************************
63 \subsection[TcDeriv-intro]{Introduction to how we do deriving}
65 %************************************************************************
69 data T a b = C1 (Foo a) (Bar b)
74 [NOTE: See end of these comments for what to do with
75 data (C a, D b) => T a b = ...
78 We want to come up with an instance declaration of the form
80 instance (Ping a, Pong b, ...) => Eq (T a b) where
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.
87 Let's call the context reqd for the T instance of class C at types
88 (a,b, ...) C (T a b). Thus:
90 Eq (T a b) = (Ping a, Pong b, ...)
92 Now we can get a (recursive) equation from the @data@ decl:
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
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.
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.
107 Let's suppose Eq (Foo a) = Eq a, and Eq (Bar b) = Ping b.
111 Eq (T a b) = {} -- The empty set
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
118 After simplification:
119 = Eq a u Ping b u {} u {} u {}
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
128 After simplification:
133 = Eq a u Ping b u Eq b u Ping a
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
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
143 So, here are the synonyms for the ``equation'' structures:
146 type DerivEqn = (Name, Class, TyCon, [TyVar], DerivRhs)
147 -- The Name is the name for the DFun we'll build
148 -- The tyvars bind all the variables in the RHS
150 pprDerivEqn (n,c,tc,tvs,rhs)
151 = parens (hsep [ppr n, ppr c, ppr tc, ppr tvs] <+> equals <+> ppr rhs)
153 type DerivRhs = ThetaType
154 type DerivSoln = DerivRhs
158 A note about contexts on data decls
159 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
162 data (RealFloat a) => Complex a = !a :+ !a deriving( Read )
164 We will need an instance decl like:
166 instance (Read a, RealFloat a) => Read (Complex a) where
169 The RealFloat in the context is because the read method for Complex is bound
170 to construct a Complex, and doing that requires that the argument type is
173 But this ain't true for Show, Eq, Ord, etc, since they don't construct
174 a Complex; they only take them apart.
176 Our approach: identify the offending classes, and add the data type
177 context to the instance decl. The "offending classes" are
181 FURTHER NOTE ADDED March 2002. In fact, Haskell98 now requires that
182 pattern matching against a constructor from a data type with a context
183 gives rise to the constraints for that context -- or at least the thinned
184 version. So now all classes are "offending".
188 %************************************************************************
190 \subsection[TcDeriv-driver]{Top-level function for \tr{derivings}}
192 %************************************************************************
195 tcDeriving :: PersistentRenamerState
196 -> Module -- name of module under scrutiny
197 -> InstEnv -- What we already know about instances
198 -> FixityEnv -- used in deriving Show and Read
199 -> [RenamedTyClDecl] -- All type constructors
200 -> TcM ([InstInfo], -- The generated "instance decls".
201 RenamedHsBinds) -- Extra generated bindings
203 tcDeriving prs mod inst_env get_fixity tycl_decls
204 = recoverTc (returnTc ([], EmptyBinds)) $
205 getDOptsTc `thenNF_Tc` \ dflags ->
207 -- Fish the "deriving"-related information out of the TcEnv
208 -- and make the necessary "equations".
209 makeDerivEqns tycl_decls `thenTc` \ (ordinary_eqns, newtype_inst_info) ->
211 -- Add the newtype-derived instances to the inst env
212 -- before tacking the "ordinary" ones
213 inst_env1 = extend_inst_env dflags inst_env
214 (map iDFunId newtype_inst_info)
216 deriveOrdinaryStuff mod prs inst_env1 get_fixity
217 ordinary_eqns `thenTc` \ (ordinary_inst_info, binds) ->
219 inst_info = newtype_inst_info ++ ordinary_inst_info
222 ioToTc (dumpIfSet_dyn dflags Opt_D_dump_deriv "Derived instances"
223 (ddump_deriving inst_info binds)) `thenTc_`
225 returnTc (inst_info, binds)
228 ddump_deriving :: [InstInfo] -> RenamedHsBinds -> SDoc
229 ddump_deriving inst_infos extra_binds
230 = vcat (map pprInstInfo inst_infos) $$ ppr extra_binds
233 -----------------------------------------
234 deriveOrdinaryStuff mod prs inst_env_in get_fixity [] -- Short cut
235 = returnTc ([], EmptyBinds)
237 deriveOrdinaryStuff mod prs inst_env_in get_fixity eqns
238 = -- Take the equation list and solve it, to deliver a list of
239 -- solutions, a.k.a. the contexts for the instance decls
240 -- required for the corresponding equations.
241 solveDerivEqns inst_env_in eqns `thenTc` \ new_dfuns ->
243 -- Now augment the InstInfos, adding in the rather boring
244 -- actual-code-to-do-the-methods binds. We may also need to
245 -- generate extra not-one-inst-decl-specific binds, notably
246 -- "con2tag" and/or "tag2con" functions. We do these
248 gen_taggery_Names new_dfuns `thenTc` \ nm_alist_etc ->
250 tcGetEnv `thenNF_Tc` \ env ->
251 getDOptsTc `thenNF_Tc` \ dflags ->
253 extra_mbind_list = map gen_tag_n_con_monobind nm_alist_etc
254 extra_mbinds = foldr AndMonoBinds EmptyMonoBinds extra_mbind_list
255 method_binds_s = map (gen_bind get_fixity) new_dfuns
256 mbinders = collectLocatedMonoBinders extra_mbinds
258 -- Rename to get RenamedBinds.
259 -- The only tricky bit is that the extra_binds must scope over the
260 -- method bindings for the instances.
261 (rn_method_binds_s, rn_extra_binds)
262 = renameDerivedCode dflags mod prs (
263 bindLocatedLocalsRn (ptext (SLIT("deriving"))) mbinders $ \ _ ->
264 rnTopMonoBinds extra_mbinds [] `thenRn` \ (rn_extra_binds, _) ->
265 mapRn rn_meths method_binds_s `thenRn` \ rn_method_binds_s ->
266 returnRn (rn_method_binds_s, rn_extra_binds)
268 new_inst_infos = zipWith gen_inst_info new_dfuns rn_method_binds_s
270 returnTc (new_inst_infos, rn_extra_binds)
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 `thenRn` \ (meths', _) ->
279 returnRn meths' -- Ignore the free vars returned
283 %************************************************************************
285 \subsection[TcDeriv-eqns]{Forming the equations}
287 %************************************************************************
289 @makeDerivEqns@ fishes around to find the info about needed derived
290 instances. Complicating factors:
293 We can only derive @Enum@ if the data type is an enumeration
294 type (all nullary data constructors).
297 We can only derive @Ix@ if the data type is an enumeration {\em
298 or} has just one data constructor (e.g., tuples).
301 [See Appendix~E in the Haskell~1.2 report.] This code here deals w/
305 makeDerivEqns :: [RenamedTyClDecl]
306 -> TcM ([DerivEqn], -- Ordinary derivings
307 [InstInfo]) -- Special newtype derivings
309 makeDerivEqns tycl_decls
310 = mapAndUnzipTc mk_eqn derive_these `thenTc` \ (maybe_ordinaries, maybe_newtypes) ->
311 returnTc (catMaybes maybe_ordinaries, catMaybes maybe_newtypes)
313 ------------------------------------------------------------------
314 derive_these :: [(NewOrData, Name, RenamedHsPred)]
315 -- Find the (nd, TyCon, Pred) pairs that must be `derived'
316 -- NB: only source-language decls have deriving, no imported ones do
317 derive_these = [ (nd, tycon, pred)
318 | TyData {tcdND = nd, tcdName = tycon, tcdDerivs = Just preds} <- tycl_decls,
321 ------------------------------------------------------------------
322 mk_eqn :: (NewOrData, Name, RenamedHsPred) -> NF_TcM (Maybe DerivEqn, Maybe InstInfo)
323 -- We swizzle the tyvars and datacons out of the tycon
324 -- to make the rest of the equation
326 mk_eqn (new_or_data, tycon_name, pred)
327 = tcLookupTyCon tycon_name `thenNF_Tc` \ tycon ->
328 tcAddSrcLoc (getSrcLoc tycon) $
329 tcAddErrCtxt (derivCtxt Nothing tycon) $
330 tcExtendTyVarEnv (tyConTyVars tycon) $ -- Deriving preds may (now) mention
331 -- the type variables for the type constructor
332 tcHsPred pred `thenTc` \ pred' ->
333 case getClassPredTys_maybe pred' of
334 Nothing -> bale_out (malformedPredErr tycon pred)
335 Just (clas, tys) -> mk_eqn_help new_or_data tycon clas tys
337 ------------------------------------------------------------------
338 mk_eqn_help DataType tycon clas tys
339 | Just err <- chk_out clas tycon tys
340 = bale_out (derivingThingErr clas tys tycon tyvars err)
342 = new_dfun_name clas tycon `thenNF_Tc` \ dfun_name ->
343 returnNF_Tc (Just (dfun_name, clas, tycon, tyvars, constraints), Nothing)
345 tyvars = tyConTyVars tycon
346 data_cons = tyConDataCons tycon
347 constraints = extra_constraints ++
348 [ mkClassPred clas [arg_ty]
349 | data_con <- tyConDataCons tycon,
350 arg_ty <- dataConRepArgTys data_con,
351 -- Use the same type variables
352 -- as the type constructor,
353 -- hence no need to instantiate
354 not (isUnLiftedType arg_ty) -- No constraints for unlifted types?
357 -- "extra_constraints": see notes above about contexts on data decls
358 extra_constraints = tyConTheta tycon
360 -- | offensive_class = tyConTheta tycon
362 -- offensive_class = classKey clas `elem` needsDataDeclCtxtClassKeys
365 mk_eqn_help NewType tycon clas tys
366 = doptsTc Opt_GlasgowExts `thenTc` \ gla_exts ->
367 if can_derive_via_isomorphism && (gla_exts || standard_instance) then
368 -- Go ahead and use the isomorphism
369 new_dfun_name clas tycon `thenNF_Tc` \ dfun_name ->
370 returnTc (Nothing, Just (NewTypeDerived (mk_dfun dfun_name)))
372 if standard_instance then
373 mk_eqn_help DataType tycon clas [] -- Go via bale-out route
375 bale_out cant_derive_err
377 -- Here is the plan for newtype derivings. We see
378 -- newtype T a1...an = T (t ak...an) deriving (C1...Cm)
379 -- where aj...an do not occur free in t, and the Ci are *partial applications* of
380 -- classes with the last parameter missing
382 -- We generate the instances
383 -- instance Ci (t ak...aj) => Ci (T a1...aj)
384 -- where T a1...aj is the partial application of the LHS of the correct kind
386 -- Running example: newtype T s a = MkT (ST s a) deriving( Monad )
388 kind = tyVarKind (last (classTyVars clas))
389 -- Kind of the thing we want to instance
390 -- e.g. argument kind of Monad, *->*
392 (arg_kinds, _) = tcSplitFunTys kind
393 n_args_to_drop = length arg_kinds
394 -- Want to drop 1 arg from (T s a) and (ST s a)
395 -- to get instance Monad (ST s) => Monad (T s)
397 (tyvars, rep_ty) = newTyConRep tycon
398 maybe_rep_app = tcSplitTyConApp_maybe rep_ty
399 Just (rep_tc, rep_ty_args) = maybe_rep_app
401 n_tyvars_to_keep = tyConArity tycon - n_args_to_drop
402 tyvars_to_drop = drop n_tyvars_to_keep tyvars
403 tyvars_to_keep = take n_tyvars_to_keep tyvars
405 n_args_to_keep = tyConArity rep_tc - n_args_to_drop
406 args_to_drop = drop n_args_to_keep rep_ty_args
407 args_to_keep = take n_args_to_keep rep_ty_args
409 ctxt_pred = mkClassPred clas (tys ++ [mkTyConApp rep_tc args_to_keep])
411 mk_dfun dfun_name = mkDictFunId dfun_name clas tyvars
412 (tys ++ [mkTyConApp tycon (mkTyVarTys tyvars_to_keep)] )
415 -- We can only do this newtype deriving thing if:
416 standard_instance = null tys && classKey clas `elem` derivableClassKeys
418 can_derive_via_isomorphism
419 = not (clas `hasKey` readClassKey) -- Never derive Read,Show this way
420 && not (clas `hasKey` showClassKey)
421 && n_tyvars_to_keep >= 0 -- Well kinded;
422 -- eg not: newtype T = T Int deriving( Monad )
423 && isJust maybe_rep_app -- The rep type is a type constructor app
424 && n_args_to_keep >= 0 -- Well kinded:
425 -- eg not: newtype T a = T Int deriving( Monad )
426 && eta_ok -- Eta reduction works
428 -- Check that eta reduction is OK
429 -- (a) the dropped-off args are identical
430 -- (b) the remaining type args mention
431 -- only the remaining type variables
432 eta_ok = (args_to_drop `tcEqTypes` mkTyVarTys tyvars_to_drop)
433 && (tyVarsOfTypes args_to_keep `subVarSet` mkVarSet tyvars_to_keep)
435 cant_derive_err = derivingThingErr clas tys tycon tyvars_to_keep
436 SLIT("too hard for cunning newtype deriving")
439 bale_out err = addErrTc err `thenNF_Tc_` returnNF_Tc (Nothing, Nothing)
441 ------------------------------------------------------------------
442 chk_out :: Class -> TyCon -> [TcType] -> Maybe FastString
443 chk_out clas tycon tys
444 | not (null tys) = Just non_std_why
445 | not (getUnique clas `elem` derivableClassKeys) = Just non_std_why
446 | clas `hasKey` enumClassKey && not is_enumeration = Just nullary_why
447 | clas `hasKey` boundedClassKey && not is_enumeration_or_single = Just single_nullary_why
448 | clas `hasKey` ixClassKey && not is_enumeration_or_single = Just single_nullary_why
449 | null data_cons = Just no_cons_why
450 | any isExistentialDataCon data_cons = Just existential_why
451 | otherwise = Nothing
453 data_cons = tyConDataCons tycon
454 is_enumeration = isEnumerationTyCon tycon
455 is_single_con = maybeToBool (maybeTyConSingleCon tycon)
456 is_enumeration_or_single = is_enumeration || is_single_con
458 single_nullary_why = SLIT("one constructor data type or type with all nullary constructors expected")
459 nullary_why = SLIT("data type with all nullary constructors expected")
460 no_cons_why = SLIT("type has no data constructors")
461 non_std_why = SLIT("not a derivable class")
462 existential_why = SLIT("it has existentially-quantified constructor(s)")
464 new_dfun_name clas tycon -- Just a simple wrapper
465 = newDFunName clas [mkTyConApp tycon []] (getSrcLoc tycon)
466 -- The type passed to newDFunName is only used to generate
467 -- a suitable string; hence the empty type arg list
470 %************************************************************************
472 \subsection[TcDeriv-fixpoint]{Finding the fixed point of \tr{deriving} equations}
474 %************************************************************************
476 A ``solution'' (to one of the equations) is a list of (k,TyVarTy tv)
477 terms, which is the final correct RHS for the corresponding original
481 Each (k,TyVarTy tv) in a solution constrains only a type
485 The (k,TyVarTy tv) pairs in a solution are canonically
486 ordered by sorting on type varible, tv, (major key) and then class, k,
491 solveDerivEqns :: InstEnv
493 -> TcM [DFunId] -- Solns in same order as eqns.
494 -- This bunch is Absolutely minimal...
496 solveDerivEqns inst_env_in orig_eqns
497 = iterateDeriv 1 initial_solutions
499 -- The initial solutions for the equations claim that each
500 -- instance has an empty context; this solution is certainly
501 -- in canonical form.
502 initial_solutions :: [DerivSoln]
503 initial_solutions = [ [] | _ <- orig_eqns ]
505 ------------------------------------------------------------------
506 -- iterateDeriv calculates the next batch of solutions,
507 -- compares it with the current one; finishes if they are the
508 -- same, otherwise recurses with the new solutions.
509 -- It fails if any iteration fails
510 iterateDeriv :: Int -> [DerivSoln] ->TcM [DFunId]
511 iterateDeriv n current_solns
512 | n > 20 -- Looks as if we are in an infinite loop
513 -- This can happen if we have -fallow-undecidable-instances
514 -- (See TcSimplify.tcSimplifyDeriv.)
515 = pprPanic "solveDerivEqns: probable loop"
516 (vcat (map pprDerivEqn orig_eqns) $$ ppr current_solns)
518 = getDOptsTc `thenNF_Tc` \ dflags ->
520 dfuns = zipWithEqual "add_solns" mk_deriv_dfun orig_eqns current_solns
521 inst_env = extend_inst_env dflags inst_env_in dfuns
524 -- Extend the inst info from the explicit instance decls
525 -- with the current set of solutions, and simplify each RHS
526 tcSetInstEnv inst_env $
527 mapTc gen_soln orig_eqns
528 ) `thenTc` \ new_solns ->
529 if (current_solns == new_solns) then
532 iterateDeriv (n+1) new_solns
534 ------------------------------------------------------------------
536 gen_soln (_, clas, tc,tyvars,deriv_rhs)
537 = tcAddSrcLoc (getSrcLoc tc) $
538 tcAddErrCtxt (derivCtxt (Just clas) tc) $
539 tcSimplifyDeriv tyvars deriv_rhs `thenTc` \ theta ->
540 returnTc (sortLt (<) theta) -- Canonicalise before returning the soluction
544 extend_inst_env dflags inst_env new_dfuns
547 (new_inst_env, _errs) = extendInstEnv dflags inst_env new_dfuns
548 -- Ignore the errors about duplicate instances.
549 -- We don't want repeated error messages
550 -- They'll appear later, when we do the top-level extendInstEnvs
552 mk_deriv_dfun (dfun_name, clas, tycon, tyvars, _) theta
553 = mkDictFunId dfun_name clas tyvars
554 [mkTyConApp tycon (mkTyVarTys tyvars)]
558 %************************************************************************
560 \subsection[TcDeriv-normal-binds]{Bindings for the various classes}
562 %************************************************************************
564 After all the trouble to figure out the required context for the
565 derived instance declarations, all that's left is to chug along to
566 produce them. They will then be shoved into @tcInstDecls2@, which
567 will do all its usual business.
569 There are lots of possibilities for code to generate. Here are
570 various general remarks.
575 We want derived instances of @Eq@ and @Ord@ (both v common) to be
576 ``you-couldn't-do-better-by-hand'' efficient.
579 Deriving @Show@---also pretty common--- should also be reasonable good code.
582 Deriving for the other classes isn't that common or that big a deal.
589 Deriving @Ord@ is done mostly with the 1.3 @compare@ method.
592 Deriving @Eq@ also uses @compare@, if we're deriving @Ord@, too.
595 We {\em normally} generate code only for the non-defaulted methods;
596 there are some exceptions for @Eq@ and (especially) @Ord@...
599 Sometimes we use a @_con2tag_<tycon>@ function, which returns a data
600 constructor's numeric (@Int#@) tag. These are generated by
601 @gen_tag_n_con_binds@, and the heuristic for deciding if one of
602 these is around is given by @hasCon2TagFun@.
604 The examples under the different sections below will make this
608 Much less often (really just for deriving @Ix@), we use a
609 @_tag2con_<tycon>@ function. See the examples.
612 We use the renamer!!! Reason: we're supposed to be
613 producing @RenamedMonoBinds@ for the methods, but that means
614 producing correctly-uniquified code on the fly. This is entirely
615 possible (the @TcM@ monad has a @UniqueSupply@), but it is painful.
616 So, instead, we produce @RdrNameMonoBinds@ then heave 'em through
617 the renamer. What a great hack!
621 -- Generate the method bindings for the required instance
622 -- (paired with class name, as we need that when renaming
624 gen_bind :: FixityEnv -> DFunId -> (Name, RdrNameMonoBinds)
625 gen_bind get_fixity dfun
628 cls_nm = className clas
629 (clas, tycon) = simpleDFunClassTyCon dfun
631 binds = assoc "gen_bind:bad derived class" gen_list
632 (nameUnique cls_nm) tycon
634 gen_list = [(eqClassKey, gen_Eq_binds)
635 ,(ordClassKey, gen_Ord_binds)
636 ,(enumClassKey, gen_Enum_binds)
637 ,(boundedClassKey, gen_Bounded_binds)
638 ,(ixClassKey, gen_Ix_binds)
639 ,(showClassKey, gen_Show_binds get_fixity)
640 ,(readClassKey, gen_Read_binds get_fixity)
645 %************************************************************************
647 \subsection[TcDeriv-taggery-Names]{What con2tag/tag2con functions are available?}
649 %************************************************************************
654 con2tag_Foo :: Foo ... -> Int#
655 tag2con_Foo :: Int -> Foo ... -- easier if Int, not Int#
656 maxtag_Foo :: Int -- ditto (NB: not unlifted)
659 We have a @con2tag@ function for a tycon if:
662 We're deriving @Eq@ and the tycon has nullary data constructors.
665 Or: we're deriving @Ord@ (unless single-constructor), @Enum@, @Ix@
669 We have a @tag2con@ function for a tycon if:
672 We're deriving @Enum@, or @Ix@ (enum type only???)
675 If we have a @tag2con@ function, we also generate a @maxtag@ constant.
678 gen_taggery_Names :: [DFunId]
679 -> TcM [(RdrName, -- for an assoc list
680 TyCon, -- related tycon
683 gen_taggery_Names dfuns
684 = foldlTc do_con2tag [] tycons_of_interest `thenTc` \ names_so_far ->
685 foldlTc do_tag2con names_so_far tycons_of_interest
687 all_CTs = map simpleDFunClassTyCon dfuns
688 all_tycons = map snd all_CTs
689 (tycons_of_interest, _) = removeDups compare all_tycons
691 do_con2tag acc_Names tycon
692 | isDataTyCon tycon &&
693 ((we_are_deriving eqClassKey tycon
694 && any isNullaryDataCon (tyConDataCons tycon))
695 || (we_are_deriving ordClassKey tycon
696 && not (maybeToBool (maybeTyConSingleCon tycon)))
697 || (we_are_deriving enumClassKey tycon)
698 || (we_are_deriving ixClassKey tycon))
700 = returnTc ((con2tag_RDR tycon, tycon, GenCon2Tag)
705 do_tag2con acc_Names tycon
706 | isDataTyCon tycon &&
707 (we_are_deriving enumClassKey tycon ||
708 we_are_deriving ixClassKey tycon
709 && isEnumerationTyCon tycon)
710 = returnTc ( (tag2con_RDR tycon, tycon, GenTag2Con)
711 : (maxtag_RDR tycon, tycon, GenMaxTag)
716 we_are_deriving clas_key tycon
717 = is_in_eqns clas_key tycon all_CTs
719 is_in_eqns clas_key tycon [] = False
720 is_in_eqns clas_key tycon ((c,t):cts)
721 = (clas_key == classKey c && tycon == t)
722 || is_in_eqns clas_key tycon cts
726 derivingThingErr clas tys tycon tyvars why
727 = sep [hsep [ptext SLIT("Can't make a derived instance of"), quotes (ppr pred)],
730 pred = mkClassPred clas (tys ++ [mkTyConApp tycon (mkTyVarTys tyvars)])
732 malformedPredErr tycon pred = ptext SLIT("Illegal deriving item") <+> ppr pred
734 derivCtxt :: Maybe Class -> TyCon -> SDoc
735 derivCtxt maybe_cls tycon
736 = ptext SLIT("When deriving") <+> cls <+> ptext SLIT("for type") <+> quotes (ppr tycon)
738 cls = case maybe_cls of
739 Nothing -> ptext SLIT("instances")
740 Just c -> ptext SLIT("the") <+> quotes (ppr c) <+> ptext SLIT("instance")