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 )
16 import CmdLineOpts ( opt_D_dump_deriv )
19 import TcEnv ( InstEnv, getEnvTyCons, tcSetInstEnv, newDFunName )
20 import TcGenDeriv -- Deriv stuff
21 import TcInstUtil ( InstInfo(..), pprInstInfo, simpleDFunClassTyCon, extendInstEnv )
22 import TcSimplify ( tcSimplifyThetas )
24 import RnBinds ( rnMethodBinds, rnTopMonoBinds )
25 import RnEnv ( bindLocatedLocalsRn )
26 import RnMonad ( RnNameSupply,
27 renameSourceCode, thenRn, mapRn, returnRn )
29 import Bag ( Bag, emptyBag, unionBags, listToBag )
30 import Class ( classKey, Class )
31 import ErrUtils ( dumpIfSet, Message )
32 import MkId ( mkDictFunId )
33 import Id ( mkVanillaId )
34 import DataCon ( dataConArgTys, isNullaryDataCon, isExistentialDataCon )
35 import PrelInfo ( needsDataDeclCtxtClassKeys )
36 import Maybes ( maybeToBool, catMaybes )
37 import Module ( Module )
38 import Name ( isLocallyDefined, getSrcLoc, NamedThing(..) )
39 import RdrName ( RdrName )
40 import RnMonad ( FixityEnv )
42 import TyCon ( tyConTyVars, tyConDataCons, tyConDerivings,
43 tyConTheta, maybeTyConSingleCon, isDataTyCon,
44 isEnumerationTyCon, isAlgTyCon, TyCon
46 import Type ( TauType, mkTyVarTys, mkTyConApp,
47 mkSigmaTy, mkDictTy, isUnboxedType,
48 splitAlgTyConApp, classesToPreds
50 import TysWiredIn ( voidTy )
53 import Bag ( bagToList )
54 import Util ( zipWithEqual, sortLt, thenCmp )
55 import ListSetOps ( removeDups, assoc )
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 type DerivRhs = [(Class, [TauType])] -- Same as a ThetaType!
150 type DerivSoln = DerivRhs
154 A note about contexts on data decls
155 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
158 data (RealFloat a) => Complex a = !a :+ !a deriving( Read )
160 We will need an instance decl like:
162 instance (Read a, RealFloat a) => Read (Complex a) where
165 The RealFloat in the context is because the read method for Complex is bound
166 to construct a Complex, and doing that requires that the argument type is
169 But this ain't true for Show, Eq, Ord, etc, since they don't construct
170 a Complex; they only take them apart.
172 Our approach: identify the offending classes, and add the data type
173 context to the instance decl. The "offending classes" are
178 %************************************************************************
180 \subsection[TcDeriv-driver]{Top-level function for \tr{derivings}}
182 %************************************************************************
185 tcDeriving :: PersistentRenamerState
186 -> Module -- name of module under scrutiny
187 -> InstEnv -- What we already know about instances
188 -> TcM ([InstInfo], -- The generated "instance decls".
189 RenamedHsBinds) -- Extra generated bindings
191 tcDeriving prs mod inst_env_in local_tycons
192 = recoverTc (returnTc ([], EmptyBinds)) $
194 -- Fish the "deriving"-related information out of the TcEnv
195 -- and make the necessary "equations".
196 makeDerivEqns 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 ->
216 extra_mbind_list = map gen_tag_n_con_monobind nm_alist_etc
217 extra_mbinds = foldr AndMonoBinds EmptyMonoBinds extra_mbind_list
218 method_binds_s = map (gen_bind (tcGST env)) new_dfuns
219 mbinders = collectLocatedMonoBinders extra_mbinds
221 -- Rename to get RenamedBinds.
222 -- The only tricky bit is that the extra_binds must scope over the
223 -- method bindings for the instances.
224 (rn_method_binds_s, rn_extra_binds)
225 = renameSourceCode mod prs (
226 bindLocatedLocalsRn (ptext (SLIT("deriving"))) mbinders $ \ _ ->
227 rnTopMonoBinds extra_mbinds [] `thenRn` \ (rn_extra_binds, _) ->
228 mapRn rn_meths method_binds_s `thenRn` \ rn_method_binds_s ->
229 returnRn (rn_method_binds_s, rn_extra_binds)
232 mapNF_Tc gen_inst_info (new_dfuns `zip` rn_method_binds_s) `thenNF_Tc` \ new_inst_infos ->
234 ioToTc (dumpIfSet opt_D_dump_deriv "Derived instances"
235 (ddump_deriving new_inst_infos rn_extra_binds)) `thenTc_`
237 returnTc (new_inst_infos, rn_extra_binds)
239 ddump_deriving :: [InstInfo] -> RenamedHsBinds -> SDoc
240 ddump_deriving inst_infos extra_binds
241 = vcat (map pprInstInfo inst_infos) $$ ppr extra_binds
244 -- Make a Real dfun instead of the dummy one we have so far
245 gen_inst_info (dfun, binds)
246 = InstInfo { iLocal = True,
247 iClass = clas, iTyVars = tyvars,
248 iTys = tys, iTheta = theta,
249 iDFunId = dfun, iBinds = binds,
250 iLoc = getSrcLoc dfun, iPrags = [] }
252 (tyvars, theta, tau) = splitSigmaTy dfun
253 (clas, tys) = splitDictTy tau
255 rn_meths meths = rnMethodBinds [] meths `thenRn` \ (meths', _) -> returnRn meths'
256 -- Ignore the free vars returned
260 %************************************************************************
262 \subsection[TcDeriv-eqns]{Forming the equations}
264 %************************************************************************
266 @makeDerivEqns@ fishes around to find the info about needed derived
267 instances. Complicating factors:
270 We can only derive @Enum@ if the data type is an enumeration
271 type (all nullary data constructors).
274 We can only derive @Ix@ if the data type is an enumeration {\em
275 or} has just one data constructor (e.g., tuples).
278 [See Appendix~E in the Haskell~1.2 report.] This code here deals w/
282 makeDerivEqns :: Module -> [TyCon] -> TcM [DerivEqn]
284 makeDerivEqns this_mod local_tycons
286 think_about_deriving = need_deriving local_tycons
287 (derive_these, _) = removeDups cmp_deriv think_about_deriving
289 if null local_data_tycons then
290 returnTc [] -- Bale out now
292 mapTc mk_eqn derive_these `thenTc` \ maybe_eqns ->
293 returnTc (catMaybes maybe_eqns)
295 ------------------------------------------------------------------
296 need_deriving :: [TyCon] -> [(Class, TyCon)]
297 -- find the tycons that have `deriving' clauses;
299 need_deriving tycons_to_consider
300 = foldr (\ tycon acc -> [(clas,tycon) | clas <- tyConDerivings tycon] ++ acc)
304 ------------------------------------------------------------------
305 cmp_deriv :: (Class, TyCon) -> (Class, TyCon) -> Ordering
306 cmp_deriv (c1, t1) (c2, t2)
307 = (c1 `compare` c2) `thenCmp` (t1 `compare` t2)
309 ------------------------------------------------------------------
310 mk_eqn :: (Class, TyCon) -> NF_TcM (Maybe DerivEqn)
311 -- we swizzle the tyvars and datacons out of the tycon
312 -- to make the rest of the equation
315 = case chk_out clas tycon of
316 Just err -> addErrTc err `thenNF_Tc_`
318 Nothing -> newDFunName this_mod clas tys locn `thenNF_Tc` \ dfun_name ->
319 returnNF_Tc (Just (dfun_name, clas, tycon, tyvars, constraints))
321 clas_key = classKey clas
322 tyvars = tyConTyVars tycon -- ToDo: Do we need new tyvars ???
323 tyvar_tys = mkTyVarTys tyvars
324 data_cons = tyConDataCons tycon
326 constraints = extra_constraints ++ concat (map mk_constraints data_cons)
328 -- "extra_constraints": see notes above about contexts on data decls
330 | offensive_class = tyConTheta tycon
333 offensive_class = clas_key `elem` needsDataDeclCtxtClassKeys
335 mk_constraints data_con
337 | arg_ty <- instd_arg_tys,
338 not (isUnboxedType arg_ty) -- No constraints for unboxed types?
341 instd_arg_tys = dataConArgTys data_con tyvar_tys
343 ------------------------------------------------------------------
344 chk_out :: Class -> TyCon -> Maybe Message
346 | clas `hasKey` enumClassKey && not is_enumeration = bog_out nullary_why
347 | clas `hasKey` boundedClassKey && not is_enumeration_or_single = bog_out single_nullary_why
348 | clas `hasKey` ixClassKey && not is_enumeration_or_single = bog_out single_nullary_why
349 | any isExistentialDataCon (tyConDataCons tycon) = Just (existentialErr clas tycon)
350 | otherwise = Nothing
352 is_enumeration = isEnumerationTyCon tycon
353 is_single_con = maybeToBool (maybeTyConSingleCon tycon)
354 is_enumeration_or_single = is_enumeration || is_single_con
356 single_nullary_why = SLIT("one constructor data type or type with all nullary constructors expected")
357 nullary_why = SLIT("data type with all nullary constructors expected")
359 bog_out why = Just (derivingThingErr clas tycon why)
362 %************************************************************************
364 \subsection[TcDeriv-fixpoint]{Finding the fixed point of \tr{deriving} equations}
366 %************************************************************************
368 A ``solution'' (to one of the equations) is a list of (k,TyVarTy tv)
369 terms, which is the final correct RHS for the corresponding original
373 Each (k,TyVarTy tv) in a solution constrains only a type
377 The (k,TyVarTy tv) pairs in a solution are canonically
378 ordered by sorting on type varible, tv, (major key) and then class, k,
383 solveDerivEqns :: InstEnv
385 -> TcM [DFunId] -- Solns in same order as eqns.
386 -- This bunch is Absolutely minimal...
388 solveDerivEqns inst_env_in orig_eqns
389 = iterateDeriv initial_solutions
391 -- The initial solutions for the equations claim that each
392 -- instance has an empty context; this solution is certainly
393 -- in canonical form.
394 initial_solutions :: [DerivSoln]
395 initial_solutions = [ [] | _ <- orig_eqns ]
397 ------------------------------------------------------------------
398 -- iterateDeriv calculates the next batch of solutions,
399 -- compares it with the current one; finishes if they are the
400 -- same, otherwise recurses with the new solutions.
401 -- It fails if any iteration fails
402 iterateDeriv :: [DerivSoln] ->TcM [DFunId]
403 iterateDeriv current_solns
404 = checkNoErrsTc (iterateOnce current_solns) `thenTc` \ (new_dfuns, new_solns) ->
405 if (current_solns == new_solns) then
408 iterateDeriv new_solns
410 ------------------------------------------------------------------
411 iterateOnce current_solns
412 = -- Extend the inst info from the explicit instance decls
413 -- with the current set of solutions, giving a
415 add_solns inst_env_in orig_eqns current_solns `thenNF_Tc` \ (new_dfuns, inst_env) ->
418 tcSetInstEnv inst_env (
419 listTc [ tcAddErrCtxt (derivCtxt tc) $
420 tcSimplifyThetas deriv_rhs
421 | (_, _,tc,_,deriv_rhs) <- orig_eqns ]
422 ) `thenTc` \ next_solns ->
424 -- Canonicalise the solutions, so they compare nicely
425 let canonicalised_next_solns = [ sortLt (<) next_soln | next_soln <- next_solns ]
427 returnTc (new_dfuns, canonicalised_next_solns)
431 add_solns :: InstEnv -- The global, non-derived ones
432 -> [DerivEqn] -> [DerivSoln]
433 -> ([DFunId], InstEnv)
434 -- the eqns and solns move "in lockstep"; we have the eqns
435 -- because we need the LHS info for addClassInstance.
437 add_solns inst_env_in eqns solns
438 = (new_dfuns, inst_env)
440 new_dfuns = zipWithEqual "add_solns" mk_deriv_dfun eqns solns
441 (inst_env, _) = extendInstEnv inst_env_in
442 -- Ignore the errors about duplicate instances.
443 -- We don't want repeated error messages
444 -- They'll appear later, when we do the top-level extendInstEnvs
446 mk_deriv_dfun (dfun_name clas, tycon, tyvars, _) theta
447 = mkDictFunId dfun_name clas tyvars [mkTyConApp tycon (mkTyVarTys tyvars)] theta
450 %************************************************************************
452 \subsection[TcDeriv-normal-binds]{Bindings for the various classes}
454 %************************************************************************
456 After all the trouble to figure out the required context for the
457 derived instance declarations, all that's left is to chug along to
458 produce them. They will then be shoved into @tcInstDecls2@, which
459 will do all its usual business.
461 There are lots of possibilities for code to generate. Here are
462 various general remarks.
467 We want derived instances of @Eq@ and @Ord@ (both v common) to be
468 ``you-couldn't-do-better-by-hand'' efficient.
471 Deriving @Show@---also pretty common--- should also be reasonable good code.
474 Deriving for the other classes isn't that common or that big a deal.
481 Deriving @Ord@ is done mostly with the 1.3 @compare@ method.
484 Deriving @Eq@ also uses @compare@, if we're deriving @Ord@, too.
487 We {\em normally} generate code only for the non-defaulted methods;
488 there are some exceptions for @Eq@ and (especially) @Ord@...
491 Sometimes we use a @_con2tag_<tycon>@ function, which returns a data
492 constructor's numeric (@Int#@) tag. These are generated by
493 @gen_tag_n_con_binds@, and the heuristic for deciding if one of
494 these is around is given by @hasCon2TagFun@.
496 The examples under the different sections below will make this
500 Much less often (really just for deriving @Ix@), we use a
501 @_tag2con_<tycon>@ function. See the examples.
504 We use the renamer!!! Reason: we're supposed to be
505 producing @RenamedMonoBinds@ for the methods, but that means
506 producing correctly-uniquified code on the fly. This is entirely
507 possible (the @TcM@ monad has a @UniqueSupply@), but it is painful.
508 So, instead, we produce @RdrNameMonoBinds@ then heave 'em through
509 the renamer. What a great hack!
513 -- Generate the method bindings for the required instance
514 -- (paired with class name, as we need that when generating dict
516 gen_bind :: GlobalSymbolTable -> DFunId -> RdrNameMonoBinds
517 gen_bind fixities inst
518 | not (isLocallyDefined tycon) = EmptyMonoBinds
519 | clas `hasKey` showClassKey = gen_Show_binds fixities tycon
520 | clas `hasKey` readClassKey = gen_Read_binds fixities tycon
522 = assoc "gen_bind:bad derived class"
523 [(eqClassKey, gen_Eq_binds)
524 ,(ordClassKey, gen_Ord_binds)
525 ,(enumClassKey, gen_Enum_binds)
526 ,(boundedClassKey, gen_Bounded_binds)
527 ,(ixClassKey, gen_Ix_binds)
532 (clas, tycon) = simpleDFunClassTyCon dfun
536 %************************************************************************
538 \subsection[TcDeriv-taggery-Names]{What con2tag/tag2con functions are available?}
540 %************************************************************************
545 con2tag_Foo :: Foo ... -> Int#
546 tag2con_Foo :: Int -> Foo ... -- easier if Int, not Int#
547 maxtag_Foo :: Int -- ditto (NB: not unboxed)
550 We have a @con2tag@ function for a tycon if:
553 We're deriving @Eq@ and the tycon has nullary data constructors.
556 Or: we're deriving @Ord@ (unless single-constructor), @Enum@, @Ix@
560 We have a @tag2con@ function for a tycon if:
563 We're deriving @Enum@, or @Ix@ (enum type only???)
566 If we have a @tag2con@ function, we also generate a @maxtag@ constant.
569 gen_taggery_Names :: [DFunId]
570 -> TcM [(RdrName, -- for an assoc list
571 TyCon, -- related tycon
574 gen_taggery_Names dfuns
575 = foldlTc do_con2tag [] tycons_of_interest `thenTc` \ names_so_far ->
576 foldlTc do_tag2con names_so_far tycons_of_interest
578 all_CTs = map simplDFunClassTyCon dfuns
579 all_tycons = map snd all_CTs
580 (tycons_of_interest, _) = removeDups compare all_tycons
582 do_con2tag acc_Names tycon
583 | isDataTyCon tycon &&
584 ((we_are_deriving eqClassKey tycon
585 && any isNullaryDataCon (tyConDataCons tycon))
586 || (we_are_deriving ordClassKey tycon
587 && not (maybeToBool (maybeTyConSingleCon tycon)))
588 || (we_are_deriving enumClassKey tycon)
589 || (we_are_deriving ixClassKey tycon))
591 = returnTc ((con2tag_RDR tycon, tycon, GenCon2Tag)
596 do_tag2con acc_Names tycon
597 | isDataTyCon tycon &&
598 (we_are_deriving enumClassKey tycon ||
599 we_are_deriving ixClassKey tycon
600 && isEnumerationTyCon tycon)
601 = returnTc ( (tag2con_RDR tycon, tycon, GenTag2Con)
602 : (maxtag_RDR tycon, tycon, GenMaxTag)
607 we_are_deriving clas_key tycon
608 = is_in_eqns clas_key tycon all_CTs
610 is_in_eqns clas_key tycon [] = False
611 is_in_eqns clas_key tycon ((c,t):cts)
612 = (clas_key == classKey c && tycon == t)
613 || is_in_eqns clas_key tycon cts
618 derivingThingErr :: Class -> TyCon -> FAST_STRING -> Message
620 derivingThingErr clas tycon why
621 = sep [hsep [ptext SLIT("Can't make a derived instance of"), quotes (ppr clas)],
622 hsep [ptext SLIT("for the type"), quotes (ppr tycon)],
625 existentialErr clas tycon
626 = sep [ptext SLIT("Can't derive any instances for type") <+> quotes (ppr tycon),
627 ptext SLIT("because it has existentially-quantified constructor(s)")]
630 = ptext SLIT("When deriving classes for") <+> quotes (ppr tycon)