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(..), collectMonoBinders )
14 import RdrHsSyn ( RdrNameMonoBinds )
15 import RnHsSyn ( RenamedHsBinds, RenamedMonoBinds )
16 import CmdLineOpts ( opt_D_dump_deriv )
19 import Inst ( InstanceMapper )
20 import TcEnv ( getEnvTyCons )
21 import TcGenDeriv -- Deriv stuff
22 import TcInstUtil ( InstInfo(..), buildInstanceEnvs )
23 import TcSimplify ( tcSimplifyThetas )
25 import RnBinds ( rnMethodBinds, rnTopMonoBinds )
26 import RnEnv ( newDFunName, bindLocatedLocalsRn )
27 import RnMonad ( RnNameSupply,
28 renameSourceCode, thenRn, mapRn, returnRn )
30 import Bag ( Bag, emptyBag, unionBags, listToBag )
31 import Class ( classKey, Class )
32 import ErrUtils ( dumpIfSet, Message, pprBagOfErrors )
33 import MkId ( mkDictFunId )
34 import Id ( mkVanillaId )
35 import DataCon ( dataConArgTys, isNullaryDataCon )
36 import PrelInfo ( needsDataDeclCtxtClassKeys )
37 import Maybes ( maybeToBool )
38 import Module ( ModuleName )
39 import Name ( isLocallyDefined, getSrcLoc,
43 import RdrName ( RdrName )
44 import RnMonad ( Fixities )
45 import SrcLoc ( mkGeneratedSrcLoc, SrcLoc )
46 import TyCon ( tyConTyVars, tyConDataCons, tyConDerivings,
47 tyConTheta, maybeTyConSingleCon, isDataTyCon,
48 isEnumerationTyCon, isAlgTyCon, TyCon
50 import Type ( TauType, mkTyVarTys, mkTyConApp,
51 mkSigmaTy, mkDictTy, isUnboxedType,
54 import TysWiredIn ( voidTy )
56 import Unique -- Keys stuff
57 import Bag ( bagToList )
58 import Util ( zipWithEqual, sortLt, removeDups, assoc, thenCmp )
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 = (Class, TyCon, [TyVar], DerivRhs)
148 -- The tyvars bind all the variables in the RHS
149 -- NEW: it's convenient to re-use InstInfo
150 -- We'll "panic" out some fields...
152 type DerivRhs = [(Class, [TauType])] -- Same as a 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
182 %************************************************************************
184 \subsection[TcDeriv-driver]{Top-level function for \tr{derivings}}
186 %************************************************************************
189 tcDeriving :: ModuleName -- name of module under scrutiny
190 -> Fixities -- for the deriving code (Show/Read.)
191 -> RnNameSupply -- for "renaming" bits of generated code
192 -> Bag InstInfo -- What we already know about instances
193 -> TcM s (Bag InstInfo, -- The generated "instance decls".
194 RenamedHsBinds) -- Extra generated bindings
196 tcDeriving modname fixs rn_name_supply inst_decl_infos_in
197 = recoverTc (returnTc (emptyBag, EmptyBinds)) $
199 -- Fish the "deriving"-related information out of the TcEnv
200 -- and make the necessary "equations".
201 makeDerivEqns `thenTc` \ eqns ->
203 returnTc (emptyBag, EmptyBinds)
206 -- Take the equation list and solve it, to deliver a list of
207 -- solutions, a.k.a. the contexts for the instance decls
208 -- required for the corresponding equations.
209 solveDerivEqns inst_decl_infos_in eqns `thenTc` \ new_inst_infos ->
211 -- Now augment the InstInfos, adding in the rather boring
212 -- actual-code-to-do-the-methods binds. We may also need to
213 -- generate extra not-one-inst-decl-specific binds, notably
214 -- "con2tag" and/or "tag2con" functions. We do these
217 gen_taggery_Names new_inst_infos `thenTc` \ nm_alist_etc ->
221 extra_mbind_list = map gen_tag_n_con_monobind nm_alist_etc
222 extra_mbinds = foldr AndMonoBinds EmptyMonoBinds extra_mbind_list
223 method_binds_s = map (gen_bind fixs) new_inst_infos
224 mbinders = bagToList (collectMonoBinders extra_mbinds)
226 -- Rename to get RenamedBinds.
227 -- The only tricky bit is that the extra_binds must scope over the
228 -- method bindings for the instances.
229 (dfun_names_w_method_binds, rn_extra_binds)
230 = renameSourceCode modname rn_name_supply (
231 bindLocatedLocalsRn (ptext (SLIT("deriving"))) mbinders $ \ _ ->
232 rnTopMonoBinds extra_mbinds [] `thenRn` \ (rn_extra_binds, _) ->
233 mapRn rn_one method_binds_s `thenRn` \ dfun_names_w_method_binds ->
234 returnRn (dfun_names_w_method_binds, rn_extra_binds)
236 rn_one (cl_nm, tycon_nm, meth_binds)
237 = newDFunName (cl_nm, tycon_nm)
238 mkGeneratedSrcLoc `thenRn` \ dfun_name ->
239 rnMethodBinds meth_binds `thenRn` \ (rn_meth_binds, _) ->
240 returnRn (dfun_name, rn_meth_binds)
242 really_new_inst_infos = zipWith gen_inst_info
244 dfun_names_w_method_binds
246 ddump_deriv = ddump_deriving really_new_inst_infos rn_extra_binds
248 ioToTc (dumpIfSet opt_D_dump_deriv "Derived instances" ddump_deriv) `thenTc_`
250 returnTc (listToBag really_new_inst_infos, rn_extra_binds)
252 ddump_deriving :: [InstInfo] -> RenamedHsBinds -> SDoc
253 ddump_deriving inst_infos extra_binds
254 = vcat (map pp_info inst_infos) $$ ppr extra_binds
256 pp_info (InstInfo clas tvs [ty] inst_decl_theta _ mbinds _ _)
257 = ppr (mkSigmaTy tvs inst_decl_theta (mkDictTy clas [ty]))
263 %************************************************************************
265 \subsection[TcDeriv-eqns]{Forming the equations}
267 %************************************************************************
269 @makeDerivEqns@ fishes around to find the info about needed derived
270 instances. Complicating factors:
273 We can only derive @Enum@ if the data type is an enumeration
274 type (all nullary data constructors).
277 We can only derive @Ix@ if the data type is an enumeration {\em
278 or} has just one data constructor (e.g., tuples).
281 [See Appendix~E in the Haskell~1.2 report.] This code here deals w/
285 makeDerivEqns :: TcM s [DerivEqn]
288 = tcGetEnv `thenNF_Tc` \ env ->
290 local_data_tycons = filter (\tc -> isLocallyDefined tc && isAlgTyCon tc)
293 think_about_deriving = need_deriving local_data_tycons
294 (derive_these, _) = removeDups cmp_deriv think_about_deriving
295 eqns = map mk_eqn derive_these
297 if null local_data_tycons then
298 returnTc [] -- Bale out now
300 mapTc chk_out think_about_deriving `thenTc_`
303 ------------------------------------------------------------------
304 need_deriving :: [TyCon] -> [(Class, TyCon)]
305 -- find the tycons that have `deriving' clauses;
307 need_deriving tycons_to_consider
308 = foldr (\ tycon acc -> [(clas,tycon) | clas <- tyConDerivings tycon] ++ acc)
312 ------------------------------------------------------------------
313 chk_out :: (Class, TyCon) -> TcM s ()
314 chk_out this_one@(clas, tycon)
316 clas_key = classKey clas
318 is_enumeration = isEnumerationTyCon tycon
319 is_single_con = maybeToBool (maybeTyConSingleCon tycon)
321 single_nullary_why = SLIT("one constructor data type or type with all nullary constructors expected")
322 nullary_why = SLIT("data type with all nullary constructors expected")
324 chk_clas clas_uniq clas_str clas_why cond
325 = if (clas_uniq == clas_key)
326 then checkTc cond (derivingThingErr clas_str clas_why tycon)
329 -- Are things OK for deriving Enum (if appropriate)?
330 chk_clas enumClassKey (SLIT("Enum")) nullary_why is_enumeration `thenTc_`
332 -- Are things OK for deriving Bounded (if appropriate)?
333 chk_clas boundedClassKey (SLIT("Bounded")) single_nullary_why
334 (is_enumeration || is_single_con) `thenTc_`
336 -- Are things OK for deriving Ix (if appropriate)?
337 chk_clas ixClassKey (SLIT("Ix.Ix")) single_nullary_why
338 (is_enumeration || is_single_con)
340 ------------------------------------------------------------------
341 cmp_deriv :: (Class, TyCon) -> (Class, TyCon) -> Ordering
342 cmp_deriv (c1, t1) (c2, t2)
343 = (c1 `compare` c2) `thenCmp` (t1 `compare` t2)
345 ------------------------------------------------------------------
346 mk_eqn :: (Class, TyCon) -> DerivEqn
347 -- we swizzle the tyvars and datacons out of the tycon
348 -- to make the rest of the equation
351 = (clas, tycon, tyvars, constraints)
353 clas_key = classKey clas
354 tyvars = tyConTyVars tycon -- ToDo: Do we need new tyvars ???
355 tyvar_tys = mkTyVarTys tyvars
356 data_cons = tyConDataCons tycon
358 constraints = extra_constraints ++ concat (map mk_constraints data_cons)
360 -- "extra_constraints": see notes above about contexts on data decls
362 | offensive_class = tyConTheta tycon
365 offensive_class = clas_key `elem` needsDataDeclCtxtClassKeys
367 mk_constraints data_con
369 | arg_ty <- instd_arg_tys,
370 not (isUnboxedType arg_ty) -- No constraints for unboxed types?
373 instd_arg_tys = dataConArgTys data_con tyvar_tys
376 %************************************************************************
378 \subsection[TcDeriv-fixpoint]{Finding the fixed point of \tr{deriving} equations}
380 %************************************************************************
382 A ``solution'' (to one of the equations) is a list of (k,TyVarTy tv)
383 terms, which is the final correct RHS for the corresponding original
387 Each (k,TyVarTy tv) in a solution constrains only a type
391 The (k,TyVarTy tv) pairs in a solution are canonically
392 ordered by sorting on type varible, tv, (major key) and then class, k,
397 solveDerivEqns :: Bag InstInfo
399 -> TcM s [InstInfo] -- Solns in same order as eqns.
400 -- This bunch is Absolutely minimal...
402 solveDerivEqns inst_decl_infos_in orig_eqns
403 = iterateDeriv initial_solutions
405 -- The initial solutions for the equations claim that each
406 -- instance has an empty context; this solution is certainly
407 -- in canonical form.
408 initial_solutions :: [DerivSoln]
409 initial_solutions = [ [] | _ <- orig_eqns ]
411 ------------------------------------------------------------------
412 -- iterateDeriv calculates the next batch of solutions,
413 -- compares it with the current one; finishes if they are the
414 -- same, otherwise recurses with the new solutions.
415 -- It fails if any iteration fails
416 iterateDeriv :: [DerivSoln] ->TcM s [InstInfo]
417 iterateDeriv current_solns
418 = checkNoErrsTc (iterateOnce current_solns) `thenTc` \ (new_inst_infos, new_solns) ->
419 if (current_solns == new_solns) then
420 returnTc new_inst_infos
422 iterateDeriv new_solns
424 ------------------------------------------------------------------
425 iterateOnce current_solns
426 = -- Extend the inst info from the explicit instance decls
427 -- with the current set of solutions, giving a
429 add_solns inst_decl_infos_in orig_eqns current_solns
430 `thenNF_Tc` \ (new_inst_infos, inst_mapper) ->
432 class_to_inst_env cls = inst_mapper cls
436 listTc [ tcAddErrCtxt (derivCtxt tc) $
437 tcSimplifyThetas class_to_inst_env deriv_rhs
438 | (_,tc,_,deriv_rhs) <- orig_eqns ] `thenTc` \ next_solns ->
440 -- Canonicalise the solutions, so they compare nicely
441 let canonicalised_next_solns
442 = [ sortLt (<) next_soln | next_soln <- next_solns ]
444 returnTc (new_inst_infos, canonicalised_next_solns)
448 add_solns :: Bag InstInfo -- The global, non-derived ones
449 -> [DerivEqn] -> [DerivSoln]
450 -> NF_TcM s ([InstInfo], -- The new, derived ones
452 -- the eqns and solns move "in lockstep"; we have the eqns
453 -- because we need the LHS info for addClassInstance.
455 add_solns inst_infos_in eqns solns
457 = discardErrsTc (buildInstanceEnvs all_inst_infos) `thenNF_Tc` \ inst_mapper ->
458 -- We do the discard-errs so that we don't get repeated error messages
459 -- about duplicate instances.
460 -- They'll appear later, when we do the top-level buildInstanceEnvs.
462 returnNF_Tc (new_inst_infos, inst_mapper)
464 new_inst_infos = zipWithEqual "add_solns" mk_deriv_inst_info eqns solns
466 all_inst_infos = inst_infos_in `unionBags` listToBag new_inst_infos
468 mk_deriv_inst_info (clas, tycon, tyvars, _) theta
469 = InstInfo clas tyvars [mkTyConApp tycon (mkTyVarTys tyvars)]
472 (my_panic "binds") (getSrcLoc tycon)
473 (my_panic "upragmas")
476 = mkVanillaId (getName tycon) dummy_dfun_ty
477 -- The name is getSrcLoc'd in an error message
479 dummy_dfun_ty = mkSigmaTy tyvars theta voidTy
480 -- All we need from the dfun is its "theta" part, used during
481 -- equation simplification (tcSimplifyThetas). The final
482 -- dfun_id will have the superclass dictionaries as arguments too,
483 -- but that'll be added after the equations are solved. For now,
484 -- it's enough just to make a dummy dfun with the simple theta part.
486 -- The part after the theta is dummied here as voidTy; actually it's
487 -- (C (T a b)), but it doesn't seem worth constructing it.
488 -- We can't leave it as a panic because to get the theta part we
489 -- have to run down the type!
491 my_panic str = panic "add_soln" -- pprPanic ("add_soln:"++str) (hsep [char ':', ppr clas, ppr tycon])
494 %************************************************************************
496 \subsection[TcDeriv-normal-binds]{Bindings for the various classes}
498 %************************************************************************
500 After all the trouble to figure out the required context for the
501 derived instance declarations, all that's left is to chug along to
502 produce them. They will then be shoved into @tcInstDecls2@, which
503 will do all its usual business.
505 There are lots of possibilities for code to generate. Here are
506 various general remarks.
511 We want derived instances of @Eq@ and @Ord@ (both v common) to be
512 ``you-couldn't-do-better-by-hand'' efficient.
515 Deriving @Show@---also pretty common--- should also be reasonable good code.
518 Deriving for the other classes isn't that common or that big a deal.
525 Deriving @Ord@ is done mostly with the 1.3 @compare@ method.
528 Deriving @Eq@ also uses @compare@, if we're deriving @Ord@, too.
531 We {\em normally} generate code only for the non-defaulted methods;
532 there are some exceptions for @Eq@ and (especially) @Ord@...
535 Sometimes we use a @_con2tag_<tycon>@ function, which returns a data
536 constructor's numeric (@Int#@) tag. These are generated by
537 @gen_tag_n_con_binds@, and the heuristic for deciding if one of
538 these is around is given by @hasCon2TagFun@.
540 The examples under the different sections below will make this
544 Much less often (really just for deriving @Ix@), we use a
545 @_tag2con_<tycon>@ function. See the examples.
548 We use the renamer!!! Reason: we're supposed to be
549 producing @RenamedMonoBinds@ for the methods, but that means
550 producing correctly-uniquified code on the fly. This is entirely
551 possible (the @TcM@ monad has a @UniqueSupply@), but it is painful.
552 So, instead, we produce @RdrNameMonoBinds@ then heave 'em through
553 the renamer. What a great hack!
557 -- Generate the method bindings for the required instance
558 -- (paired with class name, as we need that when generating dict
560 gen_bind :: Fixities -> InstInfo -> ({-class-}OccName, {-tyCon-}OccName, RdrNameMonoBinds)
561 gen_bind fixities (InstInfo clas _ [ty] _ _ _ _ _)
563 = (clas_nm, tycon_nm, EmptyMonoBinds)
564 | ckey == showClassKey
565 = (clas_nm, tycon_nm, gen_Show_binds fixities tycon)
566 | ckey == readClassKey
567 = (clas_nm, tycon_nm, gen_Read_binds fixities tycon)
569 = (clas_nm, tycon_nm,
570 assoc "gen_bind:bad derived class"
571 [(eqClassKey, gen_Eq_binds)
572 ,(ordClassKey, gen_Ord_binds)
573 ,(enumClassKey, gen_Enum_binds)
574 ,(boundedClassKey, gen_Bounded_binds)
575 ,(ixClassKey, gen_Ix_binds)
580 clas_nm = nameOccName (getName clas)
581 tycon_nm = nameOccName (getName tycon)
582 from_here = isLocallyDefined tycon
583 (tycon,_,_) = splitAlgTyConApp ty
587 gen_inst_info :: InstInfo
588 -> (Name, RenamedMonoBinds)
589 -> InstInfo -- the gen'd (filled-in) "instance decl"
591 gen_inst_info (InstInfo clas tyvars tys@(ty:_) inst_decl_theta _ _ locn _)
592 (dfun_name, meth_binds)
594 -- Generate the various instance-related Ids
595 InstInfo clas tyvars tys inst_decl_theta
600 dfun_id = mkDictFunId dfun_name clas tyvars tys inst_decl_theta
602 from_here = isLocallyDefined tycon
603 (tycon,_,_) = splitAlgTyConApp ty
607 %************************************************************************
609 \subsection[TcDeriv-taggery-Names]{What con2tag/tag2con functions are available?}
611 %************************************************************************
616 con2tag_Foo :: Foo ... -> Int#
617 tag2con_Foo :: Int -> Foo ... -- easier if Int, not Int#
618 maxtag_Foo :: Int -- ditto (NB: not unboxed)
621 We have a @con2tag@ function for a tycon if:
624 We're deriving @Eq@ and the tycon has nullary data constructors.
627 Or: we're deriving @Ord@ (unless single-constructor), @Enum@, @Ix@
631 We have a @tag2con@ function for a tycon if:
634 We're deriving @Enum@, or @Ix@ (enum type only???)
637 If we have a @tag2con@ function, we also generate a @maxtag@ constant.
640 gen_taggery_Names :: [InstInfo]
641 -> TcM s [(RdrName, -- for an assoc list
642 TyCon, -- related tycon
645 gen_taggery_Names inst_infos
646 = --pprTrace "gen_taggery:\n" (vcat [hsep [ppr c, ppr t] | (c,t) <- all_CTs]) $
647 foldlTc do_con2tag [] tycons_of_interest `thenTc` \ names_so_far ->
648 foldlTc do_tag2con names_so_far tycons_of_interest
650 all_CTs = [ (c, get_tycon ty) | (InstInfo c _ [ty] _ _ _ _ _) <- inst_infos ]
652 get_tycon ty = case splitAlgTyConApp ty of { (tc, _, _) -> tc }
654 all_tycons = map snd all_CTs
655 (tycons_of_interest, _) = removeDups compare all_tycons
657 do_con2tag acc_Names tycon
658 | isDataTyCon tycon &&
659 ((we_are_deriving eqClassKey tycon
660 && any isNullaryDataCon (tyConDataCons tycon))
661 || (we_are_deriving ordClassKey tycon
662 && not (maybeToBool (maybeTyConSingleCon tycon)))
663 || (we_are_deriving enumClassKey tycon)
664 || (we_are_deriving ixClassKey tycon))
666 = returnTc ((con2tag_RDR tycon, tycon, GenCon2Tag)
671 do_tag2con acc_Names tycon
672 | isDataTyCon tycon &&
673 (we_are_deriving enumClassKey tycon ||
674 we_are_deriving ixClassKey tycon
675 && isEnumerationTyCon tycon)
676 = returnTc ( (tag2con_RDR tycon, tycon, GenTag2Con)
677 : (maxtag_RDR tycon, tycon, GenMaxTag)
682 we_are_deriving clas_key tycon
683 = is_in_eqns clas_key tycon all_CTs
685 is_in_eqns clas_key tycon [] = False
686 is_in_eqns clas_key tycon ((c,t):cts)
687 = (clas_key == classKey c && tycon == t)
688 || is_in_eqns clas_key tycon cts
693 derivingThingErr :: FAST_STRING -> FAST_STRING -> TyCon -> Message
695 derivingThingErr thing why tycon
696 = hang (hsep [ptext SLIT("Can't make a derived instance of"), ptext thing])
697 0 (hang (hsep [ptext SLIT("for the type"), quotes (ppr tycon)])
698 0 (parens (ptext why)))
701 = ptext SLIT("When deriving classes for") <+> quotes (ppr tycon)