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"
14 import CmdLineOpts ( DynFlag(..) )
16 import Generics ( mkTyConGenericBinds )
18 import TcEnv ( newDFunName, pprInstInfoDetails,
19 InstInfo(..), InstBindings(..),
20 tcLookupClass, tcLookupTyCon, tcExtendTyVarEnv
22 import TcGenDeriv -- Deriv stuff
23 import InstEnv ( simpleDFunClassTyCon, extendInstEnv )
24 import TcHsType ( tcHsDeriv )
25 import TcSimplify ( tcSimplifyDeriv )
27 import RnBinds ( rnMethodBinds, rnTopBinds )
28 import RnEnv ( bindLocalNames )
29 import HscTypes ( DFunId, FixityEnv )
31 import Class ( className, classArity, classKey, classTyVars, classSCTheta, Class )
32 import Type ( zipTvSubst, substTheta )
33 import ErrUtils ( dumpIfSet_dyn )
34 import MkId ( mkDictFunId )
35 import DataCon ( isNullarySrcDataCon, isVanillaDataCon, dataConOrigArgTys )
36 import Maybes ( catMaybes )
37 import RdrName ( RdrName )
38 import Name ( Name, getSrcLoc )
39 import NameSet ( duDefs )
40 import Kind ( splitKindFunTys )
41 import TyCon ( tyConTyVars, tyConDataCons, tyConArity, tyConHasGenerics,
42 tyConStupidTheta, isProductTyCon, isDataTyCon, newTyConRhs,
43 isEnumerationTyCon, isRecursiveTyCon, TyCon
45 import TcType ( TcType, ThetaType, mkTyVarTys, mkTyConApp, tcTyConAppTyCon,
46 isUnLiftedType, mkClassPred, tyVarsOfTypes, isArgTypeKind,
47 tcEqTypes, tcSplitAppTys, mkAppTys, tcSplitDFunTy )
48 import Var ( TyVar, tyVarKind, idType, varName )
49 import VarSet ( mkVarSet, subVarSet )
51 import SrcLoc ( srcLocSpan, Located(..) )
52 import Util ( zipWithEqual, sortLe, notNull )
53 import ListSetOps ( removeDups, assocMaybe )
58 %************************************************************************
60 \subsection[TcDeriv-intro]{Introduction to how we do deriving}
62 %************************************************************************
66 data T a b = C1 (Foo a) (Bar b)
71 [NOTE: See end of these comments for what to do with
72 data (C a, D b) => T a b = ...
75 We want to come up with an instance declaration of the form
77 instance (Ping a, Pong b, ...) => Eq (T a b) where
80 It is pretty easy, albeit tedious, to fill in the code "...". The
81 trick is to figure out what the context for the instance decl is,
82 namely @Ping@, @Pong@ and friends.
84 Let's call the context reqd for the T instance of class C at types
85 (a,b, ...) C (T a b). Thus:
87 Eq (T a b) = (Ping a, Pong b, ...)
89 Now we can get a (recursive) equation from the @data@ decl:
91 Eq (T a b) = Eq (Foo a) u Eq (Bar b) -- From C1
92 u Eq (T b a) u Eq Int -- From C2
93 u Eq (T a a) -- From C3
95 Foo and Bar may have explicit instances for @Eq@, in which case we can
96 just substitute for them. Alternatively, either or both may have
97 their @Eq@ instances given by @deriving@ clauses, in which case they
98 form part of the system of equations.
100 Now all we need do is simplify and solve the equations, iterating to
101 find the least fixpoint. Notice that the order of the arguments can
102 switch around, as here in the recursive calls to T.
104 Let's suppose Eq (Foo a) = Eq a, and Eq (Bar b) = Ping b.
108 Eq (T a b) = {} -- The empty set
111 Eq (T a b) = Eq (Foo a) u Eq (Bar b) -- From C1
112 u Eq (T b a) u Eq Int -- From C2
113 u Eq (T a a) -- From C3
115 After simplification:
116 = Eq a u Ping b u {} u {} u {}
121 Eq (T a b) = Eq (Foo a) u Eq (Bar b) -- From C1
122 u Eq (T b a) u Eq Int -- From C2
123 u Eq (T a a) -- From C3
125 After simplification:
130 = Eq a u Ping b u Eq b u Ping a
132 The next iteration gives the same result, so this is the fixpoint. We
133 need to make a canonical form of the RHS to ensure convergence. We do
134 this by simplifying the RHS to a form in which
136 - the classes constrain only tyvars
137 - the list is sorted by tyvar (major key) and then class (minor key)
138 - no duplicates, of course
140 So, here are the synonyms for the ``equation'' structures:
143 type DerivEqn = (Name, Class, TyCon, [TyVar], DerivRhs)
144 -- The Name is the name for the DFun we'll build
145 -- The tyvars bind all the variables in the RHS
147 pprDerivEqn (n,c,tc,tvs,rhs)
148 = parens (hsep [ppr n, ppr c, ppr tc, ppr tvs] <+> equals <+> ppr rhs)
150 type DerivRhs = ThetaType
151 type DerivSoln = DerivRhs
155 [Data decl contexts] A note about contexts on data decls
156 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
159 data (RealFloat a) => Complex a = !a :+ !a deriving( Read )
161 We will need an instance decl like:
163 instance (Read a, RealFloat a) => Read (Complex a) where
166 The RealFloat in the context is because the read method for Complex is bound
167 to construct a Complex, and doing that requires that the argument type is
170 But this ain't true for Show, Eq, Ord, etc, since they don't construct
171 a Complex; they only take them apart.
173 Our approach: identify the offending classes, and add the data type
174 context to the instance decl. The "offending classes" are
178 FURTHER NOTE ADDED March 2002. In fact, Haskell98 now requires that
179 pattern matching against a constructor from a data type with a context
180 gives rise to the constraints for that context -- or at least the thinned
181 version. So now all classes are "offending".
188 newtype T = T Char deriving( C [a] )
190 Notice the free 'a' in the deriving. We have to fill this out to
191 newtype T = T Char deriving( forall a. C [a] )
193 And then translate it to:
194 instance C [a] Char => C [a] T where ...
199 %************************************************************************
201 \subsection[TcDeriv-driver]{Top-level function for \tr{derivings}}
203 %************************************************************************
206 tcDeriving :: [LTyClDecl Name] -- All type constructors
207 -> TcM ([InstInfo], -- The generated "instance decls"
208 [HsBindGroup Name]) -- Extra generated top-level bindings
210 tcDeriving tycl_decls
211 = recoverM (returnM ([], [])) $
212 do { -- Fish the "deriving"-related information out of the TcEnv
213 -- and make the necessary "equations".
214 ; (ordinary_eqns, newtype_inst_info) <- makeDerivEqns tycl_decls
216 ; (ordinary_inst_info, deriv_binds)
217 <- extendLocalInstEnv (map iDFunId newtype_inst_info) $
218 deriveOrdinaryStuff ordinary_eqns
219 -- Add the newtype-derived instances to the inst env
220 -- before tacking the "ordinary" ones
222 -- Generate the generic to/from functions from each type declaration
223 ; gen_binds <- mkGenericBinds tycl_decls
224 ; let inst_info = newtype_inst_info ++ ordinary_inst_info
226 -- Rename these extra bindings, discarding warnings about unused bindings etc
227 -- Set -fglasgow exts so that we can have type signatures in patterns,
228 -- which is used in the generic binds
230 <- discardWarnings $ setOptM Opt_GlasgowExts $ do
231 { (rn_deriv, _dus1) <- rnTopBinds deriv_binds []
232 ; (rn_gen, dus_gen) <- rnTopBinds gen_binds []
233 ; keepAliveSetTc (duDefs dus_gen) -- Mark these guys to
235 ; return (rn_deriv ++ rn_gen) }
239 ; ioToTcRn (dumpIfSet_dyn dflags Opt_D_dump_deriv "Derived instances"
240 (ddump_deriving inst_info rn_binds))
242 ; returnM (inst_info, rn_binds)
245 ddump_deriving :: [InstInfo] -> [HsBindGroup Name] -> SDoc
246 ddump_deriving inst_infos extra_binds
247 = vcat (map pprInstInfoDetails inst_infos) $$ vcat (map ppr extra_binds)
249 -----------------------------------------
250 deriveOrdinaryStuff [] -- Short cut
251 = returnM ([], emptyLHsBinds)
253 deriveOrdinaryStuff eqns
254 = do { -- Take the equation list and solve it, to deliver a list of
255 -- solutions, a.k.a. the contexts for the instance decls
256 -- required for the corresponding equations.
257 ; new_dfuns <- solveDerivEqns eqns
259 -- Generate the InstInfo for each dfun,
260 -- plus any auxiliary bindings it needs
261 ; (inst_infos, aux_binds_s) <- mapAndUnzipM genInst new_dfuns
263 -- Generate any extra not-one-inst-decl-specific binds,
264 -- notably "con2tag" and/or "tag2con" functions.
265 ; extra_binds <- genTaggeryBinds new_dfuns
268 ; returnM (inst_infos, unionManyBags (extra_binds : aux_binds_s))
271 -----------------------------------------
272 mkGenericBinds tycl_decls
273 = do { tcs <- mapM tcLookupTyCon
275 L _ (TyData { tcdLName = L _ tc_name }) <- tycl_decls]
276 -- We are only interested in the data type declarations
277 ; return (unionManyBags [ mkTyConGenericBinds tc |
278 tc <- tcs, tyConHasGenerics tc ]) }
279 -- And then only in the ones whose 'has-generics' flag is on
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 :: [LTyClDecl Name]
306 -> TcM ([DerivEqn], -- Ordinary derivings
307 [InstInfo]) -- Special newtype derivings
309 makeDerivEqns tycl_decls
310 = mapAndUnzipM mk_eqn derive_these `thenM` \ (maybe_ordinaries, maybe_newtypes) ->
311 returnM (catMaybes maybe_ordinaries, catMaybes maybe_newtypes)
313 ------------------------------------------------------------------
314 derive_these :: [(NewOrData, Name, LHsType Name)]
315 -- Find the (nd, TyCon, Pred) pairs that must be `derived'
316 derive_these = [ (nd, tycon, pred)
317 | L _ (TyData { tcdND = nd, tcdLName = L _ tycon,
318 tcdDerivs = Just preds }) <- tycl_decls,
321 ------------------------------------------------------------------
322 mk_eqn :: (NewOrData, Name, LHsType Name) -> 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 -- The "deriv_ty" is a LHsType to take account of the fact that for newtype derivign
327 -- we allow deriving (forall a. C [a]).
329 mk_eqn (new_or_data, tycon_name, hs_deriv_ty)
330 = tcLookupTyCon tycon_name `thenM` \ tycon ->
331 setSrcSpan (srcLocSpan (getSrcLoc tycon)) $
332 addErrCtxt (derivCtxt Nothing tycon) $
333 tcExtendTyVarEnv (tyConTyVars tycon) $ -- Deriving preds may (now) mention
334 -- the type variables for the type constructor
335 tcHsDeriv hs_deriv_ty `thenM` \ (deriv_tvs, clas, tys) ->
336 doptM Opt_GlasgowExts `thenM` \ gla_exts ->
337 mk_eqn_help gla_exts new_or_data tycon deriv_tvs clas tys
339 ------------------------------------------------------------------
340 mk_eqn_help gla_exts DataType tycon deriv_tvs clas tys
341 | Just err <- checkSideConditions gla_exts tycon deriv_tvs clas tys
342 = bale_out (derivingThingErr clas tys tycon (tyConTyVars tycon) err)
344 = do { eqn <- mkDataTypeEqn tycon clas
345 ; returnM (Just eqn, Nothing) }
347 mk_eqn_help gla_exts NewType tycon deriv_tvs clas tys
348 | can_derive_via_isomorphism && (gla_exts || std_class_via_iso clas)
349 = -- Go ahead and use the isomorphism
350 traceTc (text "newtype deriving:" <+> ppr tycon <+> ppr rep_tys) `thenM_`
351 new_dfun_name clas tycon `thenM` \ dfun_name ->
352 returnM (Nothing, Just (InstInfo { iDFunId = mk_dfun dfun_name,
353 iBinds = NewTypeDerived rep_tys }))
354 | std_class gla_exts clas
355 = mk_eqn_help gla_exts DataType tycon deriv_tvs clas tys -- Go via bale-out route
357 | otherwise -- Non-standard instance
358 = bale_out (if gla_exts then
359 cant_derive_err -- Too hard
361 non_std_err) -- Just complain about being a non-std instance
363 -- Here is the plan for newtype derivings. We see
364 -- newtype T a1...an = T (t ak...an) deriving (.., C s1 .. sm, ...)
365 -- where t is a type,
366 -- ak...an is a suffix of a1..an
367 -- ak...an do not occur free in t,
368 -- (C s1 ... sm) is a *partial applications* of class C
369 -- with the last parameter missing
371 -- We generate the instances
372 -- instance C s1 .. sm (t ak...ap) => C s1 .. sm (T a1...ap)
373 -- where T a1...ap is the partial application of the LHS of the correct kind
376 -- Running example: newtype T s a = MkT (ST s a) deriving( Monad )
377 -- instance Monad (ST s) => Monad (T s) where
378 -- fail = coerce ... (fail @ ST s)
379 -- (Actually we don't need the coerce, because non-rec newtypes are transparent
381 clas_tyvars = classTyVars clas
382 kind = tyVarKind (last clas_tyvars)
383 -- Kind of the thing we want to instance
384 -- e.g. argument kind of Monad, *->*
386 (arg_kinds, _) = splitKindFunTys kind
387 n_args_to_drop = length arg_kinds
388 -- Want to drop 1 arg from (T s a) and (ST s a)
389 -- to get instance Monad (ST s) => Monad (T s)
391 -- Note [newtype representation]
392 -- Need newTyConRhs *not* newTyConRep to get the representation
393 -- type, because the latter looks through all intermediate newtypes
395 -- newtype B = MkB Int
396 -- newtype A = MkA B deriving( Num )
397 -- We want the Num instance of B, *not* the Num instance of Int,
398 -- when making the Num instance of A!
399 (tc_tvs, rep_ty) = newTyConRhs tycon
400 (rep_fn, rep_ty_args) = tcSplitAppTys rep_ty
402 n_tyvars_to_keep = tyConArity tycon - n_args_to_drop
403 tyvars_to_drop = drop n_tyvars_to_keep tc_tvs
404 tyvars_to_keep = take n_tyvars_to_keep tc_tvs
406 n_args_to_keep = length rep_ty_args - n_args_to_drop
407 args_to_drop = drop n_args_to_keep rep_ty_args
408 args_to_keep = take n_args_to_keep rep_ty_args
410 rep_tys = tys ++ [mkAppTys rep_fn args_to_keep]
411 rep_pred = mkClassPred clas rep_tys
412 -- rep_pred is the representation dictionary, from where
413 -- we are gong to get all the methods for the newtype dictionary
415 inst_tys = (tys ++ [mkTyConApp tycon (mkTyVarTys tyvars_to_keep)])
416 -- The 'tys' here come from the partial application
417 -- in the deriving clause. The last arg is the new
420 -- We must pass the superclasses; the newtype might be an instance
421 -- of them in a different way than the representation type
422 -- E.g. newtype Foo a = Foo a deriving( Show, Num, Eq )
423 -- Then the Show instance is not done via isomprphism; it shows
425 -- The Num instance is derived via isomorphism, but the Show superclass
426 -- dictionary must the Show instance for Foo, *not* the Show dictionary
427 -- gotten from the Num dictionary. So we must build a whole new dictionary
428 -- not just use the Num one. The instance we want is something like:
429 -- instance (Num a, Show (Foo a), Eq (Foo a)) => Num (Foo a) where
432 -- There's no 'corece' needed because after the type checker newtypes
435 sc_theta = substTheta (zipTvSubst clas_tyvars inst_tys)
438 -- If there are no tyvars, there's no need
439 -- to abstract over the dictionaries we need
440 dict_tvs = deriv_tvs ++ tc_tvs
441 dict_args | null dict_tvs = []
442 | otherwise = rep_pred : sc_theta
444 -- Finally! Here's where we build the dictionary Id
445 mk_dfun dfun_name = mkDictFunId dfun_name dict_tvs dict_args clas inst_tys
447 -------------------------------------------------------------------
448 -- Figuring out whether we can only do this newtype-deriving thing
450 right_arity = length tys + 1 == classArity clas
452 -- Never derive Read,Show,Typeable,Data this way
453 non_iso_classes = [readClassKey, showClassKey, typeableClassKey, dataClassKey]
454 can_derive_via_isomorphism
455 = not (getUnique clas `elem` non_iso_classes)
456 && right_arity -- Well kinded;
457 -- eg not: newtype T ... deriving( ST )
458 -- because ST needs *2* type params
459 && n_tyvars_to_keep >= 0 -- Type constructor has right kind:
460 -- eg not: newtype T = T Int deriving( Monad )
461 && n_args_to_keep >= 0 -- Rep type has right kind:
462 -- eg not: newtype T a = T Int deriving( Monad )
463 && eta_ok -- Eta reduction works
464 && not (isRecursiveTyCon tycon) -- Does not work for recursive tycons:
465 -- newtype A = MkA [A]
467 -- instance Eq [A] => Eq A !!
468 -- Here's a recursive newtype that's actually OK
469 -- newtype S1 = S1 [T1 ()]
470 -- newtype T1 a = T1 (StateT S1 IO a ) deriving( Monad )
471 -- It's currently rejected. Oh well.
472 -- In fact we generate an instance decl that has method of form
473 -- meth @ instTy = meth @ repTy
474 -- (no coerce's). We'd need a coerce if we wanted to handle
475 -- recursive newtypes too
477 -- Check that eta reduction is OK
478 -- (a) the dropped-off args are identical
479 -- (b) the remaining type args mention
480 -- only the remaining type variables
481 eta_ok = (args_to_drop `tcEqTypes` mkTyVarTys tyvars_to_drop)
482 && (tyVarsOfTypes args_to_keep `subVarSet` mkVarSet tyvars_to_keep)
484 cant_derive_err = derivingThingErr clas tys tycon tyvars_to_keep
485 (vcat [ptext SLIT("even with cunning newtype deriving:"),
486 if isRecursiveTyCon tycon then
487 ptext SLIT("the newtype is recursive")
489 if not right_arity then
490 quotes (ppr (mkClassPred clas tys)) <+> ptext SLIT("does not have arity 1")
492 if not (n_tyvars_to_keep >= 0) then
493 ptext SLIT("the type constructor has wrong kind")
494 else if not (n_args_to_keep >= 0) then
495 ptext SLIT("the representation type has wrong kind")
496 else if not eta_ok then
497 ptext SLIT("the eta-reduction property does not hold")
501 non_std_err = derivingThingErr clas tys tycon tyvars_to_keep
502 (vcat [non_std_why clas,
503 ptext SLIT("Try -fglasgow-exts for GHC's newtype-deriving extension")])
505 bale_out err = addErrTc err `thenM_` returnM (Nothing, Nothing)
507 std_class gla_exts clas
508 = key `elem` derivableClassKeys
509 || (gla_exts && (key == typeableClassKey || key == dataClassKey))
513 std_class_via_iso clas -- These standard classes can be derived for a newtype
514 -- using the isomorphism trick *even if no -fglasgow-exts*
515 = classKey clas `elem` [eqClassKey, ordClassKey, ixClassKey, boundedClassKey]
516 -- Not Read/Show because they respect the type
517 -- Not Enum, becuase newtypes are never in Enum
520 new_dfun_name clas tycon -- Just a simple wrapper
521 = newDFunName clas [mkTyConApp tycon []] (getSrcLoc tycon)
522 -- The type passed to newDFunName is only used to generate
523 -- a suitable string; hence the empty type arg list
525 ------------------------------------------------------------------
526 mkDataTypeEqn :: TyCon -> Class -> TcM DerivEqn
527 mkDataTypeEqn tycon clas
528 | clas `hasKey` typeableClassKey
529 = -- The Typeable class is special in several ways
530 -- data T a b = ... deriving( Typeable )
532 -- instance Typeable2 T where ...
534 -- 1. There are no constraints in the instance
535 -- 2. There are no type variables either
536 -- 3. The actual class we want to generate isn't necessarily
537 -- Typeable; it depends on the arity of the type
538 do { real_clas <- tcLookupClass (typeableClassNames !! tyConArity tycon)
539 ; dfun_name <- new_dfun_name real_clas tycon
540 ; return (dfun_name, real_clas, tycon, [], []) }
543 = do { dfun_name <- new_dfun_name clas tycon
544 ; return (dfun_name, clas, tycon, tyvars, constraints) }
546 tyvars = tyConTyVars tycon
547 constraints = extra_constraints ++ ordinary_constraints
548 extra_constraints = tyConStupidTheta tycon
549 -- "extra_constraints": see note [Data decl contexts] above
552 = [ mkClassPred clas [arg_ty]
553 | data_con <- tyConDataCons tycon,
554 arg_ty <- dataConOrigArgTys data_con,
555 not (isUnLiftedType arg_ty) -- No constraints for unlifted types?
559 ------------------------------------------------------------------
560 -- Check side conditions that dis-allow derivability for particular classes
561 -- This is *apart* from the newtype-deriving mechanism
563 checkSideConditions :: Bool -> TyCon -> [TyVar] -> Class -> [TcType] -> Maybe SDoc
564 checkSideConditions gla_exts tycon deriv_tvs clas tys
565 | notNull deriv_tvs || notNull tys
566 = Just ty_args_why -- e.g. deriving( Foo s )
568 = case [cond | (key,cond) <- sideConditions, key == getUnique clas] of
569 [] -> Just (non_std_why clas)
570 [cond] -> cond (gla_exts, tycon)
571 other -> pprPanic "checkSideConditions" (ppr clas)
573 ty_args_why = quotes (ppr (mkClassPred clas tys)) <+> ptext SLIT("is not a class")
575 non_std_why clas = quotes (ppr clas) <+> ptext SLIT("is not a derivable class")
577 sideConditions :: [(Unique, Condition)]
579 = [ (eqClassKey, cond_std),
580 (ordClassKey, cond_std),
581 (readClassKey, cond_std),
582 (showClassKey, cond_std),
583 (enumClassKey, cond_std `andCond` cond_isEnumeration),
584 (ixClassKey, cond_std `andCond` (cond_isEnumeration `orCond` cond_isProduct)),
585 (boundedClassKey, cond_std `andCond` (cond_isEnumeration `orCond` cond_isProduct)),
586 (typeableClassKey, cond_glaExts `andCond` cond_typeableOK),
587 (dataClassKey, cond_glaExts `andCond` cond_std)
590 type Condition = (Bool, TyCon) -> Maybe SDoc -- Nothing => OK
592 orCond :: Condition -> Condition -> Condition
595 Nothing -> Nothing -- c1 succeeds
596 Just x -> case c2 tc of -- c1 fails
598 Just y -> Just (x $$ ptext SLIT(" and") $$ y)
601 andCond c1 c2 tc = case c1 tc of
602 Nothing -> c2 tc -- c1 succeeds
603 Just x -> Just x -- c1 fails
605 cond_std :: Condition
606 cond_std (gla_exts, tycon)
607 | any (not . isVanillaDataCon) data_cons = Just existential_why
608 | null data_cons = Just no_cons_why
609 | otherwise = Nothing
611 data_cons = tyConDataCons tycon
612 no_cons_why = quotes (ppr tycon) <+> ptext SLIT("has no data constructors")
613 existential_why = quotes (ppr tycon) <+> ptext SLIT("has existentially-quantified constructor(s)")
615 cond_isEnumeration :: Condition
616 cond_isEnumeration (gla_exts, tycon)
617 | isEnumerationTyCon tycon = Nothing
618 | otherwise = Just why
620 why = quotes (ppr tycon) <+> ptext SLIT("has non-nullary constructors")
622 cond_isProduct :: Condition
623 cond_isProduct (gla_exts, tycon)
624 | isProductTyCon tycon = Nothing
625 | otherwise = Just why
627 why = quotes (ppr tycon) <+> ptext SLIT("has more than one constructor")
629 cond_typeableOK :: Condition
630 -- OK for Typeable class
631 -- Currently: (a) args all of kind *
632 -- (b) 7 or fewer args
633 cond_typeableOK (gla_exts, tycon)
634 | tyConArity tycon > 7 = Just too_many
635 | not (all (isArgTypeKind . tyVarKind) (tyConTyVars tycon)) = Just bad_kind
636 | otherwise = Nothing
638 too_many = quotes (ppr tycon) <+> ptext SLIT("has too many arguments")
639 bad_kind = quotes (ppr tycon) <+> ptext SLIT("has arguments of kind other than `*'")
641 cond_glaExts :: Condition
642 cond_glaExts (gla_exts, tycon) | gla_exts = Nothing
643 | otherwise = Just why
645 why = ptext SLIT("You need -fglasgow-exts to derive an instance for this class")
648 %************************************************************************
650 \subsection[TcDeriv-fixpoint]{Finding the fixed point of \tr{deriving} equations}
652 %************************************************************************
654 A ``solution'' (to one of the equations) is a list of (k,TyVarTy tv)
655 terms, which is the final correct RHS for the corresponding original
659 Each (k,TyVarTy tv) in a solution constrains only a type
663 The (k,TyVarTy tv) pairs in a solution are canonically
664 ordered by sorting on type varible, tv, (major key) and then class, k,
669 solveDerivEqns :: [DerivEqn]
670 -> TcM [DFunId] -- Solns in same order as eqns.
671 -- This bunch is Absolutely minimal...
673 solveDerivEqns orig_eqns
674 = iterateDeriv 1 initial_solutions
676 -- The initial solutions for the equations claim that each
677 -- instance has an empty context; this solution is certainly
678 -- in canonical form.
679 initial_solutions :: [DerivSoln]
680 initial_solutions = [ [] | _ <- orig_eqns ]
682 ------------------------------------------------------------------
683 -- iterateDeriv calculates the next batch of solutions,
684 -- compares it with the current one; finishes if they are the
685 -- same, otherwise recurses with the new solutions.
686 -- It fails if any iteration fails
687 iterateDeriv :: Int -> [DerivSoln] ->TcM [DFunId]
688 iterateDeriv n current_solns
689 | n > 20 -- Looks as if we are in an infinite loop
690 -- This can happen if we have -fallow-undecidable-instances
691 -- (See TcSimplify.tcSimplifyDeriv.)
692 = pprPanic "solveDerivEqns: probable loop"
693 (vcat (map pprDerivEqn orig_eqns) $$ ppr current_solns)
696 dfuns = zipWithEqual "add_solns" mk_deriv_dfun orig_eqns current_solns
699 -- Extend the inst info from the explicit instance decls
700 -- with the current set of solutions, and simplify each RHS
701 extendLocalInstEnv dfuns $
702 mappM gen_soln orig_eqns
703 ) `thenM` \ new_solns ->
704 if (current_solns == new_solns) then
707 iterateDeriv (n+1) new_solns
709 ------------------------------------------------------------------
711 gen_soln (_, clas, tc,tyvars,deriv_rhs)
712 = setSrcSpan (srcLocSpan (getSrcLoc tc)) $
713 addErrCtxt (derivCtxt (Just clas) tc) $
714 tcSimplifyDeriv tyvars deriv_rhs `thenM` \ theta ->
715 returnM (sortLe (<=) theta) -- Canonicalise before returning the soluction
717 mk_deriv_dfun (dfun_name, clas, tycon, tyvars, _) theta
718 = mkDictFunId dfun_name tyvars theta
719 clas [mkTyConApp tycon (mkTyVarTys tyvars)]
721 extendLocalInstEnv :: [DFunId] -> TcM a -> TcM a
722 -- Add new locall-defined instances; don't bother to check
723 -- for functional dependency errors -- that'll happen in TcInstDcls
724 extendLocalInstEnv dfuns thing_inside
725 = do { env <- getGblEnv
726 ; let inst_env' = foldl extendInstEnv (tcg_inst_env env) dfuns
727 env' = env { tcg_inst_env = inst_env' }
728 ; setGblEnv env' thing_inside }
731 %************************************************************************
733 \subsection[TcDeriv-normal-binds]{Bindings for the various classes}
735 %************************************************************************
737 After all the trouble to figure out the required context for the
738 derived instance declarations, all that's left is to chug along to
739 produce them. They will then be shoved into @tcInstDecls2@, which
740 will do all its usual business.
742 There are lots of possibilities for code to generate. Here are
743 various general remarks.
748 We want derived instances of @Eq@ and @Ord@ (both v common) to be
749 ``you-couldn't-do-better-by-hand'' efficient.
752 Deriving @Show@---also pretty common--- should also be reasonable good code.
755 Deriving for the other classes isn't that common or that big a deal.
762 Deriving @Ord@ is done mostly with the 1.3 @compare@ method.
765 Deriving @Eq@ also uses @compare@, if we're deriving @Ord@, too.
768 We {\em normally} generate code only for the non-defaulted methods;
769 there are some exceptions for @Eq@ and (especially) @Ord@...
772 Sometimes we use a @_con2tag_<tycon>@ function, which returns a data
773 constructor's numeric (@Int#@) tag. These are generated by
774 @gen_tag_n_con_binds@, and the heuristic for deciding if one of
775 these is around is given by @hasCon2TagFun@.
777 The examples under the different sections below will make this
781 Much less often (really just for deriving @Ix@), we use a
782 @_tag2con_<tycon>@ function. See the examples.
785 We use the renamer!!! Reason: we're supposed to be
786 producing @LHsBinds Name@ for the methods, but that means
787 producing correctly-uniquified code on the fly. This is entirely
788 possible (the @TcM@ monad has a @UniqueSupply@), but it is painful.
789 So, instead, we produce @MonoBinds RdrName@ then heave 'em through
790 the renamer. What a great hack!
794 -- Generate the InstInfo for the required instance,
795 -- plus any auxiliary bindings required
796 genInst :: DFunId -> TcM (InstInfo, LHsBinds RdrName)
798 = getFixityEnv `thenM` \ fix_env ->
800 (tyvars,_,clas,[ty]) = tcSplitDFunTy (idType dfun)
801 clas_nm = className clas
802 tycon = tcTyConAppTyCon ty
803 (meth_binds, aux_binds) = genDerivBinds clas fix_env tycon
805 -- Bring the right type variables into
806 -- scope, and rename the method binds
807 bindLocalNames (map varName tyvars) $
808 rnMethodBinds clas_nm [] meth_binds `thenM` \ (rn_meth_binds, _fvs) ->
810 -- Build the InstInfo
811 returnM (InstInfo { iDFunId = dfun, iBinds = VanillaInst rn_meth_binds [] },
814 genDerivBinds clas fix_env tycon
815 | className clas `elem` typeableClassNames
816 = (gen_Typeable_binds tycon, emptyLHsBinds)
819 = case assocMaybe gen_list (getUnique clas) of
820 Just gen_fn -> gen_fn fix_env tycon
821 Nothing -> pprPanic "genDerivBinds: bad derived class" (ppr clas)
823 gen_list :: [(Unique, FixityEnv -> TyCon -> (LHsBinds RdrName, LHsBinds RdrName))]
824 gen_list = [(eqClassKey, no_aux_binds (ignore_fix_env gen_Eq_binds))
825 ,(ordClassKey, no_aux_binds (ignore_fix_env gen_Ord_binds))
826 ,(enumClassKey, no_aux_binds (ignore_fix_env gen_Enum_binds))
827 ,(boundedClassKey, no_aux_binds (ignore_fix_env gen_Bounded_binds))
828 ,(ixClassKey, no_aux_binds (ignore_fix_env gen_Ix_binds))
829 ,(typeableClassKey,no_aux_binds (ignore_fix_env gen_Typeable_binds))
830 ,(showClassKey, no_aux_binds gen_Show_binds)
831 ,(readClassKey, no_aux_binds gen_Read_binds)
832 ,(dataClassKey, gen_Data_binds)
835 -- no_aux_binds is used for generators that don't
836 -- need to produce any auxiliary bindings
837 no_aux_binds f fix_env tc = (f fix_env tc, emptyLHsBinds)
838 ignore_fix_env f fix_env tc = f tc
842 %************************************************************************
844 \subsection[TcDeriv-taggery-Names]{What con2tag/tag2con functions are available?}
846 %************************************************************************
851 con2tag_Foo :: Foo ... -> Int#
852 tag2con_Foo :: Int -> Foo ... -- easier if Int, not Int#
853 maxtag_Foo :: Int -- ditto (NB: not unlifted)
856 We have a @con2tag@ function for a tycon if:
859 We're deriving @Eq@ and the tycon has nullary data constructors.
862 Or: we're deriving @Ord@ (unless single-constructor), @Enum@, @Ix@
866 We have a @tag2con@ function for a tycon if:
869 We're deriving @Enum@, or @Ix@ (enum type only???)
872 If we have a @tag2con@ function, we also generate a @maxtag@ constant.
875 genTaggeryBinds :: [DFunId] -> TcM (LHsBinds RdrName)
876 genTaggeryBinds dfuns
877 = do { names_so_far <- foldlM do_con2tag [] tycons_of_interest
878 ; nm_alist_etc <- foldlM do_tag2con names_so_far tycons_of_interest
879 ; return (listToBag (map gen_tag_n_con_monobind nm_alist_etc)) }
881 all_CTs = map simpleDFunClassTyCon dfuns
882 all_tycons = map snd all_CTs
883 (tycons_of_interest, _) = removeDups compare all_tycons
885 do_con2tag acc_Names tycon
886 | isDataTyCon tycon &&
887 ((we_are_deriving eqClassKey tycon
888 && any isNullarySrcDataCon (tyConDataCons tycon))
889 || (we_are_deriving ordClassKey tycon
890 && not (isProductTyCon tycon))
891 || (we_are_deriving enumClassKey tycon)
892 || (we_are_deriving ixClassKey tycon))
894 = returnM ((con2tag_RDR tycon, tycon, GenCon2Tag)
899 do_tag2con acc_Names tycon
900 | isDataTyCon tycon &&
901 (we_are_deriving enumClassKey tycon ||
902 we_are_deriving ixClassKey tycon
903 && isEnumerationTyCon tycon)
904 = returnM ( (tag2con_RDR tycon, tycon, GenTag2Con)
905 : (maxtag_RDR tycon, tycon, GenMaxTag)
910 we_are_deriving clas_key tycon
911 = is_in_eqns clas_key tycon all_CTs
913 is_in_eqns clas_key tycon [] = False
914 is_in_eqns clas_key tycon ((c,t):cts)
915 = (clas_key == classKey c && tycon == t)
916 || is_in_eqns clas_key tycon cts
920 derivingThingErr clas tys tycon tyvars why
921 = sep [hsep [ptext SLIT("Can't make a derived instance of"), quotes (ppr pred)],
924 pred = mkClassPred clas (tys ++ [mkTyConApp tycon (mkTyVarTys tyvars)])
926 derivCtxt :: Maybe Class -> TyCon -> SDoc
927 derivCtxt maybe_cls tycon
928 = ptext SLIT("When deriving") <+> cls <+> ptext SLIT("for type") <+> quotes (ppr tycon)
930 cls = case maybe_cls of
931 Nothing -> ptext SLIT("instances")
932 Just c -> ptext SLIT("the") <+> quotes (ppr c) <+> ptext SLIT("instance")