2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
6 Handles @deriving@ clauses on @data@ declarations.
9 module TcDeriv ( tcDeriving ) where
11 #include "HsVersions.h"
19 import TcClassDcl( tcAddDeclCtxt ) -- Small helper
20 import TcGenDeriv -- Deriv stuff
54 %************************************************************************
56 \subsection[TcDeriv-intro]{Introduction to how we do deriving}
58 %************************************************************************
62 data T a b = C1 (Foo a) (Bar b)
67 [NOTE: See end of these comments for what to do with
68 data (C a, D b) => T a b = ...
71 We want to come up with an instance declaration of the form
73 instance (Ping a, Pong b, ...) => Eq (T a b) where
76 It is pretty easy, albeit tedious, to fill in the code "...". The
77 trick is to figure out what the context for the instance decl is,
78 namely @Ping@, @Pong@ and friends.
80 Let's call the context reqd for the T instance of class C at types
81 (a,b, ...) C (T a b). Thus:
83 Eq (T a b) = (Ping a, Pong b, ...)
85 Now we can get a (recursive) equation from the @data@ decl:
87 Eq (T a b) = Eq (Foo a) u Eq (Bar b) -- From C1
88 u Eq (T b a) u Eq Int -- From C2
89 u Eq (T a a) -- From C3
91 Foo and Bar may have explicit instances for @Eq@, in which case we can
92 just substitute for them. Alternatively, either or both may have
93 their @Eq@ instances given by @deriving@ clauses, in which case they
94 form part of the system of equations.
96 Now all we need do is simplify and solve the equations, iterating to
97 find the least fixpoint. Notice that the order of the arguments can
98 switch around, as here in the recursive calls to T.
100 Let's suppose Eq (Foo a) = Eq a, and Eq (Bar b) = Ping b.
104 Eq (T a b) = {} -- The empty set
107 Eq (T a b) = Eq (Foo a) u Eq (Bar b) -- From C1
108 u Eq (T b a) u Eq Int -- From C2
109 u Eq (T a a) -- From C3
111 After simplification:
112 = Eq a u Ping b u {} u {} u {}
117 Eq (T a b) = Eq (Foo a) u Eq (Bar b) -- From C1
118 u Eq (T b a) u Eq Int -- From C2
119 u Eq (T a a) -- From C3
121 After simplification:
126 = Eq a u Ping b u Eq b u Ping a
128 The next iteration gives the same result, so this is the fixpoint. We
129 need to make a canonical form of the RHS to ensure convergence. We do
130 this by simplifying the RHS to a form in which
132 - the classes constrain only tyvars
133 - the list is sorted by tyvar (major key) and then class (minor key)
134 - no duplicates, of course
136 So, here are the synonyms for the ``equation'' structures:
139 type DerivRhs = ThetaType
140 type DerivSoln = DerivRhs
141 type DerivEqn = (SrcSpan, InstOrigin, Name, [TyVar], Class, Type, DerivRhs)
142 -- (span, orig, df, tvs, C, ty, rhs)
143 -- implies a dfun declaration of the form
144 -- df :: forall tvs. rhs => C ty
145 -- The Name is the name for the DFun we'll build
146 -- The tyvars bind all the variables in the RHS
147 -- For family indexes, the tycon is the *family* tycon
148 -- (not the representation tycon)
150 pprDerivEqn :: DerivEqn -> SDoc
151 pprDerivEqn (l, _, n, tvs, c, ty, rhs)
152 = parens (hsep [ppr l, ppr n, ppr tvs, ppr c, ppr ty]
153 <+> equals <+> ppr rhs)
157 [Data decl contexts] A note about contexts on data decls
158 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
161 data (RealFloat a) => Complex a = !a :+ !a deriving( Read )
163 We will need an instance decl like:
165 instance (Read a, RealFloat a) => Read (Complex a) where
168 The RealFloat in the context is because the read method for Complex is bound
169 to construct a Complex, and doing that requires that the argument type is
172 But this ain't true for Show, Eq, Ord, etc, since they don't construct
173 a Complex; they only take them apart.
175 Our approach: identify the offending classes, and add the data type
176 context to the instance decl. The "offending classes" are
180 FURTHER NOTE ADDED March 2002. In fact, Haskell98 now requires that
181 pattern matching against a constructor from a data type with a context
182 gives rise to the constraints for that context -- or at least the thinned
183 version. So now all classes are "offending".
190 newtype T = T Char deriving( C [a] )
192 Notice the free 'a' in the deriving. We have to fill this out to
193 newtype T = T Char deriving( forall a. C [a] )
195 And then translate it to:
196 instance C [a] Char => C [a] T where ...
201 %************************************************************************
203 \subsection[TcDeriv-driver]{Top-level function for \tr{derivings}}
205 %************************************************************************
208 tcDeriving :: [LTyClDecl Name] -- All type constructors
209 -> [LInstDecl Name] -- All instance declarations
210 -> [LDerivDecl Name] -- All stand-alone deriving declarations
211 -> TcM ([InstInfo], -- The generated "instance decls"
212 HsValBinds Name) -- Extra generated top-level bindings
214 tcDeriving tycl_decls inst_decls deriv_decls
215 = recoverM (returnM ([], emptyValBindsOut)) $
216 do { -- Fish the "deriving"-related information out of the TcEnv
217 -- and make the necessary "equations".
218 ; (ordinary_eqns, newtype_inst_info)
219 <- makeDerivEqns tycl_decls inst_decls deriv_decls
221 ; (ordinary_inst_info, deriv_binds)
222 <- extendLocalInstEnv (map iSpec newtype_inst_info) $
223 deriveOrdinaryStuff ordinary_eqns
224 -- Add the newtype-derived instances to the inst env
225 -- before tacking the "ordinary" ones
227 ; let inst_info = newtype_inst_info ++ ordinary_inst_info
229 -- If we are compiling a hs-boot file,
230 -- don't generate any derived bindings
231 ; is_boot <- tcIsHsBoot
233 return (inst_info, emptyValBindsOut)
237 -- Generate the generic to/from functions from each type declaration
238 ; gen_binds <- mkGenericBinds tycl_decls
240 -- Rename these extra bindings, discarding warnings about unused bindings etc
241 -- Set -fglasgow exts so that we can have type signatures in patterns,
242 -- which is used in the generic binds
244 <- discardWarnings $ setOptM Opt_GlasgowExts $ do
245 { (rn_deriv, _dus1) <- rnTopBinds (ValBindsIn deriv_binds [])
246 ; (rn_gen, dus_gen) <- rnTopBinds (ValBindsIn gen_binds [])
247 ; keepAliveSetTc (duDefs dus_gen) -- Mark these guys to
249 ; return (rn_deriv `plusHsValBinds` rn_gen) }
253 ; ioToTcRn (dumpIfSet_dyn dflags Opt_D_dump_deriv "Derived instances"
254 (ddump_deriving inst_info rn_binds))
256 ; returnM (inst_info, rn_binds)
259 ddump_deriving :: [InstInfo] -> HsValBinds Name -> SDoc
260 ddump_deriving inst_infos extra_binds
261 = vcat (map pprInstInfoDetails inst_infos) $$ ppr extra_binds
263 -----------------------------------------
264 deriveOrdinaryStuff [] -- Short cut
265 = returnM ([], emptyLHsBinds)
267 deriveOrdinaryStuff eqns
268 = do { -- Take the equation list and solve it, to deliver a list of
269 -- solutions, a.k.a. the contexts for the instance decls
270 -- required for the corresponding equations.
271 overlap_flag <- getOverlapFlag
272 ; inst_specs <- solveDerivEqns overlap_flag eqns
274 -- Generate the InstInfo for each dfun,
275 -- plus any auxiliary bindings it needs
276 ; (inst_infos, aux_binds_s) <- mapAndUnzipM genInst inst_specs
278 -- Generate any extra not-one-inst-decl-specific binds,
279 -- notably "con2tag" and/or "tag2con" functions.
280 ; extra_binds <- genTaggeryBinds inst_infos
283 ; returnM (map fst inst_infos,
284 unionManyBags (extra_binds : aux_binds_s))
287 -----------------------------------------
288 mkGenericBinds tycl_decls
289 = do { tcs <- mapM tcLookupTyCon
291 L _ (TyData { tcdLName = L _ tc_name }) <- tycl_decls]
292 -- We are only interested in the data type declarations
293 ; return (unionManyBags [ mkTyConGenericBinds tc |
294 tc <- tcs, tyConHasGenerics tc ]) }
295 -- And then only in the ones whose 'has-generics' flag is on
299 %************************************************************************
301 \subsection[TcDeriv-eqns]{Forming the equations}
303 %************************************************************************
305 @makeDerivEqns@ fishes around to find the info about needed derived
306 instances. Complicating factors:
309 We can only derive @Enum@ if the data type is an enumeration
310 type (all nullary data constructors).
313 We can only derive @Ix@ if the data type is an enumeration {\em
314 or} has just one data constructor (e.g., tuples).
317 [See Appendix~E in the Haskell~1.2 report.] This code here deals w/
320 Note [Newtype deriving superclasses]
321 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
322 The 'tys' here come from the partial application in the deriving
323 clause. The last arg is the new instance type.
325 We must pass the superclasses; the newtype might be an instance
326 of them in a different way than the representation type
327 E.g. newtype Foo a = Foo a deriving( Show, Num, Eq )
328 Then the Show instance is not done via isomorphism; it shows
330 The Num instance is derived via isomorphism, but the Show superclass
331 dictionary must the Show instance for Foo, *not* the Show dictionary
332 gotten from the Num dictionary. So we must build a whole new dictionary
333 not just use the Num one. The instance we want is something like:
334 instance (Num a, Show (Foo a), Eq (Foo a)) => Num (Foo a) where
337 There may be a coercion needed which we get from the tycon for the newtype
338 when the dict is constructed in TcInstDcls.tcInstDecl2
342 makeDerivEqns :: [LTyClDecl Name]
345 -> TcM ([DerivEqn], -- Ordinary derivings
346 [InstInfo]) -- Special newtype derivings
348 makeDerivEqns tycl_decls inst_decls deriv_decls
349 = do { eqns1 <- mapM deriveTyData $
350 extractTyDataPreds tycl_decls ++
351 [ pd -- traverse assoc data families
352 | L _ (InstDecl _ _ _ ats) <- inst_decls
353 , pd <- extractTyDataPreds ats ]
354 ; eqns2 <- mapM deriveStandalone deriv_decls
355 ; return ([eqn | (Just eqn, _) <- eqns1 ++ eqns2],
356 [inst | (_, Just inst) <- eqns1 ++ eqns2]) }
358 extractTyDataPreds decls =
359 [(p, d) | d@(L _ (TyData {tcdDerivs = Just preds})) <- decls, p <- preds]
362 ------------------------------------------------------------------
363 deriveStandalone :: LDerivDecl Name -> TcM (Maybe DerivEqn, Maybe InstInfo)
364 -- Standalone deriving declarations
365 -- e.g. derive instance Show T
366 -- Rather like tcLocalInstDecl
367 deriveStandalone (L loc (DerivDecl deriv_ty))
369 addErrCtxt (standaloneCtxt deriv_ty) $
370 do { (tvs, theta, tau) <- tcHsInstHead deriv_ty
371 ; (cls, inst_tys) <- checkValidInstHead tau
372 ; let cls_tys = take (length inst_tys - 1) inst_tys
373 inst_ty = last inst_tys
375 ; mkEqnHelp StandAloneDerivOrigin tvs cls cls_tys inst_ty }
377 ------------------------------------------------------------------
378 deriveTyData :: (LHsType Name, LTyClDecl Name) -> TcM (Maybe DerivEqn, Maybe InstInfo)
379 deriveTyData (deriv_pred, L loc decl@(TyData { tcdLName = L _ tycon_name,
380 tcdTyVars = tv_names,
381 tcdTyPats = ty_pats }))
384 do { let hs_ty_args = ty_pats `orElse` map (nlHsTyVar . hsLTyVarName) tv_names
385 hs_app = nlHsTyConApp tycon_name hs_ty_args
386 -- We get kinding info for the tyvars by typechecking (T a b)
387 -- Hence forming a tycon application and then dis-assembling it
388 ; (tvs, tc_app) <- tcHsQuantifiedType tv_names hs_app
389 ; tcExtendTyVarEnv tvs $ -- Deriving preds may (now) mention
390 -- the type variables for the type constructor
391 do { (deriv_tvs, cls, cls_tys) <- tcHsDeriv deriv_pred
392 -- The "deriv_pred" is a LHsType to take account of the fact that for
393 -- newtype deriving we allow deriving (forall a. C [a]).
394 ; mkEqnHelp DerivOrigin (tvs++deriv_tvs) cls cls_tys tc_app } }
395 deriveTyData (deriv_pred, other_decl)
396 = panic "derivTyData" -- Caller ensures that only TyData can happen
398 ------------------------------------------------------------------
399 mkEqnHelp orig tvs cls cls_tys tc_app
400 | Just (tycon, tc_args) <- tcSplitTyConApp_maybe tc_app
401 = do { -- Make tc_app saturated, because that's what the
402 -- mkDataTypeEqn things expect
403 -- It might not be saturated in the standalone deriving case
404 -- derive instance Monad (T a)
405 let extra_tvs = dropList tc_args (tyConTyVars tycon)
406 full_tc_args = tc_args ++ mkTyVarTys extra_tvs
407 full_tvs = tvs ++ extra_tvs
409 ; (rep_tc, rep_tc_args) <- tcLookupFamInstExact tycon full_tc_args
411 ; gla_exts <- doptM Opt_GlasgowExts
412 ; overlap_flag <- getOverlapFlag
414 -- Be careful to test rep_tc here: in the case of families, we want
415 -- to check the instance tycon, not the family tycon
416 ; if isDataTyCon rep_tc then
417 mkDataTypeEqn orig gla_exts full_tvs cls cls_tys
418 tycon full_tc_args rep_tc rep_tc_args
420 mkNewTypeEqn orig gla_exts overlap_flag full_tvs cls cls_tys
421 tycon full_tc_args rep_tc rep_tc_args }
423 = baleOut (derivingThingErr cls cls_tys tc_app
424 (ptext SLIT("Last argument of the instance must be a type application")))
426 baleOut err = addErrTc err >> returnM (Nothing, Nothing)
429 Auxiliary lookup wrapper which requires that looked up family instances are
433 tcLookupFamInstExact :: TyCon -> [Type] -> TcM (TyCon, [Type])
434 tcLookupFamInstExact tycon tys
435 = do { result@(rep_tycon, rep_tys) <- tcLookupFamInst tycon tys
436 ; let { tvs = map (Type.getTyVar
437 "TcDeriv.tcLookupFamInstExact")
439 ; variable_only_subst = all Type.isTyVarTy rep_tys &&
440 sizeVarSet (mkVarSet tvs) == length tvs
441 -- renaming may have no repetitions
443 ; unless variable_only_subst $
444 famInstNotFound tycon tys [result]
451 %************************************************************************
455 %************************************************************************
458 mkDataTypeEqn orig gla_exts tvs cls cls_tys tycon tc_args rep_tc rep_tc_args
459 | Just err <- checkSideConditions gla_exts cls cls_tys rep_tc
460 -- NB: pass the *representation* tycon to checkSideConditions
461 = baleOut (derivingThingErr cls cls_tys (mkTyConApp tycon tc_args) err)
464 = ASSERT( null cls_tys )
465 do { loc <- getSrcSpanM
466 ; eqn <- mk_data_eqn loc orig tvs cls tycon tc_args rep_tc rep_tc_args
467 ; return (Just eqn, Nothing) }
469 mk_data_eqn :: SrcSpan -> InstOrigin -> [TyVar] -> Class
470 -> TyCon -> [TcType] -> TyCon -> [TcType] -> TcM DerivEqn
471 mk_data_eqn loc orig tvs cls tycon tc_args rep_tc rep_tc_args
472 | cls `hasKey` typeableClassKey
473 = -- The Typeable class is special in several ways
474 -- data T a b = ... deriving( Typeable )
476 -- instance Typeable2 T where ...
478 -- 1. There are no constraints in the instance
479 -- 2. There are no type variables either
480 -- 3. The actual class we want to generate isn't necessarily
481 -- Typeable; it depends on the arity of the type
482 do { real_clas <- tcLookupClass (typeableClassNames !! tyConArity tycon)
483 ; dfun_name <- new_dfun_name real_clas tycon
484 ; return (loc, orig, dfun_name, [], real_clas, mkTyConApp tycon [], []) }
487 = do { dfun_name <- new_dfun_name cls tycon
488 ; let ordinary_constraints
489 = [ mkClassPred cls [arg_ty]
490 | data_con <- tyConDataCons rep_tc,
491 arg_ty <- ASSERT( isVanillaDataCon data_con )
492 dataConInstOrigArgTys data_con rep_tc_args,
493 not (isUnLiftedType arg_ty) ] -- No constraints for unlifted types?
495 tiresome_subst = zipTopTvSubst (tyConTyVars rep_tc) rep_tc_args
496 stupid_constraints = substTheta tiresome_subst (tyConStupidTheta rep_tc)
497 -- see note [Data decl contexts] above
499 ; return (loc, orig, dfun_name, tvs, cls, mkTyConApp tycon tc_args,
500 stupid_constraints ++ ordinary_constraints)
503 ------------------------------------------------------------------
504 -- Check side conditions that dis-allow derivability for particular classes
505 -- This is *apart* from the newtype-deriving mechanism
507 -- Here we get the representation tycon in case of family instances as it has
508 -- the data constructors - but we need to be careful to fall back to the
509 -- family tycon (with indexes) in error messages.
511 checkSideConditions :: Bool -> Class -> [TcType] -> TyCon -> Maybe SDoc
512 checkSideConditions gla_exts cls cls_tys rep_tc
514 = Just ty_args_why -- e.g. deriving( Foo s )
516 = case [cond | (key,cond) <- sideConditions, key == getUnique cls] of
517 [] -> Just (non_std_why cls)
518 [cond] -> cond (gla_exts, rep_tc)
519 other -> pprPanic "checkSideConditions" (ppr cls)
521 ty_args_why = quotes (ppr (mkClassPred cls cls_tys)) <+> ptext SLIT("is not a class")
523 non_std_why cls = quotes (ppr cls) <+> ptext SLIT("is not a derivable class")
525 sideConditions :: [(Unique, Condition)]
527 = [ (eqClassKey, cond_std),
528 (ordClassKey, cond_std),
529 (readClassKey, cond_std),
530 (showClassKey, cond_std),
531 (enumClassKey, cond_std `andCond` cond_isEnumeration),
532 (ixClassKey, cond_std `andCond` (cond_isEnumeration `orCond` cond_isProduct)),
533 (boundedClassKey, cond_std `andCond` (cond_isEnumeration `orCond` cond_isProduct)),
534 (typeableClassKey, cond_glaExts `andCond` cond_typeableOK),
535 (dataClassKey, cond_glaExts `andCond` cond_std)
538 type Condition = (Bool, TyCon) -> Maybe SDoc
539 -- Bool is gla-exts flag
540 -- TyCon is the *representation* tycon if the
541 -- data type is an indexed one
544 orCond :: Condition -> Condition -> Condition
547 Nothing -> Nothing -- c1 succeeds
548 Just x -> case c2 tc of -- c1 fails
550 Just y -> Just (x $$ ptext SLIT(" and") $$ y)
553 andCond c1 c2 tc = case c1 tc of
554 Nothing -> c2 tc -- c1 succeeds
555 Just x -> Just x -- c1 fails
557 cond_std :: Condition
558 cond_std (gla_exts, rep_tc)
559 | any (not . isVanillaDataCon) data_cons = Just existential_why
560 | null data_cons = Just no_cons_why
561 | otherwise = Nothing
563 data_cons = tyConDataCons rep_tc
564 no_cons_why = quotes (pprSourceTyCon rep_tc) <+>
565 ptext SLIT("has no data constructors")
566 existential_why = quotes (pprSourceTyCon rep_tc) <+>
567 ptext SLIT("has non-Haskell-98 constructor(s)")
569 cond_isEnumeration :: Condition
570 cond_isEnumeration (gla_exts, rep_tc)
571 | isEnumerationTyCon rep_tc = Nothing
572 | otherwise = Just why
574 why = quotes (pprSourceTyCon rep_tc) <+>
575 ptext SLIT("has non-nullary constructors")
577 cond_isProduct :: Condition
578 cond_isProduct (gla_exts, rep_tc)
579 | isProductTyCon rep_tc = Nothing
580 | otherwise = Just why
582 why = quotes (pprSourceTyCon rep_tc) <+>
583 ptext SLIT("has more than one constructor")
585 cond_typeableOK :: Condition
586 -- OK for Typeable class
587 -- Currently: (a) args all of kind *
588 -- (b) 7 or fewer args
589 cond_typeableOK (gla_exts, rep_tc)
590 | tyConArity rep_tc > 7 = Just too_many
591 | not (all (isSubArgTypeKind . tyVarKind) (tyConTyVars rep_tc))
593 | isFamInstTyCon rep_tc = Just fam_inst -- no Typable for family insts
594 | otherwise = Nothing
596 too_many = quotes (pprSourceTyCon rep_tc) <+>
597 ptext SLIT("has too many arguments")
598 bad_kind = quotes (pprSourceTyCon rep_tc) <+>
599 ptext SLIT("has arguments of kind other than `*'")
600 fam_inst = quotes (pprSourceTyCon rep_tc) <+>
601 ptext SLIT("is a type family")
603 cond_glaExts :: Condition
604 cond_glaExts (gla_exts, _rep_tc) | gla_exts = Nothing
605 | otherwise = Just why
607 why = ptext SLIT("You need -fglasgow-exts to derive an instance for this class")
609 std_class_via_iso clas -- These standard classes can be derived for a newtype
610 -- using the isomorphism trick *even if no -fglasgow-exts*
611 = classKey clas `elem` [eqClassKey, ordClassKey, ixClassKey, boundedClassKey]
612 -- Not Read/Show because they respect the type
613 -- Not Enum, because newtypes are never in Enum
616 new_dfun_name clas tycon -- Just a simple wrapper
617 = newDFunName clas [mkTyConApp tycon []] (getSrcSpan tycon)
618 -- The type passed to newDFunName is only used to generate
619 -- a suitable string; hence the empty type arg list
623 %************************************************************************
627 %************************************************************************
630 mkNewTypeEqn orig gla_exts overlap_flag tvs cls cls_tys
632 rep_tycon rep_tc_args
633 | can_derive_via_isomorphism && (gla_exts || std_class_via_iso cls)
634 = do { traceTc (text "newtype deriving:" <+> ppr tycon <+> ppr rep_tys)
635 ; -- Go ahead and use the isomorphism
636 dfun_name <- new_dfun_name cls tycon
637 ; return (Nothing, Just (InstInfo { iSpec = mk_inst_spec dfun_name,
638 iBinds = NewTypeDerived ntd_info })) }
640 | isNothing mb_std_err -- Use the standard H98 method
641 = do { loc <- getSrcSpanM
642 ; eqn <- mk_data_eqn loc orig tvs cls tycon tc_args rep_tycon rep_tc_args
643 ; return (Just eqn, Nothing) }
645 -- Otherwise we can't derive
646 | gla_exts = baleOut cant_derive_err -- Too hard
647 | otherwise = baleOut std_err -- Just complain about being a non-std instance
649 mb_std_err = checkSideConditions gla_exts cls cls_tys rep_tycon
650 std_err = derivingThingErr cls cls_tys tc_app $
651 vcat [fromJust mb_std_err,
652 ptext SLIT("Try -fglasgow-exts for GHC's newtype-deriving extension")]
654 -- Here is the plan for newtype derivings. We see
655 -- newtype T a1...an = MkT (t ak+1...an) deriving (.., C s1 .. sm, ...)
656 -- where t is a type,
657 -- ak+1...an is a suffix of a1..an, and are all tyars
658 -- ak+1...an do not occur free in t, nor in the s1..sm
659 -- (C s1 ... sm) is a *partial applications* of class C
660 -- with the last parameter missing
661 -- (T a1 .. ak) matches the kind of C's last argument
662 -- (and hence so does t)
664 -- We generate the instance
665 -- instance forall ({a1..ak} u fvs(s1..sm)).
666 -- C s1 .. sm t => C s1 .. sm (T a1...ak)
667 -- where T a1...ap is the partial application of
668 -- the LHS of the correct kind and p >= k
670 -- NB: the variables below are:
671 -- tc_tvs = [a1, ..., an]
672 -- tyvars_to_keep = [a1, ..., ak]
673 -- rep_ty = t ak .. an
674 -- deriv_tvs = fvs(s1..sm) \ tc_tvs
675 -- tys = [s1, ..., sm]
678 -- Running example: newtype T s a = MkT (ST s a) deriving( Monad )
679 -- We generate the instance
680 -- instance Monad (ST s) => Monad (T s) where
682 cls_tyvars = classTyVars cls
683 kind = tyVarKind (last cls_tyvars)
684 -- Kind of the thing we want to instance
685 -- e.g. argument kind of Monad, *->*
687 (arg_kinds, _) = splitKindFunTys kind
688 n_args_to_drop = length arg_kinds
689 -- Want to drop 1 arg from (T s a) and (ST s a)
690 -- to get instance Monad (ST s) => Monad (T s)
692 -- Note [newtype representation]
693 -- Need newTyConRhs *not* newTyConRep to get the representation
694 -- type, because the latter looks through all intermediate newtypes
696 -- newtype B = MkB Int
697 -- newtype A = MkA B deriving( Num )
698 -- We want the Num instance of B, *not* the Num instance of Int,
699 -- when making the Num instance of A!
700 rep_ty = newTyConInstRhs rep_tycon rep_tc_args
701 (rep_fn, rep_ty_args) = tcSplitAppTys rep_ty
703 n_tyargs_to_keep = tyConArity tycon - n_args_to_drop
704 dropped_tc_args = drop n_tyargs_to_keep tc_args
705 dropped_tvs = tyVarsOfTypes dropped_tc_args
707 n_args_to_keep = length rep_ty_args - n_args_to_drop
708 args_to_drop = drop n_args_to_keep rep_ty_args
709 args_to_keep = take n_args_to_keep rep_ty_args
711 rep_fn' = mkAppTys rep_fn args_to_keep
712 rep_tys = cls_tys ++ [rep_fn']
713 rep_pred = mkClassPred cls rep_tys
714 -- rep_pred is the representation dictionary, from where
715 -- we are gong to get all the methods for the newtype
718 tc_app = mkTyConApp tycon (take n_tyargs_to_keep tc_args)
720 -- Next we figure out what superclass dictionaries to use
721 -- See Note [Newtype deriving superclasses] above
723 inst_tys = cls_tys ++ [tc_app]
724 sc_theta = substTheta (zipOpenTvSubst cls_tyvars inst_tys)
727 -- If there are no tyvars, there's no need
728 -- to abstract over the dictionaries we need
729 -- Example: newtype T = MkT Int deriving( C )
730 -- We get the derived instance
733 -- instance C Int => C T
734 dict_tvs = filterOut (`elemVarSet` dropped_tvs) tvs
735 all_preds = rep_pred : sc_theta -- NB: rep_pred comes first
736 (dict_args, ntd_info) | null dict_tvs = ([], Just all_preds)
737 | otherwise = (all_preds, Nothing)
739 -- Finally! Here's where we build the dictionary Id
740 mk_inst_spec dfun_name = mkLocalInstance dfun overlap_flag
742 dfun = mkDictFunId dfun_name dict_tvs dict_args cls inst_tys
744 -------------------------------------------------------------------
745 -- Figuring out whether we can only do this newtype-deriving thing
747 right_arity = length cls_tys + 1 == classArity cls
749 -- Never derive Read,Show,Typeable,Data this way
750 non_iso_classes = [readClassKey, showClassKey, typeableClassKey, dataClassKey]
751 can_derive_via_isomorphism
752 = not (getUnique cls `elem` non_iso_classes)
753 && right_arity -- Well kinded;
754 -- eg not: newtype T ... deriving( ST )
755 -- because ST needs *2* type params
756 && n_tyargs_to_keep >= 0 -- Type constructor has right kind:
757 -- eg not: newtype T = T Int deriving( Monad )
758 && n_args_to_keep >= 0 -- Rep type has right kind:
759 -- eg not: newtype T a = T Int deriving( Monad )
760 && eta_ok -- Eta reduction works
761 && not (isRecursiveTyCon tycon) -- Does not work for recursive tycons:
762 -- newtype A = MkA [A]
764 -- instance Eq [A] => Eq A !!
765 -- Here's a recursive newtype that's actually OK
766 -- newtype S1 = S1 [T1 ()]
767 -- newtype T1 a = T1 (StateT S1 IO a ) deriving( Monad )
768 -- It's currently rejected. Oh well.
769 -- In fact we generate an instance decl that has method of form
770 -- meth @ instTy = meth @ repTy
771 -- (no coerce's). We'd need a coerce if we wanted to handle
772 -- recursive newtypes too
774 -- Check that eta reduction is OK
775 eta_ok = (args_to_drop `tcEqTypes` dropped_tc_args)
776 -- (a) the dropped-off args are identical in the source and rep type
777 -- newtype T a b = MkT (S [a] b) deriving( Monad )
778 -- Here the 'b' must be the same in the rep type (S [a] b)
780 && (tyVarsOfType rep_fn' `disjointVarSet` dropped_tvs)
781 -- (b) the remaining type args do not mention any of the dropped
784 && (tyVarsOfTypes cls_tys `disjointVarSet` dropped_tvs)
785 -- (c) the type class args do not mention any of the dropped type
788 && all isTyVarTy dropped_tc_args
789 -- (d) in case of newtype family instances, the eta-dropped
790 -- arguments must be type variables (not more complex indexes)
792 cant_derive_err = derivingThingErr cls cls_tys tc_app
793 (vcat [ptext SLIT("even with cunning newtype deriving:"),
794 if isRecursiveTyCon tycon then
795 ptext SLIT("the newtype may be recursive")
797 if not right_arity then
798 quotes (ppr (mkClassPred cls cls_tys)) <+> ptext SLIT("does not have arity 1")
800 if not (n_tyargs_to_keep >= 0) then
801 ptext SLIT("the type constructor has wrong kind")
802 else if not (n_args_to_keep >= 0) then
803 ptext SLIT("the representation type has wrong kind")
804 else if not eta_ok then
805 ptext SLIT("the eta-reduction property does not hold")
811 %************************************************************************
813 \subsection[TcDeriv-fixpoint]{Finding the fixed point of \tr{deriving} equations}
815 %************************************************************************
817 A ``solution'' (to one of the equations) is a list of (k,TyVarTy tv)
818 terms, which is the final correct RHS for the corresponding original
822 Each (k,TyVarTy tv) in a solution constrains only a type
826 The (k,TyVarTy tv) pairs in a solution are canonically
827 ordered by sorting on type varible, tv, (major key) and then class, k,
832 solveDerivEqns :: OverlapFlag
834 -> TcM [Instance]-- Solns in same order as eqns.
835 -- This bunch is Absolutely minimal...
837 solveDerivEqns overlap_flag orig_eqns
838 = do { traceTc (text "solveDerivEqns" <+> vcat (map pprDerivEqn orig_eqns))
839 ; iterateDeriv 1 initial_solutions }
841 -- The initial solutions for the equations claim that each
842 -- instance has an empty context; this solution is certainly
843 -- in canonical form.
844 initial_solutions :: [DerivSoln]
845 initial_solutions = [ [] | _ <- orig_eqns ]
847 ------------------------------------------------------------------
848 -- iterateDeriv calculates the next batch of solutions,
849 -- compares it with the current one; finishes if they are the
850 -- same, otherwise recurses with the new solutions.
851 -- It fails if any iteration fails
852 iterateDeriv :: Int -> [DerivSoln] -> TcM [Instance]
853 iterateDeriv n current_solns
854 | n > 20 -- Looks as if we are in an infinite loop
855 -- This can happen if we have -fallow-undecidable-instances
856 -- (See TcSimplify.tcSimplifyDeriv.)
857 = pprPanic "solveDerivEqns: probable loop"
858 (vcat (map pprDerivEqn orig_eqns) $$ ppr current_solns)
861 inst_specs = zipWithEqual "add_solns" mk_inst_spec
862 orig_eqns current_solns
865 -- Extend the inst info from the explicit instance decls
866 -- with the current set of solutions, and simplify each RHS
867 extendLocalInstEnv inst_specs $
868 mappM gen_soln orig_eqns
869 ) `thenM` \ new_solns ->
870 if (current_solns == new_solns) then
873 iterateDeriv (n+1) new_solns
875 ------------------------------------------------------------------
876 gen_soln :: DerivEqn -> TcM [PredType]
877 gen_soln (loc, orig, _, tyvars, clas, inst_ty, deriv_rhs)
879 addErrCtxt (derivInstCtxt clas [inst_ty]) $
880 do { theta <- tcSimplifyDeriv orig tyvars deriv_rhs
881 -- checkValidInstance tyvars theta clas [inst_ty]
882 -- Not necessary; see Note [Exotic derived instance contexts]
885 -- Check for a bizarre corner case, when the derived instance decl should
886 -- have form instance C a b => D (T a) where ...
887 -- Note that 'b' isn't a parameter of T. This gives rise to all sorts
888 -- of problems; in particular, it's hard to compare solutions for
889 -- equality when finding the fixpoint. So I just rule it out for now.
890 ; let tv_set = mkVarSet tyvars
891 weird_preds = [pred | pred <- theta, not (tyVarsOfPred pred `subVarSet` tv_set)]
892 ; mapM_ (addErrTc . badDerivedPred) weird_preds
894 -- Claim: the result instance declaration is guaranteed valid
895 -- Hence no need to call:
896 -- checkValidInstance tyvars theta clas inst_tys
897 ; return (sortLe (<=) theta) } -- Canonicalise before returning the solution
899 ------------------------------------------------------------------
900 mk_inst_spec :: DerivEqn -> DerivSoln -> Instance
901 mk_inst_spec (loc, orig, dfun_name, tyvars, clas, inst_ty, _) theta
902 = mkLocalInstance dfun overlap_flag
904 dfun = mkDictFunId dfun_name tyvars theta clas [inst_ty]
906 extendLocalInstEnv :: [Instance] -> TcM a -> TcM a
907 -- Add new locally-defined instances; don't bother to check
908 -- for functional dependency errors -- that'll happen in TcInstDcls
909 extendLocalInstEnv dfuns thing_inside
910 = do { env <- getGblEnv
911 ; let inst_env' = extendInstEnvList (tcg_inst_env env) dfuns
912 env' = env { tcg_inst_env = inst_env' }
913 ; setGblEnv env' thing_inside }
917 %************************************************************************
919 \subsection[TcDeriv-normal-binds]{Bindings for the various classes}
921 %************************************************************************
923 After all the trouble to figure out the required context for the
924 derived instance declarations, all that's left is to chug along to
925 produce them. They will then be shoved into @tcInstDecls2@, which
926 will do all its usual business.
928 There are lots of possibilities for code to generate. Here are
929 various general remarks.
934 We want derived instances of @Eq@ and @Ord@ (both v common) to be
935 ``you-couldn't-do-better-by-hand'' efficient.
938 Deriving @Show@---also pretty common--- should also be reasonable good code.
941 Deriving for the other classes isn't that common or that big a deal.
948 Deriving @Ord@ is done mostly with the 1.3 @compare@ method.
951 Deriving @Eq@ also uses @compare@, if we're deriving @Ord@, too.
954 We {\em normally} generate code only for the non-defaulted methods;
955 there are some exceptions for @Eq@ and (especially) @Ord@...
958 Sometimes we use a @_con2tag_<tycon>@ function, which returns a data
959 constructor's numeric (@Int#@) tag. These are generated by
960 @gen_tag_n_con_binds@, and the heuristic for deciding if one of
961 these is around is given by @hasCon2TagFun@.
963 The examples under the different sections below will make this
967 Much less often (really just for deriving @Ix@), we use a
968 @_tag2con_<tycon>@ function. See the examples.
971 We use the renamer!!! Reason: we're supposed to be
972 producing @LHsBinds Name@ for the methods, but that means
973 producing correctly-uniquified code on the fly. This is entirely
974 possible (the @TcM@ monad has a @UniqueSupply@), but it is painful.
975 So, instead, we produce @MonoBinds RdrName@ then heave 'em through
976 the renamer. What a great hack!
980 -- Generate the InstInfo for the required instance paired with the
981 -- *representation* tycon for that instance,
982 -- plus any auxiliary bindings required
984 -- Representation tycons differ from the tycon in the instance signature in
985 -- case of instances for indexed families.
987 genInst :: Instance -> TcM ((InstInfo, TyCon), LHsBinds RdrName)
989 = do { fix_env <- getFixityEnv
991 (tyvars,_,clas,[ty]) = instanceHead spec
992 clas_nm = className clas
993 (visible_tycon, tyArgs) = tcSplitTyConApp ty
995 -- In case of a family instance, we need to use the representation
996 -- tycon (after all, it has the data constructors)
997 ; (tycon, _) <- tcLookupFamInstExact visible_tycon tyArgs
998 ; let (meth_binds, aux_binds) = genDerivBinds clas fix_env tycon
1000 -- Bring the right type variables into
1001 -- scope, and rename the method binds
1002 -- It's a bit yukky that we return *renamed* InstInfo, but
1003 -- *non-renamed* auxiliary bindings
1004 ; (rn_meth_binds, _fvs) <- discardWarnings $
1005 bindLocalNames (map Var.varName tyvars) $
1006 rnMethodBinds clas_nm (\n -> []) [] meth_binds
1008 -- Build the InstInfo
1009 ; return ((InstInfo { iSpec = spec,
1010 iBinds = VanillaInst rn_meth_binds [] }, tycon),
1014 genDerivBinds clas fix_env tycon
1015 | className clas `elem` typeableClassNames
1016 = (gen_Typeable_binds tycon, emptyLHsBinds)
1019 = case assocMaybe gen_list (getUnique clas) of
1020 Just gen_fn -> gen_fn fix_env tycon
1021 Nothing -> pprPanic "genDerivBinds: bad derived class" (ppr clas)
1023 gen_list :: [(Unique, FixityEnv -> TyCon -> (LHsBinds RdrName, LHsBinds RdrName))]
1024 gen_list = [(eqClassKey, no_aux_binds (ignore_fix_env gen_Eq_binds))
1025 ,(ordClassKey, no_aux_binds (ignore_fix_env gen_Ord_binds))
1026 ,(enumClassKey, no_aux_binds (ignore_fix_env gen_Enum_binds))
1027 ,(boundedClassKey, no_aux_binds (ignore_fix_env gen_Bounded_binds))
1028 ,(ixClassKey, no_aux_binds (ignore_fix_env gen_Ix_binds))
1029 ,(typeableClassKey,no_aux_binds (ignore_fix_env gen_Typeable_binds))
1030 ,(showClassKey, no_aux_binds gen_Show_binds)
1031 ,(readClassKey, no_aux_binds gen_Read_binds)
1032 ,(dataClassKey, gen_Data_binds)
1035 -- no_aux_binds is used for generators that don't
1036 -- need to produce any auxiliary bindings
1037 no_aux_binds f fix_env tc = (f fix_env tc, emptyLHsBinds)
1038 ignore_fix_env f fix_env tc = f tc
1042 %************************************************************************
1044 \subsection[TcDeriv-taggery-Names]{What con2tag/tag2con functions are available?}
1046 %************************************************************************
1051 con2tag_Foo :: Foo ... -> Int#
1052 tag2con_Foo :: Int -> Foo ... -- easier if Int, not Int#
1053 maxtag_Foo :: Int -- ditto (NB: not unlifted)
1056 We have a @con2tag@ function for a tycon if:
1059 We're deriving @Eq@ and the tycon has nullary data constructors.
1062 Or: we're deriving @Ord@ (unless single-constructor), @Enum@, @Ix@
1063 (enum type only????)
1066 We have a @tag2con@ function for a tycon if:
1069 We're deriving @Enum@, or @Ix@ (enum type only???)
1072 If we have a @tag2con@ function, we also generate a @maxtag@ constant.
1075 genTaggeryBinds :: [(InstInfo, TyCon)] -> TcM (LHsBinds RdrName)
1076 genTaggeryBinds infos
1077 = do { names_so_far <- foldlM do_con2tag [] tycons_of_interest
1078 ; nm_alist_etc <- foldlM do_tag2con names_so_far tycons_of_interest
1079 ; return (listToBag (map gen_tag_n_con_monobind nm_alist_etc)) }
1081 all_CTs = [ (fst (simpleInstInfoClsTy info), tc)
1082 | (info, tc) <- infos]
1083 all_tycons = map snd all_CTs
1084 (tycons_of_interest, _) = removeDups compare all_tycons
1086 do_con2tag acc_Names tycon
1087 | isDataTyCon tycon &&
1088 ((we_are_deriving eqClassKey tycon
1089 && any isNullarySrcDataCon (tyConDataCons tycon))
1090 || (we_are_deriving ordClassKey tycon
1091 && not (isProductTyCon tycon))
1092 || (we_are_deriving enumClassKey tycon)
1093 || (we_are_deriving ixClassKey tycon))
1095 = returnM ((con2tag_RDR tycon, tycon, GenCon2Tag)
1100 do_tag2con acc_Names tycon
1101 | isDataTyCon tycon &&
1102 (we_are_deriving enumClassKey tycon ||
1103 we_are_deriving ixClassKey tycon
1104 && isEnumerationTyCon tycon)
1105 = returnM ( (tag2con_RDR tycon, tycon, GenTag2Con)
1106 : (maxtag_RDR tycon, tycon, GenMaxTag)
1111 we_are_deriving clas_key tycon
1112 = is_in_eqns clas_key tycon all_CTs
1114 is_in_eqns clas_key tycon [] = False
1115 is_in_eqns clas_key tycon ((c,t):cts)
1116 = (clas_key == classKey c && tycon == t)
1117 || is_in_eqns clas_key tycon cts
1121 derivingThingErr clas tys ty why
1122 = sep [hsep [ptext SLIT("Can't make a derived instance of"),
1124 nest 2 (parens why)]
1126 pred = mkClassPred clas (tys ++ [ty])
1128 standaloneCtxt :: LHsType Name -> SDoc
1129 standaloneCtxt ty = ptext SLIT("In the stand-alone deriving instance for") <+> quotes (ppr ty)
1131 derivInstCtxt clas inst_tys
1132 = ptext SLIT("When deriving the instance for") <+> parens (pprClassPred clas inst_tys)
1135 = vcat [ptext SLIT("Can't derive instances where the instance context mentions"),
1136 ptext SLIT("type variables that are not data type parameters"),
1137 nest 2 (ptext SLIT("Offending constraint:") <+> ppr pred)]