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 ppr_info inst_infos) $$ ppr extra_binds
237 ppr_info inst_info = pprInstInfo inst_info $$
238 nest 4 (pprInstInfoDetails inst_info)
239 -- pprInstInfo doesn't print much: only the type
241 -----------------------------------------
242 deriveOrdinaryStuff [] -- Short cut
243 = returnM ([], EmptyMonoBinds)
245 deriveOrdinaryStuff eqns
246 = do { -- Take the equation list and solve it, to deliver a list of
247 -- solutions, a.k.a. the contexts for the instance decls
248 -- required for the corresponding equations.
249 ; new_dfuns <- solveDerivEqns eqns
251 -- Generate the InstInfo for each dfun,
252 -- plus any auxiliary bindings it needs
253 ; (inst_infos, aux_binds_s) <- mapAndUnzipM genInst new_dfuns
255 -- Generate any extra not-one-inst-decl-specific binds,
256 -- notably "con2tag" and/or "tag2con" functions.
257 ; extra_binds <- genTaggeryBinds new_dfuns
260 ; returnM (inst_infos, andMonoBindList (extra_binds : aux_binds_s)) }
264 %************************************************************************
266 \subsection[TcDeriv-eqns]{Forming the equations}
268 %************************************************************************
270 @makeDerivEqns@ fishes around to find the info about needed derived
271 instances. Complicating factors:
274 We can only derive @Enum@ if the data type is an enumeration
275 type (all nullary data constructors).
278 We can only derive @Ix@ if the data type is an enumeration {\em
279 or} has just one data constructor (e.g., tuples).
282 [See Appendix~E in the Haskell~1.2 report.] This code here deals w/
286 makeDerivEqns :: [RenamedTyClDecl]
287 -> TcM ([DerivEqn], -- Ordinary derivings
288 [InstInfo]) -- Special newtype derivings
290 makeDerivEqns tycl_decls
291 = mapAndUnzipM mk_eqn derive_these `thenM` \ (maybe_ordinaries, maybe_newtypes) ->
292 returnM (catMaybes maybe_ordinaries, catMaybes maybe_newtypes)
294 ------------------------------------------------------------------
295 derive_these :: [(NewOrData, Name, RenamedHsPred)]
296 -- Find the (nd, TyCon, Pred) pairs that must be `derived'
297 -- NB: only source-language decls have deriving, no imported ones do
298 derive_these = [ (nd, tycon, pred)
299 | TyData {tcdND = nd, tcdName = tycon, tcdDerivs = Just preds} <- tycl_decls,
302 ------------------------------------------------------------------
303 mk_eqn :: (NewOrData, Name, RenamedHsPred) -> TcM (Maybe DerivEqn, Maybe InstInfo)
304 -- We swizzle the tyvars and datacons out of the tycon
305 -- to make the rest of the equation
307 mk_eqn (new_or_data, tycon_name, pred)
308 = tcLookupTyCon tycon_name `thenM` \ tycon ->
309 addSrcLoc (getSrcLoc tycon) $
310 addErrCtxt (derivCtxt Nothing tycon) $
311 tcExtendTyVarEnv (tyConTyVars tycon) $ -- Deriving preds may (now) mention
312 -- the type variables for the type constructor
313 tcHsPred pred `thenM` \ pred' ->
314 case getClassPredTys_maybe pred' of
315 Nothing -> bale_out (malformedPredErr tycon pred)
316 Just (clas, tys) -> doptM Opt_GlasgowExts `thenM` \ gla_exts ->
317 mk_eqn_help gla_exts new_or_data tycon clas tys
319 ------------------------------------------------------------------
320 mk_eqn_help gla_exts DataType tycon clas tys
321 | Just err <- checkSideConditions gla_exts clas tycon tys
322 = bale_out (derivingThingErr clas tys tycon tyvars err)
324 = new_dfun_name clas tycon `thenM` \ dfun_name ->
325 returnM (Just (dfun_name, clas, tycon, tyvars, constraints), Nothing)
327 tyvars = tyConTyVars tycon
328 constraints = extra_constraints ++ ordinary_constraints
329 -- "extra_constraints": see note [Data decl contexts] above
330 extra_constraints = tyConTheta tycon
333 | clas `hasKey` typeableClassKey -- For the Typeable class, the constraints
334 -- don't involve the constructor ags, only
336 -- e.g. data T a b = ...
338 -- instance (Typeable a, Typable b)
339 -- => Typeable (T a b) where
340 = [mkClassPred clas [mkTyVarTy tv] | tv <- tyvars]
342 = [ mkClassPred clas [arg_ty]
343 | data_con <- tyConDataCons tycon,
344 arg_ty <- dataConOrigArgTys data_con,
345 -- Use the same type variables
346 -- as the type constructor,
347 -- hence no need to instantiate
348 not (isUnLiftedType arg_ty) -- No constraints for unlifted types?
351 mk_eqn_help gla_exts NewType tycon clas tys
352 | can_derive_via_isomorphism && (gla_exts || standard_class gla_exts clas)
353 = -- Go ahead and use the isomorphism
354 traceTc (text "newtype deriving:" <+> ppr tycon <+> ppr rep_tys) `thenM_`
355 new_dfun_name clas tycon `thenM` \ dfun_name ->
356 returnM (Nothing, Just (InstInfo { iDFunId = mk_dfun dfun_name,
357 iBinds = NewTypeDerived rep_tys }))
358 | standard_class gla_exts clas
359 = mk_eqn_help gla_exts DataType tycon clas tys -- Go via bale-out route
361 | otherwise -- Non-standard instance
362 = bale_out (if gla_exts then
363 cant_derive_err -- Too hard
365 non_std_err) -- Just complain about being a non-std instance
367 -- Here is the plan for newtype derivings. We see
368 -- newtype T a1...an = T (t ak...an) deriving (.., C s1 .. sm, ...)
369 -- where aj...an do not occur free in t, and the (C s1 ... sm) is a
370 -- *partial applications* of class C with the last parameter missing
372 -- We generate the instances
373 -- instance C s1 .. sm (t ak...aj) => C s1 .. sm (T a1...aj)
374 -- where T a1...aj is the partial application of the LHS of the correct kind
376 -- Running example: newtype T s a = MkT (ST s a) deriving( Monad )
377 -- instance Monad (ST s) => Monad (T s) where
378 -- fail = coerce ... (fail @ ST s)
380 clas_tyvars = classTyVars clas
381 kind = tyVarKind (last clas_tyvars)
382 -- Kind of the thing we want to instance
383 -- e.g. argument kind of Monad, *->*
385 (arg_kinds, _) = tcSplitFunTys kind
386 n_args_to_drop = length arg_kinds
387 -- Want to drop 1 arg from (T s a) and (ST s a)
388 -- to get instance Monad (ST s) => Monad (T s)
390 -- Note [newtype representation]
391 -- We must not use newTyConRep to get the representation
392 -- type, because that looks through all intermediate newtypes
393 -- To get the RHS of *this* newtype, just look at the data
394 -- constructor. For example
395 -- newtype B = MkB Int
396 -- newtype A = MkA B deriving( Num )
397 -- We want the Num instance of B, *not* the Num instance of Int,
398 -- when making the Num instance of A!
399 tyvars = tyConTyVars tycon
400 rep_ty = head (dataConOrigArgTys (head (tyConDataCons tycon)))
401 (rep_fn, rep_ty_args) = tcSplitAppTys rep_ty
403 n_tyvars_to_keep = tyConArity tycon - n_args_to_drop
404 tyvars_to_drop = drop n_tyvars_to_keep tyvars
405 tyvars_to_keep = take n_tyvars_to_keep tyvars
407 n_args_to_keep = length rep_ty_args - n_args_to_drop
408 args_to_drop = drop n_args_to_keep rep_ty_args
409 args_to_keep = take n_args_to_keep rep_ty_args
411 rep_tys = tys ++ [mkAppTys rep_fn args_to_keep]
412 rep_pred = mkClassPred clas rep_tys
413 -- rep_pred is the representation dictionary, from where
414 -- we are gong to get all the methods for the newtype dictionary
416 inst_tys = (tys ++ [mkTyConApp tycon (mkTyVarTys tyvars_to_keep)])
417 -- The 'tys' here come from the partial application
418 -- in the deriving clause. The last arg is the new
421 -- We must pass the superclasses; the newtype might be an instance
422 -- of them in a different way than the representation type
423 -- E.g. newtype Foo a = Foo a deriving( Show, Num, Eq )
424 -- Then the Show instance is not done via isomprphism; it shows
426 -- The Num instance is derived via isomorphism, but the Show superclass
427 -- dictionary must the Show instance for Foo, *not* the Show dictionary
428 -- gotten from the Num dictionary. So we must build a whole new dictionary
429 -- not just use the Num one. The instance we want is something like:
430 -- instance (Num a, Show (Foo a), Eq (Foo a)) => Num (Foo a) where
433 -- There's no 'corece' needed because after the type checker newtypes
436 sc_theta = substTheta (mkTyVarSubst clas_tyvars inst_tys)
439 -- If there are no tyvars, there's no need
440 -- to abstract over the dictionaries we need
441 dict_args | null tyvars = []
442 | otherwise = rep_pred : sc_theta
444 -- Finally! Here's where we build the dictionary Id
445 mk_dfun dfun_name = mkDictFunId dfun_name tyvars dict_args clas inst_tys
447 -------------------------------------------------------------------
448 -- Figuring out whether we can only do this newtype-deriving thing
450 right_arity = length tys + 1 == classArity clas
452 -- Never derive Read,Show,Typeable,Data this way
453 non_iso_classes = [readClassKey, showClassKey, typeableClassKey, dataClassKey]
454 can_derive_via_isomorphism
455 = not (getUnique clas `elem` non_iso_classes)
456 && right_arity -- Well kinded;
457 -- eg not: newtype T ... deriving( ST )
458 -- because ST needs *2* type params
459 && n_tyvars_to_keep >= 0 -- Type constructor has right kind:
460 -- eg not: newtype T = T Int deriving( Monad )
461 && n_args_to_keep >= 0 -- Rep type has right kind:
462 -- eg not: newtype T a = T Int deriving( Monad )
463 && eta_ok -- Eta reduction works
464 && not (isRecursiveTyCon tycon) -- Does not work for recursive tycons:
465 -- newtype A = MkA [A]
467 -- instance Eq [A] => Eq A !!
469 -- Here's a recursive newtype that's actually OK
470 -- newtype S1 = S1 [T1 ()]
471 -- newtype T1 a = T1 (StateT S1 IO a ) deriving( Monad )
472 -- It's currently rejected. Oh well.
474 -- Check that eta reduction is OK
475 -- (a) the dropped-off args are identical
476 -- (b) the remaining type args mention
477 -- only the remaining type variables
478 eta_ok = (args_to_drop `tcEqTypes` mkTyVarTys tyvars_to_drop)
479 && (tyVarsOfTypes args_to_keep `subVarSet` mkVarSet tyvars_to_keep)
481 cant_derive_err = derivingThingErr clas tys tycon tyvars_to_keep
482 (vcat [ptext SLIT("even with cunning newtype deriving:"),
483 if isRecursiveTyCon tycon then
484 ptext SLIT("the newtype is recursive")
486 if not right_arity then
487 quotes (ppr (mkClassPred clas tys)) <+> ptext SLIT("does not have arity 1")
489 if not (n_tyvars_to_keep >= 0) then
490 ptext SLIT("the type constructor has wrong kind")
491 else if not (n_args_to_keep >= 0) then
492 ptext SLIT("the representation type has wrong kind")
493 else if not eta_ok then
494 ptext SLIT("the eta-reduction property does not hold")
498 non_std_err = derivingThingErr clas tys tycon tyvars_to_keep
499 (vcat [non_std_why clas,
500 ptext SLIT("Try -fglasgow-exts for GHC's newtype-deriving extension")])
502 bale_out err = addErrTc err `thenM_` returnM (Nothing, Nothing)
503 standard_class gla_exts clas = key `elem` derivableClassKeys
504 || (gla_exts && (key == typeableClassKey || key == dataClassKey))
511 new_dfun_name clas tycon -- Just a simple wrapper
512 = newDFunName clas [mkTyConApp tycon []] (getSrcLoc tycon)
513 -- The type passed to newDFunName is only used to generate
514 -- a suitable string; hence the empty type arg list
516 ------------------------------------------------------------------
517 -- Check side conditions that dis-allow derivability for particular classes
518 -- This is *apart* from the newtype-deriving mechanism
520 checkSideConditions :: Bool -> Class -> TyCon -> [TcType] -> Maybe SDoc
521 checkSideConditions gla_exts clas tycon tys
523 = Just ty_args_why -- e.g. deriving( Foo s )
525 = case [cond | (key,cond) <- sideConditions, key == getUnique clas] of
526 [] -> Just (non_std_why clas)
527 [cond] -> cond (gla_exts, tycon)
528 other -> pprPanic "checkSideConditions" (ppr clas)
530 ty_args_why = quotes (ppr (mkClassPred clas tys)) <+> ptext SLIT("is not a class")
532 non_std_why clas = quotes (ppr clas) <+> ptext SLIT("is not a derivable class")
534 sideConditions :: [(Unique, Condition)]
536 = [ (eqClassKey, cond_std),
537 (ordClassKey, cond_std),
538 (readClassKey, cond_std),
539 (showClassKey, cond_std),
540 (enumClassKey, cond_std `andCond` cond_isEnumeration),
541 (ixClassKey, cond_std `andCond` (cond_isEnumeration `orCond` cond_isProduct)),
542 (boundedClassKey, cond_std `andCond` (cond_isEnumeration `orCond` cond_isProduct)),
543 (typeableClassKey, cond_glaExts `andCond` cond_allTypeKind),
544 (dataClassKey, cond_glaExts `andCond` cond_std)
547 type Condition = (Bool, TyCon) -> Maybe SDoc -- Nothing => OK
549 orCond :: Condition -> Condition -> Condition
552 Nothing -> Nothing -- c1 succeeds
553 Just x -> case c2 tc of -- c1 fails
555 Just y -> Just (x $$ ptext SLIT(" and") $$ y)
558 andCond c1 c2 tc = case c1 tc of
559 Nothing -> c2 tc -- c1 succeeds
560 Just x -> Just x -- c1 fails
562 cond_std :: Condition
563 cond_std (gla_exts, tycon)
564 | any isExistentialDataCon data_cons = Just existential_why
565 | null data_cons = Just no_cons_why
566 | otherwise = Nothing
568 data_cons = tyConDataCons tycon
569 no_cons_why = quotes (ppr tycon) <+> ptext SLIT("has no data constructors")
570 existential_why = quotes (ppr tycon) <+> ptext SLIT("has existentially-quantified constructor(s)")
572 cond_isEnumeration :: Condition
573 cond_isEnumeration (gla_exts, tycon)
574 | isEnumerationTyCon tycon = Nothing
575 | otherwise = Just why
577 why = quotes (ppr tycon) <+> ptext SLIT("has non-nullary constructors")
579 cond_isProduct :: Condition
580 cond_isProduct (gla_exts, tycon)
581 | isProductTyCon tycon = Nothing
582 | otherwise = Just why
584 why = quotes (ppr tycon) <+> ptext SLIT("has more than one constructor")
586 cond_allTypeKind :: Condition
587 cond_allTypeKind (gla_exts, tycon)
588 | all (isTypeKind . tyVarKind) (tyConTyVars tycon) = Nothing
589 | otherwise = Just why
591 why = quotes (ppr tycon) <+> ptext SLIT("is parameterised over arguments of kind other than `*'")
593 cond_glaExts :: Condition
594 cond_glaExts (gla_exts, tycon) | gla_exts = Nothing
595 | otherwise = Just why
597 why = ptext SLIT("You need -fglasgow-exts to derive an instance for this class")
600 %************************************************************************
602 \subsection[TcDeriv-fixpoint]{Finding the fixed point of \tr{deriving} equations}
604 %************************************************************************
606 A ``solution'' (to one of the equations) is a list of (k,TyVarTy tv)
607 terms, which is the final correct RHS for the corresponding original
611 Each (k,TyVarTy tv) in a solution constrains only a type
615 The (k,TyVarTy tv) pairs in a solution are canonically
616 ordered by sorting on type varible, tv, (major key) and then class, k,
621 solveDerivEqns :: [DerivEqn]
622 -> TcM [DFunId] -- Solns in same order as eqns.
623 -- This bunch is Absolutely minimal...
625 solveDerivEqns orig_eqns
626 = iterateDeriv 1 initial_solutions
628 -- The initial solutions for the equations claim that each
629 -- instance has an empty context; this solution is certainly
630 -- in canonical form.
631 initial_solutions :: [DerivSoln]
632 initial_solutions = [ [] | _ <- orig_eqns ]
634 ------------------------------------------------------------------
635 -- iterateDeriv calculates the next batch of solutions,
636 -- compares it with the current one; finishes if they are the
637 -- same, otherwise recurses with the new solutions.
638 -- It fails if any iteration fails
639 iterateDeriv :: Int -> [DerivSoln] ->TcM [DFunId]
640 iterateDeriv n current_solns
641 | n > 20 -- Looks as if we are in an infinite loop
642 -- This can happen if we have -fallow-undecidable-instances
643 -- (See TcSimplify.tcSimplifyDeriv.)
644 = pprPanic "solveDerivEqns: probable loop"
645 (vcat (map pprDerivEqn orig_eqns) $$ ppr current_solns)
648 dfuns = zipWithEqual "add_solns" mk_deriv_dfun orig_eqns current_solns
651 -- Extend the inst info from the explicit instance decls
652 -- with the current set of solutions, and simplify each RHS
653 extendLocalInstEnv dfuns $
654 mappM gen_soln orig_eqns
655 ) `thenM` \ new_solns ->
656 if (current_solns == new_solns) then
659 iterateDeriv (n+1) new_solns
661 ------------------------------------------------------------------
663 gen_soln (_, clas, tc,tyvars,deriv_rhs)
664 = addSrcLoc (getSrcLoc tc) $
665 addErrCtxt (derivCtxt (Just clas) tc) $
666 tcSimplifyDeriv tyvars deriv_rhs `thenM` \ theta ->
667 returnM (sortLt (<) theta) -- Canonicalise before returning the soluction
669 mk_deriv_dfun (dfun_name, clas, tycon, tyvars, _) theta
670 = mkDictFunId dfun_name tyvars theta
671 clas [mkTyConApp tycon (mkTyVarTys tyvars)]
673 extendLocalInstEnv :: [DFunId] -> TcM a -> TcM a
674 -- Add new locall-defined instances; don't bother to check
675 -- for functional dependency errors -- that'll happen in TcInstDcls
676 extendLocalInstEnv dfuns thing_inside
677 = do { env <- getGblEnv
678 ; let inst_env' = foldl extendInstEnv (tcg_inst_env env) dfuns
679 env' = env { tcg_inst_env = inst_env' }
680 ; setGblEnv env' thing_inside }
683 %************************************************************************
685 \subsection[TcDeriv-normal-binds]{Bindings for the various classes}
687 %************************************************************************
689 After all the trouble to figure out the required context for the
690 derived instance declarations, all that's left is to chug along to
691 produce them. They will then be shoved into @tcInstDecls2@, which
692 will do all its usual business.
694 There are lots of possibilities for code to generate. Here are
695 various general remarks.
700 We want derived instances of @Eq@ and @Ord@ (both v common) to be
701 ``you-couldn't-do-better-by-hand'' efficient.
704 Deriving @Show@---also pretty common--- should also be reasonable good code.
707 Deriving for the other classes isn't that common or that big a deal.
714 Deriving @Ord@ is done mostly with the 1.3 @compare@ method.
717 Deriving @Eq@ also uses @compare@, if we're deriving @Ord@, too.
720 We {\em normally} generate code only for the non-defaulted methods;
721 there are some exceptions for @Eq@ and (especially) @Ord@...
724 Sometimes we use a @_con2tag_<tycon>@ function, which returns a data
725 constructor's numeric (@Int#@) tag. These are generated by
726 @gen_tag_n_con_binds@, and the heuristic for deciding if one of
727 these is around is given by @hasCon2TagFun@.
729 The examples under the different sections below will make this
733 Much less often (really just for deriving @Ix@), we use a
734 @_tag2con_<tycon>@ function. See the examples.
737 We use the renamer!!! Reason: we're supposed to be
738 producing @RenamedMonoBinds@ for the methods, but that means
739 producing correctly-uniquified code on the fly. This is entirely
740 possible (the @TcM@ monad has a @UniqueSupply@), but it is painful.
741 So, instead, we produce @RdrNameMonoBinds@ then heave 'em through
742 the renamer. What a great hack!
746 -- Generate the InstInfo for the required instance,
747 -- plus any auxiliary bindings required
748 genInst :: DFunId -> TcM (InstInfo, RdrNameMonoBinds)
750 = getFixityEnv `thenM` \ fix_env ->
752 (tyvars,_,clas,[ty]) = tcSplitDFunTy (idType dfun)
753 clas_nm = className clas
754 tycon = tcTyConAppTyCon ty
755 (meth_binds, aux_binds) = assoc "gen_bind:bad derived class"
756 gen_list (getUnique clas) fix_env tycon
758 -- Bring the right type variables into
759 -- scope, and rename the method binds
760 bindLocalNames (map varName tyvars) $
761 rnMethodBinds clas_nm [] meth_binds `thenM` \ (rn_meth_binds, _fvs) ->
763 -- Build the InstInfo
764 returnM (InstInfo { iDFunId = dfun, iBinds = VanillaInst rn_meth_binds [] },
767 gen_list :: [(Unique, FixityEnv -> TyCon -> (RdrNameMonoBinds, RdrNameMonoBinds))]
768 gen_list = [(eqClassKey, no_aux_binds (ignore_fix_env gen_Eq_binds))
769 ,(ordClassKey, no_aux_binds (ignore_fix_env gen_Ord_binds))
770 ,(enumClassKey, no_aux_binds (ignore_fix_env gen_Enum_binds))
771 ,(boundedClassKey, no_aux_binds (ignore_fix_env gen_Bounded_binds))
772 ,(ixClassKey, no_aux_binds (ignore_fix_env gen_Ix_binds))
773 ,(typeableClassKey,no_aux_binds (ignore_fix_env gen_Typeable_binds))
774 ,(showClassKey, no_aux_binds gen_Show_binds)
775 ,(readClassKey, no_aux_binds gen_Read_binds)
776 ,(dataClassKey, gen_Data_binds)
779 -- no_aux_binds is used for generators that don't
780 -- need to produce any auxiliary bindings
781 no_aux_binds f fix_env tc = (f fix_env tc, EmptyMonoBinds)
782 ignore_fix_env f fix_env tc = f tc
786 %************************************************************************
788 \subsection[TcDeriv-taggery-Names]{What con2tag/tag2con functions are available?}
790 %************************************************************************
795 con2tag_Foo :: Foo ... -> Int#
796 tag2con_Foo :: Int -> Foo ... -- easier if Int, not Int#
797 maxtag_Foo :: Int -- ditto (NB: not unlifted)
800 We have a @con2tag@ function for a tycon if:
803 We're deriving @Eq@ and the tycon has nullary data constructors.
806 Or: we're deriving @Ord@ (unless single-constructor), @Enum@, @Ix@
810 We have a @tag2con@ function for a tycon if:
813 We're deriving @Enum@, or @Ix@ (enum type only???)
816 If we have a @tag2con@ function, we also generate a @maxtag@ constant.
819 genTaggeryBinds :: [DFunId] -> TcM RdrNameMonoBinds
820 genTaggeryBinds dfuns
821 = do { names_so_far <- foldlM do_con2tag [] tycons_of_interest
822 ; nm_alist_etc <- foldlM do_tag2con names_so_far tycons_of_interest
823 ; return (andMonoBindList (map gen_tag_n_con_monobind nm_alist_etc)) }
825 all_CTs = map simpleDFunClassTyCon dfuns
826 all_tycons = map snd all_CTs
827 (tycons_of_interest, _) = removeDups compare all_tycons
829 do_con2tag acc_Names tycon
830 | isDataTyCon tycon &&
831 ((we_are_deriving eqClassKey tycon
832 && any isNullaryDataCon (tyConDataCons tycon))
833 || (we_are_deriving ordClassKey tycon
834 && not (isProductTyCon tycon))
835 || (we_are_deriving enumClassKey tycon)
836 || (we_are_deriving ixClassKey tycon))
838 = returnM ((con2tag_RDR tycon, tycon, GenCon2Tag)
843 do_tag2con acc_Names tycon
844 | isDataTyCon tycon &&
845 (we_are_deriving enumClassKey tycon ||
846 we_are_deriving ixClassKey tycon
847 && isEnumerationTyCon tycon)
848 = returnM ( (tag2con_RDR tycon, tycon, GenTag2Con)
849 : (maxtag_RDR tycon, tycon, GenMaxTag)
854 we_are_deriving clas_key tycon
855 = is_in_eqns clas_key tycon all_CTs
857 is_in_eqns clas_key tycon [] = False
858 is_in_eqns clas_key tycon ((c,t):cts)
859 = (clas_key == classKey c && tycon == t)
860 || is_in_eqns clas_key tycon cts
864 derivingThingErr clas tys tycon tyvars why
865 = sep [hsep [ptext SLIT("Can't make a derived instance of"), quotes (ppr pred)],
868 pred = mkClassPred clas (tys ++ [mkTyConApp tycon (mkTyVarTys tyvars)])
870 malformedPredErr tycon pred = ptext SLIT("Illegal deriving item") <+> ppr pred
872 derivCtxt :: Maybe Class -> TyCon -> SDoc
873 derivCtxt maybe_cls tycon
874 = ptext SLIT("When deriving") <+> cls <+> ptext SLIT("for type") <+> quotes (ppr tycon)
876 cls = case maybe_cls of
877 Nothing -> ptext SLIT("instances")
878 Just c -> ptext SLIT("the") <+> quotes (ppr c) <+> ptext SLIT("instance")