2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[TcDeriv]{Deriving}
6 Handles @deriving@ clauses on @data@ declarations.
9 module TcDeriv ( tcDeriving ) where
11 #include "HsVersions.h"
13 import HsSyn ( HsBinds(..), TyClDecl(..), MonoBinds(..),
15 import RdrHsSyn ( RdrNameMonoBinds )
16 import RnHsSyn ( RenamedHsBinds, RenamedTyClDecl, RenamedHsPred )
17 import CmdLineOpts ( DynFlag(..) )
19 import Generics ( mkGenericBinds )
21 import TcEnv ( newDFunName,
22 InstInfo(..), pprInstInfo, InstBindings(..),
23 pprInstInfoDetails, tcLookupTyCon, tcExtendTyVarEnv
25 import TcGenDeriv -- Deriv stuff
26 import InstEnv ( simpleDFunClassTyCon, extendInstEnv )
27 import TcHsType ( tcHsPred )
28 import TcSimplify ( tcSimplifyDeriv )
30 import RnBinds ( rnMethodBinds, rnTopMonoBinds )
31 import RnEnv ( bindLocalNames )
32 import TcRnMonad ( thenM, returnM, mapAndUnzipM )
33 import HscTypes ( DFunId, FixityEnv, typeEnvTyCons )
35 import BasicTypes ( NewOrData(..) )
36 import Class ( className, classArity, classKey, classTyVars, classSCTheta, Class )
37 import Subst ( mkTyVarSubst, substTheta )
38 import ErrUtils ( dumpIfSet_dyn )
39 import MkId ( mkDictFunId )
40 import DataCon ( dataConOrigArgTys, isNullaryDataCon, isExistentialDataCon )
41 import Maybes ( catMaybes )
42 import Name ( Name, getSrcLoc )
43 import NameSet ( NameSet, emptyNameSet, duDefs )
44 import Unique ( Unique, getUnique )
46 import TyCon ( tyConTyVars, tyConDataCons, tyConArity,
47 tyConTheta, isProductTyCon, isDataTyCon,
48 isEnumerationTyCon, isRecursiveTyCon, TyCon
50 import TcType ( TcType, ThetaType, mkTyVarTy, mkTyVarTys, mkTyConApp,
51 getClassPredTys_maybe, tcTyConAppTyCon,
52 isUnLiftedType, mkClassPred, tyVarsOfTypes, tcSplitFunTys, isTypeKind,
53 tcEqTypes, tcSplitAppTys, mkAppTys, tcSplitDFunTy )
54 import Var ( TyVar, tyVarKind, idType, varName )
55 import VarSet ( mkVarSet, subVarSet )
57 import Util ( zipWithEqual, sortLt, notNull )
58 import ListSetOps ( removeDups, assoc )
62 %************************************************************************
64 \subsection[TcDeriv-intro]{Introduction to how we do deriving}
66 %************************************************************************
70 data T a b = C1 (Foo a) (Bar b)
75 [NOTE: See end of these comments for what to do with
76 data (C a, D b) => T a b = ...
79 We want to come up with an instance declaration of the form
81 instance (Ping a, Pong b, ...) => Eq (T a b) where
84 It is pretty easy, albeit tedious, to fill in the code "...". The
85 trick is to figure out what the context for the instance decl is,
86 namely @Ping@, @Pong@ and friends.
88 Let's call the context reqd for the T instance of class C at types
89 (a,b, ...) C (T a b). Thus:
91 Eq (T a b) = (Ping a, Pong b, ...)
93 Now we can get a (recursive) equation from the @data@ decl:
95 Eq (T a b) = Eq (Foo a) u Eq (Bar b) -- From C1
96 u Eq (T b a) u Eq Int -- From C2
97 u Eq (T a a) -- From C3
99 Foo and Bar may have explicit instances for @Eq@, in which case we can
100 just substitute for them. Alternatively, either or both may have
101 their @Eq@ instances given by @deriving@ clauses, in which case they
102 form part of the system of equations.
104 Now all we need do is simplify and solve the equations, iterating to
105 find the least fixpoint. Notice that the order of the arguments can
106 switch around, as here in the recursive calls to T.
108 Let's suppose Eq (Foo a) = Eq a, and Eq (Bar b) = Ping b.
112 Eq (T a b) = {} -- The empty set
115 Eq (T a b) = Eq (Foo a) u Eq (Bar b) -- From C1
116 u Eq (T b a) u Eq Int -- From C2
117 u Eq (T a a) -- From C3
119 After simplification:
120 = Eq a u Ping b u {} u {} u {}
125 Eq (T a b) = Eq (Foo a) u Eq (Bar b) -- From C1
126 u Eq (T b a) u Eq Int -- From C2
127 u Eq (T a a) -- From C3
129 After simplification:
134 = Eq a u Ping b u Eq b u Ping a
136 The next iteration gives the same result, so this is the fixpoint. We
137 need to make a canonical form of the RHS to ensure convergence. We do
138 this by simplifying the RHS to a form in which
140 - the classes constrain only tyvars
141 - the list is sorted by tyvar (major key) and then class (minor key)
142 - no duplicates, of course
144 So, here are the synonyms for the ``equation'' structures:
147 type DerivEqn = (Name, Class, TyCon, [TyVar], DerivRhs)
148 -- The Name is the name for the DFun we'll build
149 -- The tyvars bind all the variables in the RHS
151 pprDerivEqn (n,c,tc,tvs,rhs)
152 = parens (hsep [ppr n, ppr c, ppr tc, ppr tvs] <+> equals <+> ppr rhs)
154 type DerivRhs = ThetaType
155 type DerivSoln = DerivRhs
159 [Data decl contexts] A note about contexts on data decls
160 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
163 data (RealFloat a) => Complex a = !a :+ !a deriving( Read )
165 We will need an instance decl like:
167 instance (Read a, RealFloat a) => Read (Complex a) where
170 The RealFloat in the context is because the read method for Complex is bound
171 to construct a Complex, and doing that requires that the argument type is
174 But this ain't true for Show, Eq, Ord, etc, since they don't construct
175 a Complex; they only take them apart.
177 Our approach: identify the offending classes, and add the data type
178 context to the instance decl. The "offending classes" are
182 FURTHER NOTE ADDED March 2002. In fact, Haskell98 now requires that
183 pattern matching against a constructor from a data type with a context
184 gives rise to the constraints for that context -- or at least the thinned
185 version. So now all classes are "offending".
189 %************************************************************************
191 \subsection[TcDeriv-driver]{Top-level function for \tr{derivings}}
193 %************************************************************************
196 tcDeriving :: [RenamedTyClDecl] -- All type constructors
197 -> TcM ([InstInfo], -- The generated "instance decls"
198 RenamedHsBinds, -- Extra generated top-level bindings
199 NameSet) -- Binders to keep alive
201 tcDeriving tycl_decls
202 = recoverM (returnM ([], EmptyBinds, emptyNameSet)) $
203 do { -- Fish the "deriving"-related information out of the TcEnv
204 -- and make the necessary "equations".
205 ; (ordinary_eqns, newtype_inst_info) <- makeDerivEqns tycl_decls
207 ; (ordinary_inst_info, deriv_binds)
208 <- extendLocalInstEnv (map iDFunId newtype_inst_info) $
209 deriveOrdinaryStuff ordinary_eqns
210 -- Add the newtype-derived instances to the inst env
211 -- before tacking the "ordinary" ones
213 -- Generate the generic to/from functions from each type declaration
214 ; tcg_env <- getGblEnv
215 ; let gen_binds = mkGenericBinds (typeEnvTyCons (tcg_type_env tcg_env))
216 ; let inst_info = newtype_inst_info ++ ordinary_inst_info
218 -- Rename these extra bindings, discarding warnings about unused bindings etc
219 ; (rn_binds, gen_bndrs)
220 <- discardWarnings $ do
221 { (rn_deriv, _dus1) <- rnTopMonoBinds deriv_binds []
222 ; (rn_gen, dus_gen) <- rnTopMonoBinds gen_binds []
223 ; return (rn_deriv `ThenBinds` rn_gen, duDefs dus_gen) }
227 ; ioToTcRn (dumpIfSet_dyn dflags Opt_D_dump_deriv "Derived instances"
228 (ddump_deriving inst_info rn_binds))
230 ; returnM (inst_info, rn_binds, gen_bndrs)
233 ddump_deriving :: [InstInfo] -> RenamedHsBinds -> SDoc
234 ddump_deriving inst_infos extra_binds
235 = vcat (map pprInstInfoDetails inst_infos) $$ ppr extra_binds
237 -----------------------------------------
238 deriveOrdinaryStuff [] -- Short cut
239 = returnM ([], EmptyMonoBinds)
241 deriveOrdinaryStuff eqns
242 = do { -- Take the equation list and solve it, to deliver a list of
243 -- solutions, a.k.a. the contexts for the instance decls
244 -- required for the corresponding equations.
245 ; new_dfuns <- solveDerivEqns eqns
247 -- Generate the InstInfo for each dfun,
248 -- plus any auxiliary bindings it needs
249 ; (inst_infos, aux_binds_s) <- mapAndUnzipM genInst new_dfuns
251 -- Generate any extra not-one-inst-decl-specific binds,
252 -- notably "con2tag" and/or "tag2con" functions.
253 ; extra_binds <- genTaggeryBinds new_dfuns
256 ; returnM (inst_infos, andMonoBindList (extra_binds : aux_binds_s)) }
260 %************************************************************************
262 \subsection[TcDeriv-eqns]{Forming the equations}
264 %************************************************************************
266 @makeDerivEqns@ fishes around to find the info about needed derived
267 instances. Complicating factors:
270 We can only derive @Enum@ if the data type is an enumeration
271 type (all nullary data constructors).
274 We can only derive @Ix@ if the data type is an enumeration {\em
275 or} has just one data constructor (e.g., tuples).
278 [See Appendix~E in the Haskell~1.2 report.] This code here deals w/
282 makeDerivEqns :: [RenamedTyClDecl]
283 -> TcM ([DerivEqn], -- Ordinary derivings
284 [InstInfo]) -- Special newtype derivings
286 makeDerivEqns tycl_decls
287 = mapAndUnzipM mk_eqn derive_these `thenM` \ (maybe_ordinaries, maybe_newtypes) ->
288 returnM (catMaybes maybe_ordinaries, catMaybes maybe_newtypes)
290 ------------------------------------------------------------------
291 derive_these :: [(NewOrData, Name, RenamedHsPred)]
292 -- Find the (nd, TyCon, Pred) pairs that must be `derived'
293 -- NB: only source-language decls have deriving, no imported ones do
294 derive_these = [ (nd, tycon, pred)
295 | TyData {tcdND = nd, tcdName = tycon, tcdDerivs = Just preds} <- tycl_decls,
298 ------------------------------------------------------------------
299 mk_eqn :: (NewOrData, Name, RenamedHsPred) -> TcM (Maybe DerivEqn, Maybe InstInfo)
300 -- We swizzle the tyvars and datacons out of the tycon
301 -- to make the rest of the equation
303 mk_eqn (new_or_data, tycon_name, pred)
304 = tcLookupTyCon tycon_name `thenM` \ tycon ->
305 addSrcLoc (getSrcLoc tycon) $
306 addErrCtxt (derivCtxt Nothing tycon) $
307 tcExtendTyVarEnv (tyConTyVars tycon) $ -- Deriving preds may (now) mention
308 -- the type variables for the type constructor
309 tcHsPred pred `thenM` \ pred' ->
310 case getClassPredTys_maybe pred' of
311 Nothing -> bale_out (malformedPredErr tycon pred)
312 Just (clas, tys) -> doptM Opt_GlasgowExts `thenM` \ gla_exts ->
313 mk_eqn_help gla_exts new_or_data tycon clas tys
315 ------------------------------------------------------------------
316 mk_eqn_help gla_exts DataType tycon clas tys
317 | Just err <- checkSideConditions gla_exts clas tycon tys
318 = bale_out (derivingThingErr clas tys tycon tyvars err)
320 = new_dfun_name clas tycon `thenM` \ dfun_name ->
321 returnM (Just (dfun_name, clas, tycon, tyvars, constraints), Nothing)
323 tyvars = tyConTyVars tycon
324 constraints = extra_constraints ++ ordinary_constraints
325 -- "extra_constraints": see note [Data decl contexts] above
326 extra_constraints = tyConTheta tycon
329 | clas `hasKey` typeableClassKey -- For the Typeable class, the constraints
330 -- don't involve the constructor ags, only
332 -- e.g. data T a b = ...
334 -- instance (Typeable a, Typable b)
335 -- => Typeable (T a b) where
336 = [mkClassPred clas [mkTyVarTy tv] | tv <- tyvars]
338 = [ mkClassPred clas [arg_ty]
339 | data_con <- tyConDataCons tycon,
340 arg_ty <- dataConOrigArgTys data_con,
341 -- Use the same type variables
342 -- as the type constructor,
343 -- hence no need to instantiate
344 not (isUnLiftedType arg_ty) -- No constraints for unlifted types?
347 mk_eqn_help gla_exts NewType tycon clas tys
348 | can_derive_via_isomorphism && (gla_exts || standard_class gla_exts 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 | standard_class gla_exts clas
355 = mk_eqn_help gla_exts DataType tycon 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 aj...an do not occur free in t, and the (C s1 ... sm) is a
366 -- *partial applications* of class C with the last parameter missing
368 -- We generate the instances
369 -- instance C s1 .. sm (t ak...aj) => C s1 .. sm (T a1...aj)
370 -- where T a1...aj is the partial application of the LHS of the correct kind
372 -- Running example: newtype T s a = MkT (ST s a) deriving( Monad )
373 -- instance Monad (ST s) => Monad (T s) where
374 -- fail = coerce ... (fail @ ST s)
376 clas_tyvars = classTyVars clas
377 kind = tyVarKind (last clas_tyvars)
378 -- Kind of the thing we want to instance
379 -- e.g. argument kind of Monad, *->*
381 (arg_kinds, _) = tcSplitFunTys kind
382 n_args_to_drop = length arg_kinds
383 -- Want to drop 1 arg from (T s a) and (ST s a)
384 -- to get instance Monad (ST s) => Monad (T s)
386 -- Note [newtype representation]
387 -- We must not use newTyConRep to get the representation
388 -- type, because that looks through all intermediate newtypes
389 -- To get the RHS of *this* newtype, just look at the data
390 -- constructor. For example
391 -- newtype B = MkB Int
392 -- newtype A = MkA B deriving( Num )
393 -- We want the Num instance of B, *not* the Num instance of Int,
394 -- when making the Num instance of A!
395 tyvars = tyConTyVars tycon
396 rep_ty = head (dataConOrigArgTys (head (tyConDataCons tycon)))
397 (rep_fn, rep_ty_args) = tcSplitAppTys rep_ty
399 n_tyvars_to_keep = tyConArity tycon - n_args_to_drop
400 tyvars_to_drop = drop n_tyvars_to_keep tyvars
401 tyvars_to_keep = take n_tyvars_to_keep tyvars
403 n_args_to_keep = length rep_ty_args - n_args_to_drop
404 args_to_drop = drop n_args_to_keep rep_ty_args
405 args_to_keep = take n_args_to_keep rep_ty_args
407 rep_tys = tys ++ [mkAppTys rep_fn args_to_keep]
408 rep_pred = mkClassPred clas rep_tys
409 -- rep_pred is the representation dictionary, from where
410 -- we are gong to get all the methods for the newtype dictionary
412 inst_tys = (tys ++ [mkTyConApp tycon (mkTyVarTys tyvars_to_keep)])
413 -- The 'tys' here come from the partial application
414 -- in the deriving clause. The last arg is the new
417 -- We must pass the superclasses; the newtype might be an instance
418 -- of them in a different way than the representation type
419 -- E.g. newtype Foo a = Foo a deriving( Show, Num, Eq )
420 -- Then the Show instance is not done via isomprphism; it shows
422 -- The Num instance is derived via isomorphism, but the Show superclass
423 -- dictionary must the Show instance for Foo, *not* the Show dictionary
424 -- gotten from the Num dictionary. So we must build a whole new dictionary
425 -- not just use the Num one. The instance we want is something like:
426 -- instance (Num a, Show (Foo a), Eq (Foo a)) => Num (Foo a) where
429 -- There's no 'corece' needed because after the type checker newtypes
432 sc_theta = substTheta (mkTyVarSubst clas_tyvars inst_tys)
435 -- If there are no tyvars, there's no need
436 -- to abstract over the dictionaries we need
437 dict_args | null tyvars = []
438 | otherwise = rep_pred : sc_theta
440 -- Finally! Here's where we build the dictionary Id
441 mk_dfun dfun_name = mkDictFunId dfun_name tyvars dict_args clas inst_tys
443 -------------------------------------------------------------------
444 -- Figuring out whether we can only do this newtype-deriving thing
446 right_arity = length tys + 1 == classArity clas
448 -- Never derive Read,Show,Typeable,Data this way
449 non_iso_classes = [readClassKey, showClassKey, typeableClassKey, dataClassKey]
450 can_derive_via_isomorphism
451 = not (getUnique clas `elem` non_iso_classes)
452 && right_arity -- Well kinded;
453 -- eg not: newtype T ... deriving( ST )
454 -- because ST needs *2* type params
455 && n_tyvars_to_keep >= 0 -- Type constructor has right kind:
456 -- eg not: newtype T = T Int deriving( Monad )
457 && n_args_to_keep >= 0 -- Rep type has right kind:
458 -- eg not: newtype T a = T Int deriving( Monad )
459 && eta_ok -- Eta reduction works
460 && not (isRecursiveTyCon tycon) -- Does not work for recursive tycons:
461 -- newtype A = MkA [A]
463 -- instance Eq [A] => Eq A !!
465 -- Here's a recursive newtype that's actually OK
466 -- newtype S1 = S1 [T1 ()]
467 -- newtype T1 a = T1 (StateT S1 IO a ) deriving( Monad )
468 -- It's currently rejected. Oh well.
470 -- Check that eta reduction is OK
471 -- (a) the dropped-off args are identical
472 -- (b) the remaining type args mention
473 -- only the remaining type variables
474 eta_ok = (args_to_drop `tcEqTypes` mkTyVarTys tyvars_to_drop)
475 && (tyVarsOfTypes args_to_keep `subVarSet` mkVarSet tyvars_to_keep)
477 cant_derive_err = derivingThingErr clas tys tycon tyvars_to_keep
478 (vcat [ptext SLIT("even with cunning newtype deriving:"),
479 if isRecursiveTyCon tycon then
480 ptext SLIT("the newtype is recursive")
482 if not right_arity then
483 quotes (ppr (mkClassPred clas tys)) <+> ptext SLIT("does not have arity 1")
485 if not (n_tyvars_to_keep >= 0) then
486 ptext SLIT("the type constructor has wrong kind")
487 else if not (n_args_to_keep >= 0) then
488 ptext SLIT("the representation type has wrong kind")
489 else if not eta_ok then
490 ptext SLIT("the eta-reduction property does not hold")
494 non_std_err = derivingThingErr clas tys tycon tyvars_to_keep
495 (vcat [non_std_why clas,
496 ptext SLIT("Try -fglasgow-exts for GHC's newtype-deriving extension")])
498 bale_out err = addErrTc err `thenM_` returnM (Nothing, Nothing)
499 standard_class gla_exts clas = key `elem` derivableClassKeys
500 || (gla_exts && (key == typeableClassKey || key == dataClassKey))
507 new_dfun_name clas tycon -- Just a simple wrapper
508 = newDFunName clas [mkTyConApp tycon []] (getSrcLoc tycon)
509 -- The type passed to newDFunName is only used to generate
510 -- a suitable string; hence the empty type arg list
512 ------------------------------------------------------------------
513 -- Check side conditions that dis-allow derivability for particular classes
514 -- This is *apart* from the newtype-deriving mechanism
516 checkSideConditions :: Bool -> Class -> TyCon -> [TcType] -> Maybe SDoc
517 checkSideConditions gla_exts clas tycon tys
519 = Just ty_args_why -- e.g. deriving( Foo s )
521 = case [cond | (key,cond) <- sideConditions, key == getUnique clas] of
522 [] -> Just (non_std_why clas)
523 [cond] -> cond (gla_exts, tycon)
524 other -> pprPanic "checkSideConditions" (ppr clas)
526 ty_args_why = quotes (ppr (mkClassPred clas tys)) <+> ptext SLIT("is not a class")
528 non_std_why clas = quotes (ppr clas) <+> ptext SLIT("is not a derivable class")
530 sideConditions :: [(Unique, Condition)]
532 = [ (eqClassKey, cond_std),
533 (ordClassKey, cond_std),
534 (readClassKey, cond_std),
535 (showClassKey, cond_std),
536 (enumClassKey, cond_std `andCond` cond_isEnumeration),
537 (ixClassKey, cond_std `andCond` (cond_isEnumeration `orCond` cond_isProduct)),
538 (boundedClassKey, cond_std `andCond` (cond_isEnumeration `orCond` cond_isProduct)),
539 (typeableClassKey, cond_glaExts `andCond` cond_allTypeKind),
540 (dataClassKey, cond_glaExts `andCond` cond_std)
543 type Condition = (Bool, TyCon) -> Maybe SDoc -- Nothing => OK
545 orCond :: Condition -> Condition -> Condition
548 Nothing -> Nothing -- c1 succeeds
549 Just x -> case c2 tc of -- c1 fails
551 Just y -> Just (x $$ ptext SLIT(" and") $$ y)
554 andCond c1 c2 tc = case c1 tc of
555 Nothing -> c2 tc -- c1 succeeds
556 Just x -> Just x -- c1 fails
558 cond_std :: Condition
559 cond_std (gla_exts, tycon)
560 | any isExistentialDataCon data_cons = Just existential_why
561 | null data_cons = Just no_cons_why
562 | otherwise = Nothing
564 data_cons = tyConDataCons tycon
565 no_cons_why = quotes (ppr tycon) <+> ptext SLIT("has no data constructors")
566 existential_why = quotes (ppr tycon) <+> ptext SLIT("has existentially-quantified constructor(s)")
568 cond_isEnumeration :: Condition
569 cond_isEnumeration (gla_exts, tycon)
570 | isEnumerationTyCon tycon = Nothing
571 | otherwise = Just why
573 why = quotes (ppr tycon) <+> ptext SLIT("has non-nullary constructors")
575 cond_isProduct :: Condition
576 cond_isProduct (gla_exts, tycon)
577 | isProductTyCon tycon = Nothing
578 | otherwise = Just why
580 why = quotes (ppr tycon) <+> ptext SLIT("has more than one constructor")
582 cond_allTypeKind :: Condition
583 cond_allTypeKind (gla_exts, tycon)
584 | all (isTypeKind . tyVarKind) (tyConTyVars tycon) = Nothing
585 | otherwise = Just why
587 why = quotes (ppr tycon) <+> ptext SLIT("is parameterised over arguments of kind other than `*'")
589 cond_glaExts :: Condition
590 cond_glaExts (gla_exts, tycon) | gla_exts = Nothing
591 | otherwise = Just why
593 why = ptext SLIT("You need -fglasgow-exts to derive an instance for this class")
596 %************************************************************************
598 \subsection[TcDeriv-fixpoint]{Finding the fixed point of \tr{deriving} equations}
600 %************************************************************************
602 A ``solution'' (to one of the equations) is a list of (k,TyVarTy tv)
603 terms, which is the final correct RHS for the corresponding original
607 Each (k,TyVarTy tv) in a solution constrains only a type
611 The (k,TyVarTy tv) pairs in a solution are canonically
612 ordered by sorting on type varible, tv, (major key) and then class, k,
617 solveDerivEqns :: [DerivEqn]
618 -> TcM [DFunId] -- Solns in same order as eqns.
619 -- This bunch is Absolutely minimal...
621 solveDerivEqns orig_eqns
622 = iterateDeriv 1 initial_solutions
624 -- The initial solutions for the equations claim that each
625 -- instance has an empty context; this solution is certainly
626 -- in canonical form.
627 initial_solutions :: [DerivSoln]
628 initial_solutions = [ [] | _ <- orig_eqns ]
630 ------------------------------------------------------------------
631 -- iterateDeriv calculates the next batch of solutions,
632 -- compares it with the current one; finishes if they are the
633 -- same, otherwise recurses with the new solutions.
634 -- It fails if any iteration fails
635 iterateDeriv :: Int -> [DerivSoln] ->TcM [DFunId]
636 iterateDeriv n current_solns
637 | n > 20 -- Looks as if we are in an infinite loop
638 -- This can happen if we have -fallow-undecidable-instances
639 -- (See TcSimplify.tcSimplifyDeriv.)
640 = pprPanic "solveDerivEqns: probable loop"
641 (vcat (map pprDerivEqn orig_eqns) $$ ppr current_solns)
644 dfuns = zipWithEqual "add_solns" mk_deriv_dfun orig_eqns current_solns
647 -- Extend the inst info from the explicit instance decls
648 -- with the current set of solutions, and simplify each RHS
649 extendLocalInstEnv dfuns $
650 mappM gen_soln orig_eqns
651 ) `thenM` \ new_solns ->
652 if (current_solns == new_solns) then
655 iterateDeriv (n+1) new_solns
657 ------------------------------------------------------------------
659 gen_soln (_, clas, tc,tyvars,deriv_rhs)
660 = addSrcLoc (getSrcLoc tc) $
661 addErrCtxt (derivCtxt (Just clas) tc) $
662 tcSimplifyDeriv tyvars deriv_rhs `thenM` \ theta ->
663 returnM (sortLt (<) theta) -- Canonicalise before returning the soluction
665 mk_deriv_dfun (dfun_name, clas, tycon, tyvars, _) theta
666 = mkDictFunId dfun_name tyvars theta
667 clas [mkTyConApp tycon (mkTyVarTys tyvars)]
669 extendLocalInstEnv :: [DFunId] -> TcM a -> TcM a
670 -- Add new locall-defined instances; don't bother to check
671 -- for functional dependency errors -- that'll happen in TcInstDcls
672 extendLocalInstEnv dfuns thing_inside
673 = do { env <- getGblEnv
674 ; let inst_env' = foldl extendInstEnv (tcg_inst_env env) dfuns
675 env' = env { tcg_inst_env = inst_env' }
676 ; setGblEnv env' thing_inside }
679 %************************************************************************
681 \subsection[TcDeriv-normal-binds]{Bindings for the various classes}
683 %************************************************************************
685 After all the trouble to figure out the required context for the
686 derived instance declarations, all that's left is to chug along to
687 produce them. They will then be shoved into @tcInstDecls2@, which
688 will do all its usual business.
690 There are lots of possibilities for code to generate. Here are
691 various general remarks.
696 We want derived instances of @Eq@ and @Ord@ (both v common) to be
697 ``you-couldn't-do-better-by-hand'' efficient.
700 Deriving @Show@---also pretty common--- should also be reasonable good code.
703 Deriving for the other classes isn't that common or that big a deal.
710 Deriving @Ord@ is done mostly with the 1.3 @compare@ method.
713 Deriving @Eq@ also uses @compare@, if we're deriving @Ord@, too.
716 We {\em normally} generate code only for the non-defaulted methods;
717 there are some exceptions for @Eq@ and (especially) @Ord@...
720 Sometimes we use a @_con2tag_<tycon>@ function, which returns a data
721 constructor's numeric (@Int#@) tag. These are generated by
722 @gen_tag_n_con_binds@, and the heuristic for deciding if one of
723 these is around is given by @hasCon2TagFun@.
725 The examples under the different sections below will make this
729 Much less often (really just for deriving @Ix@), we use a
730 @_tag2con_<tycon>@ function. See the examples.
733 We use the renamer!!! Reason: we're supposed to be
734 producing @RenamedMonoBinds@ for the methods, but that means
735 producing correctly-uniquified code on the fly. This is entirely
736 possible (the @TcM@ monad has a @UniqueSupply@), but it is painful.
737 So, instead, we produce @RdrNameMonoBinds@ then heave 'em through
738 the renamer. What a great hack!
742 -- Generate the InstInfo for the required instance,
743 -- plus any auxiliary bindings required
744 genInst :: DFunId -> TcM (InstInfo, RdrNameMonoBinds)
746 = getFixityEnv `thenM` \ fix_env ->
748 (tyvars,_,clas,[ty]) = tcSplitDFunTy (idType dfun)
749 clas_nm = className clas
750 tycon = tcTyConAppTyCon ty
751 (meth_binds, aux_binds) = assoc "gen_bind:bad derived class"
752 gen_list (getUnique clas) fix_env tycon
754 -- Bring the right type variables into
755 -- scope, and rename the method binds
756 bindLocalNames (map varName tyvars) $
757 rnMethodBinds clas_nm [] meth_binds `thenM` \ (rn_meth_binds, _fvs) ->
759 -- Build the InstInfo
760 returnM (InstInfo { iDFunId = dfun, iBinds = VanillaInst rn_meth_binds [] },
763 gen_list :: [(Unique, FixityEnv -> TyCon -> (RdrNameMonoBinds, RdrNameMonoBinds))]
764 gen_list = [(eqClassKey, no_aux_binds (ignore_fix_env gen_Eq_binds))
765 ,(ordClassKey, no_aux_binds (ignore_fix_env gen_Ord_binds))
766 ,(enumClassKey, no_aux_binds (ignore_fix_env gen_Enum_binds))
767 ,(boundedClassKey, no_aux_binds (ignore_fix_env gen_Bounded_binds))
768 ,(ixClassKey, no_aux_binds (ignore_fix_env gen_Ix_binds))
769 ,(typeableClassKey,no_aux_binds (ignore_fix_env gen_Typeable_binds))
770 ,(showClassKey, no_aux_binds gen_Show_binds)
771 ,(readClassKey, no_aux_binds gen_Read_binds)
772 ,(dataClassKey, gen_Data_binds)
775 -- no_aux_binds is used for generators that don't
776 -- need to produce any auxiliary bindings
777 no_aux_binds f fix_env tc = (f fix_env tc, EmptyMonoBinds)
778 ignore_fix_env f fix_env tc = f tc
782 %************************************************************************
784 \subsection[TcDeriv-taggery-Names]{What con2tag/tag2con functions are available?}
786 %************************************************************************
791 con2tag_Foo :: Foo ... -> Int#
792 tag2con_Foo :: Int -> Foo ... -- easier if Int, not Int#
793 maxtag_Foo :: Int -- ditto (NB: not unlifted)
796 We have a @con2tag@ function for a tycon if:
799 We're deriving @Eq@ and the tycon has nullary data constructors.
802 Or: we're deriving @Ord@ (unless single-constructor), @Enum@, @Ix@
806 We have a @tag2con@ function for a tycon if:
809 We're deriving @Enum@, or @Ix@ (enum type only???)
812 If we have a @tag2con@ function, we also generate a @maxtag@ constant.
815 genTaggeryBinds :: [DFunId] -> TcM RdrNameMonoBinds
816 genTaggeryBinds dfuns
817 = do { names_so_far <- foldlM do_con2tag [] tycons_of_interest
818 ; nm_alist_etc <- foldlM do_tag2con names_so_far tycons_of_interest
819 ; return (andMonoBindList (map gen_tag_n_con_monobind nm_alist_etc)) }
821 all_CTs = map simpleDFunClassTyCon dfuns
822 all_tycons = map snd all_CTs
823 (tycons_of_interest, _) = removeDups compare all_tycons
825 do_con2tag acc_Names tycon
826 | isDataTyCon tycon &&
827 ((we_are_deriving eqClassKey tycon
828 && any isNullaryDataCon (tyConDataCons tycon))
829 || (we_are_deriving ordClassKey tycon
830 && not (isProductTyCon tycon))
831 || (we_are_deriving enumClassKey tycon)
832 || (we_are_deriving ixClassKey tycon))
834 = returnM ((con2tag_RDR tycon, tycon, GenCon2Tag)
839 do_tag2con acc_Names tycon
840 | isDataTyCon tycon &&
841 (we_are_deriving enumClassKey tycon ||
842 we_are_deriving ixClassKey tycon
843 && isEnumerationTyCon tycon)
844 = returnM ( (tag2con_RDR tycon, tycon, GenTag2Con)
845 : (maxtag_RDR tycon, tycon, GenMaxTag)
850 we_are_deriving clas_key tycon
851 = is_in_eqns clas_key tycon all_CTs
853 is_in_eqns clas_key tycon [] = False
854 is_in_eqns clas_key tycon ((c,t):cts)
855 = (clas_key == classKey c && tycon == t)
856 || is_in_eqns clas_key tycon cts
860 derivingThingErr clas tys tycon tyvars why
861 = sep [hsep [ptext SLIT("Can't make a derived instance of"), quotes (ppr pred)],
864 pred = mkClassPred clas (tys ++ [mkTyConApp tycon (mkTyVarTys tyvars)])
866 malformedPredErr tycon pred = ptext SLIT("Illegal deriving item") <+> ppr pred
868 derivCtxt :: Maybe Class -> TyCon -> SDoc
869 derivCtxt maybe_cls tycon
870 = ptext SLIT("When deriving") <+> cls <+> ptext SLIT("for type") <+> quotes (ppr tycon)
872 cls = case maybe_cls of
873 Nothing -> ptext SLIT("instances")
874 Just c -> ptext SLIT("the") <+> quotes (ppr c) <+> ptext SLIT("instance")