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 -- Type signatures in patterns are used in the generic binds
244 setOptM Opt_PatternSignatures $
246 { (rn_deriv, _dus1) <- rnTopBinds (ValBindsIn deriv_binds [])
247 ; (rn_gen, dus_gen) <- rnTopBinds (ValBindsIn gen_binds [])
248 ; keepAliveSetTc (duDefs dus_gen) -- Mark these guys to
250 ; return (rn_deriv `plusHsValBinds` rn_gen) }
254 ; ioToTcRn (dumpIfSet_dyn dflags Opt_D_dump_deriv "Derived instances"
255 (ddump_deriving inst_info rn_binds))
257 ; returnM (inst_info, rn_binds)
260 ddump_deriving :: [InstInfo] -> HsValBinds Name -> SDoc
261 ddump_deriving inst_infos extra_binds
262 = vcat (map pprInstInfoDetails inst_infos) $$ ppr extra_binds
264 -----------------------------------------
265 deriveOrdinaryStuff [] -- Short cut
266 = returnM ([], emptyLHsBinds)
268 deriveOrdinaryStuff eqns
269 = do { -- Take the equation list and solve it, to deliver a list of
270 -- solutions, a.k.a. the contexts for the instance decls
271 -- required for the corresponding equations.
272 overlap_flag <- getOverlapFlag
273 ; inst_specs <- solveDerivEqns overlap_flag eqns
275 -- Generate the InstInfo for each dfun,
276 -- plus any auxiliary bindings it needs
277 ; (inst_infos, aux_binds_s) <- mapAndUnzipM genInst inst_specs
279 -- Generate any extra not-one-inst-decl-specific binds,
280 -- notably "con2tag" and/or "tag2con" functions.
281 ; extra_binds <- genTaggeryBinds inst_infos
284 ; returnM (map fst inst_infos,
285 unionManyBags (extra_binds : aux_binds_s))
288 -----------------------------------------
289 mkGenericBinds tycl_decls
290 = do { tcs <- mapM tcLookupTyCon
292 L _ (TyData { tcdLName = L _ tc_name }) <- tycl_decls]
293 -- We are only interested in the data type declarations
294 ; return (unionManyBags [ mkTyConGenericBinds tc |
295 tc <- tcs, tyConHasGenerics tc ]) }
296 -- And then only in the ones whose 'has-generics' flag is on
300 %************************************************************************
302 \subsection[TcDeriv-eqns]{Forming the equations}
304 %************************************************************************
306 @makeDerivEqns@ fishes around to find the info about needed derived
307 instances. Complicating factors:
310 We can only derive @Enum@ if the data type is an enumeration
311 type (all nullary data constructors).
314 We can only derive @Ix@ if the data type is an enumeration {\em
315 or} has just one data constructor (e.g., tuples).
318 [See Appendix~E in the Haskell~1.2 report.] This code here deals w/
321 Note [Newtype deriving superclasses]
322 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
323 The 'tys' here come from the partial application in the deriving
324 clause. The last arg is the new instance type.
326 We must pass the superclasses; the newtype might be an instance
327 of them in a different way than the representation type
328 E.g. newtype Foo a = Foo a deriving( Show, Num, Eq )
329 Then the Show instance is not done via isomorphism; it shows
331 The Num instance is derived via isomorphism, but the Show superclass
332 dictionary must the Show instance for Foo, *not* the Show dictionary
333 gotten from the Num dictionary. So we must build a whole new dictionary
334 not just use the Num one. The instance we want is something like:
335 instance (Num a, Show (Foo a), Eq (Foo a)) => Num (Foo a) where
338 There may be a coercion needed which we get from the tycon for the newtype
339 when the dict is constructed in TcInstDcls.tcInstDecl2
343 makeDerivEqns :: [LTyClDecl Name]
346 -> TcM ([DerivEqn], -- Ordinary derivings
347 [InstInfo]) -- Special newtype derivings
349 makeDerivEqns tycl_decls inst_decls deriv_decls
350 = do { eqns1 <- mapM deriveTyData $
351 extractTyDataPreds tycl_decls ++
352 [ pd -- traverse assoc data families
353 | L _ (InstDecl _ _ _ ats) <- inst_decls
354 , pd <- extractTyDataPreds ats ]
355 ; eqns2 <- mapM deriveStandalone deriv_decls
356 ; return ([eqn | (Just eqn, _) <- eqns1 ++ eqns2],
357 [inst | (_, Just inst) <- eqns1 ++ eqns2]) }
359 extractTyDataPreds decls =
360 [(p, d) | d@(L _ (TyData {tcdDerivs = Just preds})) <- decls, p <- preds]
363 ------------------------------------------------------------------
364 deriveStandalone :: LDerivDecl Name -> TcM (Maybe DerivEqn, Maybe InstInfo)
365 -- Standalone deriving declarations
366 -- e.g. derive instance Show T
367 -- Rather like tcLocalInstDecl
368 deriveStandalone (L loc (DerivDecl deriv_ty))
370 addErrCtxt (standaloneCtxt deriv_ty) $
371 do { (tvs, theta, tau) <- tcHsInstHead deriv_ty
372 ; (cls, inst_tys) <- checkValidInstHead tau
373 ; let cls_tys = take (length inst_tys - 1) inst_tys
374 inst_ty = last inst_tys
376 ; mkEqnHelp StandAloneDerivOrigin tvs cls cls_tys inst_ty }
378 ------------------------------------------------------------------
379 deriveTyData :: (LHsType Name, LTyClDecl Name) -> TcM (Maybe DerivEqn, Maybe InstInfo)
380 deriveTyData (deriv_pred, L loc decl@(TyData { tcdLName = L _ tycon_name,
381 tcdTyVars = tv_names,
382 tcdTyPats = ty_pats }))
385 do { let hs_ty_args = ty_pats `orElse` map (nlHsTyVar . hsLTyVarName) tv_names
386 hs_app = nlHsTyConApp tycon_name hs_ty_args
387 -- We get kinding info for the tyvars by typechecking (T a b)
388 -- Hence forming a tycon application and then dis-assembling it
389 ; (tvs, tc_app) <- tcHsQuantifiedType tv_names hs_app
390 ; tcExtendTyVarEnv tvs $ -- Deriving preds may (now) mention
391 -- the type variables for the type constructor
392 do { (deriv_tvs, cls, cls_tys) <- tcHsDeriv deriv_pred
393 -- The "deriv_pred" is a LHsType to take account of the fact that for
394 -- newtype deriving we allow deriving (forall a. C [a]).
395 ; mkEqnHelp DerivOrigin (tvs++deriv_tvs) cls cls_tys tc_app } }
396 deriveTyData (deriv_pred, other_decl)
397 = panic "derivTyData" -- Caller ensures that only TyData can happen
399 ------------------------------------------------------------------
400 mkEqnHelp orig tvs cls cls_tys tc_app
401 | Just (tycon, tc_args) <- tcSplitTyConApp_maybe tc_app
402 = do { -- Make tc_app saturated, because that's what the
403 -- mkDataTypeEqn things expect
404 -- It might not be saturated in the standalone deriving case
405 -- derive instance Monad (T a)
406 let extra_tvs = dropList tc_args (tyConTyVars tycon)
407 full_tc_args = tc_args ++ mkTyVarTys extra_tvs
408 full_tvs = tvs ++ extra_tvs
410 ; (rep_tc, rep_tc_args) <- tcLookupFamInstExact tycon full_tc_args
412 ; mayDeriveDataTypeable <- doptM Opt_DeriveDataTypeable
413 ; newtype_deriving <- doptM Opt_GeneralizedNewtypeDeriving
414 ; overlap_flag <- getOverlapFlag
416 -- Be careful to test rep_tc here: in the case of families, we want
417 -- to check the instance tycon, not the family tycon
418 ; if isDataTyCon rep_tc then
419 mkDataTypeEqn orig mayDeriveDataTypeable full_tvs cls cls_tys
420 tycon full_tc_args rep_tc rep_tc_args
422 mkNewTypeEqn orig mayDeriveDataTypeable newtype_deriving overlap_flag
424 tycon full_tc_args rep_tc rep_tc_args }
426 = baleOut (derivingThingErr cls cls_tys tc_app
427 (ptext SLIT("Last argument of the instance must be a type application")))
429 baleOut err = addErrTc err >> returnM (Nothing, Nothing)
432 Auxiliary lookup wrapper which requires that looked up family instances are
436 tcLookupFamInstExact :: TyCon -> [Type] -> TcM (TyCon, [Type])
437 tcLookupFamInstExact tycon tys
438 = do { result@(rep_tycon, rep_tys) <- tcLookupFamInst tycon tys
439 ; let { tvs = map (Type.getTyVar
440 "TcDeriv.tcLookupFamInstExact")
442 ; variable_only_subst = all Type.isTyVarTy rep_tys &&
443 sizeVarSet (mkVarSet tvs) == length tvs
444 -- renaming may have no repetitions
446 ; unless variable_only_subst $
447 famInstNotFound tycon tys [result]
454 %************************************************************************
458 %************************************************************************
461 mkDataTypeEqn orig mayDeriveDataTypeable tvs cls cls_tys
462 tycon tc_args rep_tc rep_tc_args
463 | Just err <- checkSideConditions mayDeriveDataTypeable cls cls_tys rep_tc
464 -- NB: pass the *representation* tycon to checkSideConditions
465 = baleOut (derivingThingErr cls cls_tys (mkTyConApp tycon tc_args) err)
468 = ASSERT( null cls_tys )
469 do { loc <- getSrcSpanM
470 ; eqn <- mk_data_eqn loc orig tvs cls tycon tc_args rep_tc rep_tc_args
471 ; return (Just eqn, Nothing) }
473 mk_data_eqn :: SrcSpan -> InstOrigin -> [TyVar] -> Class
474 -> TyCon -> [TcType] -> TyCon -> [TcType] -> TcM DerivEqn
475 mk_data_eqn loc orig tvs cls tycon tc_args rep_tc rep_tc_args
476 | cls `hasKey` typeableClassKey
477 = -- The Typeable class is special in several ways
478 -- data T a b = ... deriving( Typeable )
480 -- instance Typeable2 T where ...
482 -- 1. There are no constraints in the instance
483 -- 2. There are no type variables either
484 -- 3. The actual class we want to generate isn't necessarily
485 -- Typeable; it depends on the arity of the type
486 do { real_clas <- tcLookupClass (typeableClassNames !! tyConArity tycon)
487 ; dfun_name <- new_dfun_name real_clas tycon
488 ; return (loc, orig, dfun_name, [], real_clas, mkTyConApp tycon [], []) }
491 = do { dfun_name <- new_dfun_name cls tycon
492 ; let ordinary_constraints
493 = [ mkClassPred cls [arg_ty]
494 | data_con <- tyConDataCons rep_tc,
495 arg_ty <- ASSERT( isVanillaDataCon data_con )
496 dataConInstOrigArgTys data_con rep_tc_args,
497 not (isUnLiftedType arg_ty) ] -- No constraints for unlifted types?
499 tiresome_subst = zipTopTvSubst (tyConTyVars rep_tc) rep_tc_args
500 stupid_constraints = substTheta tiresome_subst (tyConStupidTheta rep_tc)
501 -- see note [Data decl contexts] above
503 ; return (loc, orig, dfun_name, tvs, cls, mkTyConApp tycon tc_args,
504 stupid_constraints ++ ordinary_constraints)
507 ------------------------------------------------------------------
508 -- Check side conditions that dis-allow derivability for particular classes
509 -- This is *apart* from the newtype-deriving mechanism
511 -- Here we get the representation tycon in case of family instances as it has
512 -- the data constructors - but we need to be careful to fall back to the
513 -- family tycon (with indexes) in error messages.
515 checkSideConditions :: Bool -> Class -> [TcType] -> TyCon -> Maybe SDoc
516 checkSideConditions mayDeriveDataTypeable cls cls_tys rep_tc
518 = Just ty_args_why -- e.g. deriving( Foo s )
520 = case [cond | (key,cond) <- sideConditions, key == getUnique cls] of
521 [] -> Just (non_std_why cls)
522 [cond] -> cond (mayDeriveDataTypeable, rep_tc)
523 other -> pprPanic "checkSideConditions" (ppr cls)
525 ty_args_why = quotes (ppr (mkClassPred cls cls_tys)) <+> ptext SLIT("is not a class")
527 non_std_why cls = quotes (ppr cls) <+> ptext SLIT("is not a derivable class")
529 sideConditions :: [(Unique, Condition)]
531 = [ (eqClassKey, cond_std),
532 (ordClassKey, cond_std),
533 (readClassKey, cond_std),
534 (showClassKey, cond_std),
535 (enumClassKey, cond_std `andCond` cond_isEnumeration),
536 (ixClassKey, cond_std `andCond` (cond_isEnumeration `orCond` cond_isProduct)),
537 (boundedClassKey, cond_std `andCond` (cond_isEnumeration `orCond` cond_isProduct)),
538 (typeableClassKey, cond_mayDeriveDataTypeable `andCond` cond_typeableOK),
539 (dataClassKey, cond_mayDeriveDataTypeable `andCond` cond_std)
542 type Condition = (Bool, TyCon) -> Maybe SDoc
543 -- Bool is whether or not we are allowed to derive Data and Typeable
544 -- TyCon is the *representation* tycon if the
545 -- data type is an indexed one
548 orCond :: Condition -> Condition -> Condition
551 Nothing -> Nothing -- c1 succeeds
552 Just x -> case c2 tc of -- c1 fails
554 Just y -> Just (x $$ ptext SLIT(" and") $$ y)
557 andCond c1 c2 tc = case c1 tc of
558 Nothing -> c2 tc -- c1 succeeds
559 Just x -> Just x -- c1 fails
561 cond_std :: Condition
563 | any (not . isVanillaDataCon) data_cons = Just existential_why
564 | null data_cons = Just no_cons_why
565 | otherwise = Nothing
567 data_cons = tyConDataCons rep_tc
568 no_cons_why = quotes (pprSourceTyCon rep_tc) <+>
569 ptext SLIT("has no data constructors")
570 existential_why = quotes (pprSourceTyCon rep_tc) <+>
571 ptext SLIT("has non-Haskell-98 constructor(s)")
573 cond_isEnumeration :: Condition
574 cond_isEnumeration (_, rep_tc)
575 | isEnumerationTyCon rep_tc = Nothing
576 | otherwise = Just why
578 why = quotes (pprSourceTyCon rep_tc) <+>
579 ptext SLIT("has non-nullary constructors")
581 cond_isProduct :: Condition
582 cond_isProduct (_, rep_tc)
583 | isProductTyCon rep_tc = Nothing
584 | otherwise = Just why
586 why = quotes (pprSourceTyCon rep_tc) <+>
587 ptext SLIT("has more than one constructor")
589 cond_typeableOK :: Condition
590 -- OK for Typeable class
591 -- Currently: (a) args all of kind *
592 -- (b) 7 or fewer args
593 cond_typeableOK (_, rep_tc)
594 | tyConArity rep_tc > 7 = Just too_many
595 | not (all (isSubArgTypeKind . tyVarKind) (tyConTyVars rep_tc))
597 | isFamInstTyCon rep_tc = Just fam_inst -- no Typable for family insts
598 | otherwise = Nothing
600 too_many = quotes (pprSourceTyCon rep_tc) <+>
601 ptext SLIT("has too many arguments")
602 bad_kind = quotes (pprSourceTyCon rep_tc) <+>
603 ptext SLIT("has arguments of kind other than `*'")
604 fam_inst = quotes (pprSourceTyCon rep_tc) <+>
605 ptext SLIT("is a type family")
607 cond_mayDeriveDataTypeable :: Condition
608 cond_mayDeriveDataTypeable (mayDeriveDataTypeable, _)
609 | mayDeriveDataTypeable = Nothing
610 | otherwise = Just why
612 why = ptext SLIT("You need -fglasgow-exts to derive an instance for this class")
614 std_class_via_iso clas -- These standard classes can be derived for a newtype
615 -- using the isomorphism trick *even if no -fglasgow-exts*
616 = classKey clas `elem` [eqClassKey, ordClassKey, ixClassKey, boundedClassKey]
617 -- Not Read/Show because they respect the type
618 -- Not Enum, because newtypes are never in Enum
621 new_dfun_name clas tycon -- Just a simple wrapper
622 = newDFunName clas [mkTyConApp tycon []] (getSrcSpan tycon)
623 -- The type passed to newDFunName is only used to generate
624 -- a suitable string; hence the empty type arg list
628 %************************************************************************
632 %************************************************************************
635 mkNewTypeEqn :: InstOrigin -> Bool -> Bool -> OverlapFlag -> [Var] -> Class
636 -> [Type] -> TyCon -> [Type] -> TyCon -> [Type]
637 -> TcRn (Maybe DerivEqn, Maybe InstInfo)
638 mkNewTypeEqn orig mayDeriveDataTypeable newtype_deriving overlap_flag tvs cls cls_tys
640 rep_tycon rep_tc_args
641 | can_derive_via_isomorphism && (newtype_deriving || std_class_via_iso cls)
642 = do { traceTc (text "newtype deriving:" <+> ppr tycon <+> ppr rep_tys)
643 ; -- Go ahead and use the isomorphism
644 dfun_name <- new_dfun_name cls tycon
645 ; return (Nothing, Just (InstInfo { iSpec = mk_inst_spec dfun_name,
646 iBinds = NewTypeDerived ntd_info })) }
648 | isNothing mb_std_err -- Use the standard H98 method
649 = do { loc <- getSrcSpanM
650 ; eqn <- mk_data_eqn loc orig tvs cls tycon tc_args rep_tycon rep_tc_args
651 ; return (Just eqn, Nothing) }
653 -- Otherwise we can't derive
654 | newtype_deriving = baleOut cant_derive_err -- Too hard
655 | otherwise = baleOut std_err -- Just complain about being a non-std instance
657 mb_std_err = checkSideConditions mayDeriveDataTypeable cls cls_tys rep_tycon
658 std_err = derivingThingErr cls cls_tys tc_app $
659 vcat [fromJust mb_std_err,
660 ptext SLIT("Try -XGeneralizedNewtypeDeriving for GHC's newtype-deriving extension")]
662 -- Here is the plan for newtype derivings. We see
663 -- newtype T a1...an = MkT (t ak+1...an) deriving (.., C s1 .. sm, ...)
664 -- where t is a type,
665 -- ak+1...an is a suffix of a1..an, and are all tyars
666 -- ak+1...an do not occur free in t, nor in the s1..sm
667 -- (C s1 ... sm) is a *partial applications* of class C
668 -- with the last parameter missing
669 -- (T a1 .. ak) matches the kind of C's last argument
670 -- (and hence so does t)
672 -- We generate the instance
673 -- instance forall ({a1..ak} u fvs(s1..sm)).
674 -- C s1 .. sm t => C s1 .. sm (T a1...ak)
675 -- where T a1...ap is the partial application of
676 -- the LHS of the correct kind and p >= k
678 -- NB: the variables below are:
679 -- tc_tvs = [a1, ..., an]
680 -- tyvars_to_keep = [a1, ..., ak]
681 -- rep_ty = t ak .. an
682 -- deriv_tvs = fvs(s1..sm) \ tc_tvs
683 -- tys = [s1, ..., sm]
686 -- Running example: newtype T s a = MkT (ST s a) deriving( Monad )
687 -- We generate the instance
688 -- instance Monad (ST s) => Monad (T s) where
690 cls_tyvars = classTyVars cls
691 kind = tyVarKind (last cls_tyvars)
692 -- Kind of the thing we want to instance
693 -- e.g. argument kind of Monad, *->*
695 (arg_kinds, _) = splitKindFunTys kind
696 n_args_to_drop = length arg_kinds
697 -- Want to drop 1 arg from (T s a) and (ST s a)
698 -- to get instance Monad (ST s) => Monad (T s)
700 -- Note [newtype representation]
701 -- Need newTyConRhs *not* newTyConRep to get the representation
702 -- type, because the latter looks through all intermediate newtypes
704 -- newtype B = MkB Int
705 -- newtype A = MkA B deriving( Num )
706 -- We want the Num instance of B, *not* the Num instance of Int,
707 -- when making the Num instance of A!
708 rep_ty = newTyConInstRhs rep_tycon rep_tc_args
709 (rep_fn, rep_ty_args) = tcSplitAppTys rep_ty
711 n_tyargs_to_keep = tyConArity tycon - n_args_to_drop
712 dropped_tc_args = drop n_tyargs_to_keep tc_args
713 dropped_tvs = tyVarsOfTypes dropped_tc_args
715 n_args_to_keep = length rep_ty_args - n_args_to_drop
716 args_to_drop = drop n_args_to_keep rep_ty_args
717 args_to_keep = take n_args_to_keep rep_ty_args
719 rep_fn' = mkAppTys rep_fn args_to_keep
720 rep_tys = cls_tys ++ [rep_fn']
721 rep_pred = mkClassPred cls rep_tys
722 -- rep_pred is the representation dictionary, from where
723 -- we are gong to get all the methods for the newtype
726 tc_app = mkTyConApp tycon (take n_tyargs_to_keep tc_args)
728 -- Next we figure out what superclass dictionaries to use
729 -- See Note [Newtype deriving superclasses] above
731 inst_tys = cls_tys ++ [tc_app]
732 sc_theta = substTheta (zipOpenTvSubst cls_tyvars inst_tys)
735 -- If there are no tyvars, there's no need
736 -- to abstract over the dictionaries we need
737 -- Example: newtype T = MkT Int deriving( C )
738 -- We get the derived instance
741 -- instance C Int => C T
742 dict_tvs = filterOut (`elemVarSet` dropped_tvs) tvs
743 all_preds = rep_pred : sc_theta -- NB: rep_pred comes first
744 (dict_args, ntd_info) | null dict_tvs = ([], Just all_preds)
745 | otherwise = (all_preds, Nothing)
747 -- Finally! Here's where we build the dictionary Id
748 mk_inst_spec dfun_name = mkLocalInstance dfun overlap_flag
750 dfun = mkDictFunId dfun_name dict_tvs dict_args cls inst_tys
752 -------------------------------------------------------------------
753 -- Figuring out whether we can only do this newtype-deriving thing
755 right_arity = length cls_tys + 1 == classArity cls
757 -- Never derive Read,Show,Typeable,Data this way
758 non_iso_classes = [readClassKey, showClassKey, typeableClassKey, dataClassKey]
759 can_derive_via_isomorphism
760 = not (getUnique cls `elem` non_iso_classes)
761 && right_arity -- Well kinded;
762 -- eg not: newtype T ... deriving( ST )
763 -- because ST needs *2* type params
764 && n_tyargs_to_keep >= 0 -- Type constructor has right kind:
765 -- eg not: newtype T = T Int deriving( Monad )
766 && n_args_to_keep >= 0 -- Rep type has right kind:
767 -- eg not: newtype T a = T Int deriving( Monad )
768 && eta_ok -- Eta reduction works
769 && not (isRecursiveTyCon tycon) -- Does not work for recursive tycons:
770 -- newtype A = MkA [A]
772 -- instance Eq [A] => Eq A !!
773 -- Here's a recursive newtype that's actually OK
774 -- newtype S1 = S1 [T1 ()]
775 -- newtype T1 a = T1 (StateT S1 IO a ) deriving( Monad )
776 -- It's currently rejected. Oh well.
777 -- In fact we generate an instance decl that has method of form
778 -- meth @ instTy = meth @ repTy
779 -- (no coerce's). We'd need a coerce if we wanted to handle
780 -- recursive newtypes too
782 -- Check that eta reduction is OK
783 eta_ok = (args_to_drop `tcEqTypes` dropped_tc_args)
784 -- (a) the dropped-off args are identical in the source and rep type
785 -- newtype T a b = MkT (S [a] b) deriving( Monad )
786 -- Here the 'b' must be the same in the rep type (S [a] b)
788 && (tyVarsOfType rep_fn' `disjointVarSet` dropped_tvs)
789 -- (b) the remaining type args do not mention any of the dropped
792 && (tyVarsOfTypes cls_tys `disjointVarSet` dropped_tvs)
793 -- (c) the type class args do not mention any of the dropped type
796 && all isTyVarTy dropped_tc_args
797 -- (d) in case of newtype family instances, the eta-dropped
798 -- arguments must be type variables (not more complex indexes)
800 cant_derive_err = derivingThingErr cls cls_tys tc_app
801 (vcat [ptext SLIT("even with cunning newtype deriving:"),
802 if isRecursiveTyCon tycon then
803 ptext SLIT("the newtype may be recursive")
805 if not right_arity then
806 quotes (ppr (mkClassPred cls cls_tys)) <+> ptext SLIT("does not have arity 1")
808 if not (n_tyargs_to_keep >= 0) then
809 ptext SLIT("the type constructor has wrong kind")
810 else if not (n_args_to_keep >= 0) then
811 ptext SLIT("the representation type has wrong kind")
812 else if not eta_ok then
813 ptext SLIT("the eta-reduction property does not hold")
819 %************************************************************************
821 \subsection[TcDeriv-fixpoint]{Finding the fixed point of \tr{deriving} equations}
823 %************************************************************************
825 A ``solution'' (to one of the equations) is a list of (k,TyVarTy tv)
826 terms, which is the final correct RHS for the corresponding original
830 Each (k,TyVarTy tv) in a solution constrains only a type
834 The (k,TyVarTy tv) pairs in a solution are canonically
835 ordered by sorting on type varible, tv, (major key) and then class, k,
840 solveDerivEqns :: OverlapFlag
842 -> TcM [Instance]-- Solns in same order as eqns.
843 -- This bunch is Absolutely minimal...
845 solveDerivEqns overlap_flag orig_eqns
846 = do { traceTc (text "solveDerivEqns" <+> vcat (map pprDerivEqn orig_eqns))
847 ; iterateDeriv 1 initial_solutions }
849 -- The initial solutions for the equations claim that each
850 -- instance has an empty context; this solution is certainly
851 -- in canonical form.
852 initial_solutions :: [DerivSoln]
853 initial_solutions = [ [] | _ <- orig_eqns ]
855 ------------------------------------------------------------------
856 -- iterateDeriv calculates the next batch of solutions,
857 -- compares it with the current one; finishes if they are the
858 -- same, otherwise recurses with the new solutions.
859 -- It fails if any iteration fails
860 iterateDeriv :: Int -> [DerivSoln] -> TcM [Instance]
861 iterateDeriv n current_solns
862 | n > 20 -- Looks as if we are in an infinite loop
863 -- This can happen if we have -fallow-undecidable-instances
864 -- (See TcSimplify.tcSimplifyDeriv.)
865 = pprPanic "solveDerivEqns: probable loop"
866 (vcat (map pprDerivEqn orig_eqns) $$ ppr current_solns)
869 inst_specs = zipWithEqual "add_solns" mk_inst_spec
870 orig_eqns current_solns
873 -- Extend the inst info from the explicit instance decls
874 -- with the current set of solutions, and simplify each RHS
875 extendLocalInstEnv inst_specs $
876 mappM gen_soln orig_eqns
877 ) `thenM` \ new_solns ->
878 if (current_solns == new_solns) then
881 iterateDeriv (n+1) new_solns
883 ------------------------------------------------------------------
884 gen_soln :: DerivEqn -> TcM [PredType]
885 gen_soln (loc, orig, _, tyvars, clas, inst_ty, deriv_rhs)
887 addErrCtxt (derivInstCtxt clas [inst_ty]) $
888 do { theta <- tcSimplifyDeriv orig tyvars deriv_rhs
889 -- checkValidInstance tyvars theta clas [inst_ty]
890 -- Not necessary; see Note [Exotic derived instance contexts]
893 -- Check for a bizarre corner case, when the derived instance decl should
894 -- have form instance C a b => D (T a) where ...
895 -- Note that 'b' isn't a parameter of T. This gives rise to all sorts
896 -- of problems; in particular, it's hard to compare solutions for
897 -- equality when finding the fixpoint. So I just rule it out for now.
898 ; let tv_set = mkVarSet tyvars
899 weird_preds = [pred | pred <- theta, not (tyVarsOfPred pred `subVarSet` tv_set)]
900 ; mapM_ (addErrTc . badDerivedPred) weird_preds
902 -- Claim: the result instance declaration is guaranteed valid
903 -- Hence no need to call:
904 -- checkValidInstance tyvars theta clas inst_tys
905 ; return (sortLe (<=) theta) } -- Canonicalise before returning the solution
907 ------------------------------------------------------------------
908 mk_inst_spec :: DerivEqn -> DerivSoln -> Instance
909 mk_inst_spec (loc, orig, dfun_name, tyvars, clas, inst_ty, _) theta
910 = mkLocalInstance dfun overlap_flag
912 dfun = mkDictFunId dfun_name tyvars theta clas [inst_ty]
914 extendLocalInstEnv :: [Instance] -> TcM a -> TcM a
915 -- Add new locally-defined instances; don't bother to check
916 -- for functional dependency errors -- that'll happen in TcInstDcls
917 extendLocalInstEnv dfuns thing_inside
918 = do { env <- getGblEnv
919 ; let inst_env' = extendInstEnvList (tcg_inst_env env) dfuns
920 env' = env { tcg_inst_env = inst_env' }
921 ; setGblEnv env' thing_inside }
925 %************************************************************************
927 \subsection[TcDeriv-normal-binds]{Bindings for the various classes}
929 %************************************************************************
931 After all the trouble to figure out the required context for the
932 derived instance declarations, all that's left is to chug along to
933 produce them. They will then be shoved into @tcInstDecls2@, which
934 will do all its usual business.
936 There are lots of possibilities for code to generate. Here are
937 various general remarks.
942 We want derived instances of @Eq@ and @Ord@ (both v common) to be
943 ``you-couldn't-do-better-by-hand'' efficient.
946 Deriving @Show@---also pretty common--- should also be reasonable good code.
949 Deriving for the other classes isn't that common or that big a deal.
956 Deriving @Ord@ is done mostly with the 1.3 @compare@ method.
959 Deriving @Eq@ also uses @compare@, if we're deriving @Ord@, too.
962 We {\em normally} generate code only for the non-defaulted methods;
963 there are some exceptions for @Eq@ and (especially) @Ord@...
966 Sometimes we use a @_con2tag_<tycon>@ function, which returns a data
967 constructor's numeric (@Int#@) tag. These are generated by
968 @gen_tag_n_con_binds@, and the heuristic for deciding if one of
969 these is around is given by @hasCon2TagFun@.
971 The examples under the different sections below will make this
975 Much less often (really just for deriving @Ix@), we use a
976 @_tag2con_<tycon>@ function. See the examples.
979 We use the renamer!!! Reason: we're supposed to be
980 producing @LHsBinds Name@ for the methods, but that means
981 producing correctly-uniquified code on the fly. This is entirely
982 possible (the @TcM@ monad has a @UniqueSupply@), but it is painful.
983 So, instead, we produce @MonoBinds RdrName@ then heave 'em through
984 the renamer. What a great hack!
988 -- Generate the InstInfo for the required instance paired with the
989 -- *representation* tycon for that instance,
990 -- plus any auxiliary bindings required
992 -- Representation tycons differ from the tycon in the instance signature in
993 -- case of instances for indexed families.
995 genInst :: Instance -> TcM ((InstInfo, TyCon), LHsBinds RdrName)
997 = do { fix_env <- getFixityEnv
999 (tyvars,_,clas,[ty]) = instanceHead spec
1000 clas_nm = className clas
1001 (visible_tycon, tyArgs) = tcSplitTyConApp ty
1003 -- In case of a family instance, we need to use the representation
1004 -- tycon (after all, it has the data constructors)
1005 ; (tycon, _) <- tcLookupFamInstExact visible_tycon tyArgs
1006 ; let (meth_binds, aux_binds) = genDerivBinds clas fix_env tycon
1008 -- Bring the right type variables into
1009 -- scope, and rename the method binds
1010 -- It's a bit yukky that we return *renamed* InstInfo, but
1011 -- *non-renamed* auxiliary bindings
1012 ; (rn_meth_binds, _fvs) <- discardWarnings $
1013 bindLocalNames (map Var.varName tyvars) $
1014 rnMethodBinds clas_nm (\n -> []) [] meth_binds
1016 -- Build the InstInfo
1017 ; return ((InstInfo { iSpec = spec,
1018 iBinds = VanillaInst rn_meth_binds [] }, tycon),
1022 genDerivBinds clas fix_env tycon
1023 | className clas `elem` typeableClassNames
1024 = (gen_Typeable_binds tycon, emptyLHsBinds)
1027 = case assocMaybe gen_list (getUnique clas) of
1028 Just gen_fn -> gen_fn fix_env tycon
1029 Nothing -> pprPanic "genDerivBinds: bad derived class" (ppr clas)
1031 gen_list :: [(Unique, FixityEnv -> TyCon -> (LHsBinds RdrName, LHsBinds RdrName))]
1032 gen_list = [(eqClassKey, no_aux_binds (ignore_fix_env gen_Eq_binds))
1033 ,(ordClassKey, no_aux_binds (ignore_fix_env gen_Ord_binds))
1034 ,(enumClassKey, no_aux_binds (ignore_fix_env gen_Enum_binds))
1035 ,(boundedClassKey, no_aux_binds (ignore_fix_env gen_Bounded_binds))
1036 ,(ixClassKey, no_aux_binds (ignore_fix_env gen_Ix_binds))
1037 ,(typeableClassKey,no_aux_binds (ignore_fix_env gen_Typeable_binds))
1038 ,(showClassKey, no_aux_binds gen_Show_binds)
1039 ,(readClassKey, no_aux_binds gen_Read_binds)
1040 ,(dataClassKey, gen_Data_binds)
1043 -- no_aux_binds is used for generators that don't
1044 -- need to produce any auxiliary bindings
1045 no_aux_binds f fix_env tc = (f fix_env tc, emptyLHsBinds)
1046 ignore_fix_env f fix_env tc = f tc
1050 %************************************************************************
1052 \subsection[TcDeriv-taggery-Names]{What con2tag/tag2con functions are available?}
1054 %************************************************************************
1059 con2tag_Foo :: Foo ... -> Int#
1060 tag2con_Foo :: Int -> Foo ... -- easier if Int, not Int#
1061 maxtag_Foo :: Int -- ditto (NB: not unlifted)
1064 We have a @con2tag@ function for a tycon if:
1067 We're deriving @Eq@ and the tycon has nullary data constructors.
1070 Or: we're deriving @Ord@ (unless single-constructor), @Enum@, @Ix@
1071 (enum type only????)
1074 We have a @tag2con@ function for a tycon if:
1077 We're deriving @Enum@, or @Ix@ (enum type only???)
1080 If we have a @tag2con@ function, we also generate a @maxtag@ constant.
1083 genTaggeryBinds :: [(InstInfo, TyCon)] -> TcM (LHsBinds RdrName)
1084 genTaggeryBinds infos
1085 = do { names_so_far <- foldlM do_con2tag [] tycons_of_interest
1086 ; nm_alist_etc <- foldlM do_tag2con names_so_far tycons_of_interest
1087 ; return (listToBag (map gen_tag_n_con_monobind nm_alist_etc)) }
1089 all_CTs = [ (fst (simpleInstInfoClsTy info), tc)
1090 | (info, tc) <- infos]
1091 all_tycons = map snd all_CTs
1092 (tycons_of_interest, _) = removeDups compare all_tycons
1094 do_con2tag acc_Names tycon
1095 | isDataTyCon tycon &&
1096 ((we_are_deriving eqClassKey tycon
1097 && any isNullarySrcDataCon (tyConDataCons tycon))
1098 || (we_are_deriving ordClassKey tycon
1099 && not (isProductTyCon tycon))
1100 || (we_are_deriving enumClassKey tycon)
1101 || (we_are_deriving ixClassKey tycon))
1103 = returnM ((con2tag_RDR tycon, tycon, GenCon2Tag)
1108 do_tag2con acc_Names tycon
1109 | isDataTyCon tycon &&
1110 (we_are_deriving enumClassKey tycon ||
1111 we_are_deriving ixClassKey tycon
1112 && isEnumerationTyCon tycon)
1113 = returnM ( (tag2con_RDR tycon, tycon, GenTag2Con)
1114 : (maxtag_RDR tycon, tycon, GenMaxTag)
1119 we_are_deriving clas_key tycon
1120 = is_in_eqns clas_key tycon all_CTs
1122 is_in_eqns clas_key tycon [] = False
1123 is_in_eqns clas_key tycon ((c,t):cts)
1124 = (clas_key == classKey c && tycon == t)
1125 || is_in_eqns clas_key tycon cts
1129 derivingThingErr clas tys ty why
1130 = sep [hsep [ptext SLIT("Can't make a derived instance of"),
1132 nest 2 (parens why)]
1134 pred = mkClassPred clas (tys ++ [ty])
1136 standaloneCtxt :: LHsType Name -> SDoc
1137 standaloneCtxt ty = ptext SLIT("In the stand-alone deriving instance for") <+> quotes (ppr ty)
1139 derivInstCtxt clas inst_tys
1140 = ptext SLIT("When deriving the instance for") <+> parens (pprClassPred clas inst_tys)
1143 = vcat [ptext SLIT("Can't derive instances where the instance context mentions"),
1144 ptext SLIT("type variables that are not data type parameters"),
1145 nest 2 (ptext SLIT("Offending constraint:") <+> ppr pred)]