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 TcMType ( checkValidInstance )
19 import TcEnv ( newDFunName, pprInstInfoDetails,
20 InstInfo(..), InstBindings(..), simpleInstInfoClsTy,
21 tcLookupClass, tcLookupTyCon, tcLookupLocatedTyCon, tcExtendTyVarEnv
23 import TcGenDeriv -- Deriv stuff
24 import InstEnv ( Instance, OverlapFlag, mkLocalInstance, instanceHead, extendInstEnvList )
25 import Inst ( getOverlapFlag )
26 import TcHsType ( tcHsDeriv )
27 import TcSimplify ( tcSimplifyDeriv )
29 import RnBinds ( rnMethodBinds, rnTopBinds )
30 import RnEnv ( bindLocalNames )
31 import HscTypes ( FixityEnv )
33 import Class ( className, classArity, classKey, classTyVars, classSCTheta, Class )
34 import Type ( zipOpenTvSubst, substTheta, pprThetaArrow, pprClassPred, mkTyVarTy )
35 import ErrUtils ( dumpIfSet_dyn )
36 import MkId ( mkDictFunId )
37 import DataCon ( isNullarySrcDataCon, isVanillaDataCon, dataConInstOrigArgTys )
38 import Maybes ( catMaybes )
39 import RdrName ( RdrName )
40 import Name ( Name, getSrcLoc )
41 import NameSet ( duDefs )
42 import Type ( splitKindFunTys )
43 import TyCon ( tyConTyVars, tyConDataCons, tyConArity, tyConHasGenerics,
44 tyConStupidTheta, isProductTyCon, isDataTyCon, isNewTyCon, newTyConRhs,
45 isEnumerationTyCon, isRecursiveTyCon, TyCon
47 import TcType ( TcType, ThetaType, mkTyVarTys, mkTyConApp, tcTyConAppTyCon,
48 isUnLiftedType, mkClassPred, tyVarsOfType, tyVarsOfTypes,
49 isSubArgTypeKind, tcEqTypes, tcSplitAppTys, mkAppTys )
50 import Var ( TyVar, tyVarKind, varName )
51 import VarSet ( mkVarSet, disjointVarSet )
53 import SrcLoc ( srcLocSpan, Located(..), unLoc )
54 import Util ( zipWithEqual, sortLe, notNull )
55 import ListSetOps ( removeDups, assocMaybe )
60 %************************************************************************
62 \subsection[TcDeriv-intro]{Introduction to how we do deriving}
64 %************************************************************************
68 data T a b = C1 (Foo a) (Bar b)
73 [NOTE: See end of these comments for what to do with
74 data (C a, D b) => T a b = ...
77 We want to come up with an instance declaration of the form
79 instance (Ping a, Pong b, ...) => Eq (T a b) where
82 It is pretty easy, albeit tedious, to fill in the code "...". The
83 trick is to figure out what the context for the instance decl is,
84 namely @Ping@, @Pong@ and friends.
86 Let's call the context reqd for the T instance of class C at types
87 (a,b, ...) C (T a b). Thus:
89 Eq (T a b) = (Ping a, Pong b, ...)
91 Now we can get a (recursive) equation from the @data@ decl:
93 Eq (T a b) = Eq (Foo a) u Eq (Bar b) -- From C1
94 u Eq (T b a) u Eq Int -- From C2
95 u Eq (T a a) -- From C3
97 Foo and Bar may have explicit instances for @Eq@, in which case we can
98 just substitute for them. Alternatively, either or both may have
99 their @Eq@ instances given by @deriving@ clauses, in which case they
100 form part of the system of equations.
102 Now all we need do is simplify and solve the equations, iterating to
103 find the least fixpoint. Notice that the order of the arguments can
104 switch around, as here in the recursive calls to T.
106 Let's suppose Eq (Foo a) = Eq a, and Eq (Bar b) = Ping b.
110 Eq (T a b) = {} -- The empty set
113 Eq (T a b) = Eq (Foo a) u Eq (Bar b) -- From C1
114 u Eq (T b a) u Eq Int -- From C2
115 u Eq (T a a) -- From C3
117 After simplification:
118 = Eq a u Ping b u {} u {} u {}
123 Eq (T a b) = Eq (Foo a) u Eq (Bar b) -- From C1
124 u Eq (T b a) u Eq Int -- From C2
125 u Eq (T a a) -- From C3
127 After simplification:
132 = Eq a u Ping b u Eq b u Ping a
134 The next iteration gives the same result, so this is the fixpoint. We
135 need to make a canonical form of the RHS to ensure convergence. We do
136 this by simplifying the RHS to a form in which
138 - the classes constrain only tyvars
139 - the list is sorted by tyvar (major key) and then class (minor key)
140 - no duplicates, of course
142 So, here are the synonyms for the ``equation'' structures:
145 type DerivEqn = (Name, Class, TyCon, [TyVar], DerivRhs)
146 -- The Name is the name for the DFun we'll build
147 -- The tyvars bind all the variables in the RHS
149 pprDerivEqn (n,c,tc,tvs,rhs)
150 = parens (hsep [ppr n, ppr c, ppr tc, ppr tvs] <+> equals <+> ppr rhs)
152 type DerivRhs = ThetaType
153 type DerivSoln = DerivRhs
157 [Data decl contexts] A note about contexts on data decls
158 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
161 data (RealFloat a) => Complex a = !a :+ !a deriving( Read )
163 We will need an instance decl like:
165 instance (Read a, RealFloat a) => Read (Complex a) where
168 The RealFloat in the context is because the read method for Complex is bound
169 to construct a Complex, and doing that requires that the argument type is
172 But this ain't true for Show, Eq, Ord, etc, since they don't construct
173 a Complex; they only take them apart.
175 Our approach: identify the offending classes, and add the data type
176 context to the instance decl. The "offending classes" are
180 FURTHER NOTE ADDED March 2002. In fact, Haskell98 now requires that
181 pattern matching against a constructor from a data type with a context
182 gives rise to the constraints for that context -- or at least the thinned
183 version. So now all classes are "offending".
190 newtype T = T Char deriving( C [a] )
192 Notice the free 'a' in the deriving. We have to fill this out to
193 newtype T = T Char deriving( forall a. C [a] )
195 And then translate it to:
196 instance C [a] Char => C [a] T where ...
201 %************************************************************************
203 \subsection[TcDeriv-driver]{Top-level function for \tr{derivings}}
205 %************************************************************************
208 tcDeriving :: [LTyClDecl Name] -- All type constructors
209 -> [LDerivDecl Name] -- All stand-alone deriving declarations
210 -> TcM ([InstInfo], -- The generated "instance decls"
211 HsValBinds Name) -- Extra generated top-level bindings
213 tcDeriving tycl_decls deriv_decls
214 = recoverM (returnM ([], emptyValBindsOut)) $
215 do { -- Fish the "deriving"-related information out of the TcEnv
216 -- and make the necessary "equations".
217 overlap_flag <- getOverlapFlag
218 ; (ordinary_eqns, newtype_inst_info)
219 <- makeDerivEqns overlap_flag tycl_decls deriv_decls
221 ; (ordinary_inst_info, deriv_binds)
222 <- extendLocalInstEnv (map iSpec newtype_inst_info) $
223 deriveOrdinaryStuff overlap_flag ordinary_eqns
224 -- Add the newtype-derived instances to the inst env
225 -- before tacking the "ordinary" ones
227 ; let inst_info = newtype_inst_info ++ ordinary_inst_info
229 -- If we are compiling a hs-boot file,
230 -- don't generate any derived bindings
231 ; is_boot <- tcIsHsBoot
233 return (inst_info, emptyValBindsOut)
237 -- Generate the generic to/from functions from each type declaration
238 ; gen_binds <- mkGenericBinds tycl_decls
240 -- Rename these extra bindings, discarding warnings about unused bindings etc
241 -- Set -fglasgow exts so that we can have type signatures in patterns,
242 -- which is used in the generic binds
244 <- discardWarnings $ setOptM Opt_GlasgowExts $ do
245 { (rn_deriv, _dus1) <- rnTopBinds (ValBindsIn deriv_binds [])
246 ; (rn_gen, dus_gen) <- rnTopBinds (ValBindsIn gen_binds [])
247 ; keepAliveSetTc (duDefs dus_gen) -- Mark these guys to
249 ; return (rn_deriv `plusHsValBinds` rn_gen) }
253 ; ioToTcRn (dumpIfSet_dyn dflags Opt_D_dump_deriv "Derived instances"
254 (ddump_deriving inst_info rn_binds))
256 ; returnM (inst_info, rn_binds)
259 ddump_deriving :: [InstInfo] -> HsValBinds Name -> SDoc
260 ddump_deriving inst_infos extra_binds
261 = vcat (map pprInstInfoDetails inst_infos) $$ ppr extra_binds
263 -----------------------------------------
264 deriveOrdinaryStuff overlap_flag [] -- Short cut
265 = returnM ([], emptyLHsBinds)
267 deriveOrdinaryStuff overlap_flag eqns
268 = do { -- Take the equation list and solve it, to deliver a list of
269 -- solutions, a.k.a. the contexts for the instance decls
270 -- required for the corresponding equations.
271 inst_specs <- solveDerivEqns overlap_flag eqns
273 -- Generate the InstInfo for each dfun,
274 -- plus any auxiliary bindings it needs
275 ; (inst_infos, aux_binds_s) <- mapAndUnzipM genInst inst_specs
277 -- Generate any extra not-one-inst-decl-specific binds,
278 -- notably "con2tag" and/or "tag2con" functions.
279 ; extra_binds <- genTaggeryBinds inst_infos
282 ; returnM (inst_infos, unionManyBags (extra_binds : aux_binds_s))
285 -----------------------------------------
286 mkGenericBinds tycl_decls
287 = do { tcs <- mapM tcLookupTyCon
289 L _ (TyData { tcdLName = L _ tc_name }) <- tycl_decls]
290 -- We are only interested in the data type declarations
291 ; return (unionManyBags [ mkTyConGenericBinds tc |
292 tc <- tcs, tyConHasGenerics tc ]) }
293 -- And then only in the ones whose 'has-generics' flag is on
297 %************************************************************************
299 \subsection[TcDeriv-eqns]{Forming the equations}
301 %************************************************************************
303 @makeDerivEqns@ fishes around to find the info about needed derived
304 instances. Complicating factors:
307 We can only derive @Enum@ if the data type is an enumeration
308 type (all nullary data constructors).
311 We can only derive @Ix@ if the data type is an enumeration {\em
312 or} has just one data constructor (e.g., tuples).
315 [See Appendix~E in the Haskell~1.2 report.] This code here deals w/
318 Note [Newtype deriving superclasses]
319 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
320 The 'tys' here come from the partial application in the deriving
321 clause. The last arg is the new instance type.
323 We must pass the superclasses; the newtype might be an instance
324 of them in a different way than the representation type
325 E.g. newtype Foo a = Foo a deriving( Show, Num, Eq )
326 Then the Show instance is not done via isomorphism; it shows
328 The Num instance is derived via isomorphism, but the Show superclass
329 dictionary must the Show instance for Foo, *not* the Show dictionary
330 gotten from the Num dictionary. So we must build a whole new dictionary
331 not just use the Num one. The instance we want is something like:
332 instance (Num a, Show (Foo a), Eq (Foo a)) => Num (Foo a) where
335 There may be a coercion needed which we get from the tycon for the newtype
336 when the dict is constructed in TcInstDcls.tcInstDecl2
340 makeDerivEqns :: OverlapFlag
343 -> TcM ([DerivEqn], -- Ordinary derivings
344 [InstInfo]) -- Special newtype derivings
346 makeDerivEqns overlap_flag tycl_decls deriv_decls
347 = do derive_these_top_level <- mapM top_level_deriv deriv_decls >>= return . catMaybes
348 (maybe_ordinaries, maybe_newtypes)
349 <- mapAndUnzipM mk_eqn (derive_these ++ derive_these_top_level)
350 return (catMaybes maybe_ordinaries, catMaybes maybe_newtypes)
352 ------------------------------------------------------------------
353 derive_these :: [(NewOrData, Name, LHsType Name)]
354 -- Find the (nd, TyCon, Pred) pairs that must be `derived'
355 derive_these = [ (nd, tycon, pred)
356 | L _ (TyData { tcdND = nd, tcdLName = L _ tycon,
357 tcdDerivs = Just preds }) <- tycl_decls,
360 top_level_deriv :: LDerivDecl Name -> TcM (Maybe (NewOrData, Name, LHsType Name))
361 top_level_deriv d@(L l (DerivDecl inst ty_name)) = recoverM (returnM Nothing) $ setSrcSpan l $
362 do tycon <- tcLookupLocatedTyCon ty_name
363 let new_or_data = if isNewTyCon tycon then NewType else DataType
364 traceTc (text "Stand-alone deriving:" <+> ppr (new_or_data, unLoc ty_name, inst))
365 return $ Just (new_or_data, unLoc ty_name, inst)
367 ------------------------------------------------------------------
368 -- takes (whether newtype or data, name of data type, partially applied type class)
369 mk_eqn :: (NewOrData, Name, LHsType Name) -> TcM (Maybe DerivEqn, Maybe InstInfo)
370 -- We swizzle the tyvars and datacons out of the tycon
371 -- to make the rest of the equation
373 -- The "deriv_ty" is a LHsType to take account of the fact that for newtype derivign
374 -- we allow deriving (forall a. C [a]).
376 mk_eqn (new_or_data, tycon_name, hs_deriv_ty)
377 = tcLookupTyCon tycon_name `thenM` \ tycon ->
378 setSrcSpan (srcLocSpan (getSrcLoc tycon)) $
379 addErrCtxt (derivCtxt tycon) $
380 tcExtendTyVarEnv (tyConTyVars tycon) $ -- Deriving preds may (now) mention
381 -- the type variables for the type constructor
382 tcHsDeriv hs_deriv_ty `thenM` \ (deriv_tvs, clas, tys) ->
383 doptM Opt_GlasgowExts `thenM` \ gla_exts ->
384 mk_eqn_help gla_exts new_or_data tycon deriv_tvs clas tys
386 ------------------------------------------------------------------
387 -- data/newtype T a = ... deriving( C t1 t2 )
388 -- leads to a call to mk_eqn_help with
389 -- tycon = T, deriv_tvs = ftv(t1,t2), clas = C, tys = [t1,t2]
391 mk_eqn_help gla_exts DataType tycon deriv_tvs clas tys
392 | Just err <- checkSideConditions gla_exts tycon deriv_tvs clas tys
393 = bale_out (derivingThingErr clas tys tycon (tyConTyVars tycon) err)
395 = do { eqn <- mkDataTypeEqn tycon clas
396 ; returnM (Just eqn, Nothing) }
398 mk_eqn_help gla_exts NewType tycon deriv_tvs clas tys
399 | can_derive_via_isomorphism && (gla_exts || std_class_via_iso clas)
400 = do { traceTc (text "newtype deriving:" <+> ppr tycon <+> ppr rep_tys)
401 ; -- Go ahead and use the isomorphism
402 dfun_name <- new_dfun_name clas tycon
403 ; return (Nothing, Just (InstInfo { iSpec = mk_inst_spec dfun_name,
404 iBinds = NewTypeDerived ntd_info })) }
405 | std_class gla_exts clas
406 = mk_eqn_help gla_exts DataType tycon deriv_tvs clas tys -- Go via bale-out route
408 | otherwise -- Non-standard instance
409 = bale_out (if gla_exts then
410 cant_derive_err -- Too hard
412 non_std_err) -- Just complain about being a non-std instance
414 -- Here is the plan for newtype derivings. We see
415 -- newtype T a1...an = MkT (t ak+1...an) deriving (.., C s1 .. sm, ...)
416 -- where t is a type,
417 -- ak+1...an is a suffix of a1..an
418 -- ak+1...an do not occur free in t, nor in the s1..sm
419 -- (C s1 ... sm) is a *partial applications* of class C
420 -- with the last parameter missing
421 -- (T a1 .. ak) matches the kind of C's last argument
422 -- (and hence so does t)
424 -- We generate the instance
425 -- instance forall ({a1..ak} u fvs(s1..sm)).
426 -- C s1 .. sm t => C s1 .. sm (T a1...ak)
427 -- where T a1...ap is the partial application of
428 -- the LHS of the correct kind and p >= k
430 -- NB: the variables below are:
431 -- tc_tvs = [a1, ..., an]
432 -- tyvars_to_keep = [a1, ..., ak]
433 -- rep_ty = t ak .. an
434 -- deriv_tvs = fvs(s1..sm) \ tc_tvs
435 -- tys = [s1, ..., sm]
438 -- Running example: newtype T s a = MkT (ST s a) deriving( Monad )
439 -- We generate the instance
440 -- instance Monad (ST s) => Monad (T s) where
442 clas_tyvars = classTyVars clas
443 kind = tyVarKind (last clas_tyvars)
444 -- Kind of the thing we want to instance
445 -- e.g. argument kind of Monad, *->*
447 (arg_kinds, _) = splitKindFunTys kind
448 n_args_to_drop = length arg_kinds
449 -- Want to drop 1 arg from (T s a) and (ST s a)
450 -- to get instance Monad (ST s) => Monad (T s)
452 -- Note [newtype representation]
453 -- Need newTyConRhs *not* newTyConRep to get the representation
454 -- type, because the latter looks through all intermediate newtypes
456 -- newtype B = MkB Int
457 -- newtype A = MkA B deriving( Num )
458 -- We want the Num instance of B, *not* the Num instance of Int,
459 -- when making the Num instance of A!
460 (tc_tvs, rep_ty) = newTyConRhs tycon
461 (rep_fn, rep_ty_args) = tcSplitAppTys rep_ty
463 n_tyvars_to_keep = tyConArity tycon - n_args_to_drop
464 tyvars_to_drop = drop n_tyvars_to_keep tc_tvs
465 tyvars_to_keep = take n_tyvars_to_keep tc_tvs
467 n_args_to_keep = length rep_ty_args - n_args_to_drop
468 args_to_drop = drop n_args_to_keep rep_ty_args
469 args_to_keep = take n_args_to_keep rep_ty_args
471 rep_fn' = mkAppTys rep_fn args_to_keep
472 rep_tys = tys ++ [rep_fn']
473 rep_pred = mkClassPred clas rep_tys
474 -- rep_pred is the representation dictionary, from where
475 -- we are gong to get all the methods for the newtype dictionary
477 -- Next we figure out what superclass dictionaries to use
478 -- See Note [Newtype deriving superclasses] above
480 inst_tys = tys ++ [mkTyConApp tycon (mkTyVarTys tyvars_to_keep)]
481 sc_theta = substTheta (zipOpenTvSubst clas_tyvars inst_tys)
484 -- If there are no tyvars, there's no need
485 -- to abstract over the dictionaries we need
486 -- Example: newtype T = MkT Int deriving( C )
487 -- We get the derived instance
490 -- instance C Int => C T
491 dict_tvs = deriv_tvs ++ tyvars_to_keep
492 all_preds = rep_pred : sc_theta -- NB: rep_pred comes first
493 (dict_args, ntd_info) | null dict_tvs = ([], Just all_preds)
494 | otherwise = (all_preds, Nothing)
496 -- Finally! Here's where we build the dictionary Id
497 mk_inst_spec dfun_name = mkLocalInstance dfun overlap_flag
499 dfun = mkDictFunId dfun_name dict_tvs dict_args clas inst_tys
501 -------------------------------------------------------------------
502 -- Figuring out whether we can only do this newtype-deriving thing
504 right_arity = length tys + 1 == classArity clas
506 -- Never derive Read,Show,Typeable,Data this way
507 non_iso_classes = [readClassKey, showClassKey, typeableClassKey, dataClassKey]
508 can_derive_via_isomorphism
509 = not (getUnique clas `elem` non_iso_classes)
510 && right_arity -- Well kinded;
511 -- eg not: newtype T ... deriving( ST )
512 -- because ST needs *2* type params
513 && n_tyvars_to_keep >= 0 -- Type constructor has right kind:
514 -- eg not: newtype T = T Int deriving( Monad )
515 && n_args_to_keep >= 0 -- Rep type has right kind:
516 -- eg not: newtype T a = T Int deriving( Monad )
517 && eta_ok -- Eta reduction works
518 && not (isRecursiveTyCon tycon) -- Does not work for recursive tycons:
519 -- newtype A = MkA [A]
521 -- instance Eq [A] => Eq A !!
522 -- Here's a recursive newtype that's actually OK
523 -- newtype S1 = S1 [T1 ()]
524 -- newtype T1 a = T1 (StateT S1 IO a ) deriving( Monad )
525 -- It's currently rejected. Oh well.
526 -- In fact we generate an instance decl that has method of form
527 -- meth @ instTy = meth @ repTy
528 -- (no coerce's). We'd need a coerce if we wanted to handle
529 -- recursive newtypes too
531 -- Check that eta reduction is OK
532 -- (a) the dropped-off args are identical
533 -- (b) the remaining type args do not mention any of teh dropped type variables
534 -- (c) the type class args do not mention any of teh dropped type variables
535 dropped_tvs = mkVarSet tyvars_to_drop
536 eta_ok = (args_to_drop `tcEqTypes` mkTyVarTys tyvars_to_drop)
537 && (tyVarsOfType rep_fn' `disjointVarSet` dropped_tvs)
538 && (tyVarsOfTypes tys `disjointVarSet` dropped_tvs)
540 cant_derive_err = derivingThingErr clas tys tycon tyvars_to_keep
541 (vcat [ptext SLIT("even with cunning newtype deriving:"),
542 if isRecursiveTyCon tycon then
543 ptext SLIT("the newtype is recursive")
545 if not right_arity then
546 quotes (ppr (mkClassPred clas tys)) <+> ptext SLIT("does not have arity 1")
548 if not (n_tyvars_to_keep >= 0) then
549 ptext SLIT("the type constructor has wrong kind")
550 else if not (n_args_to_keep >= 0) then
551 ptext SLIT("the representation type has wrong kind")
552 else if not eta_ok then
553 ptext SLIT("the eta-reduction property does not hold")
557 non_std_err = derivingThingErr clas tys tycon tyvars_to_keep
558 (vcat [non_std_why clas,
559 ptext SLIT("Try -fglasgow-exts for GHC's newtype-deriving extension")])
561 bale_out err = addErrTc err `thenM_` returnM (Nothing, Nothing)
563 std_class gla_exts clas
564 = key `elem` derivableClassKeys
565 || (gla_exts && (key == typeableClassKey || key == dataClassKey))
569 std_class_via_iso clas -- These standard classes can be derived for a newtype
570 -- using the isomorphism trick *even if no -fglasgow-exts*
571 = classKey clas `elem` [eqClassKey, ordClassKey, ixClassKey, boundedClassKey]
572 -- Not Read/Show because they respect the type
573 -- Not Enum, becuase newtypes are never in Enum
576 new_dfun_name clas tycon -- Just a simple wrapper
577 = newDFunName clas [mkTyConApp tycon []] (getSrcLoc tycon)
578 -- The type passed to newDFunName is only used to generate
579 -- a suitable string; hence the empty type arg list
581 ------------------------------------------------------------------
582 mkDataTypeEqn :: TyCon -> Class -> TcM DerivEqn
583 mkDataTypeEqn tycon clas
584 | clas `hasKey` typeableClassKey
585 = -- The Typeable class is special in several ways
586 -- data T a b = ... deriving( Typeable )
588 -- instance Typeable2 T where ...
590 -- 1. There are no constraints in the instance
591 -- 2. There are no type variables either
592 -- 3. The actual class we want to generate isn't necessarily
593 -- Typeable; it depends on the arity of the type
594 do { real_clas <- tcLookupClass (typeableClassNames !! tyConArity tycon)
595 ; dfun_name <- new_dfun_name real_clas tycon
596 ; return (dfun_name, real_clas, tycon, [], []) }
599 = do { dfun_name <- new_dfun_name clas tycon
600 ; return (dfun_name, clas, tycon, tyvars, constraints) }
602 tyvars = tyConTyVars tycon
603 constraints = extra_constraints ++ ordinary_constraints
604 extra_constraints = tyConStupidTheta tycon
605 -- "extra_constraints": see note [Data decl contexts] above
608 = [ mkClassPred clas [arg_ty]
609 | data_con <- tyConDataCons tycon,
610 arg_ty <- dataConInstOrigArgTys data_con (map mkTyVarTy (tyConTyVars tycon)),
611 not (isUnLiftedType arg_ty) -- No constraints for unlifted types?
615 ------------------------------------------------------------------
616 -- Check side conditions that dis-allow derivability for particular classes
617 -- This is *apart* from the newtype-deriving mechanism
619 checkSideConditions :: Bool -> TyCon -> [TyVar] -> Class -> [TcType] -> Maybe SDoc
620 checkSideConditions gla_exts tycon deriv_tvs clas tys
621 | notNull deriv_tvs || notNull tys
622 = Just ty_args_why -- e.g. deriving( Foo s )
624 = case [cond | (key,cond) <- sideConditions, key == getUnique clas] of
625 [] -> Just (non_std_why clas)
626 [cond] -> cond (gla_exts, tycon)
627 other -> pprPanic "checkSideConditions" (ppr clas)
629 ty_args_why = quotes (ppr (mkClassPred clas tys)) <+> ptext SLIT("is not a class")
631 non_std_why clas = quotes (ppr clas) <+> ptext SLIT("is not a derivable class")
633 sideConditions :: [(Unique, Condition)]
635 = [ (eqClassKey, cond_std),
636 (ordClassKey, cond_std),
637 (readClassKey, cond_std),
638 (showClassKey, cond_std),
639 (enumClassKey, cond_std `andCond` cond_isEnumeration),
640 (ixClassKey, cond_std `andCond` (cond_isEnumeration `orCond` cond_isProduct)),
641 (boundedClassKey, cond_std `andCond` (cond_isEnumeration `orCond` cond_isProduct)),
642 (typeableClassKey, cond_glaExts `andCond` cond_typeableOK),
643 (dataClassKey, cond_glaExts `andCond` cond_std)
646 type Condition = (Bool, TyCon) -> Maybe SDoc -- Nothing => OK
648 orCond :: Condition -> Condition -> Condition
651 Nothing -> Nothing -- c1 succeeds
652 Just x -> case c2 tc of -- c1 fails
654 Just y -> Just (x $$ ptext SLIT(" and") $$ y)
657 andCond c1 c2 tc = case c1 tc of
658 Nothing -> c2 tc -- c1 succeeds
659 Just x -> Just x -- c1 fails
661 cond_std :: Condition
662 cond_std (gla_exts, tycon)
663 | any (not . isVanillaDataCon) data_cons = Just existential_why
664 | null data_cons = Just no_cons_why
665 | otherwise = Nothing
667 data_cons = tyConDataCons tycon
668 no_cons_why = quotes (ppr tycon) <+> ptext SLIT("has no data constructors")
669 existential_why = quotes (ppr tycon) <+> ptext SLIT("has non-Haskell-98 constructor(s)")
671 cond_isEnumeration :: Condition
672 cond_isEnumeration (gla_exts, tycon)
673 | isEnumerationTyCon tycon = Nothing
674 | otherwise = Just why
676 why = quotes (ppr tycon) <+> ptext SLIT("has non-nullary constructors")
678 cond_isProduct :: Condition
679 cond_isProduct (gla_exts, tycon)
680 | isProductTyCon tycon = Nothing
681 | otherwise = Just why
683 why = quotes (ppr tycon) <+> ptext SLIT("has more than one constructor")
685 cond_typeableOK :: Condition
686 -- OK for Typeable class
687 -- Currently: (a) args all of kind *
688 -- (b) 7 or fewer args
689 cond_typeableOK (gla_exts, tycon)
690 | tyConArity tycon > 7 = Just too_many
691 | not (all (isSubArgTypeKind . tyVarKind) (tyConTyVars tycon)) = Just bad_kind
692 | otherwise = Nothing
694 too_many = quotes (ppr tycon) <+> ptext SLIT("has too many arguments")
695 bad_kind = quotes (ppr tycon) <+> ptext SLIT("has arguments of kind other than `*'")
697 cond_glaExts :: Condition
698 cond_glaExts (gla_exts, tycon) | gla_exts = Nothing
699 | otherwise = Just why
701 why = ptext SLIT("You need -fglasgow-exts to derive an instance for this class")
704 %************************************************************************
706 \subsection[TcDeriv-fixpoint]{Finding the fixed point of \tr{deriving} equations}
708 %************************************************************************
710 A ``solution'' (to one of the equations) is a list of (k,TyVarTy tv)
711 terms, which is the final correct RHS for the corresponding original
715 Each (k,TyVarTy tv) in a solution constrains only a type
719 The (k,TyVarTy tv) pairs in a solution are canonically
720 ordered by sorting on type varible, tv, (major key) and then class, k,
725 solveDerivEqns :: OverlapFlag
727 -> TcM [Instance]-- Solns in same order as eqns.
728 -- This bunch is Absolutely minimal...
730 solveDerivEqns overlap_flag orig_eqns
731 = iterateDeriv 1 initial_solutions
733 -- The initial solutions for the equations claim that each
734 -- instance has an empty context; this solution is certainly
735 -- in canonical form.
736 initial_solutions :: [DerivSoln]
737 initial_solutions = [ [] | _ <- orig_eqns ]
739 ------------------------------------------------------------------
740 -- iterateDeriv calculates the next batch of solutions,
741 -- compares it with the current one; finishes if they are the
742 -- same, otherwise recurses with the new solutions.
743 -- It fails if any iteration fails
744 iterateDeriv :: Int -> [DerivSoln] -> TcM [Instance]
745 iterateDeriv n current_solns
746 | n > 20 -- Looks as if we are in an infinite loop
747 -- This can happen if we have -fallow-undecidable-instances
748 -- (See TcSimplify.tcSimplifyDeriv.)
749 = pprPanic "solveDerivEqns: probable loop"
750 (vcat (map pprDerivEqn orig_eqns) $$ ppr current_solns)
753 inst_specs = zipWithEqual "add_solns" mk_inst_spec
754 orig_eqns current_solns
757 -- Extend the inst info from the explicit instance decls
758 -- with the current set of solutions, and simplify each RHS
759 extendLocalInstEnv inst_specs $
760 mappM gen_soln orig_eqns
761 ) `thenM` \ new_solns ->
762 if (current_solns == new_solns) then
765 iterateDeriv (n+1) new_solns
767 ------------------------------------------------------------------
768 gen_soln (_, clas, tc,tyvars,deriv_rhs)
769 = setSrcSpan (srcLocSpan (getSrcLoc tc)) $
770 do { let inst_tys = [mkTyConApp tc (mkTyVarTys tyvars)]
771 ; theta <- addErrCtxt (derivInstCtxt1 clas inst_tys) $
772 tcSimplifyDeriv tc tyvars deriv_rhs
773 ; addErrCtxt (derivInstCtxt2 theta clas inst_tys) $
774 checkValidInstance tyvars theta clas inst_tys
775 ; return (sortLe (<=) theta) } -- Canonicalise before returning the soluction
779 ------------------------------------------------------------------
780 mk_inst_spec (dfun_name, clas, tycon, tyvars, _) theta
781 = mkLocalInstance dfun overlap_flag
783 dfun = mkDictFunId dfun_name tyvars theta clas
784 [mkTyConApp tycon (mkTyVarTys tyvars)]
786 extendLocalInstEnv :: [Instance] -> TcM a -> TcM a
787 -- Add new locally-defined instances; don't bother to check
788 -- for functional dependency errors -- that'll happen in TcInstDcls
789 extendLocalInstEnv dfuns thing_inside
790 = do { env <- getGblEnv
791 ; let inst_env' = extendInstEnvList (tcg_inst_env env) dfuns
792 env' = env { tcg_inst_env = inst_env' }
793 ; setGblEnv env' thing_inside }
796 %************************************************************************
798 \subsection[TcDeriv-normal-binds]{Bindings for the various classes}
800 %************************************************************************
802 After all the trouble to figure out the required context for the
803 derived instance declarations, all that's left is to chug along to
804 produce them. They will then be shoved into @tcInstDecls2@, which
805 will do all its usual business.
807 There are lots of possibilities for code to generate. Here are
808 various general remarks.
813 We want derived instances of @Eq@ and @Ord@ (both v common) to be
814 ``you-couldn't-do-better-by-hand'' efficient.
817 Deriving @Show@---also pretty common--- should also be reasonable good code.
820 Deriving for the other classes isn't that common or that big a deal.
827 Deriving @Ord@ is done mostly with the 1.3 @compare@ method.
830 Deriving @Eq@ also uses @compare@, if we're deriving @Ord@, too.
833 We {\em normally} generate code only for the non-defaulted methods;
834 there are some exceptions for @Eq@ and (especially) @Ord@...
837 Sometimes we use a @_con2tag_<tycon>@ function, which returns a data
838 constructor's numeric (@Int#@) tag. These are generated by
839 @gen_tag_n_con_binds@, and the heuristic for deciding if one of
840 these is around is given by @hasCon2TagFun@.
842 The examples under the different sections below will make this
846 Much less often (really just for deriving @Ix@), we use a
847 @_tag2con_<tycon>@ function. See the examples.
850 We use the renamer!!! Reason: we're supposed to be
851 producing @LHsBinds Name@ for the methods, but that means
852 producing correctly-uniquified code on the fly. This is entirely
853 possible (the @TcM@ monad has a @UniqueSupply@), but it is painful.
854 So, instead, we produce @MonoBinds RdrName@ then heave 'em through
855 the renamer. What a great hack!
859 -- Generate the InstInfo for the required instance,
860 -- plus any auxiliary bindings required
861 genInst :: Instance -> TcM (InstInfo, LHsBinds RdrName)
863 = do { fix_env <- getFixityEnv
865 (tyvars,_,clas,[ty]) = instanceHead spec
866 clas_nm = className clas
867 tycon = tcTyConAppTyCon ty
868 (meth_binds, aux_binds) = genDerivBinds clas fix_env tycon
870 -- Bring the right type variables into
871 -- scope, and rename the method binds
872 -- It's a bit yukky that we return *renamed* InstInfo, but
873 -- *non-renamed* auxiliary bindings
874 ; (rn_meth_binds, _fvs) <- discardWarnings $
875 bindLocalNames (map varName tyvars) $
876 rnMethodBinds clas_nm (\n -> []) [] meth_binds
878 -- Build the InstInfo
879 ; return (InstInfo { iSpec = spec,
880 iBinds = VanillaInst rn_meth_binds [] },
884 genDerivBinds clas fix_env tycon
885 | className clas `elem` typeableClassNames
886 = (gen_Typeable_binds tycon, emptyLHsBinds)
889 = case assocMaybe gen_list (getUnique clas) of
890 Just gen_fn -> gen_fn fix_env tycon
891 Nothing -> pprPanic "genDerivBinds: bad derived class" (ppr clas)
893 gen_list :: [(Unique, FixityEnv -> TyCon -> (LHsBinds RdrName, LHsBinds RdrName))]
894 gen_list = [(eqClassKey, no_aux_binds (ignore_fix_env gen_Eq_binds))
895 ,(ordClassKey, no_aux_binds (ignore_fix_env gen_Ord_binds))
896 ,(enumClassKey, no_aux_binds (ignore_fix_env gen_Enum_binds))
897 ,(boundedClassKey, no_aux_binds (ignore_fix_env gen_Bounded_binds))
898 ,(ixClassKey, no_aux_binds (ignore_fix_env gen_Ix_binds))
899 ,(typeableClassKey,no_aux_binds (ignore_fix_env gen_Typeable_binds))
900 ,(showClassKey, no_aux_binds gen_Show_binds)
901 ,(readClassKey, no_aux_binds gen_Read_binds)
902 ,(dataClassKey, gen_Data_binds)
905 -- no_aux_binds is used for generators that don't
906 -- need to produce any auxiliary bindings
907 no_aux_binds f fix_env tc = (f fix_env tc, emptyLHsBinds)
908 ignore_fix_env f fix_env tc = f tc
912 %************************************************************************
914 \subsection[TcDeriv-taggery-Names]{What con2tag/tag2con functions are available?}
916 %************************************************************************
921 con2tag_Foo :: Foo ... -> Int#
922 tag2con_Foo :: Int -> Foo ... -- easier if Int, not Int#
923 maxtag_Foo :: Int -- ditto (NB: not unlifted)
926 We have a @con2tag@ function for a tycon if:
929 We're deriving @Eq@ and the tycon has nullary data constructors.
932 Or: we're deriving @Ord@ (unless single-constructor), @Enum@, @Ix@
936 We have a @tag2con@ function for a tycon if:
939 We're deriving @Enum@, or @Ix@ (enum type only???)
942 If we have a @tag2con@ function, we also generate a @maxtag@ constant.
945 genTaggeryBinds :: [InstInfo] -> TcM (LHsBinds RdrName)
946 genTaggeryBinds infos
947 = do { names_so_far <- foldlM do_con2tag [] tycons_of_interest
948 ; nm_alist_etc <- foldlM do_tag2con names_so_far tycons_of_interest
949 ; return (listToBag (map gen_tag_n_con_monobind nm_alist_etc)) }
951 all_CTs = [ (cls, tcTyConAppTyCon ty)
953 let (cls,ty) = simpleInstInfoClsTy info ]
954 all_tycons = map snd all_CTs
955 (tycons_of_interest, _) = removeDups compare all_tycons
957 do_con2tag acc_Names tycon
958 | isDataTyCon tycon &&
959 ((we_are_deriving eqClassKey tycon
960 && any isNullarySrcDataCon (tyConDataCons tycon))
961 || (we_are_deriving ordClassKey tycon
962 && not (isProductTyCon tycon))
963 || (we_are_deriving enumClassKey tycon)
964 || (we_are_deriving ixClassKey tycon))
966 = returnM ((con2tag_RDR tycon, tycon, GenCon2Tag)
971 do_tag2con acc_Names tycon
972 | isDataTyCon tycon &&
973 (we_are_deriving enumClassKey tycon ||
974 we_are_deriving ixClassKey tycon
975 && isEnumerationTyCon tycon)
976 = returnM ( (tag2con_RDR tycon, tycon, GenTag2Con)
977 : (maxtag_RDR tycon, tycon, GenMaxTag)
982 we_are_deriving clas_key tycon
983 = is_in_eqns clas_key tycon all_CTs
985 is_in_eqns clas_key tycon [] = False
986 is_in_eqns clas_key tycon ((c,t):cts)
987 = (clas_key == classKey c && tycon == t)
988 || is_in_eqns clas_key tycon cts
992 derivingThingErr clas tys tycon tyvars why
993 = sep [hsep [ptext SLIT("Can't make a derived instance of"), quotes (ppr pred)],
996 pred = mkClassPred clas (tys ++ [mkTyConApp tycon (mkTyVarTys tyvars)])
998 derivCtxt :: TyCon -> SDoc
1000 = ptext SLIT("When deriving instances for") <+> quotes (ppr tycon)
1002 derivInstCtxt1 clas inst_tys
1003 = ptext SLIT("When deriving the instance for") <+> quotes (pprClassPred clas inst_tys)
1005 derivInstCtxt2 theta clas inst_tys
1006 = vcat [ptext SLIT("In the derived instance declaration"),
1007 nest 2 (ptext SLIT("instance") <+> sep [pprThetaArrow theta,
1008 pprClassPred clas inst_tys])]