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(..), collectLocatedMonoBinders )
14 import RdrHsSyn ( RdrNameMonoBinds )
15 import RnHsSyn ( RenamedHsBinds, RenamedMonoBinds )
16 import CmdLineOpts ( DynFlag(..), DynFlags )
19 import TcEnv ( TcEnv, tcSetInstEnv, newDFunName, InstInfo(..), pprInstInfo )
20 import TcGenDeriv -- Deriv stuff
21 import InstEnv ( InstEnv, simpleDFunClassTyCon, extendInstEnv )
22 import TcSimplify ( tcSimplifyThetas )
24 import RnBinds ( rnMethodBinds, rnTopMonoBinds )
25 import RnEnv ( bindLocatedLocalsRn )
26 import RnMonad ( --RnNameSupply,
27 renameSourceCode, thenRn, mapRn, returnRn )
28 import HscTypes ( DFunId, PersistentRenamerState )
30 import BasicTypes ( Fixity )
31 import Class ( classKey, Class )
32 import ErrUtils ( dumpIfSet_dyn, Message )
33 import MkId ( mkDictFunId )
35 import DataCon ( dataConArgTys, isNullaryDataCon, isExistentialDataCon )
36 import PrelInfo ( needsDataDeclCtxtClassKeys )
37 import Maybes ( maybeToBool, catMaybes )
38 import Module ( Module )
39 import Name ( Name, isLocallyDefined, getSrcLoc )
40 import RdrName ( RdrName )
42 import TyCon ( tyConTyVars, tyConDataCons, tyConDerivings,
43 tyConTheta, maybeTyConSingleCon, isDataTyCon,
44 isEnumerationTyCon, TyCon
46 import Type ( TauType, PredType(..), mkTyVarTys, mkTyConApp,
47 splitDFunTy, isUnboxedType
51 import Util ( zipWithEqual, sortLt, thenCmp )
52 import ListSetOps ( removeDups, assoc )
56 %************************************************************************
58 \subsection[TcDeriv-intro]{Introduction to how we do deriving}
60 %************************************************************************
64 data T a b = C1 (Foo a) (Bar b)
69 [NOTE: See end of these comments for what to do with
70 data (C a, D b) => T a b = ...
73 We want to come up with an instance declaration of the form
75 instance (Ping a, Pong b, ...) => Eq (T a b) where
78 It is pretty easy, albeit tedious, to fill in the code "...". The
79 trick is to figure out what the context for the instance decl is,
80 namely @Ping@, @Pong@ and friends.
82 Let's call the context reqd for the T instance of class C at types
83 (a,b, ...) C (T a b). Thus:
85 Eq (T a b) = (Ping a, Pong b, ...)
87 Now we can get a (recursive) equation from the @data@ decl:
89 Eq (T a b) = Eq (Foo a) u Eq (Bar b) -- From C1
90 u Eq (T b a) u Eq Int -- From C2
91 u Eq (T a a) -- From C3
93 Foo and Bar may have explicit instances for @Eq@, in which case we can
94 just substitute for them. Alternatively, either or both may have
95 their @Eq@ instances given by @deriving@ clauses, in which case they
96 form part of the system of equations.
98 Now all we need do is simplify and solve the equations, iterating to
99 find the least fixpoint. Notice that the order of the arguments can
100 switch around, as here in the recursive calls to T.
102 Let's suppose Eq (Foo a) = Eq a, and Eq (Bar b) = Ping b.
106 Eq (T a b) = {} -- The empty set
109 Eq (T a b) = Eq (Foo a) u Eq (Bar b) -- From C1
110 u Eq (T b a) u Eq Int -- From C2
111 u Eq (T a a) -- From C3
113 After simplification:
114 = Eq a u Ping b u {} u {} u {}
119 Eq (T a b) = Eq (Foo a) u Eq (Bar b) -- From C1
120 u Eq (T b a) u Eq Int -- From C2
121 u Eq (T a a) -- From C3
123 After simplification:
128 = Eq a u Ping b u Eq b u Ping a
130 The next iteration gives the same result, so this is the fixpoint. We
131 need to make a canonical form of the RHS to ensure convergence. We do
132 this by simplifying the RHS to a form in which
134 - the classes constrain only tyvars
135 - the list is sorted by tyvar (major key) and then class (minor key)
136 - no duplicates, of course
138 So, here are the synonyms for the ``equation'' structures:
141 type DerivEqn = (Name, Class, TyCon, [TyVar], DerivRhs)
142 -- The Name is the name for the DFun we'll build
143 -- The tyvars bind all the variables in the RHS
145 type DerivRhs = [(Class, [TauType])] -- Same as a ThetaType!
146 --[PredType] -- ... | Class Class [Type==TauType]
148 type DerivSoln = DerivRhs
152 A note about contexts on data decls
153 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
156 data (RealFloat a) => Complex a = !a :+ !a deriving( Read )
158 We will need an instance decl like:
160 instance (Read a, RealFloat a) => Read (Complex a) where
163 The RealFloat in the context is because the read method for Complex is bound
164 to construct a Complex, and doing that requires that the argument type is
167 But this ain't true for Show, Eq, Ord, etc, since they don't construct
168 a Complex; they only take them apart.
170 Our approach: identify the offending classes, and add the data type
171 context to the instance decl. The "offending classes" are
176 %************************************************************************
178 \subsection[TcDeriv-driver]{Top-level function for \tr{derivings}}
180 %************************************************************************
183 tcDeriving :: PersistentRenamerState
184 -> Module -- name of module under scrutiny
185 -> InstEnv -- What we already know about instances
186 -> (Name -> Maybe Fixity) -- used in deriving Show and Read
187 -> [TyCon] -- "local_tycons" ???
188 -> TcM ([InstInfo], -- The generated "instance decls".
189 RenamedHsBinds) -- Extra generated bindings
191 tcDeriving prs mod inst_env_in get_fixity local_tycons
192 = recoverTc (returnTc ([], EmptyBinds)) $
194 -- Fish the "deriving"-related information out of the TcEnv
195 -- and make the necessary "equations".
196 makeDerivEqns mod local_tycons `thenTc` \ eqns ->
198 returnTc ([], EmptyBinds)
201 -- Take the equation list and solve it, to deliver a list of
202 -- solutions, a.k.a. the contexts for the instance decls
203 -- required for the corresponding equations.
204 solveDerivEqns inst_env_in eqns `thenTc` \ new_dfuns ->
206 -- Now augment the InstInfos, adding in the rather boring
207 -- actual-code-to-do-the-methods binds. We may also need to
208 -- generate extra not-one-inst-decl-specific binds, notably
209 -- "con2tag" and/or "tag2con" functions. We do these
212 gen_taggery_Names new_dfuns `thenTc` \ nm_alist_etc ->
214 tcGetEnv `thenNF_Tc` \ env ->
215 getDOptsTc `thenTc` \ dflags ->
217 extra_mbind_list = map gen_tag_n_con_monobind nm_alist_etc
218 extra_mbinds = foldr AndMonoBinds EmptyMonoBinds extra_mbind_list
219 method_binds_s = map (gen_bind get_fixity) new_dfuns
220 mbinders = collectLocatedMonoBinders extra_mbinds
222 -- Rename to get RenamedBinds.
223 -- The only tricky bit is that the extra_binds must scope over the
224 -- method bindings for the instances.
225 (rn_method_binds_s, rn_extra_binds)
226 = renameSourceCode dflags mod prs (
227 bindLocatedLocalsRn (ptext (SLIT("deriving"))) mbinders $ \ _ ->
228 rnTopMonoBinds extra_mbinds [] `thenRn` \ (rn_extra_binds, _) ->
229 mapRn rn_meths method_binds_s `thenRn` \ rn_method_binds_s ->
230 returnRn (rn_method_binds_s, rn_extra_binds)
233 new_inst_infos = map gen_inst_info (new_dfuns `zip` rn_method_binds_s)
236 ioToTc (dumpIfSet_dyn dflags Opt_D_dump_deriv "Derived instances"
237 (ddump_deriving new_inst_infos rn_extra_binds)) `thenTc_`
239 returnTc (new_inst_infos, rn_extra_binds)
241 ddump_deriving :: [InstInfo] -> RenamedHsBinds -> SDoc
242 ddump_deriving inst_infos extra_binds
243 = vcat (map pprInstInfo inst_infos) $$ ppr extra_binds
246 -- Make a Real dfun instead of the dummy one we have so far
247 gen_inst_info :: (DFunId, RenamedMonoBinds) -> InstInfo
248 gen_inst_info (dfun, binds)
249 = InstInfo { iLocal = True,
250 iClass = clas, iTyVars = tyvars,
251 iTys = tys, iTheta = theta,
254 iLoc = getSrcLoc dfun, iPrags = [] }
256 (tyvars, theta, clas, tys) = splitDFunTy (idType dfun)
258 rn_meths meths = rnMethodBinds [] meths `thenRn` \ (meths', _) -> returnRn meths'
259 -- Ignore the free vars returned
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 :: Module -> [TyCon] -> TcM [DerivEqn]
287 makeDerivEqns this_mod local_tycons
289 think_about_deriving = need_deriving local_tycons
290 (derive_these, _) = removeDups cmp_deriv think_about_deriving
292 if null local_tycons then
293 returnTc [] -- Bale out now
295 mapTc mk_eqn derive_these `thenTc` \ maybe_eqns ->
296 returnTc (catMaybes maybe_eqns)
298 ------------------------------------------------------------------
299 need_deriving :: [TyCon] -> [(Class, TyCon)]
300 -- find the tycons that have `deriving' clauses;
302 need_deriving tycons_to_consider
303 = foldr (\ tycon acc -> [(clas,tycon) | clas <- tyConDerivings tycon] ++ acc)
307 ------------------------------------------------------------------
308 cmp_deriv :: (Class, TyCon) -> (Class, TyCon) -> Ordering
309 cmp_deriv (c1, t1) (c2, t2)
310 = (c1 `compare` c2) `thenCmp` (t1 `compare` t2)
312 ------------------------------------------------------------------
313 mk_eqn :: (Class, TyCon) -> NF_TcM (Maybe DerivEqn)
314 -- we swizzle the tyvars and datacons out of the tycon
315 -- to make the rest of the equation
318 = case chk_out clas tycon of
319 Just err -> addErrTc err `thenNF_Tc_`
321 Nothing -> newDFunName this_mod clas tyvar_tys locn `thenNF_Tc` \ dfun_name ->
322 returnNF_Tc (Just (dfun_name, clas, tycon, tyvars, constraints))
324 clas_key = classKey clas
325 tyvars = tyConTyVars tycon -- ToDo: Do we need new tyvars ???
326 tyvar_tys = mkTyVarTys tyvars
327 data_cons = tyConDataCons tycon
328 locn = getSrcLoc tycon
330 constraints = extra_constraints ++ concat (map mk_constraints data_cons)
332 -- "extra_constraints": see notes above about contexts on data decls
334 | offensive_class = tyConTheta tycon
337 offensive_class = clas_key `elem` needsDataDeclCtxtClassKeys
339 mk_constraints data_con
341 | arg_ty <- instd_arg_tys,
342 not (isUnboxedType arg_ty) -- No constraints for unboxed types?
345 instd_arg_tys = dataConArgTys data_con tyvar_tys
347 ------------------------------------------------------------------
348 chk_out :: Class -> TyCon -> Maybe Message
350 | clas `hasKey` enumClassKey && not is_enumeration = bog_out nullary_why
351 | clas `hasKey` boundedClassKey && not is_enumeration_or_single = bog_out single_nullary_why
352 | clas `hasKey` ixClassKey && not is_enumeration_or_single = bog_out single_nullary_why
353 | any isExistentialDataCon (tyConDataCons tycon) = Just (existentialErr clas tycon)
354 | otherwise = Nothing
356 is_enumeration = isEnumerationTyCon tycon
357 is_single_con = maybeToBool (maybeTyConSingleCon tycon)
358 is_enumeration_or_single = is_enumeration || is_single_con
360 single_nullary_why = SLIT("one constructor data type or type with all nullary constructors expected")
361 nullary_why = SLIT("data type with all nullary constructors expected")
363 bog_out why = Just (derivingThingErr clas tycon why)
366 %************************************************************************
368 \subsection[TcDeriv-fixpoint]{Finding the fixed point of \tr{deriving} equations}
370 %************************************************************************
372 A ``solution'' (to one of the equations) is a list of (k,TyVarTy tv)
373 terms, which is the final correct RHS for the corresponding original
377 Each (k,TyVarTy tv) in a solution constrains only a type
381 The (k,TyVarTy tv) pairs in a solution are canonically
382 ordered by sorting on type varible, tv, (major key) and then class, k,
387 solveDerivEqns :: InstEnv
389 -> TcM [DFunId] -- Solns in same order as eqns.
390 -- This bunch is Absolutely minimal...
392 solveDerivEqns inst_env_in orig_eqns
393 = iterateDeriv initial_solutions
395 -- The initial solutions for the equations claim that each
396 -- instance has an empty context; this solution is certainly
397 -- in canonical form.
398 initial_solutions :: [DerivSoln]
399 initial_solutions = [ [] | _ <- orig_eqns ]
401 ------------------------------------------------------------------
402 -- iterateDeriv calculates the next batch of solutions,
403 -- compares it with the current one; finishes if they are the
404 -- same, otherwise recurses with the new solutions.
405 -- It fails if any iteration fails
406 iterateDeriv :: [DerivSoln] ->TcM [DFunId]
407 iterateDeriv current_solns
408 = checkNoErrsTc (iterateOnce current_solns)
409 `thenTc` \ (new_dfuns, new_solns) ->
410 if (current_solns == new_solns) then
413 iterateDeriv new_solns
415 ------------------------------------------------------------------
416 iterateOnce current_solns
417 = -- Extend the inst info from the explicit instance decls
418 -- with the current set of solutions, giving a
419 getDOptsTc `thenTc` \ dflags ->
420 let (new_dfuns, inst_env) =
421 add_solns dflags inst_env_in orig_eqns current_solns
424 tcSetInstEnv inst_env (
425 listTc [ tcAddErrCtxt (derivCtxt tc) $
426 tcSimplifyThetas deriv_rhs
427 | (_, _,tc,_,deriv_rhs) <- orig_eqns ]
428 ) `thenTc` \ next_solns ->
430 -- Canonicalise the solutions, so they compare nicely
431 let canonicalised_next_solns = [ sortLt (<) next_soln | next_soln <- next_solns ]
433 returnTc (new_dfuns, canonicalised_next_solns)
437 add_solns :: DynFlags
438 -> InstEnv -- The global, non-derived ones
439 -> [DerivEqn] -> [DerivSoln]
440 -> ([DFunId], InstEnv)
441 -- the eqns and solns move "in lockstep"; we have the eqns
442 -- because we need the LHS info for addClassInstance.
444 add_solns dflags inst_env_in eqns solns
445 = (new_dfuns, inst_env)
447 new_dfuns = zipWithEqual "add_solns" mk_deriv_dfun eqns solns
448 (inst_env, _) = extendInstEnv dflags inst_env_in new_dfuns
449 -- Ignore the errors about duplicate instances.
450 -- We don't want repeated error messages
451 -- They'll appear later, when we do the top-level extendInstEnvs
453 mk_deriv_dfun (dfun_name, clas, tycon, tyvars, _) theta
454 = mkDictFunId dfun_name clas tyvars [mkTyConApp tycon (mkTyVarTys tyvars)]
455 (map pair2PredType theta)
457 pair2PredType (clas, tautypes) = Class clas tautypes
460 %************************************************************************
462 \subsection[TcDeriv-normal-binds]{Bindings for the various classes}
464 %************************************************************************
466 After all the trouble to figure out the required context for the
467 derived instance declarations, all that's left is to chug along to
468 produce them. They will then be shoved into @tcInstDecls2@, which
469 will do all its usual business.
471 There are lots of possibilities for code to generate. Here are
472 various general remarks.
477 We want derived instances of @Eq@ and @Ord@ (both v common) to be
478 ``you-couldn't-do-better-by-hand'' efficient.
481 Deriving @Show@---also pretty common--- should also be reasonable good code.
484 Deriving for the other classes isn't that common or that big a deal.
491 Deriving @Ord@ is done mostly with the 1.3 @compare@ method.
494 Deriving @Eq@ also uses @compare@, if we're deriving @Ord@, too.
497 We {\em normally} generate code only for the non-defaulted methods;
498 there are some exceptions for @Eq@ and (especially) @Ord@...
501 Sometimes we use a @_con2tag_<tycon>@ function, which returns a data
502 constructor's numeric (@Int#@) tag. These are generated by
503 @gen_tag_n_con_binds@, and the heuristic for deciding if one of
504 these is around is given by @hasCon2TagFun@.
506 The examples under the different sections below will make this
510 Much less often (really just for deriving @Ix@), we use a
511 @_tag2con_<tycon>@ function. See the examples.
514 We use the renamer!!! Reason: we're supposed to be
515 producing @RenamedMonoBinds@ for the methods, but that means
516 producing correctly-uniquified code on the fly. This is entirely
517 possible (the @TcM@ monad has a @UniqueSupply@), but it is painful.
518 So, instead, we produce @RdrNameMonoBinds@ then heave 'em through
519 the renamer. What a great hack!
523 -- Generate the method bindings for the required instance
524 -- (paired with class name, as we need that when generating dict
526 gen_bind :: (Name -> Maybe Fixity) -> DFunId -> RdrNameMonoBinds
527 gen_bind get_fixity dfun
528 | not (isLocallyDefined tycon) = EmptyMonoBinds
529 | clas `hasKey` showClassKey = gen_Show_binds get_fixity tycon
530 | clas `hasKey` readClassKey = gen_Read_binds get_fixity tycon
532 = assoc "gen_bind:bad derived class"
533 [(eqClassKey, gen_Eq_binds)
534 ,(ordClassKey, gen_Ord_binds)
535 ,(enumClassKey, gen_Enum_binds)
536 ,(boundedClassKey, gen_Bounded_binds)
537 ,(ixClassKey, gen_Ix_binds)
542 (clas, tycon) = simpleDFunClassTyCon dfun
546 %************************************************************************
548 \subsection[TcDeriv-taggery-Names]{What con2tag/tag2con functions are available?}
550 %************************************************************************
555 con2tag_Foo :: Foo ... -> Int#
556 tag2con_Foo :: Int -> Foo ... -- easier if Int, not Int#
557 maxtag_Foo :: Int -- ditto (NB: not unboxed)
560 We have a @con2tag@ function for a tycon if:
563 We're deriving @Eq@ and the tycon has nullary data constructors.
566 Or: we're deriving @Ord@ (unless single-constructor), @Enum@, @Ix@
570 We have a @tag2con@ function for a tycon if:
573 We're deriving @Enum@, or @Ix@ (enum type only???)
576 If we have a @tag2con@ function, we also generate a @maxtag@ constant.
579 gen_taggery_Names :: [DFunId]
580 -> TcM [(RdrName, -- for an assoc list
581 TyCon, -- related tycon
584 gen_taggery_Names dfuns
585 = foldlTc do_con2tag [] tycons_of_interest `thenTc` \ names_so_far ->
586 foldlTc do_tag2con names_so_far tycons_of_interest
588 all_CTs = map simpleDFunClassTyCon dfuns
589 all_tycons = map snd all_CTs
590 (tycons_of_interest, _) = removeDups compare all_tycons
592 do_con2tag acc_Names tycon
593 | isDataTyCon tycon &&
594 ((we_are_deriving eqClassKey tycon
595 && any isNullaryDataCon (tyConDataCons tycon))
596 || (we_are_deriving ordClassKey tycon
597 && not (maybeToBool (maybeTyConSingleCon tycon)))
598 || (we_are_deriving enumClassKey tycon)
599 || (we_are_deriving ixClassKey tycon))
601 = returnTc ((con2tag_RDR tycon, tycon, GenCon2Tag)
606 do_tag2con acc_Names tycon
607 | isDataTyCon tycon &&
608 (we_are_deriving enumClassKey tycon ||
609 we_are_deriving ixClassKey tycon
610 && isEnumerationTyCon tycon)
611 = returnTc ( (tag2con_RDR tycon, tycon, GenTag2Con)
612 : (maxtag_RDR tycon, tycon, GenMaxTag)
617 we_are_deriving clas_key tycon
618 = is_in_eqns clas_key tycon all_CTs
620 is_in_eqns clas_key tycon [] = False
621 is_in_eqns clas_key tycon ((c,t):cts)
622 = (clas_key == classKey c && tycon == t)
623 || is_in_eqns clas_key tycon cts
627 derivingThingErr :: Class -> TyCon -> FAST_STRING -> Message
629 derivingThingErr clas tycon why
630 = sep [hsep [ptext SLIT("Can't make a derived instance of"), quotes (ppr clas)],
631 hsep [ptext SLIT("for the type"), quotes (ppr tycon)],
634 existentialErr clas tycon
635 = sep [ptext SLIT("Can't derive any instances for type") <+> quotes (ppr tycon),
636 ptext SLIT("because it has existentially-quantified constructor(s)")]
639 = ptext SLIT("When deriving classes for") <+> quotes (ppr tycon)