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 DynFlags ( DynFlag(..) )
16 import Generics ( mkTyConGenericBinds )
18 import TcEnv ( newDFunName, pprInstInfoDetails,
19 InstInfo(..), InstBindings(..), simpleInstInfoClsTy,
20 tcLookupClass, tcLookupTyCon, tcExtendTyVarEnv
22 import TcGenDeriv -- Deriv stuff
23 import InstEnv ( Instance, OverlapFlag, mkLocalInstance, instanceHead, extendInstEnvList )
24 import Inst ( getOverlapFlag )
25 import TcHsType ( tcHsDeriv )
26 import TcSimplify ( tcSimplifyDeriv )
28 import RnBinds ( rnMethodBinds, rnTopBinds )
29 import RnEnv ( bindLocalNames )
30 import HscTypes ( FixityEnv )
32 import Class ( className, classArity, classKey, classTyVars, classSCTheta, Class )
33 import Type ( zipOpenTvSubst, substTheta )
34 import ErrUtils ( dumpIfSet_dyn )
35 import MkId ( mkDictFunId )
36 import DataCon ( isNullarySrcDataCon, isVanillaDataCon, dataConOrigArgTys )
37 import Maybes ( catMaybes )
38 import RdrName ( RdrName )
39 import Name ( Name, getSrcLoc )
40 import NameSet ( duDefs )
41 import Kind ( splitKindFunTys )
42 import TyCon ( tyConTyVars, tyConDataCons, tyConArity, tyConHasGenerics,
43 tyConStupidTheta, isProductTyCon, isDataTyCon, newTyConRhs,
44 isEnumerationTyCon, isRecursiveTyCon, TyCon
46 import TcType ( TcType, ThetaType, mkTyVarTys, mkTyConApp, tcTyConAppTyCon,
47 isUnLiftedType, mkClassPred, tyVarsOfType,
48 isArgTypeKind, tcEqTypes, tcSplitAppTys, mkAppTys )
49 import Var ( TyVar, tyVarKind, varName )
50 import VarSet ( mkVarSet, subVarSet )
52 import SrcLoc ( srcLocSpan, Located(..) )
53 import Util ( zipWithEqual, sortLe, notNull )
54 import ListSetOps ( removeDups, assocMaybe )
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 pprDerivEqn (n,c,tc,tvs,rhs)
149 = parens (hsep [ppr n, ppr c, ppr tc, ppr tvs] <+> equals <+> ppr rhs)
151 type DerivRhs = ThetaType
152 type DerivSoln = DerivRhs
156 [Data decl contexts] A note about contexts on data decls
157 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
160 data (RealFloat a) => Complex a = !a :+ !a deriving( Read )
162 We will need an instance decl like:
164 instance (Read a, RealFloat a) => Read (Complex a) where
167 The RealFloat in the context is because the read method for Complex is bound
168 to construct a Complex, and doing that requires that the argument type is
171 But this ain't true for Show, Eq, Ord, etc, since they don't construct
172 a Complex; they only take them apart.
174 Our approach: identify the offending classes, and add the data type
175 context to the instance decl. The "offending classes" are
179 FURTHER NOTE ADDED March 2002. In fact, Haskell98 now requires that
180 pattern matching against a constructor from a data type with a context
181 gives rise to the constraints for that context -- or at least the thinned
182 version. So now all classes are "offending".
189 newtype T = T Char deriving( C [a] )
191 Notice the free 'a' in the deriving. We have to fill this out to
192 newtype T = T Char deriving( forall a. C [a] )
194 And then translate it to:
195 instance C [a] Char => C [a] T where ...
200 %************************************************************************
202 \subsection[TcDeriv-driver]{Top-level function for \tr{derivings}}
204 %************************************************************************
207 tcDeriving :: [LTyClDecl Name] -- All type constructors
208 -> TcM ([InstInfo], -- The generated "instance decls"
209 HsValBinds Name) -- Extra generated top-level bindings
211 tcDeriving tycl_decls
212 = recoverM (returnM ([], emptyValBindsOut)) $
213 do { -- Fish the "deriving"-related information out of the TcEnv
214 -- and make the necessary "equations".
215 overlap_flag <- getOverlapFlag
216 ; (ordinary_eqns, newtype_inst_info) <- makeDerivEqns overlap_flag tycl_decls
218 ; (ordinary_inst_info, deriv_binds)
219 <- extendLocalInstEnv (map iSpec newtype_inst_info) $
220 deriveOrdinaryStuff overlap_flag ordinary_eqns
221 -- Add the newtype-derived instances to the inst env
222 -- before tacking the "ordinary" ones
224 ; let inst_info = newtype_inst_info ++ ordinary_inst_info
226 -- If we are compiling a hs-boot file,
227 -- don't generate any derived bindings
228 ; is_boot <- tcIsHsBoot
230 return (inst_info, emptyValBindsOut)
234 -- Generate the generic to/from functions from each type declaration
235 ; gen_binds <- mkGenericBinds tycl_decls
237 -- Rename these extra bindings, discarding warnings about unused bindings etc
238 -- Set -fglasgow exts so that we can have type signatures in patterns,
239 -- which is used in the generic binds
241 <- discardWarnings $ setOptM Opt_GlasgowExts $ do
242 { (rn_deriv, _dus1) <- rnTopBinds (ValBindsIn deriv_binds [])
243 ; (rn_gen, dus_gen) <- rnTopBinds (ValBindsIn gen_binds [])
244 ; keepAliveSetTc (duDefs dus_gen) -- Mark these guys to
246 ; return (rn_deriv `plusHsValBinds` rn_gen) }
250 ; ioToTcRn (dumpIfSet_dyn dflags Opt_D_dump_deriv "Derived instances"
251 (ddump_deriving inst_info rn_binds))
253 ; returnM (inst_info, rn_binds)
256 ddump_deriving :: [InstInfo] -> HsValBinds Name -> SDoc
257 ddump_deriving inst_infos extra_binds
258 = vcat (map pprInstInfoDetails inst_infos) $$ ppr extra_binds
260 -----------------------------------------
261 deriveOrdinaryStuff overlap_flag [] -- Short cut
262 = returnM ([], emptyLHsBinds)
264 deriveOrdinaryStuff overlap_flag eqns
265 = do { -- Take the equation list and solve it, to deliver a list of
266 -- solutions, a.k.a. the contexts for the instance decls
267 -- required for the corresponding equations.
268 inst_specs <- solveDerivEqns overlap_flag eqns
270 -- Generate the InstInfo for each dfun,
271 -- plus any auxiliary bindings it needs
272 ; (inst_infos, aux_binds_s) <- mapAndUnzipM genInst inst_specs
274 -- Generate any extra not-one-inst-decl-specific binds,
275 -- notably "con2tag" and/or "tag2con" functions.
276 ; extra_binds <- genTaggeryBinds inst_infos
279 ; returnM (inst_infos, unionManyBags (extra_binds : aux_binds_s))
282 -----------------------------------------
283 mkGenericBinds tycl_decls
284 = do { tcs <- mapM tcLookupTyCon
286 L _ (TyData { tcdLName = L _ tc_name }) <- tycl_decls]
287 -- We are only interested in the data type declarations
288 ; return (unionManyBags [ mkTyConGenericBinds tc |
289 tc <- tcs, tyConHasGenerics tc ]) }
290 -- And then only in the ones whose 'has-generics' flag is on
294 %************************************************************************
296 \subsection[TcDeriv-eqns]{Forming the equations}
298 %************************************************************************
300 @makeDerivEqns@ fishes around to find the info about needed derived
301 instances. Complicating factors:
304 We can only derive @Enum@ if the data type is an enumeration
305 type (all nullary data constructors).
308 We can only derive @Ix@ if the data type is an enumeration {\em
309 or} has just one data constructor (e.g., tuples).
312 [See Appendix~E in the Haskell~1.2 report.] This code here deals w/
316 makeDerivEqns :: OverlapFlag
318 -> TcM ([DerivEqn], -- Ordinary derivings
319 [InstInfo]) -- Special newtype derivings
321 makeDerivEqns overlap_flag tycl_decls
322 = mapAndUnzipM mk_eqn derive_these `thenM` \ (maybe_ordinaries, maybe_newtypes) ->
323 returnM (catMaybes maybe_ordinaries, catMaybes maybe_newtypes)
325 ------------------------------------------------------------------
326 derive_these :: [(NewOrData, Name, LHsType Name)]
327 -- Find the (nd, TyCon, Pred) pairs that must be `derived'
328 derive_these = [ (nd, tycon, pred)
329 | L _ (TyData { tcdND = nd, tcdLName = L _ tycon,
330 tcdDerivs = Just preds }) <- tycl_decls,
333 ------------------------------------------------------------------
334 mk_eqn :: (NewOrData, Name, LHsType Name) -> TcM (Maybe DerivEqn, Maybe InstInfo)
335 -- We swizzle the tyvars and datacons out of the tycon
336 -- to make the rest of the equation
338 -- The "deriv_ty" is a LHsType to take account of the fact that for newtype derivign
339 -- we allow deriving (forall a. C [a]).
341 mk_eqn (new_or_data, tycon_name, hs_deriv_ty)
342 = tcLookupTyCon tycon_name `thenM` \ tycon ->
343 setSrcSpan (srcLocSpan (getSrcLoc tycon)) $
344 addErrCtxt (derivCtxt Nothing tycon) $
345 tcExtendTyVarEnv (tyConTyVars tycon) $ -- Deriving preds may (now) mention
346 -- the type variables for the type constructor
347 tcHsDeriv hs_deriv_ty `thenM` \ (deriv_tvs, clas, tys) ->
348 doptM Opt_GlasgowExts `thenM` \ gla_exts ->
349 mk_eqn_help gla_exts new_or_data tycon deriv_tvs clas tys
351 ------------------------------------------------------------------
352 mk_eqn_help gla_exts DataType tycon deriv_tvs clas tys
353 | Just err <- checkSideConditions gla_exts tycon deriv_tvs clas tys
354 = bale_out (derivingThingErr clas tys tycon (tyConTyVars tycon) err)
356 = do { eqn <- mkDataTypeEqn tycon clas
357 ; returnM (Just eqn, Nothing) }
359 mk_eqn_help gla_exts NewType tycon deriv_tvs clas tys
360 | can_derive_via_isomorphism && (gla_exts || std_class_via_iso clas)
361 = -- Go ahead and use the isomorphism
362 traceTc (text "newtype deriving:" <+> ppr tycon <+> ppr rep_tys) `thenM_`
363 new_dfun_name clas tycon `thenM` \ dfun_name ->
364 returnM (Nothing, Just (InstInfo { iSpec = mk_inst_spec dfun_name,
365 iBinds = NewTypeDerived rep_tys }))
366 | std_class gla_exts clas
367 = mk_eqn_help gla_exts DataType tycon deriv_tvs clas tys -- Go via bale-out route
369 | otherwise -- Non-standard instance
370 = bale_out (if gla_exts then
371 cant_derive_err -- Too hard
373 non_std_err) -- Just complain about being a non-std instance
375 -- Here is the plan for newtype derivings. We see
376 -- newtype T a1...an = T (t ak...an) deriving (.., C s1 .. sm, ...)
377 -- where t is a type,
378 -- ak...an is a suffix of a1..an
379 -- ak...an do not occur free in t,
380 -- (C s1 ... sm) is a *partial applications* of class C
381 -- with the last parameter missing
383 -- We generate the instances
384 -- instance C s1 .. sm (t ak...ap) => C s1 .. sm (T a1...ap)
385 -- where T a1...ap is the partial application of the LHS of the correct kind
388 -- Running example: newtype T s a = MkT (ST s a) deriving( Monad )
389 -- instance Monad (ST s) => Monad (T s) where
390 -- fail = coerce ... (fail @ ST s)
391 -- (Actually we don't need the coerce, because non-rec newtypes are transparent
393 clas_tyvars = classTyVars clas
394 kind = tyVarKind (last clas_tyvars)
395 -- Kind of the thing we want to instance
396 -- e.g. argument kind of Monad, *->*
398 (arg_kinds, _) = splitKindFunTys kind
399 n_args_to_drop = length arg_kinds
400 -- Want to drop 1 arg from (T s a) and (ST s a)
401 -- to get instance Monad (ST s) => Monad (T s)
403 -- Note [newtype representation]
404 -- Need newTyConRhs *not* newTyConRep to get the representation
405 -- type, because the latter looks through all intermediate newtypes
407 -- newtype B = MkB Int
408 -- newtype A = MkA B deriving( Num )
409 -- We want the Num instance of B, *not* the Num instance of Int,
410 -- when making the Num instance of A!
411 (tc_tvs, rep_ty) = newTyConRhs tycon
412 (rep_fn, rep_ty_args) = tcSplitAppTys rep_ty
414 n_tyvars_to_keep = tyConArity tycon - n_args_to_drop
415 tyvars_to_drop = drop n_tyvars_to_keep tc_tvs
416 tyvars_to_keep = take n_tyvars_to_keep tc_tvs
418 n_args_to_keep = length rep_ty_args - n_args_to_drop
419 args_to_drop = drop n_args_to_keep rep_ty_args
420 args_to_keep = take n_args_to_keep rep_ty_args
422 rep_fn' = mkAppTys rep_fn args_to_keep
423 rep_tys = tys ++ [rep_fn']
424 rep_pred = mkClassPred clas rep_tys
425 -- rep_pred is the representation dictionary, from where
426 -- we are gong to get all the methods for the newtype dictionary
428 inst_tys = (tys ++ [mkTyConApp tycon (mkTyVarTys tyvars_to_keep)])
429 -- The 'tys' here come from the partial application
430 -- in the deriving clause. The last arg is the new
433 -- We must pass the superclasses; the newtype might be an instance
434 -- of them in a different way than the representation type
435 -- E.g. newtype Foo a = Foo a deriving( Show, Num, Eq )
436 -- Then the Show instance is not done via isomprphism; it shows
438 -- The Num instance is derived via isomorphism, but the Show superclass
439 -- dictionary must the Show instance for Foo, *not* the Show dictionary
440 -- gotten from the Num dictionary. So we must build a whole new dictionary
441 -- not just use the Num one. The instance we want is something like:
442 -- instance (Num a, Show (Foo a), Eq (Foo a)) => Num (Foo a) where
445 -- There's no 'corece' needed because after the type checker newtypes
448 sc_theta = substTheta (zipOpenTvSubst clas_tyvars inst_tys)
451 -- If there are no tyvars, there's no need
452 -- to abstract over the dictionaries we need
453 dict_tvs = deriv_tvs ++ tc_tvs
454 dict_args | null dict_tvs = []
455 | otherwise = rep_pred : sc_theta
457 -- Finally! Here's where we build the dictionary Id
458 mk_inst_spec dfun_name
459 = mkLocalInstance dfun overlap_flag
461 dfun = mkDictFunId dfun_name dict_tvs dict_args clas inst_tys
463 -------------------------------------------------------------------
464 -- Figuring out whether we can only do this newtype-deriving thing
466 right_arity = length tys + 1 == classArity clas
468 -- Never derive Read,Show,Typeable,Data this way
469 non_iso_classes = [readClassKey, showClassKey, typeableClassKey, dataClassKey]
470 can_derive_via_isomorphism
471 = not (getUnique clas `elem` non_iso_classes)
472 && right_arity -- Well kinded;
473 -- eg not: newtype T ... deriving( ST )
474 -- because ST needs *2* type params
475 && n_tyvars_to_keep >= 0 -- Type constructor has right kind:
476 -- eg not: newtype T = T Int deriving( Monad )
477 && n_args_to_keep >= 0 -- Rep type has right kind:
478 -- eg not: newtype T a = T Int deriving( Monad )
479 && eta_ok -- Eta reduction works
480 && not (isRecursiveTyCon tycon) -- Does not work for recursive tycons:
481 -- newtype A = MkA [A]
483 -- instance Eq [A] => Eq A !!
484 -- Here's a recursive newtype that's actually OK
485 -- newtype S1 = S1 [T1 ()]
486 -- newtype T1 a = T1 (StateT S1 IO a ) deriving( Monad )
487 -- It's currently rejected. Oh well.
488 -- In fact we generate an instance decl that has method of form
489 -- meth @ instTy = meth @ repTy
490 -- (no coerce's). We'd need a coerce if we wanted to handle
491 -- recursive newtypes too
493 -- Check that eta reduction is OK
494 -- (a) the dropped-off args are identical
495 -- (b) the remaining type args mention
496 -- only the remaining type variables
497 eta_ok = (args_to_drop `tcEqTypes` mkTyVarTys tyvars_to_drop)
498 && (tyVarsOfType rep_fn' `subVarSet` mkVarSet tyvars_to_keep)
500 cant_derive_err = derivingThingErr clas tys tycon tyvars_to_keep
501 (vcat [ptext SLIT("even with cunning newtype deriving:"),
502 if isRecursiveTyCon tycon then
503 ptext SLIT("the newtype is recursive")
505 if not right_arity then
506 quotes (ppr (mkClassPred clas tys)) <+> ptext SLIT("does not have arity 1")
508 if not (n_tyvars_to_keep >= 0) then
509 ptext SLIT("the type constructor has wrong kind")
510 else if not (n_args_to_keep >= 0) then
511 ptext SLIT("the representation type has wrong kind")
512 else if not eta_ok then
513 ptext SLIT("the eta-reduction property does not hold")
517 non_std_err = derivingThingErr clas tys tycon tyvars_to_keep
518 (vcat [non_std_why clas,
519 ptext SLIT("Try -fglasgow-exts for GHC's newtype-deriving extension")])
521 bale_out err = addErrTc err `thenM_` returnM (Nothing, Nothing)
523 std_class gla_exts clas
524 = key `elem` derivableClassKeys
525 || (gla_exts && (key == typeableClassKey || key == dataClassKey))
529 std_class_via_iso clas -- These standard classes can be derived for a newtype
530 -- using the isomorphism trick *even if no -fglasgow-exts*
531 = classKey clas `elem` [eqClassKey, ordClassKey, ixClassKey, boundedClassKey]
532 -- Not Read/Show because they respect the type
533 -- Not Enum, becuase newtypes are never in Enum
536 new_dfun_name clas tycon -- Just a simple wrapper
537 = newDFunName clas [mkTyConApp tycon []] (getSrcLoc tycon)
538 -- The type passed to newDFunName is only used to generate
539 -- a suitable string; hence the empty type arg list
541 ------------------------------------------------------------------
542 mkDataTypeEqn :: TyCon -> Class -> TcM DerivEqn
543 mkDataTypeEqn tycon clas
544 | clas `hasKey` typeableClassKey
545 = -- The Typeable class is special in several ways
546 -- data T a b = ... deriving( Typeable )
548 -- instance Typeable2 T where ...
550 -- 1. There are no constraints in the instance
551 -- 2. There are no type variables either
552 -- 3. The actual class we want to generate isn't necessarily
553 -- Typeable; it depends on the arity of the type
554 do { real_clas <- tcLookupClass (typeableClassNames !! tyConArity tycon)
555 ; dfun_name <- new_dfun_name real_clas tycon
556 ; return (dfun_name, real_clas, tycon, [], []) }
559 = do { dfun_name <- new_dfun_name clas tycon
560 ; return (dfun_name, clas, tycon, tyvars, constraints) }
562 tyvars = tyConTyVars tycon
563 constraints = extra_constraints ++ ordinary_constraints
564 extra_constraints = tyConStupidTheta tycon
565 -- "extra_constraints": see note [Data decl contexts] above
568 = [ mkClassPred clas [arg_ty]
569 | data_con <- tyConDataCons tycon,
570 arg_ty <- dataConOrigArgTys data_con,
571 not (isUnLiftedType arg_ty) -- No constraints for unlifted types?
575 ------------------------------------------------------------------
576 -- Check side conditions that dis-allow derivability for particular classes
577 -- This is *apart* from the newtype-deriving mechanism
579 checkSideConditions :: Bool -> TyCon -> [TyVar] -> Class -> [TcType] -> Maybe SDoc
580 checkSideConditions gla_exts tycon deriv_tvs clas tys
581 | notNull deriv_tvs || notNull tys
582 = Just ty_args_why -- e.g. deriving( Foo s )
584 = case [cond | (key,cond) <- sideConditions, key == getUnique clas] of
585 [] -> Just (non_std_why clas)
586 [cond] -> cond (gla_exts, tycon)
587 other -> pprPanic "checkSideConditions" (ppr clas)
589 ty_args_why = quotes (ppr (mkClassPred clas tys)) <+> ptext SLIT("is not a class")
591 non_std_why clas = quotes (ppr clas) <+> ptext SLIT("is not a derivable class")
593 sideConditions :: [(Unique, Condition)]
595 = [ (eqClassKey, cond_std),
596 (ordClassKey, cond_std),
597 (readClassKey, cond_std),
598 (showClassKey, cond_std),
599 (enumClassKey, cond_std `andCond` cond_isEnumeration),
600 (ixClassKey, cond_std `andCond` (cond_isEnumeration `orCond` cond_isProduct)),
601 (boundedClassKey, cond_std `andCond` (cond_isEnumeration `orCond` cond_isProduct)),
602 (typeableClassKey, cond_glaExts `andCond` cond_typeableOK),
603 (dataClassKey, cond_glaExts `andCond` cond_std)
606 type Condition = (Bool, TyCon) -> Maybe SDoc -- Nothing => OK
608 orCond :: Condition -> Condition -> Condition
611 Nothing -> Nothing -- c1 succeeds
612 Just x -> case c2 tc of -- c1 fails
614 Just y -> Just (x $$ ptext SLIT(" and") $$ y)
617 andCond c1 c2 tc = case c1 tc of
618 Nothing -> c2 tc -- c1 succeeds
619 Just x -> Just x -- c1 fails
621 cond_std :: Condition
622 cond_std (gla_exts, tycon)
623 | any (not . isVanillaDataCon) data_cons = Just existential_why
624 | null data_cons = Just no_cons_why
625 | otherwise = Nothing
627 data_cons = tyConDataCons tycon
628 no_cons_why = quotes (ppr tycon) <+> ptext SLIT("has no data constructors")
629 existential_why = quotes (ppr tycon) <+> ptext SLIT("has non-Haskell-98 constructor(s)")
631 cond_isEnumeration :: Condition
632 cond_isEnumeration (gla_exts, tycon)
633 | isEnumerationTyCon tycon = Nothing
634 | otherwise = Just why
636 why = quotes (ppr tycon) <+> ptext SLIT("has non-nullary constructors")
638 cond_isProduct :: Condition
639 cond_isProduct (gla_exts, tycon)
640 | isProductTyCon tycon = Nothing
641 | otherwise = Just why
643 why = quotes (ppr tycon) <+> ptext SLIT("has more than one constructor")
645 cond_typeableOK :: Condition
646 -- OK for Typeable class
647 -- Currently: (a) args all of kind *
648 -- (b) 7 or fewer args
649 cond_typeableOK (gla_exts, tycon)
650 | tyConArity tycon > 7 = Just too_many
651 | not (all (isArgTypeKind . tyVarKind) (tyConTyVars tycon)) = Just bad_kind
652 | otherwise = Nothing
654 too_many = quotes (ppr tycon) <+> ptext SLIT("has too many arguments")
655 bad_kind = quotes (ppr tycon) <+> ptext SLIT("has arguments of kind other than `*'")
657 cond_glaExts :: Condition
658 cond_glaExts (gla_exts, tycon) | gla_exts = Nothing
659 | otherwise = Just why
661 why = ptext SLIT("You need -fglasgow-exts to derive an instance for this class")
664 %************************************************************************
666 \subsection[TcDeriv-fixpoint]{Finding the fixed point of \tr{deriving} equations}
668 %************************************************************************
670 A ``solution'' (to one of the equations) is a list of (k,TyVarTy tv)
671 terms, which is the final correct RHS for the corresponding original
675 Each (k,TyVarTy tv) in a solution constrains only a type
679 The (k,TyVarTy tv) pairs in a solution are canonically
680 ordered by sorting on type varible, tv, (major key) and then class, k,
685 solveDerivEqns :: OverlapFlag
687 -> TcM [Instance]-- Solns in same order as eqns.
688 -- This bunch is Absolutely minimal...
690 solveDerivEqns overlap_flag orig_eqns
691 = iterateDeriv 1 initial_solutions
693 -- The initial solutions for the equations claim that each
694 -- instance has an empty context; this solution is certainly
695 -- in canonical form.
696 initial_solutions :: [DerivSoln]
697 initial_solutions = [ [] | _ <- orig_eqns ]
699 ------------------------------------------------------------------
700 -- iterateDeriv calculates the next batch of solutions,
701 -- compares it with the current one; finishes if they are the
702 -- same, otherwise recurses with the new solutions.
703 -- It fails if any iteration fails
704 iterateDeriv :: Int -> [DerivSoln] -> TcM [Instance]
705 iterateDeriv n current_solns
706 | n > 20 -- Looks as if we are in an infinite loop
707 -- This can happen if we have -fallow-undecidable-instances
708 -- (See TcSimplify.tcSimplifyDeriv.)
709 = pprPanic "solveDerivEqns: probable loop"
710 (vcat (map pprDerivEqn orig_eqns) $$ ppr current_solns)
713 inst_specs = zipWithEqual "add_solns" mk_inst_spec
714 orig_eqns current_solns
717 -- Extend the inst info from the explicit instance decls
718 -- with the current set of solutions, and simplify each RHS
719 extendLocalInstEnv inst_specs $
720 mappM gen_soln orig_eqns
721 ) `thenM` \ new_solns ->
722 if (current_solns == new_solns) then
725 iterateDeriv (n+1) new_solns
727 ------------------------------------------------------------------
728 gen_soln (_, clas, tc,tyvars,deriv_rhs)
729 = setSrcSpan (srcLocSpan (getSrcLoc tc)) $
730 addErrCtxt (derivCtxt (Just clas) tc) $
731 tcSimplifyDeriv tc tyvars deriv_rhs `thenM` \ theta ->
732 returnM (sortLe (<=) theta) -- Canonicalise before returning the soluction
734 ------------------------------------------------------------------
735 mk_inst_spec (dfun_name, clas, tycon, tyvars, _) theta
736 = mkLocalInstance dfun overlap_flag
738 dfun = mkDictFunId dfun_name tyvars theta clas
739 [mkTyConApp tycon (mkTyVarTys tyvars)]
741 extendLocalInstEnv :: [Instance] -> TcM a -> TcM a
742 -- Add new locally-defined instances; don't bother to check
743 -- for functional dependency errors -- that'll happen in TcInstDcls
744 extendLocalInstEnv dfuns thing_inside
745 = do { env <- getGblEnv
746 ; let inst_env' = extendInstEnvList (tcg_inst_env env) dfuns
747 env' = env { tcg_inst_env = inst_env' }
748 ; setGblEnv env' thing_inside }
751 %************************************************************************
753 \subsection[TcDeriv-normal-binds]{Bindings for the various classes}
755 %************************************************************************
757 After all the trouble to figure out the required context for the
758 derived instance declarations, all that's left is to chug along to
759 produce them. They will then be shoved into @tcInstDecls2@, which
760 will do all its usual business.
762 There are lots of possibilities for code to generate. Here are
763 various general remarks.
768 We want derived instances of @Eq@ and @Ord@ (both v common) to be
769 ``you-couldn't-do-better-by-hand'' efficient.
772 Deriving @Show@---also pretty common--- should also be reasonable good code.
775 Deriving for the other classes isn't that common or that big a deal.
782 Deriving @Ord@ is done mostly with the 1.3 @compare@ method.
785 Deriving @Eq@ also uses @compare@, if we're deriving @Ord@, too.
788 We {\em normally} generate code only for the non-defaulted methods;
789 there are some exceptions for @Eq@ and (especially) @Ord@...
792 Sometimes we use a @_con2tag_<tycon>@ function, which returns a data
793 constructor's numeric (@Int#@) tag. These are generated by
794 @gen_tag_n_con_binds@, and the heuristic for deciding if one of
795 these is around is given by @hasCon2TagFun@.
797 The examples under the different sections below will make this
801 Much less often (really just for deriving @Ix@), we use a
802 @_tag2con_<tycon>@ function. See the examples.
805 We use the renamer!!! Reason: we're supposed to be
806 producing @LHsBinds Name@ for the methods, but that means
807 producing correctly-uniquified code on the fly. This is entirely
808 possible (the @TcM@ monad has a @UniqueSupply@), but it is painful.
809 So, instead, we produce @MonoBinds RdrName@ then heave 'em through
810 the renamer. What a great hack!
814 -- Generate the InstInfo for the required instance,
815 -- plus any auxiliary bindings required
816 genInst :: Instance -> TcM (InstInfo, LHsBinds RdrName)
818 = do { fix_env <- getFixityEnv
820 (tyvars,_,clas,[ty]) = instanceHead spec
821 clas_nm = className clas
822 tycon = tcTyConAppTyCon ty
823 (meth_binds, aux_binds) = genDerivBinds clas fix_env tycon
825 -- Bring the right type variables into
826 -- scope, and rename the method binds
827 -- It's a bit yukky that we return *renamed* InstInfo, but
828 -- *non-renamed* auxiliary bindings
829 ; (rn_meth_binds, _fvs) <- discardWarnings $
830 bindLocalNames (map varName tyvars) $
831 rnMethodBinds clas_nm [] meth_binds
833 -- Build the InstInfo
834 ; return (InstInfo { iSpec = spec,
835 iBinds = VanillaInst rn_meth_binds [] },
839 genDerivBinds clas fix_env tycon
840 | className clas `elem` typeableClassNames
841 = (gen_Typeable_binds tycon, emptyLHsBinds)
844 = case assocMaybe gen_list (getUnique clas) of
845 Just gen_fn -> gen_fn fix_env tycon
846 Nothing -> pprPanic "genDerivBinds: bad derived class" (ppr clas)
848 gen_list :: [(Unique, FixityEnv -> TyCon -> (LHsBinds RdrName, LHsBinds RdrName))]
849 gen_list = [(eqClassKey, no_aux_binds (ignore_fix_env gen_Eq_binds))
850 ,(ordClassKey, no_aux_binds (ignore_fix_env gen_Ord_binds))
851 ,(enumClassKey, no_aux_binds (ignore_fix_env gen_Enum_binds))
852 ,(boundedClassKey, no_aux_binds (ignore_fix_env gen_Bounded_binds))
853 ,(ixClassKey, no_aux_binds (ignore_fix_env gen_Ix_binds))
854 ,(typeableClassKey,no_aux_binds (ignore_fix_env gen_Typeable_binds))
855 ,(showClassKey, no_aux_binds gen_Show_binds)
856 ,(readClassKey, no_aux_binds gen_Read_binds)
857 ,(dataClassKey, gen_Data_binds)
860 -- no_aux_binds is used for generators that don't
861 -- need to produce any auxiliary bindings
862 no_aux_binds f fix_env tc = (f fix_env tc, emptyLHsBinds)
863 ignore_fix_env f fix_env tc = f tc
867 %************************************************************************
869 \subsection[TcDeriv-taggery-Names]{What con2tag/tag2con functions are available?}
871 %************************************************************************
876 con2tag_Foo :: Foo ... -> Int#
877 tag2con_Foo :: Int -> Foo ... -- easier if Int, not Int#
878 maxtag_Foo :: Int -- ditto (NB: not unlifted)
881 We have a @con2tag@ function for a tycon if:
884 We're deriving @Eq@ and the tycon has nullary data constructors.
887 Or: we're deriving @Ord@ (unless single-constructor), @Enum@, @Ix@
891 We have a @tag2con@ function for a tycon if:
894 We're deriving @Enum@, or @Ix@ (enum type only???)
897 If we have a @tag2con@ function, we also generate a @maxtag@ constant.
900 genTaggeryBinds :: [InstInfo] -> TcM (LHsBinds RdrName)
901 genTaggeryBinds infos
902 = do { names_so_far <- foldlM do_con2tag [] tycons_of_interest
903 ; nm_alist_etc <- foldlM do_tag2con names_so_far tycons_of_interest
904 ; return (listToBag (map gen_tag_n_con_monobind nm_alist_etc)) }
906 all_CTs = [ (cls, tcTyConAppTyCon ty)
908 let (cls,ty) = simpleInstInfoClsTy info ]
909 all_tycons = map snd all_CTs
910 (tycons_of_interest, _) = removeDups compare all_tycons
912 do_con2tag acc_Names tycon
913 | isDataTyCon tycon &&
914 ((we_are_deriving eqClassKey tycon
915 && any isNullarySrcDataCon (tyConDataCons tycon))
916 || (we_are_deriving ordClassKey tycon
917 && not (isProductTyCon tycon))
918 || (we_are_deriving enumClassKey tycon)
919 || (we_are_deriving ixClassKey tycon))
921 = returnM ((con2tag_RDR tycon, tycon, GenCon2Tag)
926 do_tag2con acc_Names tycon
927 | isDataTyCon tycon &&
928 (we_are_deriving enumClassKey tycon ||
929 we_are_deriving ixClassKey tycon
930 && isEnumerationTyCon tycon)
931 = returnM ( (tag2con_RDR tycon, tycon, GenTag2Con)
932 : (maxtag_RDR tycon, tycon, GenMaxTag)
937 we_are_deriving clas_key tycon
938 = is_in_eqns clas_key tycon all_CTs
940 is_in_eqns clas_key tycon [] = False
941 is_in_eqns clas_key tycon ((c,t):cts)
942 = (clas_key == classKey c && tycon == t)
943 || is_in_eqns clas_key tycon cts
947 derivingThingErr clas tys tycon tyvars why
948 = sep [hsep [ptext SLIT("Can't make a derived instance of"), quotes (ppr pred)],
951 pred = mkClassPred clas (tys ++ [mkTyConApp tycon (mkTyVarTys tyvars)])
953 derivCtxt :: Maybe Class -> TyCon -> SDoc
954 derivCtxt maybe_cls tycon
955 = ptext SLIT("When deriving") <+> cls <+> ptext SLIT("for type") <+> quotes (ppr tycon)
957 cls = case maybe_cls of
958 Nothing -> ptext SLIT("instances")
959 Just c -> ptext SLIT("the") <+> quotes (ppr c) <+> ptext SLIT("instance")