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 ( mkTyConGenericBinds )
21 import TcEnv ( newDFunName,
22 InstInfo(..), 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, tyConHasGenerics,
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 ; gen_binds <- mkGenericBinds tycl_decls
215 ; let inst_info = newtype_inst_info ++ ordinary_inst_info
217 -- Rename these extra bindings, discarding warnings about unused bindings etc
218 -- Set -fglasgow exts so that we can have type signatures in patterns,
219 -- which is used in the generic binds
220 ; (rn_binds, gen_bndrs)
221 <- discardWarnings $ setOptM Opt_GlasgowExts $ do
222 { (rn_deriv, _dus1) <- rnTopMonoBinds deriv_binds []
223 ; (rn_gen, dus_gen) <- rnTopMonoBinds gen_binds []
224 ; return (rn_deriv `ThenBinds` rn_gen, duDefs dus_gen) }
228 ; ioToTcRn (dumpIfSet_dyn dflags Opt_D_dump_deriv "Derived instances"
229 (ddump_deriving inst_info rn_binds))
231 ; returnM (inst_info, rn_binds, gen_bndrs)
234 ddump_deriving :: [InstInfo] -> RenamedHsBinds -> SDoc
235 ddump_deriving inst_infos extra_binds
236 = vcat (map pprInstInfoDetails inst_infos) $$ ppr extra_binds
238 -----------------------------------------
239 deriveOrdinaryStuff [] -- Short cut
240 = returnM ([], EmptyMonoBinds)
242 deriveOrdinaryStuff eqns
243 = do { -- Take the equation list and solve it, to deliver a list of
244 -- solutions, a.k.a. the contexts for the instance decls
245 -- required for the corresponding equations.
246 ; new_dfuns <- solveDerivEqns eqns
248 -- Generate the InstInfo for each dfun,
249 -- plus any auxiliary bindings it needs
250 ; (inst_infos, aux_binds_s) <- mapAndUnzipM genInst new_dfuns
252 -- Generate any extra not-one-inst-decl-specific binds,
253 -- notably "con2tag" and/or "tag2con" functions.
254 ; extra_binds <- genTaggeryBinds new_dfuns
257 ; returnM (inst_infos, andMonoBindList (extra_binds : aux_binds_s)) }
259 -----------------------------------------
260 mkGenericBinds tycl_decls
261 = do { tcs <- mapM tcLookupTyCon [tc_name | TyData { tcdName = tc_name } <- tycl_decls]
262 -- We are only interested in the data type declarations
263 ; return (andMonoBindList [mkTyConGenericBinds tc | tc <- tcs, tyConHasGenerics tc]) }
264 -- And then only in the ones whose 'has-generics' flag is on
268 %************************************************************************
270 \subsection[TcDeriv-eqns]{Forming the equations}
272 %************************************************************************
274 @makeDerivEqns@ fishes around to find the info about needed derived
275 instances. Complicating factors:
278 We can only derive @Enum@ if the data type is an enumeration
279 type (all nullary data constructors).
282 We can only derive @Ix@ if the data type is an enumeration {\em
283 or} has just one data constructor (e.g., tuples).
286 [See Appendix~E in the Haskell~1.2 report.] This code here deals w/
290 makeDerivEqns :: [RenamedTyClDecl]
291 -> TcM ([DerivEqn], -- Ordinary derivings
292 [InstInfo]) -- Special newtype derivings
294 makeDerivEqns tycl_decls
295 = mapAndUnzipM mk_eqn derive_these `thenM` \ (maybe_ordinaries, maybe_newtypes) ->
296 returnM (catMaybes maybe_ordinaries, catMaybes maybe_newtypes)
298 ------------------------------------------------------------------
299 derive_these :: [(NewOrData, Name, RenamedHsPred)]
300 -- Find the (nd, TyCon, Pred) pairs that must be `derived'
301 -- NB: only source-language decls have deriving, no imported ones do
302 derive_these = [ (nd, tycon, pred)
303 | TyData {tcdND = nd, tcdName = tycon, tcdDerivs = Just preds} <- tycl_decls,
306 ------------------------------------------------------------------
307 mk_eqn :: (NewOrData, Name, RenamedHsPred) -> TcM (Maybe DerivEqn, Maybe InstInfo)
308 -- We swizzle the tyvars and datacons out of the tycon
309 -- to make the rest of the equation
311 mk_eqn (new_or_data, tycon_name, pred)
312 = tcLookupTyCon tycon_name `thenM` \ tycon ->
313 addSrcLoc (getSrcLoc tycon) $
314 addErrCtxt (derivCtxt Nothing tycon) $
315 tcExtendTyVarEnv (tyConTyVars tycon) $ -- Deriving preds may (now) mention
316 -- the type variables for the type constructor
317 tcHsPred pred `thenM` \ pred' ->
318 case getClassPredTys_maybe pred' of
319 Nothing -> bale_out (malformedPredErr tycon pred)
320 Just (clas, tys) -> doptM Opt_GlasgowExts `thenM` \ gla_exts ->
321 mk_eqn_help gla_exts new_or_data tycon clas tys
323 ------------------------------------------------------------------
324 mk_eqn_help gla_exts DataType tycon clas tys
325 | Just err <- checkSideConditions gla_exts clas tycon tys
326 = bale_out (derivingThingErr clas tys tycon tyvars err)
328 = new_dfun_name clas tycon `thenM` \ dfun_name ->
329 returnM (Just (dfun_name, clas, tycon, tyvars, constraints), Nothing)
331 tyvars = tyConTyVars tycon
332 constraints = extra_constraints ++ ordinary_constraints
333 -- "extra_constraints": see note [Data decl contexts] above
334 extra_constraints = tyConTheta tycon
337 | clas `hasKey` typeableClassKey -- For the Typeable class, the constraints
338 -- don't involve the constructor ags, only
340 -- e.g. data T a b = ...
342 -- instance (Typeable a, Typable b)
343 -- => Typeable (T a b) where
344 = [mkClassPred clas [mkTyVarTy tv] | tv <- tyvars]
346 = [ mkClassPred clas [arg_ty]
347 | data_con <- tyConDataCons tycon,
348 arg_ty <- dataConOrigArgTys data_con,
349 -- Use the same type variables
350 -- as the type constructor,
351 -- hence no need to instantiate
352 not (isUnLiftedType arg_ty) -- No constraints for unlifted types?
355 mk_eqn_help gla_exts NewType tycon clas tys
356 | can_derive_via_isomorphism && (gla_exts || standard_class gla_exts clas)
357 = -- Go ahead and use the isomorphism
358 traceTc (text "newtype deriving:" <+> ppr tycon <+> ppr rep_tys) `thenM_`
359 new_dfun_name clas tycon `thenM` \ dfun_name ->
360 returnM (Nothing, Just (InstInfo { iDFunId = mk_dfun dfun_name,
361 iBinds = NewTypeDerived rep_tys }))
362 | standard_class gla_exts clas
363 = mk_eqn_help gla_exts DataType tycon clas tys -- Go via bale-out route
365 | otherwise -- Non-standard instance
366 = bale_out (if gla_exts then
367 cant_derive_err -- Too hard
369 non_std_err) -- Just complain about being a non-std instance
371 -- Here is the plan for newtype derivings. We see
372 -- newtype T a1...an = T (t ak...an) deriving (.., C s1 .. sm, ...)
373 -- where aj...an do not occur free in t, and the (C s1 ... sm) is a
374 -- *partial applications* of class C with the last parameter missing
376 -- We generate the instances
377 -- instance C s1 .. sm (t ak...aj) => C s1 .. sm (T a1...aj)
378 -- where T a1...aj is the partial application of the LHS of the correct kind
380 -- Running example: newtype T s a = MkT (ST s a) deriving( Monad )
381 -- instance Monad (ST s) => Monad (T s) where
382 -- fail = coerce ... (fail @ ST s)
384 clas_tyvars = classTyVars clas
385 kind = tyVarKind (last clas_tyvars)
386 -- Kind of the thing we want to instance
387 -- e.g. argument kind of Monad, *->*
389 (arg_kinds, _) = tcSplitFunTys kind
390 n_args_to_drop = length arg_kinds
391 -- Want to drop 1 arg from (T s a) and (ST s a)
392 -- to get instance Monad (ST s) => Monad (T s)
394 -- Note [newtype representation]
395 -- We must not use newTyConRep to get the representation
396 -- type, because that looks through all intermediate newtypes
397 -- To get the RHS of *this* newtype, just look at the data
398 -- constructor. For example
399 -- newtype B = MkB Int
400 -- newtype A = MkA B deriving( Num )
401 -- We want the Num instance of B, *not* the Num instance of Int,
402 -- when making the Num instance of A!
403 tyvars = tyConTyVars tycon
404 rep_ty = head (dataConOrigArgTys (head (tyConDataCons tycon)))
405 (rep_fn, rep_ty_args) = tcSplitAppTys rep_ty
407 n_tyvars_to_keep = tyConArity tycon - n_args_to_drop
408 tyvars_to_drop = drop n_tyvars_to_keep tyvars
409 tyvars_to_keep = take n_tyvars_to_keep tyvars
411 n_args_to_keep = length rep_ty_args - n_args_to_drop
412 args_to_drop = drop n_args_to_keep rep_ty_args
413 args_to_keep = take n_args_to_keep rep_ty_args
415 rep_tys = tys ++ [mkAppTys rep_fn args_to_keep]
416 rep_pred = mkClassPred clas rep_tys
417 -- rep_pred is the representation dictionary, from where
418 -- we are gong to get all the methods for the newtype dictionary
420 inst_tys = (tys ++ [mkTyConApp tycon (mkTyVarTys tyvars_to_keep)])
421 -- The 'tys' here come from the partial application
422 -- in the deriving clause. The last arg is the new
425 -- We must pass the superclasses; the newtype might be an instance
426 -- of them in a different way than the representation type
427 -- E.g. newtype Foo a = Foo a deriving( Show, Num, Eq )
428 -- Then the Show instance is not done via isomprphism; it shows
430 -- The Num instance is derived via isomorphism, but the Show superclass
431 -- dictionary must the Show instance for Foo, *not* the Show dictionary
432 -- gotten from the Num dictionary. So we must build a whole new dictionary
433 -- not just use the Num one. The instance we want is something like:
434 -- instance (Num a, Show (Foo a), Eq (Foo a)) => Num (Foo a) where
437 -- There's no 'corece' needed because after the type checker newtypes
440 sc_theta = substTheta (mkTyVarSubst clas_tyvars inst_tys)
443 -- If there are no tyvars, there's no need
444 -- to abstract over the dictionaries we need
445 dict_args | null tyvars = []
446 | otherwise = rep_pred : sc_theta
448 -- Finally! Here's where we build the dictionary Id
449 mk_dfun dfun_name = mkDictFunId dfun_name tyvars dict_args clas inst_tys
451 -------------------------------------------------------------------
452 -- Figuring out whether we can only do this newtype-deriving thing
454 right_arity = length tys + 1 == classArity clas
456 -- Never derive Read,Show,Typeable,Data this way
457 non_iso_classes = [readClassKey, showClassKey, typeableClassKey, dataClassKey]
458 can_derive_via_isomorphism
459 = not (getUnique clas `elem` non_iso_classes)
460 && right_arity -- Well kinded;
461 -- eg not: newtype T ... deriving( ST )
462 -- because ST needs *2* type params
463 && n_tyvars_to_keep >= 0 -- Type constructor has right kind:
464 -- eg not: newtype T = T Int deriving( Monad )
465 && n_args_to_keep >= 0 -- Rep type has right kind:
466 -- eg not: newtype T a = T Int deriving( Monad )
467 && eta_ok -- Eta reduction works
468 && not (isRecursiveTyCon tycon) -- Does not work for recursive tycons:
469 -- newtype A = MkA [A]
471 -- instance Eq [A] => Eq A !!
473 -- Here's a recursive newtype that's actually OK
474 -- newtype S1 = S1 [T1 ()]
475 -- newtype T1 a = T1 (StateT S1 IO a ) deriving( Monad )
476 -- It's currently rejected. Oh well.
478 -- Check that eta reduction is OK
479 -- (a) the dropped-off args are identical
480 -- (b) the remaining type args mention
481 -- only the remaining type variables
482 eta_ok = (args_to_drop `tcEqTypes` mkTyVarTys tyvars_to_drop)
483 && (tyVarsOfTypes args_to_keep `subVarSet` mkVarSet tyvars_to_keep)
485 cant_derive_err = derivingThingErr clas tys tycon tyvars_to_keep
486 (vcat [ptext SLIT("even with cunning newtype deriving:"),
487 if isRecursiveTyCon tycon then
488 ptext SLIT("the newtype is recursive")
490 if not right_arity then
491 quotes (ppr (mkClassPred clas tys)) <+> ptext SLIT("does not have arity 1")
493 if not (n_tyvars_to_keep >= 0) then
494 ptext SLIT("the type constructor has wrong kind")
495 else if not (n_args_to_keep >= 0) then
496 ptext SLIT("the representation type has wrong kind")
497 else if not eta_ok then
498 ptext SLIT("the eta-reduction property does not hold")
502 non_std_err = derivingThingErr clas tys tycon tyvars_to_keep
503 (vcat [non_std_why clas,
504 ptext SLIT("Try -fglasgow-exts for GHC's newtype-deriving extension")])
506 bale_out err = addErrTc err `thenM_` returnM (Nothing, Nothing)
507 standard_class gla_exts clas = key `elem` derivableClassKeys
508 || (gla_exts && (key == typeableClassKey || key == dataClassKey))
515 new_dfun_name clas tycon -- Just a simple wrapper
516 = newDFunName clas [mkTyConApp tycon []] (getSrcLoc tycon)
517 -- The type passed to newDFunName is only used to generate
518 -- a suitable string; hence the empty type arg list
520 ------------------------------------------------------------------
521 -- Check side conditions that dis-allow derivability for particular classes
522 -- This is *apart* from the newtype-deriving mechanism
524 checkSideConditions :: Bool -> Class -> TyCon -> [TcType] -> Maybe SDoc
525 checkSideConditions gla_exts clas tycon tys
527 = Just ty_args_why -- e.g. deriving( Foo s )
529 = case [cond | (key,cond) <- sideConditions, key == getUnique clas] of
530 [] -> Just (non_std_why clas)
531 [cond] -> cond (gla_exts, tycon)
532 other -> pprPanic "checkSideConditions" (ppr clas)
534 ty_args_why = quotes (ppr (mkClassPred clas tys)) <+> ptext SLIT("is not a class")
536 non_std_why clas = quotes (ppr clas) <+> ptext SLIT("is not a derivable class")
538 sideConditions :: [(Unique, Condition)]
540 = [ (eqClassKey, cond_std),
541 (ordClassKey, cond_std),
542 (readClassKey, cond_std),
543 (showClassKey, cond_std),
544 (enumClassKey, cond_std `andCond` cond_isEnumeration),
545 (ixClassKey, cond_std `andCond` (cond_isEnumeration `orCond` cond_isProduct)),
546 (boundedClassKey, cond_std `andCond` (cond_isEnumeration `orCond` cond_isProduct)),
547 (typeableClassKey, cond_glaExts `andCond` cond_allTypeKind),
548 (dataClassKey, cond_glaExts `andCond` cond_std)
551 type Condition = (Bool, TyCon) -> Maybe SDoc -- Nothing => OK
553 orCond :: Condition -> Condition -> Condition
556 Nothing -> Nothing -- c1 succeeds
557 Just x -> case c2 tc of -- c1 fails
559 Just y -> Just (x $$ ptext SLIT(" and") $$ y)
562 andCond c1 c2 tc = case c1 tc of
563 Nothing -> c2 tc -- c1 succeeds
564 Just x -> Just x -- c1 fails
566 cond_std :: Condition
567 cond_std (gla_exts, tycon)
568 | any isExistentialDataCon data_cons = Just existential_why
569 | null data_cons = Just no_cons_why
570 | otherwise = Nothing
572 data_cons = tyConDataCons tycon
573 no_cons_why = quotes (ppr tycon) <+> ptext SLIT("has no data constructors")
574 existential_why = quotes (ppr tycon) <+> ptext SLIT("has existentially-quantified constructor(s)")
576 cond_isEnumeration :: Condition
577 cond_isEnumeration (gla_exts, tycon)
578 | isEnumerationTyCon tycon = Nothing
579 | otherwise = Just why
581 why = quotes (ppr tycon) <+> ptext SLIT("has non-nullary constructors")
583 cond_isProduct :: Condition
584 cond_isProduct (gla_exts, tycon)
585 | isProductTyCon tycon = Nothing
586 | otherwise = Just why
588 why = quotes (ppr tycon) <+> ptext SLIT("has more than one constructor")
590 cond_allTypeKind :: Condition
591 cond_allTypeKind (gla_exts, tycon)
592 | all (isTypeKind . tyVarKind) (tyConTyVars tycon) = Nothing
593 | otherwise = Just why
595 why = quotes (ppr tycon) <+> ptext SLIT("is parameterised over arguments of kind other than `*'")
597 cond_glaExts :: Condition
598 cond_glaExts (gla_exts, tycon) | gla_exts = Nothing
599 | otherwise = Just why
601 why = ptext SLIT("You need -fglasgow-exts to derive an instance for this class")
604 %************************************************************************
606 \subsection[TcDeriv-fixpoint]{Finding the fixed point of \tr{deriving} equations}
608 %************************************************************************
610 A ``solution'' (to one of the equations) is a list of (k,TyVarTy tv)
611 terms, which is the final correct RHS for the corresponding original
615 Each (k,TyVarTy tv) in a solution constrains only a type
619 The (k,TyVarTy tv) pairs in a solution are canonically
620 ordered by sorting on type varible, tv, (major key) and then class, k,
625 solveDerivEqns :: [DerivEqn]
626 -> TcM [DFunId] -- Solns in same order as eqns.
627 -- This bunch is Absolutely minimal...
629 solveDerivEqns orig_eqns
630 = iterateDeriv 1 initial_solutions
632 -- The initial solutions for the equations claim that each
633 -- instance has an empty context; this solution is certainly
634 -- in canonical form.
635 initial_solutions :: [DerivSoln]
636 initial_solutions = [ [] | _ <- orig_eqns ]
638 ------------------------------------------------------------------
639 -- iterateDeriv calculates the next batch of solutions,
640 -- compares it with the current one; finishes if they are the
641 -- same, otherwise recurses with the new solutions.
642 -- It fails if any iteration fails
643 iterateDeriv :: Int -> [DerivSoln] ->TcM [DFunId]
644 iterateDeriv n current_solns
645 | n > 20 -- Looks as if we are in an infinite loop
646 -- This can happen if we have -fallow-undecidable-instances
647 -- (See TcSimplify.tcSimplifyDeriv.)
648 = pprPanic "solveDerivEqns: probable loop"
649 (vcat (map pprDerivEqn orig_eqns) $$ ppr current_solns)
652 dfuns = zipWithEqual "add_solns" mk_deriv_dfun orig_eqns current_solns
655 -- Extend the inst info from the explicit instance decls
656 -- with the current set of solutions, and simplify each RHS
657 extendLocalInstEnv dfuns $
658 mappM gen_soln orig_eqns
659 ) `thenM` \ new_solns ->
660 if (current_solns == new_solns) then
663 iterateDeriv (n+1) new_solns
665 ------------------------------------------------------------------
667 gen_soln (_, clas, tc,tyvars,deriv_rhs)
668 = addSrcLoc (getSrcLoc tc) $
669 addErrCtxt (derivCtxt (Just clas) tc) $
670 tcSimplifyDeriv tyvars deriv_rhs `thenM` \ theta ->
671 returnM (sortLt (<) theta) -- Canonicalise before returning the soluction
673 mk_deriv_dfun (dfun_name, clas, tycon, tyvars, _) theta
674 = mkDictFunId dfun_name tyvars theta
675 clas [mkTyConApp tycon (mkTyVarTys tyvars)]
677 extendLocalInstEnv :: [DFunId] -> TcM a -> TcM a
678 -- Add new locall-defined instances; don't bother to check
679 -- for functional dependency errors -- that'll happen in TcInstDcls
680 extendLocalInstEnv dfuns thing_inside
681 = do { env <- getGblEnv
682 ; let inst_env' = foldl extendInstEnv (tcg_inst_env env) dfuns
683 env' = env { tcg_inst_env = inst_env' }
684 ; setGblEnv env' thing_inside }
687 %************************************************************************
689 \subsection[TcDeriv-normal-binds]{Bindings for the various classes}
691 %************************************************************************
693 After all the trouble to figure out the required context for the
694 derived instance declarations, all that's left is to chug along to
695 produce them. They will then be shoved into @tcInstDecls2@, which
696 will do all its usual business.
698 There are lots of possibilities for code to generate. Here are
699 various general remarks.
704 We want derived instances of @Eq@ and @Ord@ (both v common) to be
705 ``you-couldn't-do-better-by-hand'' efficient.
708 Deriving @Show@---also pretty common--- should also be reasonable good code.
711 Deriving for the other classes isn't that common or that big a deal.
718 Deriving @Ord@ is done mostly with the 1.3 @compare@ method.
721 Deriving @Eq@ also uses @compare@, if we're deriving @Ord@, too.
724 We {\em normally} generate code only for the non-defaulted methods;
725 there are some exceptions for @Eq@ and (especially) @Ord@...
728 Sometimes we use a @_con2tag_<tycon>@ function, which returns a data
729 constructor's numeric (@Int#@) tag. These are generated by
730 @gen_tag_n_con_binds@, and the heuristic for deciding if one of
731 these is around is given by @hasCon2TagFun@.
733 The examples under the different sections below will make this
737 Much less often (really just for deriving @Ix@), we use a
738 @_tag2con_<tycon>@ function. See the examples.
741 We use the renamer!!! Reason: we're supposed to be
742 producing @RenamedMonoBinds@ for the methods, but that means
743 producing correctly-uniquified code on the fly. This is entirely
744 possible (the @TcM@ monad has a @UniqueSupply@), but it is painful.
745 So, instead, we produce @RdrNameMonoBinds@ then heave 'em through
746 the renamer. What a great hack!
750 -- Generate the InstInfo for the required instance,
751 -- plus any auxiliary bindings required
752 genInst :: DFunId -> TcM (InstInfo, RdrNameMonoBinds)
754 = getFixityEnv `thenM` \ fix_env ->
756 (tyvars,_,clas,[ty]) = tcSplitDFunTy (idType dfun)
757 clas_nm = className clas
758 tycon = tcTyConAppTyCon ty
759 (meth_binds, aux_binds) = assoc "gen_bind:bad derived class"
760 gen_list (getUnique clas) fix_env tycon
762 -- Bring the right type variables into
763 -- scope, and rename the method binds
764 bindLocalNames (map varName tyvars) $
765 rnMethodBinds clas_nm [] meth_binds `thenM` \ (rn_meth_binds, _fvs) ->
767 -- Build the InstInfo
768 returnM (InstInfo { iDFunId = dfun, iBinds = VanillaInst rn_meth_binds [] },
771 gen_list :: [(Unique, FixityEnv -> TyCon -> (RdrNameMonoBinds, RdrNameMonoBinds))]
772 gen_list = [(eqClassKey, no_aux_binds (ignore_fix_env gen_Eq_binds))
773 ,(ordClassKey, no_aux_binds (ignore_fix_env gen_Ord_binds))
774 ,(enumClassKey, no_aux_binds (ignore_fix_env gen_Enum_binds))
775 ,(boundedClassKey, no_aux_binds (ignore_fix_env gen_Bounded_binds))
776 ,(ixClassKey, no_aux_binds (ignore_fix_env gen_Ix_binds))
777 ,(typeableClassKey,no_aux_binds (ignore_fix_env gen_Typeable_binds))
778 ,(showClassKey, no_aux_binds gen_Show_binds)
779 ,(readClassKey, no_aux_binds gen_Read_binds)
780 ,(dataClassKey, gen_Data_binds)
783 -- no_aux_binds is used for generators that don't
784 -- need to produce any auxiliary bindings
785 no_aux_binds f fix_env tc = (f fix_env tc, EmptyMonoBinds)
786 ignore_fix_env f fix_env tc = f tc
790 %************************************************************************
792 \subsection[TcDeriv-taggery-Names]{What con2tag/tag2con functions are available?}
794 %************************************************************************
799 con2tag_Foo :: Foo ... -> Int#
800 tag2con_Foo :: Int -> Foo ... -- easier if Int, not Int#
801 maxtag_Foo :: Int -- ditto (NB: not unlifted)
804 We have a @con2tag@ function for a tycon if:
807 We're deriving @Eq@ and the tycon has nullary data constructors.
810 Or: we're deriving @Ord@ (unless single-constructor), @Enum@, @Ix@
814 We have a @tag2con@ function for a tycon if:
817 We're deriving @Enum@, or @Ix@ (enum type only???)
820 If we have a @tag2con@ function, we also generate a @maxtag@ constant.
823 genTaggeryBinds :: [DFunId] -> TcM RdrNameMonoBinds
824 genTaggeryBinds dfuns
825 = do { names_so_far <- foldlM do_con2tag [] tycons_of_interest
826 ; nm_alist_etc <- foldlM do_tag2con names_so_far tycons_of_interest
827 ; return (andMonoBindList (map gen_tag_n_con_monobind nm_alist_etc)) }
829 all_CTs = map simpleDFunClassTyCon dfuns
830 all_tycons = map snd all_CTs
831 (tycons_of_interest, _) = removeDups compare all_tycons
833 do_con2tag acc_Names tycon
834 | isDataTyCon tycon &&
835 ((we_are_deriving eqClassKey tycon
836 && any isNullaryDataCon (tyConDataCons tycon))
837 || (we_are_deriving ordClassKey tycon
838 && not (isProductTyCon tycon))
839 || (we_are_deriving enumClassKey tycon)
840 || (we_are_deriving ixClassKey tycon))
842 = returnM ((con2tag_RDR tycon, tycon, GenCon2Tag)
847 do_tag2con acc_Names tycon
848 | isDataTyCon tycon &&
849 (we_are_deriving enumClassKey tycon ||
850 we_are_deriving ixClassKey tycon
851 && isEnumerationTyCon tycon)
852 = returnM ( (tag2con_RDR tycon, tycon, GenTag2Con)
853 : (maxtag_RDR tycon, tycon, GenMaxTag)
858 we_are_deriving clas_key tycon
859 = is_in_eqns clas_key tycon all_CTs
861 is_in_eqns clas_key tycon [] = False
862 is_in_eqns clas_key tycon ((c,t):cts)
863 = (clas_key == classKey c && tycon == t)
864 || is_in_eqns clas_key tycon cts
868 derivingThingErr clas tys tycon tyvars why
869 = sep [hsep [ptext SLIT("Can't make a derived instance of"), quotes (ppr pred)],
872 pred = mkClassPred clas (tys ++ [mkTyConApp tycon (mkTyVarTys tyvars)])
874 malformedPredErr tycon pred = ptext SLIT("Illegal deriving item") <+> ppr pred
876 derivCtxt :: Maybe Class -> TyCon -> SDoc
877 derivCtxt maybe_cls tycon
878 = ptext SLIT("When deriving") <+> cls <+> ptext SLIT("for type") <+> quotes (ppr tycon)
880 cls = case maybe_cls of
881 Nothing -> ptext SLIT("instances")
882 Just c -> ptext SLIT("the") <+> quotes (ppr c) <+> ptext SLIT("instance")