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 Unique ( Unique, getUnique )
45 import TyCon ( tyConTyVars, tyConDataCons, tyConArity,
46 tyConTheta, isProductTyCon, isDataTyCon,
47 isEnumerationTyCon, isRecursiveTyCon, TyCon
49 import TcType ( TcType, ThetaType, mkTyVarTy, mkTyVarTys, mkTyConApp,
50 getClassPredTys_maybe, tcTyConAppTyCon,
51 isUnLiftedType, mkClassPred, tyVarsOfTypes, tcSplitFunTys, isTypeKind,
52 tcEqTypes, tcSplitAppTys, mkAppTys, tcSplitDFunTy )
53 import Var ( TyVar, tyVarKind, idType, varName )
54 import VarSet ( mkVarSet, subVarSet )
56 import Util ( zipWithEqual, sortLt, notNull )
57 import ListSetOps ( removeDups, assoc )
61 %************************************************************************
63 \subsection[TcDeriv-intro]{Introduction to how we do deriving}
65 %************************************************************************
69 data T a b = C1 (Foo a) (Bar b)
74 [NOTE: See end of these comments for what to do with
75 data (C a, D b) => T a b = ...
78 We want to come up with an instance declaration of the form
80 instance (Ping a, Pong b, ...) => Eq (T a b) where
83 It is pretty easy, albeit tedious, to fill in the code "...". The
84 trick is to figure out what the context for the instance decl is,
85 namely @Ping@, @Pong@ and friends.
87 Let's call the context reqd for the T instance of class C at types
88 (a,b, ...) C (T a b). Thus:
90 Eq (T a b) = (Ping a, Pong b, ...)
92 Now we can get a (recursive) equation from the @data@ decl:
94 Eq (T a b) = Eq (Foo a) u Eq (Bar b) -- From C1
95 u Eq (T b a) u Eq Int -- From C2
96 u Eq (T a a) -- From C3
98 Foo and Bar may have explicit instances for @Eq@, in which case we can
99 just substitute for them. Alternatively, either or both may have
100 their @Eq@ instances given by @deriving@ clauses, in which case they
101 form part of the system of equations.
103 Now all we need do is simplify and solve the equations, iterating to
104 find the least fixpoint. Notice that the order of the arguments can
105 switch around, as here in the recursive calls to T.
107 Let's suppose Eq (Foo a) = Eq a, and Eq (Bar b) = Ping b.
111 Eq (T a b) = {} -- The empty set
114 Eq (T a b) = Eq (Foo a) u Eq (Bar b) -- From C1
115 u Eq (T b a) u Eq Int -- From C2
116 u Eq (T a a) -- From C3
118 After simplification:
119 = Eq a u Ping b u {} u {} u {}
124 Eq (T a b) = Eq (Foo a) u Eq (Bar b) -- From C1
125 u Eq (T b a) u Eq Int -- From C2
126 u Eq (T a a) -- From C3
128 After simplification:
133 = Eq a u Ping b u Eq b u Ping a
135 The next iteration gives the same result, so this is the fixpoint. We
136 need to make a canonical form of the RHS to ensure convergence. We do
137 this by simplifying the RHS to a form in which
139 - the classes constrain only tyvars
140 - the list is sorted by tyvar (major key) and then class (minor key)
141 - no duplicates, of course
143 So, here are the synonyms for the ``equation'' structures:
146 type DerivEqn = (Name, Class, TyCon, [TyVar], DerivRhs)
147 -- The Name is the name for the DFun we'll build
148 -- The tyvars bind all the variables in the RHS
150 pprDerivEqn (n,c,tc,tvs,rhs)
151 = parens (hsep [ppr n, ppr c, ppr tc, ppr tvs] <+> equals <+> ppr rhs)
153 type DerivRhs = ThetaType
154 type DerivSoln = DerivRhs
158 [Data decl contexts] A note about contexts on data decls
159 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
162 data (RealFloat a) => Complex a = !a :+ !a deriving( Read )
164 We will need an instance decl like:
166 instance (Read a, RealFloat a) => Read (Complex a) where
169 The RealFloat in the context is because the read method for Complex is bound
170 to construct a Complex, and doing that requires that the argument type is
173 But this ain't true for Show, Eq, Ord, etc, since they don't construct
174 a Complex; they only take them apart.
176 Our approach: identify the offending classes, and add the data type
177 context to the instance decl. The "offending classes" are
181 FURTHER NOTE ADDED March 2002. In fact, Haskell98 now requires that
182 pattern matching against a constructor from a data type with a context
183 gives rise to the constraints for that context -- or at least the thinned
184 version. So now all classes are "offending".
188 %************************************************************************
190 \subsection[TcDeriv-driver]{Top-level function for \tr{derivings}}
192 %************************************************************************
195 tcDeriving :: [RenamedTyClDecl] -- All type constructors
196 -> TcM ([InstInfo], -- The generated "instance decls"
197 RenamedHsBinds) -- Extra generated top-level bindings
199 tcDeriving tycl_decls
200 = recoverM (returnM ([], EmptyBinds)) $
201 getDOpts `thenM` \ dflags ->
203 -- Fish the "deriving"-related information out of the TcEnv
204 -- and make the necessary "equations".
205 makeDerivEqns tycl_decls `thenM` \ (ordinary_eqns, newtype_inst_info) ->
206 extendLocalInstEnv (map iDFunId newtype_inst_info) $
207 -- Add the newtype-derived instances to the inst env
208 -- before tacking the "ordinary" ones
210 deriveOrdinaryStuff ordinary_eqns `thenM` \ (ordinary_inst_info, binds) ->
212 inst_info = newtype_inst_info ++ ordinary_inst_info
215 ioToTcRn (dumpIfSet_dyn dflags Opt_D_dump_deriv "Derived instances"
216 (ddump_deriving inst_info binds)) `thenM_`
218 returnM (inst_info, binds)
221 ddump_deriving :: [InstInfo] -> RenamedHsBinds -> SDoc
222 ddump_deriving inst_infos extra_binds
223 = vcat (map ppr_info inst_infos) $$ ppr extra_binds
225 ppr_info inst_info = pprInstInfo inst_info $$
226 nest 4 (pprInstInfoDetails inst_info)
227 -- pprInstInfo doesn't print much: only the type
229 -----------------------------------------
230 deriveOrdinaryStuff [] -- Short cut
231 = returnM ([], EmptyBinds)
233 deriveOrdinaryStuff eqns
234 = do { -- Take the equation list and solve it, to deliver a list of
235 -- solutions, a.k.a. the contexts for the instance decls
236 -- required for the corresponding equations.
237 ; new_dfuns <- solveDerivEqns eqns
239 -- Generate the InstInfo for each dfun,
240 -- plus any auxiliary bindings it needs
241 ; (inst_infos, aux_binds_s) <- mapAndUnzipM genInst new_dfuns
243 -- Generate any extra not-one-inst-decl-specific binds,
244 -- notably "con2tag" and/or "tag2con" functions.
245 ; extra_binds <- genTaggeryBinds new_dfuns
247 -- Generate the generic to/from functions from each type declaration
248 ; tcg_env <- getGblEnv
249 ; let gen_binds = mkGenericBinds (typeEnvTyCons (tcg_type_env tcg_env))
251 -- Rename these extra bindings
252 ; (rn_binds, _fvs1) <- rnTopMonoBinds (extra_binds `AndMonoBinds` gen_binds) []
254 ; let all_binds = rn_binds `ThenBinds`
255 foldr ThenBinds EmptyBinds aux_binds_s
258 ; traceTc (text "tcDeriv" <+> vcat (map pprInstInfo inst_infos))
259 ; returnM (inst_infos, all_binds) }
263 %************************************************************************
265 \subsection[TcDeriv-eqns]{Forming the equations}
267 %************************************************************************
269 @makeDerivEqns@ fishes around to find the info about needed derived
270 instances. Complicating factors:
273 We can only derive @Enum@ if the data type is an enumeration
274 type (all nullary data constructors).
277 We can only derive @Ix@ if the data type is an enumeration {\em
278 or} has just one data constructor (e.g., tuples).
281 [See Appendix~E in the Haskell~1.2 report.] This code here deals w/
285 makeDerivEqns :: [RenamedTyClDecl]
286 -> TcM ([DerivEqn], -- Ordinary derivings
287 [InstInfo]) -- Special newtype derivings
289 makeDerivEqns tycl_decls
290 = mapAndUnzipM mk_eqn derive_these `thenM` \ (maybe_ordinaries, maybe_newtypes) ->
291 returnM (catMaybes maybe_ordinaries, catMaybes maybe_newtypes)
293 ------------------------------------------------------------------
294 derive_these :: [(NewOrData, Name, RenamedHsPred)]
295 -- Find the (nd, TyCon, Pred) pairs that must be `derived'
296 -- NB: only source-language decls have deriving, no imported ones do
297 derive_these = [ (nd, tycon, pred)
298 | TyData {tcdND = nd, tcdName = tycon, tcdDerivs = Just preds} <- tycl_decls,
301 ------------------------------------------------------------------
302 mk_eqn :: (NewOrData, Name, RenamedHsPred) -> TcM (Maybe DerivEqn, Maybe InstInfo)
303 -- We swizzle the tyvars and datacons out of the tycon
304 -- to make the rest of the equation
306 mk_eqn (new_or_data, tycon_name, pred)
307 = tcLookupTyCon tycon_name `thenM` \ tycon ->
308 addSrcLoc (getSrcLoc tycon) $
309 addErrCtxt (derivCtxt Nothing tycon) $
310 tcExtendTyVarEnv (tyConTyVars tycon) $ -- Deriving preds may (now) mention
311 -- the type variables for the type constructor
312 tcHsPred pred `thenM` \ pred' ->
313 case getClassPredTys_maybe pred' of
314 Nothing -> bale_out (malformedPredErr tycon pred)
315 Just (clas, tys) -> doptM Opt_GlasgowExts `thenM` \ gla_exts ->
316 mk_eqn_help gla_exts new_or_data tycon clas tys
318 ------------------------------------------------------------------
319 mk_eqn_help gla_exts DataType tycon clas tys
320 | Just err <- checkSideConditions gla_exts clas tycon tys
321 = bale_out (derivingThingErr clas tys tycon tyvars err)
323 = new_dfun_name clas tycon `thenM` \ dfun_name ->
324 returnM (Just (dfun_name, clas, tycon, tyvars, constraints), Nothing)
326 tyvars = tyConTyVars tycon
327 constraints = extra_constraints ++ ordinary_constraints
328 -- "extra_constraints": see note [Data decl contexts] above
329 extra_constraints = tyConTheta tycon
332 | clas `hasKey` typeableClassKey -- For the Typeable class, the constraints
333 -- don't involve the constructor ags, only
335 -- e.g. data T a b = ...
337 -- instance (Typeable a, Typable b)
338 -- => Typeable (T a b) where
339 = [mkClassPred clas [mkTyVarTy tv] | tv <- tyvars]
341 = [ mkClassPred clas [arg_ty]
342 | data_con <- tyConDataCons tycon,
343 arg_ty <- dataConOrigArgTys data_con,
344 -- Use the same type variables
345 -- as the type constructor,
346 -- hence no need to instantiate
347 not (isUnLiftedType arg_ty) -- No constraints for unlifted types?
350 mk_eqn_help gla_exts NewType tycon clas tys
351 | can_derive_via_isomorphism && (gla_exts || standard_class gla_exts clas)
352 = -- Go ahead and use the isomorphism
353 traceTc (text "newtype deriving:" <+> ppr tycon <+> ppr rep_tys) `thenM_`
354 new_dfun_name clas tycon `thenM` \ dfun_name ->
355 returnM (Nothing, Just (InstInfo { iDFunId = mk_dfun dfun_name,
356 iBinds = NewTypeDerived rep_tys }))
357 | standard_class gla_exts clas
358 = mk_eqn_help gla_exts DataType tycon clas tys -- Go via bale-out route
360 | otherwise -- Non-standard instance
361 = bale_out (if gla_exts then
362 cant_derive_err -- Too hard
364 non_std_err) -- Just complain about being a non-std instance
366 -- Here is the plan for newtype derivings. We see
367 -- newtype T a1...an = T (t ak...an) deriving (.., C s1 .. sm, ...)
368 -- where aj...an do not occur free in t, and the (C s1 ... sm) is a
369 -- *partial applications* of class C with the last parameter missing
371 -- We generate the instances
372 -- instance C s1 .. sm (t ak...aj) => C s1 .. sm (T a1...aj)
373 -- where T a1...aj is the partial application of the LHS of the correct kind
375 -- Running example: newtype T s a = MkT (ST s a) deriving( Monad )
376 -- instance Monad (ST s) => Monad (T s) where
377 -- fail = coerce ... (fail @ ST s)
379 clas_tyvars = classTyVars clas
380 kind = tyVarKind (last clas_tyvars)
381 -- Kind of the thing we want to instance
382 -- e.g. argument kind of Monad, *->*
384 (arg_kinds, _) = tcSplitFunTys kind
385 n_args_to_drop = length arg_kinds
386 -- Want to drop 1 arg from (T s a) and (ST s a)
387 -- to get instance Monad (ST s) => Monad (T s)
389 -- Note [newtype representation]
390 -- We must not use newTyConRep to get the representation
391 -- type, because that looks through all intermediate newtypes
392 -- To get the RHS of *this* newtype, just look at the data
393 -- constructor. For example
394 -- newtype B = MkB Int
395 -- newtype A = MkA B deriving( Num )
396 -- We want the Num instance of B, *not* the Num instance of Int,
397 -- when making the Num instance of A!
398 tyvars = tyConTyVars tycon
399 rep_ty = head (dataConOrigArgTys (head (tyConDataCons tycon)))
400 (rep_fn, rep_ty_args) = tcSplitAppTys rep_ty
402 n_tyvars_to_keep = tyConArity tycon - n_args_to_drop
403 tyvars_to_drop = drop n_tyvars_to_keep tyvars
404 tyvars_to_keep = take n_tyvars_to_keep tyvars
406 n_args_to_keep = length rep_ty_args - n_args_to_drop
407 args_to_drop = drop n_args_to_keep rep_ty_args
408 args_to_keep = take n_args_to_keep rep_ty_args
410 rep_tys = tys ++ [mkAppTys rep_fn args_to_keep]
411 rep_pred = mkClassPred clas rep_tys
412 -- rep_pred is the representation dictionary, from where
413 -- we are gong to get all the methods for the newtype dictionary
415 inst_tys = (tys ++ [mkTyConApp tycon (mkTyVarTys tyvars_to_keep)])
416 -- The 'tys' here come from the partial application
417 -- in the deriving clause. The last arg is the new
420 -- We must pass the superclasses; the newtype might be an instance
421 -- of them in a different way than the representation type
422 -- E.g. newtype Foo a = Foo a deriving( Show, Num, Eq )
423 -- Then the Show instance is not done via isomprphism; it shows
425 -- The Num instance is derived via isomorphism, but the Show superclass
426 -- dictionary must the Show instance for Foo, *not* the Show dictionary
427 -- gotten from the Num dictionary. So we must build a whole new dictionary
428 -- not just use the Num one. The instance we want is something like:
429 -- instance (Num a, Show (Foo a), Eq (Foo a)) => Num (Foo a) where
432 -- There's no 'corece' needed because after the type checker newtypes
435 sc_theta = substTheta (mkTyVarSubst clas_tyvars inst_tys)
438 -- If there are no tyvars, there's no need
439 -- to abstract over the dictionaries we need
440 dict_args | null tyvars = []
441 | otherwise = rep_pred : sc_theta
443 -- Finally! Here's where we build the dictionary Id
444 mk_dfun dfun_name = mkDictFunId dfun_name tyvars dict_args clas inst_tys
446 -------------------------------------------------------------------
447 -- Figuring out whether we can only do this newtype-deriving thing
449 right_arity = length tys + 1 == classArity clas
451 -- Never derive Read,Show,Typeable,Data this way
452 non_iso_classes = [readClassKey, showClassKey, typeableClassKey, dataClassKey]
453 can_derive_via_isomorphism
454 = not (getUnique clas `elem` non_iso_classes)
455 && right_arity -- Well kinded;
456 -- eg not: newtype T ... deriving( ST )
457 -- because ST needs *2* type params
458 && n_tyvars_to_keep >= 0 -- Type constructor has right kind:
459 -- eg not: newtype T = T Int deriving( Monad )
460 && n_args_to_keep >= 0 -- Rep type has right kind:
461 -- eg not: newtype T a = T Int deriving( Monad )
462 && eta_ok -- Eta reduction works
463 && not (isRecursiveTyCon tycon) -- Does not work for recursive tycons:
464 -- newtype A = MkA [A]
466 -- instance Eq [A] => Eq A !!
468 -- Here's a recursive newtype that's actually OK
469 -- newtype S1 = S1 [T1 ()]
470 -- newtype T1 a = T1 (StateT S1 IO a ) deriving( Monad )
471 -- It's currently rejected. Oh well.
473 -- Check that eta reduction is OK
474 -- (a) the dropped-off args are identical
475 -- (b) the remaining type args mention
476 -- only the remaining type variables
477 eta_ok = (args_to_drop `tcEqTypes` mkTyVarTys tyvars_to_drop)
478 && (tyVarsOfTypes args_to_keep `subVarSet` mkVarSet tyvars_to_keep)
480 cant_derive_err = derivingThingErr clas tys tycon tyvars_to_keep
481 (vcat [ptext SLIT("even with cunning newtype deriving:"),
482 if isRecursiveTyCon tycon then
483 ptext SLIT("the newtype is recursive")
485 if not right_arity then
486 quotes (ppr (mkClassPred clas tys)) <+> ptext SLIT("does not have arity 1")
488 if not (n_tyvars_to_keep >= 0) then
489 ptext SLIT("the type constructor has wrong kind")
490 else if not (n_args_to_keep >= 0) then
491 ptext SLIT("the representation type has wrong kind")
492 else if not eta_ok then
493 ptext SLIT("the eta-reduction property does not hold")
497 non_std_err = derivingThingErr clas tys tycon tyvars_to_keep
498 (vcat [non_std_why clas,
499 ptext SLIT("Try -fglasgow-exts for GHC's newtype-deriving extension")])
501 bale_out err = addErrTc err `thenM_` returnM (Nothing, Nothing)
502 standard_class gla_exts clas = key `elem` derivableClassKeys
503 || (gla_exts && (key == typeableClassKey || key == dataClassKey))
510 new_dfun_name clas tycon -- Just a simple wrapper
511 = newDFunName clas [mkTyConApp tycon []] (getSrcLoc tycon)
512 -- The type passed to newDFunName is only used to generate
513 -- a suitable string; hence the empty type arg list
515 ------------------------------------------------------------------
516 -- Check side conditions that dis-allow derivability for particular classes
517 -- This is *apart* from the newtype-deriving mechanism
519 checkSideConditions :: Bool -> Class -> TyCon -> [TcType] -> Maybe SDoc
520 checkSideConditions gla_exts clas tycon tys
522 = Just ty_args_why -- e.g. deriving( Foo s )
524 = case [cond | (key,cond) <- sideConditions, key == getUnique clas] of
525 [] -> Just (non_std_why clas)
526 [cond] -> cond (gla_exts, tycon)
527 other -> pprPanic "checkSideConditions" (ppr clas)
529 ty_args_why = quotes (ppr (mkClassPred clas tys)) <+> ptext SLIT("is not a class")
531 non_std_why clas = quotes (ppr clas) <+> ptext SLIT("is not a derivable class")
533 sideConditions :: [(Unique, Condition)]
535 = [ (eqClassKey, cond_std),
536 (ordClassKey, cond_std),
537 (readClassKey, cond_std),
538 (showClassKey, cond_std),
539 (enumClassKey, cond_std `andCond` cond_isEnumeration),
540 (ixClassKey, cond_std `andCond` (cond_isEnumeration `orCond` cond_isProduct)),
541 (boundedClassKey, cond_std `andCond` (cond_isEnumeration `orCond` cond_isProduct)),
542 (typeableClassKey, cond_glaExts `andCond` cond_allTypeKind),
543 (dataClassKey, cond_glaExts `andCond` cond_std)
546 type Condition = (Bool, TyCon) -> Maybe SDoc -- Nothing => OK
548 orCond :: Condition -> Condition -> Condition
551 Nothing -> Nothing -- c1 succeeds
552 Just x -> case c2 tc of -- c1 fails
554 Just y -> Just (x $$ ptext SLIT(" and") $$ y)
557 andCond c1 c2 tc = case c1 tc of
558 Nothing -> c2 tc -- c1 succeeds
559 Just x -> Just x -- c1 fails
561 cond_std :: Condition
562 cond_std (gla_exts, tycon)
563 | any isExistentialDataCon data_cons = Just existential_why
564 | null data_cons = Just no_cons_why
565 | otherwise = Nothing
567 data_cons = tyConDataCons tycon
568 no_cons_why = quotes (ppr tycon) <+> ptext SLIT("has no data constructors")
569 existential_why = quotes (ppr tycon) <+> ptext SLIT("has existentially-quantified constructor(s)")
571 cond_isEnumeration :: Condition
572 cond_isEnumeration (gla_exts, tycon)
573 | isEnumerationTyCon tycon = Nothing
574 | otherwise = Just why
576 why = quotes (ppr tycon) <+> ptext SLIT("has non-nullary constructors")
578 cond_isProduct :: Condition
579 cond_isProduct (gla_exts, tycon)
580 | isProductTyCon tycon = Nothing
581 | otherwise = Just why
583 why = quotes (ppr tycon) <+> ptext SLIT("has more than one constructor")
585 cond_allTypeKind :: Condition
586 cond_allTypeKind (gla_exts, tycon)
587 | all (isTypeKind . tyVarKind) (tyConTyVars tycon) = Nothing
588 | otherwise = Just why
590 why = quotes (ppr tycon) <+> ptext SLIT("is parameterised over arguments of kind other than `*'")
592 cond_glaExts :: Condition
593 cond_glaExts (gla_exts, tycon) | gla_exts = Nothing
594 | otherwise = Just why
596 why = ptext SLIT("You need -fglasgow-exts to derive an instance for this class")
599 %************************************************************************
601 \subsection[TcDeriv-fixpoint]{Finding the fixed point of \tr{deriving} equations}
603 %************************************************************************
605 A ``solution'' (to one of the equations) is a list of (k,TyVarTy tv)
606 terms, which is the final correct RHS for the corresponding original
610 Each (k,TyVarTy tv) in a solution constrains only a type
614 The (k,TyVarTy tv) pairs in a solution are canonically
615 ordered by sorting on type varible, tv, (major key) and then class, k,
620 solveDerivEqns :: [DerivEqn]
621 -> TcM [DFunId] -- Solns in same order as eqns.
622 -- This bunch is Absolutely minimal...
624 solveDerivEqns orig_eqns
625 = iterateDeriv 1 initial_solutions
627 -- The initial solutions for the equations claim that each
628 -- instance has an empty context; this solution is certainly
629 -- in canonical form.
630 initial_solutions :: [DerivSoln]
631 initial_solutions = [ [] | _ <- orig_eqns ]
633 ------------------------------------------------------------------
634 -- iterateDeriv calculates the next batch of solutions,
635 -- compares it with the current one; finishes if they are the
636 -- same, otherwise recurses with the new solutions.
637 -- It fails if any iteration fails
638 iterateDeriv :: Int -> [DerivSoln] ->TcM [DFunId]
639 iterateDeriv n current_solns
640 | n > 20 -- Looks as if we are in an infinite loop
641 -- This can happen if we have -fallow-undecidable-instances
642 -- (See TcSimplify.tcSimplifyDeriv.)
643 = pprPanic "solveDerivEqns: probable loop"
644 (vcat (map pprDerivEqn orig_eqns) $$ ppr current_solns)
647 dfuns = zipWithEqual "add_solns" mk_deriv_dfun orig_eqns current_solns
650 -- Extend the inst info from the explicit instance decls
651 -- with the current set of solutions, and simplify each RHS
652 extendLocalInstEnv dfuns $
653 mappM gen_soln orig_eqns
654 ) `thenM` \ new_solns ->
655 if (current_solns == new_solns) then
658 iterateDeriv (n+1) new_solns
660 ------------------------------------------------------------------
662 gen_soln (_, clas, tc,tyvars,deriv_rhs)
663 = addSrcLoc (getSrcLoc tc) $
664 addErrCtxt (derivCtxt (Just clas) tc) $
665 tcSimplifyDeriv tyvars deriv_rhs `thenM` \ theta ->
666 returnM (sortLt (<) theta) -- Canonicalise before returning the soluction
668 mk_deriv_dfun (dfun_name, clas, tycon, tyvars, _) theta
669 = mkDictFunId dfun_name tyvars theta
670 clas [mkTyConApp tycon (mkTyVarTys tyvars)]
672 extendLocalInstEnv :: [DFunId] -> TcM a -> TcM a
673 -- Add new locall-defined instances; don't bother to check
674 -- for functional dependency errors -- that'll happen in TcInstDcls
675 extendLocalInstEnv dfuns thing_inside
676 = do { env <- getGblEnv
677 ; let inst_env' = foldl extendInstEnv (tcg_inst_env env) dfuns
678 env' = env { tcg_inst_env = inst_env' }
679 ; setGblEnv env' thing_inside }
682 %************************************************************************
684 \subsection[TcDeriv-normal-binds]{Bindings for the various classes}
686 %************************************************************************
688 After all the trouble to figure out the required context for the
689 derived instance declarations, all that's left is to chug along to
690 produce them. They will then be shoved into @tcInstDecls2@, which
691 will do all its usual business.
693 There are lots of possibilities for code to generate. Here are
694 various general remarks.
699 We want derived instances of @Eq@ and @Ord@ (both v common) to be
700 ``you-couldn't-do-better-by-hand'' efficient.
703 Deriving @Show@---also pretty common--- should also be reasonable good code.
706 Deriving for the other classes isn't that common or that big a deal.
713 Deriving @Ord@ is done mostly with the 1.3 @compare@ method.
716 Deriving @Eq@ also uses @compare@, if we're deriving @Ord@, too.
719 We {\em normally} generate code only for the non-defaulted methods;
720 there are some exceptions for @Eq@ and (especially) @Ord@...
723 Sometimes we use a @_con2tag_<tycon>@ function, which returns a data
724 constructor's numeric (@Int#@) tag. These are generated by
725 @gen_tag_n_con_binds@, and the heuristic for deciding if one of
726 these is around is given by @hasCon2TagFun@.
728 The examples under the different sections below will make this
732 Much less often (really just for deriving @Ix@), we use a
733 @_tag2con_<tycon>@ function. See the examples.
736 We use the renamer!!! Reason: we're supposed to be
737 producing @RenamedMonoBinds@ for the methods, but that means
738 producing correctly-uniquified code on the fly. This is entirely
739 possible (the @TcM@ monad has a @UniqueSupply@), but it is painful.
740 So, instead, we produce @RdrNameMonoBinds@ then heave 'em through
741 the renamer. What a great hack!
745 -- Generate the InstInfo for the required instance,
746 -- plus any auxiliary bindings required
747 genInst :: DFunId -> TcM (InstInfo, RenamedHsBinds)
749 = getFixityEnv `thenM` \ fix_env ->
751 (tyvars,_,clas,[ty]) = tcSplitDFunTy (idType dfun)
752 clas_nm = className clas
753 tycon = tcTyConAppTyCon ty
754 (meth_binds, aux_binds) = assoc "gen_bind:bad derived class"
755 gen_list (getUnique clas) fix_env tycon
757 -- Rename the auxiliary bindings (if any)
758 rnTopMonoBinds aux_binds [] `thenM` \ (rn_aux_binds, _dus) ->
760 -- Bring the right type variables into
761 -- scope, and rename the method binds
762 bindLocalNames (map varName tyvars) $
763 rnMethodBinds clas_nm [] meth_binds `thenM` \ (rn_meth_binds, _fvs) ->
765 -- Build the InstInfo
766 returnM (InstInfo { iDFunId = dfun, iBinds = VanillaInst rn_meth_binds [] },
769 gen_list :: [(Unique, FixityEnv -> TyCon -> (RdrNameMonoBinds, RdrNameMonoBinds))]
770 gen_list = [(eqClassKey, no_aux_binds (ignore_fix_env gen_Eq_binds))
771 ,(ordClassKey, no_aux_binds (ignore_fix_env gen_Ord_binds))
772 ,(enumClassKey, no_aux_binds (ignore_fix_env gen_Enum_binds))
773 ,(boundedClassKey, no_aux_binds (ignore_fix_env gen_Bounded_binds))
774 ,(ixClassKey, no_aux_binds (ignore_fix_env gen_Ix_binds))
775 ,(typeableClassKey,no_aux_binds (ignore_fix_env gen_Typeable_binds))
776 ,(showClassKey, no_aux_binds gen_Show_binds)
777 ,(readClassKey, no_aux_binds gen_Read_binds)
778 ,(dataClassKey, gen_Data_binds)
781 -- no_aux_binds is used for generators that don't
782 -- need to produce any auxiliary bindings
783 no_aux_binds f fix_env tc = (f fix_env tc, EmptyMonoBinds)
784 ignore_fix_env f fix_env tc = f tc
788 %************************************************************************
790 \subsection[TcDeriv-taggery-Names]{What con2tag/tag2con functions are available?}
792 %************************************************************************
797 con2tag_Foo :: Foo ... -> Int#
798 tag2con_Foo :: Int -> Foo ... -- easier if Int, not Int#
799 maxtag_Foo :: Int -- ditto (NB: not unlifted)
802 We have a @con2tag@ function for a tycon if:
805 We're deriving @Eq@ and the tycon has nullary data constructors.
808 Or: we're deriving @Ord@ (unless single-constructor), @Enum@, @Ix@
812 We have a @tag2con@ function for a tycon if:
815 We're deriving @Enum@, or @Ix@ (enum type only???)
818 If we have a @tag2con@ function, we also generate a @maxtag@ constant.
821 genTaggeryBinds :: [DFunId] -> TcM RdrNameMonoBinds
822 genTaggeryBinds dfuns
823 = do { names_so_far <- foldlM do_con2tag [] tycons_of_interest
824 ; nm_alist_etc <- foldlM do_tag2con names_so_far tycons_of_interest
825 ; return (andMonoBindList (map gen_tag_n_con_monobind nm_alist_etc)) }
827 all_CTs = map simpleDFunClassTyCon dfuns
828 all_tycons = map snd all_CTs
829 (tycons_of_interest, _) = removeDups compare all_tycons
831 do_con2tag acc_Names tycon
832 | isDataTyCon tycon &&
833 ((we_are_deriving eqClassKey tycon
834 && any isNullaryDataCon (tyConDataCons tycon))
835 || (we_are_deriving ordClassKey tycon
836 && not (isProductTyCon tycon))
837 || (we_are_deriving enumClassKey tycon)
838 || (we_are_deriving ixClassKey tycon))
840 = returnM ((con2tag_RDR tycon, tycon, GenCon2Tag)
845 do_tag2con acc_Names tycon
846 | isDataTyCon tycon &&
847 (we_are_deriving enumClassKey tycon ||
848 we_are_deriving ixClassKey tycon
849 && isEnumerationTyCon tycon)
850 = returnM ( (tag2con_RDR tycon, tycon, GenTag2Con)
851 : (maxtag_RDR tycon, tycon, GenMaxTag)
856 we_are_deriving clas_key tycon
857 = is_in_eqns clas_key tycon all_CTs
859 is_in_eqns clas_key tycon [] = False
860 is_in_eqns clas_key tycon ((c,t):cts)
861 = (clas_key == classKey c && tycon == t)
862 || is_in_eqns clas_key tycon cts
866 derivingThingErr clas tys tycon tyvars why
867 = sep [hsep [ptext SLIT("Can't make a derived instance of"), quotes (ppr pred)],
870 pred = mkClassPred clas (tys ++ [mkTyConApp tycon (mkTyVarTys tyvars)])
872 malformedPredErr tycon pred = ptext SLIT("Illegal deriving item") <+> ppr pred
874 derivCtxt :: Maybe Class -> TyCon -> SDoc
875 derivCtxt maybe_cls tycon
876 = ptext SLIT("When deriving") <+> cls <+> ptext SLIT("for type") <+> quotes (ppr tycon)
878 cls = case maybe_cls of
879 Nothing -> ptext SLIT("instances")
880 Just c -> ptext SLIT("the") <+> quotes (ppr c) <+> ptext SLIT("instance")