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,
21 InstInfo(..), pprInstInfo, InstBindings(..),
22 pprInstInfoDetails, tcLookupTyCon, tcExtendTyVarEnv
24 import TcGenDeriv -- Deriv stuff
25 import InstEnv ( InstEnv, simpleDFunClassTyCon, extendInstEnv )
26 import TcMonoType ( tcHsPred )
27 import TcSimplify ( tcSimplifyDeriv )
29 import RnBinds ( rnMethodBinds, rnTopMonoBinds )
30 import RnEnv ( bindLocalsFVRn )
31 import TcRnMonad ( thenM, returnM, mapAndUnzipM )
32 import HscTypes ( DFunId )
34 import BasicTypes ( NewOrData(..) )
35 import Class ( className, classKey, classTyVars, classSCTheta, Class )
36 import Subst ( mkTyVarSubst, substTheta )
37 import ErrUtils ( dumpIfSet_dyn )
38 import MkId ( mkDictFunId )
39 import DataCon ( dataConRepArgTys, isNullaryDataCon, isExistentialDataCon )
40 import Maybes ( maybeToBool, catMaybes )
41 import Name ( Name, getSrcLoc, nameUnique )
43 import RdrName ( RdrName )
45 import TyCon ( tyConTyVars, tyConDataCons, tyConArity, newTyConRep,
46 tyConTheta, maybeTyConSingleCon, isDataTyCon,
47 isEnumerationTyCon, isRecursiveTyCon, TyCon
49 import TcType ( TcType, ThetaType, mkTyVarTys, mkTyConApp, getClassPredTys_maybe,
50 isUnLiftedType, mkClassPred, tyVarsOfTypes, tcSplitFunTys,
51 tcSplitTyConApp_maybe, tcEqTypes, mkAppTys )
52 import Type ( splitAppTys )
53 import Var ( TyVar, tyVarKind )
54 import VarSet ( mkVarSet, subVarSet )
56 import Util ( zipWithEqual, sortLt, notNull )
57 import ListSetOps ( removeDups, assoc )
59 import Maybe ( isJust )
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 pprDerivEqn (n,c,tc,tvs,rhs)
152 = parens (hsep [ppr n, ppr c, ppr tc, ppr tvs] <+> equals <+> ppr rhs)
154 type DerivRhs = ThetaType
155 type DerivSoln = DerivRhs
159 [Data decl contexts] A note about contexts on data decls
160 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
163 data (RealFloat a) => Complex a = !a :+ !a deriving( Read )
165 We will need an instance decl like:
167 instance (Read a, RealFloat a) => Read (Complex a) where
170 The RealFloat in the context is because the read method for Complex is bound
171 to construct a Complex, and doing that requires that the argument type is
174 But this ain't true for Show, Eq, Ord, etc, since they don't construct
175 a Complex; they only take them apart.
177 Our approach: identify the offending classes, and add the data type
178 context to the instance decl. The "offending classes" are
182 FURTHER NOTE ADDED March 2002. In fact, Haskell98 now requires that
183 pattern matching against a constructor from a data type with a context
184 gives rise to the constraints for that context -- or at least the thinned
185 version. So now all classes are "offending".
189 %************************************************************************
191 \subsection[TcDeriv-driver]{Top-level function for \tr{derivings}}
193 %************************************************************************
196 tcDeriving :: [RenamedTyClDecl] -- All type constructors
197 -> TcM ([InstInfo], -- The generated "instance decls".
198 RenamedHsBinds, -- Extra generated bindings
199 FreeVars) -- These are free in the generated bindings
201 tcDeriving tycl_decls
202 = recoverM (returnM ([], EmptyBinds, emptyFVs)) $
203 getDOpts `thenM` \ dflags ->
204 tcGetInstEnv `thenM` \ inst_env ->
206 -- Fish the "deriving"-related information out of the TcEnv
207 -- and make the necessary "equations".
208 makeDerivEqns tycl_decls `thenM` \ (ordinary_eqns, newtype_inst_info) ->
210 -- Add the newtype-derived instances to the inst env
211 -- before tacking the "ordinary" ones
212 inst_env1 = extend_inst_env dflags inst_env
213 (map iDFunId newtype_inst_info)
215 deriveOrdinaryStuff inst_env1 ordinary_eqns `thenM` \ (ordinary_inst_info, binds, fvs) ->
217 inst_info = newtype_inst_info ++ ordinary_inst_info
220 ioToTcRn (dumpIfSet_dyn dflags Opt_D_dump_deriv "Derived instances"
221 (ddump_deriving inst_info binds)) `thenM_`
223 returnM (inst_info, binds, fvs)
226 ddump_deriving :: [InstInfo] -> RenamedHsBinds -> SDoc
227 ddump_deriving inst_infos extra_binds
228 = vcat (map ppr_info inst_infos) $$ ppr extra_binds
230 ppr_info inst_info = pprInstInfo inst_info $$
231 nest 4 (pprInstInfoDetails inst_info)
232 -- pprInstInfo doesn't print much: only the type
234 -----------------------------------------
235 deriveOrdinaryStuff inst_env_in [] -- Short cut
236 = returnM ([], EmptyBinds, emptyFVs)
238 deriveOrdinaryStuff inst_env_in eqns
239 = -- Take the equation list and solve it, to deliver a list of
240 -- solutions, a.k.a. the contexts for the instance decls
241 -- required for the corresponding equations.
242 solveDerivEqns inst_env_in eqns `thenM` \ new_dfuns ->
244 -- Now augment the InstInfos, adding in the rather boring
245 -- actual-code-to-do-the-methods binds. We may also need to
246 -- generate extra not-one-inst-decl-specific binds, notably
247 -- "con2tag" and/or "tag2con" functions. We do these
249 gen_taggery_Names new_dfuns `thenM` \ nm_alist_etc ->
252 extra_mbind_list = map gen_tag_n_con_monobind nm_alist_etc
253 extra_mbinds = foldr AndMonoBinds EmptyMonoBinds extra_mbind_list
254 mbinders = collectMonoBinders extra_mbinds
256 mappM gen_bind new_dfuns `thenM` \ method_binds_s ->
258 traceTc (text "tcDeriv" <+> ppr method_binds_s) `thenM_`
259 getModule `thenM` \ this_mod ->
260 initRn (InterfaceMode this_mod) (
261 -- Rename to get RenamedBinds.
262 -- The only tricky bit is that the extra_binds must scope
263 -- over the method bindings for the instances.
264 bindLocalsFVRn (ptext (SLIT("deriving"))) mbinders $ \ _ ->
265 rnTopMonoBinds extra_mbinds [] `thenM` \ (rn_extra_binds, fvs) ->
266 mapAndUnzipM rn_meths method_binds_s `thenM` \ (rn_method_binds_s, fvs_s) ->
267 returnM ((rn_method_binds_s, rn_extra_binds),
268 fvs `plusFV` plusFVs fvs_s)
269 ) `thenM` \ ((rn_method_binds_s, rn_extra_binds), fvs) ->
271 new_inst_infos = zipWith gen_inst_info new_dfuns rn_method_binds_s
273 returnM (new_inst_infos, rn_extra_binds, fvs)
276 -- Make a Real dfun instead of the dummy one we have so far
277 gen_inst_info :: DFunId -> RenamedMonoBinds -> InstInfo
278 gen_inst_info dfun binds
279 = InstInfo { iDFunId = dfun, iBinds = VanillaInst binds [] }
281 rn_meths (cls, meths) = rnMethodBinds cls [] meths
285 %************************************************************************
287 \subsection[TcDeriv-eqns]{Forming the equations}
289 %************************************************************************
291 @makeDerivEqns@ fishes around to find the info about needed derived
292 instances. Complicating factors:
295 We can only derive @Enum@ if the data type is an enumeration
296 type (all nullary data constructors).
299 We can only derive @Ix@ if the data type is an enumeration {\em
300 or} has just one data constructor (e.g., tuples).
303 [See Appendix~E in the Haskell~1.2 report.] This code here deals w/
307 makeDerivEqns :: [RenamedTyClDecl]
308 -> TcM ([DerivEqn], -- Ordinary derivings
309 [InstInfo]) -- Special newtype derivings
311 makeDerivEqns tycl_decls
312 = mapAndUnzipM mk_eqn derive_these `thenM` \ (maybe_ordinaries, maybe_newtypes) ->
313 returnM (catMaybes maybe_ordinaries, catMaybes maybe_newtypes)
315 ------------------------------------------------------------------
316 derive_these :: [(NewOrData, Name, RenamedHsPred)]
317 -- Find the (nd, TyCon, Pred) pairs that must be `derived'
318 -- NB: only source-language decls have deriving, no imported ones do
319 derive_these = [ (nd, tycon, pred)
320 | TyData {tcdND = nd, tcdName = tycon, tcdDerivs = Just preds} <- tycl_decls,
323 ------------------------------------------------------------------
324 mk_eqn :: (NewOrData, Name, RenamedHsPred) -> TcM (Maybe DerivEqn, Maybe InstInfo)
325 -- We swizzle the tyvars and datacons out of the tycon
326 -- to make the rest of the equation
328 mk_eqn (new_or_data, tycon_name, pred)
329 = tcLookupTyCon tycon_name `thenM` \ tycon ->
330 addSrcLoc (getSrcLoc tycon) $
331 addErrCtxt (derivCtxt Nothing tycon) $
332 tcExtendTyVarEnv (tyConTyVars tycon) $ -- Deriving preds may (now) mention
333 -- the type variables for the type constructor
334 tcHsPred pred `thenM` \ pred' ->
335 case getClassPredTys_maybe pred' of
336 Nothing -> bale_out (malformedPredErr tycon pred)
337 Just (clas, tys) -> mk_eqn_help new_or_data tycon clas tys
339 ------------------------------------------------------------------
340 mk_eqn_help DataType tycon clas tys
341 | Just err <- chk_out clas tycon tys
342 = bale_out (derivingThingErr clas tys tycon tyvars err)
344 = new_dfun_name clas tycon `thenM` \ dfun_name ->
345 returnM (Just (dfun_name, clas, tycon, tyvars, constraints), Nothing)
347 tyvars = tyConTyVars tycon
348 data_cons = tyConDataCons tycon
349 constraints = extra_constraints ++
350 [ mkClassPred clas [arg_ty]
351 | data_con <- tyConDataCons tycon,
352 arg_ty <- dataConRepArgTys data_con,
353 -- Use the same type variables
354 -- as the type constructor,
355 -- hence no need to instantiate
356 not (isUnLiftedType arg_ty) -- No constraints for unlifted types?
359 -- "extra_constraints": see note [Data decl contexts] above
360 extra_constraints = tyConTheta tycon
362 mk_eqn_help NewType tycon clas tys
363 = doptM Opt_GlasgowExts `thenM` \ gla_exts ->
364 if can_derive_via_isomorphism && (gla_exts || standard_instance) then
365 -- Go ahead and use the isomorphism
366 new_dfun_name clas tycon `thenM` \ dfun_name ->
367 returnM (Nothing, Just (InstInfo { iDFunId = mk_dfun dfun_name,
368 iBinds = NewTypeDerived rep_tys }))
370 if standard_instance then
371 mk_eqn_help DataType tycon clas [] -- Go via bale-out route
373 bale_out cant_derive_err
375 -- Here is the plan for newtype derivings. We see
376 -- newtype T a1...an = T (t ak...an) deriving (.., C s1 .. sm, ...)
377 -- where aj...an do not occur free in t, and the (C s1 ... sm) is a
378 -- *partial applications* of class C with the last parameter missing
380 -- We generate the instances
381 -- instance C s1 .. sm (t ak...aj) => C s1 .. sm (T a1...aj)
382 -- where T a1...aj is the partial application of the LHS of the correct kind
384 -- Running example: newtype T s a = MkT (ST s a) deriving( Monad )
385 -- instance Monad (ST s) => Monad (T s) where
386 -- fail = coerce ... (fail @ ST s)
388 clas_tyvars = classTyVars clas
389 kind = tyVarKind (last clas_tyvars)
390 -- Kind of the thing we want to instance
391 -- e.g. argument kind of Monad, *->*
393 (arg_kinds, _) = tcSplitFunTys kind
394 n_args_to_drop = length arg_kinds
395 -- Want to drop 1 arg from (T s a) and (ST s a)
396 -- to get instance Monad (ST s) => Monad (T s)
398 (tyvars, rep_ty) = newTyConRep tycon
399 (rep_fn, rep_ty_args) = splitAppTys rep_ty
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 = length rep_ty_args - 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 rep_tys = tys ++ [mkAppTys rep_fn args_to_keep]
410 rep_pred = mkClassPred clas rep_tys
411 -- rep_pred is the representation dictionary, from where
412 -- we are gong to get all the methods for the newtype dictionary
414 inst_tys = (tys ++ [mkTyConApp tycon (mkTyVarTys tyvars_to_keep)])
415 -- The 'tys' here come from the partial application
416 -- in the deriving clause. The last arg is the new
419 -- We must pass the superclasses; the newtype might be an instance
420 -- of them in a different way than the representation type
421 -- E.g. newtype Foo a = Foo a deriving( Show, Num, Eq )
422 -- Then the Show instance is not done via isomprphism; it shows
424 -- The Num instance is derived via isomorphism, but the Show superclass
425 -- dictionary must the Show instance for Foo, *not* the Show dictionary
426 -- gotten from the Num dictionary. So we must build a whole new dictionary
427 -- not just use the Num one. The instance we want is something like:
428 -- instance (Num a, Show (Foo a), Eq (Foo a)) => Num (Foo a) where
431 -- There's no 'corece' needed because after the type checker newtypes
434 sc_theta = substTheta (mkTyVarSubst clas_tyvars inst_tys)
437 -- If there are no tyvars, there's no need
438 -- to abstract over the dictionaries we need
439 dict_args | null tyvars = []
440 | otherwise = rep_pred : sc_theta
442 -- Finally! Here's where we build the dictionary Id
443 mk_dfun dfun_name = mkDictFunId dfun_name tyvars dict_args clas inst_tys
445 -------------------------------------------------------------------
446 -- Figuring out whether we can only do this newtype-deriving thing
448 standard_instance = null tys && classKey clas `elem` derivableClassKeys
450 can_derive_via_isomorphism
451 = not (clas `hasKey` readClassKey) -- Never derive Read,Show this way
452 && not (clas `hasKey` showClassKey)
453 && n_tyvars_to_keep >= 0 -- Well kinded;
454 -- eg not: newtype T = T Int deriving( Monad )
455 && n_args_to_keep >= 0 -- Well kinded:
456 -- eg not: newtype T a = T Int deriving( Monad )
457 && eta_ok -- Eta reduction works
458 && not (isRecursiveTyCon tycon) -- Does not work for recursive tycons:
459 -- newtype A = MkA [A]
461 -- instance Eq [A] => Eq A !!
463 -- Check that eta reduction is OK
464 -- (a) the dropped-off args are identical
465 -- (b) the remaining type args mention
466 -- only the remaining type variables
467 eta_ok = (args_to_drop `tcEqTypes` mkTyVarTys tyvars_to_drop)
468 && (tyVarsOfTypes args_to_keep `subVarSet` mkVarSet tyvars_to_keep)
470 cant_derive_err = derivingThingErr clas tys tycon tyvars_to_keep
471 (vcat [ptext SLIT("too hard for cunning newtype deriving"),
472 ppr n_tyvars_to_keep,
475 ppr (isRecursiveTyCon tycon)
478 bale_out err = addErrTc err `thenM_` returnM (Nothing, Nothing)
480 ------------------------------------------------------------------
481 chk_out :: Class -> TyCon -> [TcType] -> Maybe SDoc
482 chk_out clas tycon tys
483 | notNull tys = Just non_std_why
484 | not (getUnique clas `elem` derivableClassKeys) = Just non_std_why
485 | clas `hasKey` enumClassKey && not is_enumeration = Just nullary_why
486 | clas `hasKey` boundedClassKey && not is_enumeration_or_single = Just single_nullary_why
487 | clas `hasKey` ixClassKey && not is_enumeration_or_single = Just single_nullary_why
488 | null data_cons = Just no_cons_why
489 | any isExistentialDataCon data_cons = Just existential_why
490 | otherwise = Nothing
492 data_cons = tyConDataCons tycon
493 is_enumeration = isEnumerationTyCon tycon
494 is_single_con = maybeToBool (maybeTyConSingleCon tycon)
495 is_enumeration_or_single = is_enumeration || is_single_con
497 single_nullary_why = ptext SLIT("one constructor data type or type with all nullary constructors expected")
498 nullary_why = ptext SLIT("data type with all nullary constructors expected")
499 no_cons_why = ptext SLIT("type has no data constructors")
500 non_std_why = ptext SLIT("not a derivable class")
501 existential_why = ptext SLIT("it has existentially-quantified constructor(s)")
503 new_dfun_name clas tycon -- Just a simple wrapper
504 = newDFunName clas [mkTyConApp tycon []] (getSrcLoc tycon)
505 -- The type passed to newDFunName is only used to generate
506 -- a suitable string; hence the empty type arg list
509 %************************************************************************
511 \subsection[TcDeriv-fixpoint]{Finding the fixed point of \tr{deriving} equations}
513 %************************************************************************
515 A ``solution'' (to one of the equations) is a list of (k,TyVarTy tv)
516 terms, which is the final correct RHS for the corresponding original
520 Each (k,TyVarTy tv) in a solution constrains only a type
524 The (k,TyVarTy tv) pairs in a solution are canonically
525 ordered by sorting on type varible, tv, (major key) and then class, k,
530 solveDerivEqns :: InstEnv
532 -> TcM [DFunId] -- Solns in same order as eqns.
533 -- This bunch is Absolutely minimal...
535 solveDerivEqns inst_env_in orig_eqns
536 = iterateDeriv 1 initial_solutions
538 -- The initial solutions for the equations claim that each
539 -- instance has an empty context; this solution is certainly
540 -- in canonical form.
541 initial_solutions :: [DerivSoln]
542 initial_solutions = [ [] | _ <- orig_eqns ]
544 ------------------------------------------------------------------
545 -- iterateDeriv calculates the next batch of solutions,
546 -- compares it with the current one; finishes if they are the
547 -- same, otherwise recurses with the new solutions.
548 -- It fails if any iteration fails
549 iterateDeriv :: Int -> [DerivSoln] ->TcM [DFunId]
550 iterateDeriv n current_solns
551 | n > 20 -- Looks as if we are in an infinite loop
552 -- This can happen if we have -fallow-undecidable-instances
553 -- (See TcSimplify.tcSimplifyDeriv.)
554 = pprPanic "solveDerivEqns: probable loop"
555 (vcat (map pprDerivEqn orig_eqns) $$ ppr current_solns)
557 = getDOpts `thenM` \ dflags ->
559 dfuns = zipWithEqual "add_solns" mk_deriv_dfun orig_eqns current_solns
560 inst_env = extend_inst_env dflags inst_env_in dfuns
563 -- Extend the inst info from the explicit instance decls
564 -- with the current set of solutions, and simplify each RHS
565 tcSetInstEnv inst_env $
566 mappM gen_soln orig_eqns
567 ) `thenM` \ new_solns ->
568 if (current_solns == new_solns) then
571 iterateDeriv (n+1) new_solns
573 ------------------------------------------------------------------
575 gen_soln (_, clas, tc,tyvars,deriv_rhs)
576 = addSrcLoc (getSrcLoc tc) $
577 addErrCtxt (derivCtxt (Just clas) tc) $
578 tcSimplifyDeriv tyvars deriv_rhs `thenM` \ theta ->
579 returnM (sortLt (<) theta) -- Canonicalise before returning the soluction
583 extend_inst_env dflags inst_env new_dfuns
586 (new_inst_env, _errs) = extendInstEnv dflags inst_env new_dfuns
587 -- Ignore the errors about duplicate instances.
588 -- We don't want repeated error messages
589 -- They'll appear later, when we do the top-level extendInstEnvs
591 mk_deriv_dfun (dfun_name, clas, tycon, tyvars, _) theta
592 = mkDictFunId dfun_name tyvars theta
593 clas [mkTyConApp tycon (mkTyVarTys tyvars)]
596 %************************************************************************
598 \subsection[TcDeriv-normal-binds]{Bindings for the various classes}
600 %************************************************************************
602 After all the trouble to figure out the required context for the
603 derived instance declarations, all that's left is to chug along to
604 produce them. They will then be shoved into @tcInstDecls2@, which
605 will do all its usual business.
607 There are lots of possibilities for code to generate. Here are
608 various general remarks.
613 We want derived instances of @Eq@ and @Ord@ (both v common) to be
614 ``you-couldn't-do-better-by-hand'' efficient.
617 Deriving @Show@---also pretty common--- should also be reasonable good code.
620 Deriving for the other classes isn't that common or that big a deal.
627 Deriving @Ord@ is done mostly with the 1.3 @compare@ method.
630 Deriving @Eq@ also uses @compare@, if we're deriving @Ord@, too.
633 We {\em normally} generate code only for the non-defaulted methods;
634 there are some exceptions for @Eq@ and (especially) @Ord@...
637 Sometimes we use a @_con2tag_<tycon>@ function, which returns a data
638 constructor's numeric (@Int#@) tag. These are generated by
639 @gen_tag_n_con_binds@, and the heuristic for deciding if one of
640 these is around is given by @hasCon2TagFun@.
642 The examples under the different sections below will make this
646 Much less often (really just for deriving @Ix@), we use a
647 @_tag2con_<tycon>@ function. See the examples.
650 We use the renamer!!! Reason: we're supposed to be
651 producing @RenamedMonoBinds@ for the methods, but that means
652 producing correctly-uniquified code on the fly. This is entirely
653 possible (the @TcM@ monad has a @UniqueSupply@), but it is painful.
654 So, instead, we produce @RdrNameMonoBinds@ then heave 'em through
655 the renamer. What a great hack!
659 -- Generate the method bindings for the required instance
660 -- (paired with class name, as we need that when renaming
662 gen_bind :: DFunId -> TcM (Name, RdrNameMonoBinds)
664 = getFixityEnv `thenM` \ fix_env ->
665 returnM (cls_nm, gen_binds_fn fix_env cls_nm tycon)
667 cls_nm = className clas
668 (clas, tycon) = simpleDFunClassTyCon dfun
670 gen_binds_fn fix_env cls_nm
671 = assoc "gen_bind:bad derived class"
672 gen_list (nameUnique cls_nm)
674 gen_list = [(eqClassKey, gen_Eq_binds)
675 ,(ordClassKey, gen_Ord_binds)
676 ,(enumClassKey, gen_Enum_binds)
677 ,(boundedClassKey, gen_Bounded_binds)
678 ,(ixClassKey, gen_Ix_binds)
679 ,(showClassKey, gen_Show_binds fix_env)
680 ,(readClassKey, gen_Read_binds fix_env)
685 %************************************************************************
687 \subsection[TcDeriv-taggery-Names]{What con2tag/tag2con functions are available?}
689 %************************************************************************
694 con2tag_Foo :: Foo ... -> Int#
695 tag2con_Foo :: Int -> Foo ... -- easier if Int, not Int#
696 maxtag_Foo :: Int -- ditto (NB: not unlifted)
699 We have a @con2tag@ function for a tycon if:
702 We're deriving @Eq@ and the tycon has nullary data constructors.
705 Or: we're deriving @Ord@ (unless single-constructor), @Enum@, @Ix@
709 We have a @tag2con@ function for a tycon if:
712 We're deriving @Enum@, or @Ix@ (enum type only???)
715 If we have a @tag2con@ function, we also generate a @maxtag@ constant.
718 gen_taggery_Names :: [DFunId]
719 -> TcM [(RdrName, -- for an assoc list
720 TyCon, -- related tycon
723 gen_taggery_Names dfuns
724 = foldlM do_con2tag [] tycons_of_interest `thenM` \ names_so_far ->
725 foldlM do_tag2con names_so_far tycons_of_interest
727 all_CTs = map simpleDFunClassTyCon dfuns
728 all_tycons = map snd all_CTs
729 (tycons_of_interest, _) = removeDups compare all_tycons
731 do_con2tag acc_Names tycon
732 | isDataTyCon tycon &&
733 ((we_are_deriving eqClassKey tycon
734 && any isNullaryDataCon (tyConDataCons tycon))
735 || (we_are_deriving ordClassKey tycon
736 && not (maybeToBool (maybeTyConSingleCon tycon)))
737 || (we_are_deriving enumClassKey tycon)
738 || (we_are_deriving ixClassKey tycon))
740 = returnM ((con2tag_RDR tycon, tycon, GenCon2Tag)
745 do_tag2con acc_Names tycon
746 | isDataTyCon tycon &&
747 (we_are_deriving enumClassKey tycon ||
748 we_are_deriving ixClassKey tycon
749 && isEnumerationTyCon tycon)
750 = returnM ( (tag2con_RDR tycon, tycon, GenTag2Con)
751 : (maxtag_RDR tycon, tycon, GenMaxTag)
756 we_are_deriving clas_key tycon
757 = is_in_eqns clas_key tycon all_CTs
759 is_in_eqns clas_key tycon [] = False
760 is_in_eqns clas_key tycon ((c,t):cts)
761 = (clas_key == classKey c && tycon == t)
762 || is_in_eqns clas_key tycon cts
766 derivingThingErr clas tys tycon tyvars why
767 = sep [hsep [ptext SLIT("Can't make a derived instance of"), quotes (ppr pred)],
770 pred = mkClassPred clas (tys ++ [mkTyConApp tycon (mkTyVarTys tyvars)])
772 malformedPredErr tycon pred = ptext SLIT("Illegal deriving item") <+> ppr pred
774 derivCtxt :: Maybe Class -> TyCon -> SDoc
775 derivCtxt maybe_cls tycon
776 = ptext SLIT("When deriving") <+> cls <+> ptext SLIT("for type") <+> quotes (ppr tycon)
778 cls = case maybe_cls of
779 Nothing -> ptext SLIT("instances")
780 Just c -> ptext SLIT("the") <+> quotes (ppr c) <+> ptext SLIT("instance")