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 -> [LDerivDecl Name] -- All stand-alone deriving declarations
210 -> TcM ([InstInfo], -- The generated "instance decls"
211 HsValBinds Name) -- Extra generated top-level bindings
213 tcDeriving tycl_decls deriv_decls
214 = recoverM (returnM ([], emptyValBindsOut)) $
215 do { -- Fish the "deriving"-related information out of the TcEnv
216 -- and make the necessary "equations".
217 ; (ordinary_eqns, newtype_inst_info) <- makeDerivEqns tycl_decls deriv_decls
219 ; (ordinary_inst_info, deriv_binds)
220 <- extendLocalInstEnv (map iSpec newtype_inst_info) $
221 deriveOrdinaryStuff ordinary_eqns
222 -- Add the newtype-derived instances to the inst env
223 -- before tacking the "ordinary" ones
225 ; let inst_info = newtype_inst_info ++ ordinary_inst_info
227 -- If we are compiling a hs-boot file,
228 -- don't generate any derived bindings
229 ; is_boot <- tcIsHsBoot
231 return (inst_info, emptyValBindsOut)
235 -- Generate the generic to/from functions from each type declaration
236 ; gen_binds <- mkGenericBinds tycl_decls
238 -- Rename these extra bindings, discarding warnings about unused bindings etc
239 -- Set -fglasgow exts so that we can have type signatures in patterns,
240 -- which is used in the generic binds
242 <- discardWarnings $ setOptM Opt_GlasgowExts $ do
243 { (rn_deriv, _dus1) <- rnTopBinds (ValBindsIn deriv_binds [])
244 ; (rn_gen, dus_gen) <- rnTopBinds (ValBindsIn gen_binds [])
245 ; keepAliveSetTc (duDefs dus_gen) -- Mark these guys to
247 ; return (rn_deriv `plusHsValBinds` rn_gen) }
251 ; ioToTcRn (dumpIfSet_dyn dflags Opt_D_dump_deriv "Derived instances"
252 (ddump_deriving inst_info rn_binds))
254 ; returnM (inst_info, rn_binds)
257 ddump_deriving :: [InstInfo] -> HsValBinds Name -> SDoc
258 ddump_deriving inst_infos extra_binds
259 = vcat (map pprInstInfoDetails inst_infos) $$ ppr extra_binds
261 -----------------------------------------
262 deriveOrdinaryStuff [] -- Short cut
263 = returnM ([], emptyLHsBinds)
265 deriveOrdinaryStuff eqns
266 = do { -- Take the equation list and solve it, to deliver a list of
267 -- solutions, a.k.a. the contexts for the instance decls
268 -- required for the corresponding equations.
269 overlap_flag <- getOverlapFlag
270 ; inst_specs <- solveDerivEqns overlap_flag eqns
272 -- Generate the InstInfo for each dfun,
273 -- plus any auxiliary bindings it needs
274 ; (inst_infos, aux_binds_s) <- mapAndUnzipM genInst inst_specs
276 -- Generate any extra not-one-inst-decl-specific binds,
277 -- notably "con2tag" and/or "tag2con" functions.
278 ; extra_binds <- genTaggeryBinds inst_infos
281 ; returnM (map fst inst_infos,
282 unionManyBags (extra_binds : aux_binds_s))
285 -----------------------------------------
286 mkGenericBinds tycl_decls
287 = do { tcs <- mapM tcLookupTyCon
289 L _ (TyData { tcdLName = L _ tc_name }) <- tycl_decls]
290 -- We are only interested in the data type declarations
291 ; return (unionManyBags [ mkTyConGenericBinds tc |
292 tc <- tcs, tyConHasGenerics tc ]) }
293 -- And then only in the ones whose 'has-generics' flag is on
297 %************************************************************************
299 \subsection[TcDeriv-eqns]{Forming the equations}
301 %************************************************************************
303 @makeDerivEqns@ fishes around to find the info about needed derived
304 instances. Complicating factors:
307 We can only derive @Enum@ if the data type is an enumeration
308 type (all nullary data constructors).
311 We can only derive @Ix@ if the data type is an enumeration {\em
312 or} has just one data constructor (e.g., tuples).
315 [See Appendix~E in the Haskell~1.2 report.] This code here deals w/
318 Note [Newtype deriving superclasses]
319 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
320 The 'tys' here come from the partial application in the deriving
321 clause. The last arg is the new instance type.
323 We must pass the superclasses; the newtype might be an instance
324 of them in a different way than the representation type
325 E.g. newtype Foo a = Foo a deriving( Show, Num, Eq )
326 Then the Show instance is not done via isomorphism; it shows
328 The Num instance is derived via isomorphism, but the Show superclass
329 dictionary must the Show instance for Foo, *not* the Show dictionary
330 gotten from the Num dictionary. So we must build a whole new dictionary
331 not just use the Num one. The instance we want is something like:
332 instance (Num a, Show (Foo a), Eq (Foo a)) => Num (Foo a) where
335 There may be a coercion needed which we get from the tycon for the newtype
336 when the dict is constructed in TcInstDcls.tcInstDecl2
340 makeDerivEqns :: [LTyClDecl Name]
342 -> TcM ([DerivEqn], -- Ordinary derivings
343 [InstInfo]) -- Special newtype derivings
345 makeDerivEqns tycl_decls deriv_decls
346 = do { eqns1 <- mapM deriveTyData $
347 [ (p,d) | d@(L _ (TyData {tcdDerivs = Just preds})) <- tycl_decls
349 ; eqns2 <- mapM deriveStandalone deriv_decls
350 ; return ([eqn | (Just eqn, _) <- eqns1 ++ eqns2],
351 [inst | (_, Just inst) <- eqns1 ++ eqns2]) }
353 ------------------------------------------------------------------
354 deriveStandalone :: LDerivDecl Name -> TcM (Maybe DerivEqn, Maybe InstInfo)
355 -- Standalone deriving declarations
356 -- e.g. derive instance Show T
357 -- Rather like tcLocalInstDecl
358 deriveStandalone (L loc (DerivDecl deriv_ty))
360 addErrCtxt (standaloneCtxt deriv_ty) $
361 do { (tvs, theta, tau) <- tcHsInstHead deriv_ty
362 ; (cls, inst_tys) <- checkValidInstHead tau
363 ; let cls_tys = take (length inst_tys - 1) inst_tys
364 inst_ty = last inst_tys
366 ; mkEqnHelp StandAloneDerivOrigin tvs cls cls_tys inst_ty }
368 ------------------------------------------------------------------
369 deriveTyData :: (LHsType Name, LTyClDecl Name) -> TcM (Maybe DerivEqn, Maybe InstInfo)
370 deriveTyData (deriv_pred, L loc decl@(TyData { tcdLName = L _ tycon_name,
371 tcdTyVars = tv_names,
372 tcdTyPats = ty_pats }))
375 do { let hs_ty_args = ty_pats `orElse` map (nlHsTyVar . hsLTyVarName) tv_names
376 hs_app = nlHsTyConApp tycon_name hs_ty_args
377 -- We get kinding info for the tyvars by typechecking (T a b)
378 -- Hence forming a tycon application and then dis-assembling it
379 ; (tvs, tc_app) <- tcHsQuantifiedType tv_names hs_app
380 ; tcExtendTyVarEnv tvs $ -- Deriving preds may (now) mention
381 -- the type variables for the type constructor
382 do { (deriv_tvs, cls, cls_tys) <- tcHsDeriv deriv_pred
383 -- The "deriv_pred" is a LHsType to take account of the fact that for
384 -- newtype deriving we allow deriving (forall a. C [a]).
385 ; mkEqnHelp DerivOrigin (tvs++deriv_tvs) cls cls_tys tc_app } }
386 deriveTyData (deriv_pred, other_decl)
387 = panic "derivTyData" -- Caller ensures that only TyData can happen
389 ------------------------------------------------------------------
390 mkEqnHelp orig tvs cls cls_tys tc_app
391 | Just (tycon, tc_args) <- tcSplitTyConApp_maybe tc_app
392 = do { -- Make tc_app saturated, because that's what the
393 -- mkDataTypeEqn things expect
394 -- It might not be saturated in the standalone deriving case
395 -- derive instance Monad (T a)
396 let extra_tvs = dropList tc_args (tyConTyVars tycon)
397 full_tc_args = tc_args ++ mkTyVarTys extra_tvs
398 full_tvs = tvs ++ extra_tvs
400 ; (rep_tc, rep_tc_args) <- tcLookupFamInstExact tycon full_tc_args
402 ; gla_exts <- doptM Opt_GlasgowExts
403 ; overlap_flag <- getOverlapFlag
405 -- Be careful to test rep_tc here: in the case of families, we want
406 -- to check the instance tycon, not the family tycon
407 ; if isDataTyCon rep_tc then
408 mkDataTypeEqn orig gla_exts full_tvs cls cls_tys
409 tycon full_tc_args rep_tc rep_tc_args
411 mkNewTypeEqn orig gla_exts overlap_flag full_tvs cls cls_tys
412 tycon full_tc_args rep_tc rep_tc_args }
414 = baleOut (derivingThingErr cls cls_tys tc_app
415 (ptext SLIT("Last argument of the instance must be a type application")))
417 baleOut err = addErrTc err >> returnM (Nothing, Nothing)
420 Auxiliary lookup wrapper which requires that looked up family instances are
424 tcLookupFamInstExact :: TyCon -> [Type] -> TcM (TyCon, [Type])
425 tcLookupFamInstExact tycon tys
426 = do { result@(rep_tycon, rep_tys) <- tcLookupFamInst tycon tys
427 ; let { tvs = map (Type.getTyVar
428 "TcDeriv.tcLookupFamInstExact")
430 ; variable_only_subst = all Type.isTyVarTy rep_tys &&
431 sizeVarSet (mkVarSet tvs) == length tvs
432 -- renaming may have no repetitions
434 ; unless variable_only_subst $
435 famInstNotFound tycon tys [result]
442 %************************************************************************
446 %************************************************************************
449 mkDataTypeEqn orig gla_exts tvs cls cls_tys tycon tc_args rep_tc rep_tc_args
450 | Just err <- checkSideConditions gla_exts cls cls_tys rep_tc
451 -- NB: pass the *representation* tycon to checkSideConditions
452 = baleOut (derivingThingErr cls cls_tys (mkTyConApp tycon tc_args) err)
455 = ASSERT( null cls_tys )
456 do { loc <- getSrcSpanM
457 ; eqn <- mk_data_eqn loc orig tvs cls tycon tc_args rep_tc rep_tc_args
458 ; return (Just eqn, Nothing) }
460 mk_data_eqn :: SrcSpan -> InstOrigin -> [TyVar] -> Class
461 -> TyCon -> [TcType] -> TyCon -> [TcType] -> TcM DerivEqn
462 mk_data_eqn loc orig tvs cls tycon tc_args rep_tc rep_tc_args
463 | cls `hasKey` typeableClassKey
464 = -- The Typeable class is special in several ways
465 -- data T a b = ... deriving( Typeable )
467 -- instance Typeable2 T where ...
469 -- 1. There are no constraints in the instance
470 -- 2. There are no type variables either
471 -- 3. The actual class we want to generate isn't necessarily
472 -- Typeable; it depends on the arity of the type
473 do { real_clas <- tcLookupClass (typeableClassNames !! tyConArity tycon)
474 ; dfun_name <- new_dfun_name real_clas tycon
475 ; return (loc, orig, dfun_name, [], real_clas, mkTyConApp tycon [], []) }
478 = do { dfun_name <- new_dfun_name cls tycon
479 ; let ordinary_constraints
480 = [ mkClassPred cls [arg_ty]
481 | data_con <- tyConDataCons rep_tc,
482 arg_ty <- dataConInstOrigArgTys data_con rep_tc_args,
483 not (isUnLiftedType arg_ty) ] -- No constraints for unlifted types?
485 tiresome_subst = zipTopTvSubst (tyConTyVars rep_tc) rep_tc_args
486 stupid_constraints = substTheta tiresome_subst (tyConStupidTheta rep_tc)
487 -- see note [Data decl contexts] above
489 ; return (loc, orig, dfun_name, tvs, cls, mkTyConApp tycon tc_args,
490 stupid_constraints ++ ordinary_constraints)
493 ------------------------------------------------------------------
494 -- Check side conditions that dis-allow derivability for particular classes
495 -- This is *apart* from the newtype-deriving mechanism
497 -- Here we get the representation tycon in case of family instances as it has
498 -- the data constructors - but we need to be careful to fall back to the
499 -- family tycon (with indexes) in error messages.
501 checkSideConditions :: Bool -> Class -> [TcType] -> TyCon -> Maybe SDoc
502 checkSideConditions gla_exts cls cls_tys rep_tc
504 = Just ty_args_why -- e.g. deriving( Foo s )
506 = case [cond | (key,cond) <- sideConditions, key == getUnique cls] of
507 [] -> Just (non_std_why cls)
508 [cond] -> cond (gla_exts, rep_tc)
509 other -> pprPanic "checkSideConditions" (ppr cls)
511 ty_args_why = quotes (ppr (mkClassPred cls cls_tys)) <+> ptext SLIT("is not a class")
513 non_std_why cls = quotes (ppr cls) <+> ptext SLIT("is not a derivable class")
515 sideConditions :: [(Unique, Condition)]
517 = [ (eqClassKey, cond_std),
518 (ordClassKey, cond_std),
519 (readClassKey, cond_std),
520 (showClassKey, cond_std),
521 (enumClassKey, cond_std `andCond` cond_isEnumeration),
522 (ixClassKey, cond_std `andCond` (cond_isEnumeration `orCond` cond_isProduct)),
523 (boundedClassKey, cond_std `andCond` (cond_isEnumeration `orCond` cond_isProduct)),
524 (typeableClassKey, cond_glaExts `andCond` cond_typeableOK),
525 (dataClassKey, cond_glaExts `andCond` cond_std)
528 type Condition = (Bool, TyCon) -> Maybe SDoc
529 -- Bool is gla-exts flag
530 -- TyCon is the *representation* tycon if the
531 -- data type is an indexed one
534 orCond :: Condition -> Condition -> Condition
537 Nothing -> Nothing -- c1 succeeds
538 Just x -> case c2 tc of -- c1 fails
540 Just y -> Just (x $$ ptext SLIT(" and") $$ y)
543 andCond c1 c2 tc = case c1 tc of
544 Nothing -> c2 tc -- c1 succeeds
545 Just x -> Just x -- c1 fails
547 cond_std :: Condition
548 cond_std (gla_exts, rep_tc)
549 | any (not . isVanillaDataCon) data_cons = Just existential_why
550 | null data_cons = Just no_cons_why
551 | otherwise = Nothing
553 data_cons = tyConDataCons rep_tc
554 no_cons_why = quotes (pprSourceTyCon rep_tc) <+>
555 ptext SLIT("has no data constructors")
556 existential_why = quotes (pprSourceTyCon rep_tc) <+>
557 ptext SLIT("has non-Haskell-98 constructor(s)")
559 cond_isEnumeration :: Condition
560 cond_isEnumeration (gla_exts, rep_tc)
561 | isEnumerationTyCon rep_tc = Nothing
562 | otherwise = Just why
564 why = quotes (pprSourceTyCon rep_tc) <+>
565 ptext SLIT("has non-nullary constructors")
567 cond_isProduct :: Condition
568 cond_isProduct (gla_exts, rep_tc)
569 | isProductTyCon rep_tc = Nothing
570 | otherwise = Just why
572 why = quotes (pprSourceTyCon rep_tc) <+>
573 ptext SLIT("has more than one constructor")
575 cond_typeableOK :: Condition
576 -- OK for Typeable class
577 -- Currently: (a) args all of kind *
578 -- (b) 7 or fewer args
579 cond_typeableOK (gla_exts, rep_tc)
580 | tyConArity rep_tc > 7 = Just too_many
581 | not (all (isSubArgTypeKind . tyVarKind) (tyConTyVars rep_tc))
583 | isFamInstTyCon rep_tc = Just fam_inst -- no Typable for family insts
584 | otherwise = Nothing
586 too_many = quotes (pprSourceTyCon rep_tc) <+>
587 ptext SLIT("has too many arguments")
588 bad_kind = quotes (pprSourceTyCon rep_tc) <+>
589 ptext SLIT("has arguments of kind other than `*'")
590 fam_inst = quotes (pprSourceTyCon rep_tc) <+>
591 ptext SLIT("is a type family")
593 cond_glaExts :: Condition
594 cond_glaExts (gla_exts, _rep_tc) | gla_exts = Nothing
595 | otherwise = Just why
597 why = ptext SLIT("You need -fglasgow-exts to derive an instance for this class")
599 std_class_via_iso clas -- These standard classes can be derived for a newtype
600 -- using the isomorphism trick *even if no -fglasgow-exts*
601 = classKey clas `elem` [eqClassKey, ordClassKey, ixClassKey, boundedClassKey]
602 -- Not Read/Show because they respect the type
603 -- Not Enum, because newtypes are never in Enum
606 new_dfun_name clas tycon -- Just a simple wrapper
607 = newDFunName clas [mkTyConApp tycon []] (getSrcSpan tycon)
608 -- The type passed to newDFunName is only used to generate
609 -- a suitable string; hence the empty type arg list
613 %************************************************************************
617 %************************************************************************
620 mkNewTypeEqn orig gla_exts overlap_flag tvs cls cls_tys
622 rep_tycon rep_tc_args
623 | can_derive_via_isomorphism && (gla_exts || std_class_via_iso cls)
624 = do { traceTc (text "newtype deriving:" <+> ppr tycon <+> ppr rep_tys)
625 ; -- Go ahead and use the isomorphism
626 dfun_name <- new_dfun_name cls tycon
627 ; return (Nothing, Just (InstInfo { iSpec = mk_inst_spec dfun_name,
628 iBinds = NewTypeDerived ntd_info })) }
630 | isNothing mb_std_err -- Use the standard H98 method
631 = do { loc <- getSrcSpanM
632 ; eqn <- mk_data_eqn loc orig tvs cls tycon tc_args rep_tycon rep_tc_args
633 ; return (Just eqn, Nothing) }
635 -- Otherwise we can't derive
636 | gla_exts = baleOut cant_derive_err -- Too hard
637 | otherwise = baleOut std_err -- Just complain about being a non-std instance
639 mb_std_err = checkSideConditions gla_exts cls cls_tys rep_tycon
640 std_err = derivingThingErr cls cls_tys tc_app $
641 vcat [fromJust mb_std_err,
642 ptext SLIT("Try -fglasgow-exts for GHC's newtype-deriving extension")]
644 -- Here is the plan for newtype derivings. We see
645 -- newtype T a1...an = MkT (t ak+1...an) deriving (.., C s1 .. sm, ...)
646 -- where t is a type,
647 -- ak+1...an is a suffix of a1..an, and are all tyars
648 -- ak+1...an do not occur free in t, nor in the s1..sm
649 -- (C s1 ... sm) is a *partial applications* of class C
650 -- with the last parameter missing
651 -- (T a1 .. ak) matches the kind of C's last argument
652 -- (and hence so does t)
654 -- We generate the instance
655 -- instance forall ({a1..ak} u fvs(s1..sm)).
656 -- C s1 .. sm t => C s1 .. sm (T a1...ak)
657 -- where T a1...ap is the partial application of
658 -- the LHS of the correct kind and p >= k
660 -- NB: the variables below are:
661 -- tc_tvs = [a1, ..., an]
662 -- tyvars_to_keep = [a1, ..., ak]
663 -- rep_ty = t ak .. an
664 -- deriv_tvs = fvs(s1..sm) \ tc_tvs
665 -- tys = [s1, ..., sm]
668 -- Running example: newtype T s a = MkT (ST s a) deriving( Monad )
669 -- We generate the instance
670 -- instance Monad (ST s) => Monad (T s) where
672 cls_tyvars = classTyVars cls
673 kind = tyVarKind (last cls_tyvars)
674 -- Kind of the thing we want to instance
675 -- e.g. argument kind of Monad, *->*
677 (arg_kinds, _) = splitKindFunTys kind
678 n_args_to_drop = length arg_kinds
679 -- Want to drop 1 arg from (T s a) and (ST s a)
680 -- to get instance Monad (ST s) => Monad (T s)
682 -- Note [newtype representation]
683 -- Need newTyConRhs *not* newTyConRep to get the representation
684 -- type, because the latter looks through all intermediate newtypes
686 -- newtype B = MkB Int
687 -- newtype A = MkA B deriving( Num )
688 -- We want the Num instance of B, *not* the Num instance of Int,
689 -- when making the Num instance of A!
690 rep_ty = newTyConInstRhs rep_tycon rep_tc_args
691 (rep_fn, rep_ty_args) = tcSplitAppTys rep_ty
693 n_tyargs_to_keep = tyConArity tycon - n_args_to_drop
694 dropped_tc_args = drop n_tyargs_to_keep tc_args
695 dropped_tvs = tyVarsOfTypes dropped_tc_args
697 n_args_to_keep = length rep_ty_args - n_args_to_drop
698 args_to_drop = drop n_args_to_keep rep_ty_args
699 args_to_keep = take n_args_to_keep rep_ty_args
701 rep_fn' = mkAppTys rep_fn args_to_keep
702 rep_tys = cls_tys ++ [rep_fn']
703 rep_pred = mkClassPred cls rep_tys
704 -- rep_pred is the representation dictionary, from where
705 -- we are gong to get all the methods for the newtype
708 tc_app = mkTyConApp tycon (take n_tyargs_to_keep tc_args)
710 -- Next we figure out what superclass dictionaries to use
711 -- See Note [Newtype deriving superclasses] above
713 inst_tys = cls_tys ++ [tc_app]
714 sc_theta = substTheta (zipOpenTvSubst cls_tyvars inst_tys)
717 -- If there are no tyvars, there's no need
718 -- to abstract over the dictionaries we need
719 -- Example: newtype T = MkT Int deriving( C )
720 -- We get the derived instance
723 -- instance C Int => C T
724 dict_tvs = filterOut (`elemVarSet` dropped_tvs) tvs
725 all_preds = rep_pred : sc_theta -- NB: rep_pred comes first
726 (dict_args, ntd_info) | null dict_tvs = ([], Just all_preds)
727 | otherwise = (all_preds, Nothing)
729 -- Finally! Here's where we build the dictionary Id
730 mk_inst_spec dfun_name = mkLocalInstance dfun overlap_flag
732 dfun = mkDictFunId dfun_name dict_tvs dict_args cls inst_tys
734 -------------------------------------------------------------------
735 -- Figuring out whether we can only do this newtype-deriving thing
737 right_arity = length cls_tys + 1 == classArity cls
739 -- Never derive Read,Show,Typeable,Data this way
740 non_iso_classes = [readClassKey, showClassKey, typeableClassKey, dataClassKey]
741 can_derive_via_isomorphism
742 = not (getUnique cls `elem` non_iso_classes)
743 && right_arity -- Well kinded;
744 -- eg not: newtype T ... deriving( ST )
745 -- because ST needs *2* type params
746 && n_tyargs_to_keep >= 0 -- Type constructor has right kind:
747 -- eg not: newtype T = T Int deriving( Monad )
748 && n_args_to_keep >= 0 -- Rep type has right kind:
749 -- eg not: newtype T a = T Int deriving( Monad )
750 && eta_ok -- Eta reduction works
751 && not (isRecursiveTyCon tycon) -- Does not work for recursive tycons:
752 -- newtype A = MkA [A]
754 -- instance Eq [A] => Eq A !!
755 -- Here's a recursive newtype that's actually OK
756 -- newtype S1 = S1 [T1 ()]
757 -- newtype T1 a = T1 (StateT S1 IO a ) deriving( Monad )
758 -- It's currently rejected. Oh well.
759 -- In fact we generate an instance decl that has method of form
760 -- meth @ instTy = meth @ repTy
761 -- (no coerce's). We'd need a coerce if we wanted to handle
762 -- recursive newtypes too
764 -- Check that eta reduction is OK
765 eta_ok = (args_to_drop `tcEqTypes` dropped_tc_args)
766 -- (a) the dropped-off args are identical in the source and rep type
767 -- newtype T a b = MkT (S [a] b) deriving( Monad )
768 -- Here the 'b' must be the same in the rep type (S [a] b)
770 && (tyVarsOfType rep_fn' `disjointVarSet` dropped_tvs)
771 -- (b) the remaining type args do not mention any of the dropped
774 && (tyVarsOfTypes cls_tys `disjointVarSet` dropped_tvs)
775 -- (c) the type class args do not mention any of the dropped type
778 && all isTyVarTy dropped_tc_args
779 -- (d) in case of newtype family instances, the eta-dropped
780 -- arguments must be type variables (not more complex indexes)
782 cant_derive_err = derivingThingErr cls cls_tys tc_app
783 (vcat [ptext SLIT("even with cunning newtype deriving:"),
784 if isRecursiveTyCon tycon then
785 ptext SLIT("the newtype may be recursive")
787 if not right_arity then
788 quotes (ppr (mkClassPred cls cls_tys)) <+> ptext SLIT("does not have arity 1")
790 if not (n_tyargs_to_keep >= 0) then
791 ptext SLIT("the type constructor has wrong kind")
792 else if not (n_args_to_keep >= 0) then
793 ptext SLIT("the representation type has wrong kind")
794 else if not eta_ok then
795 ptext SLIT("the eta-reduction property does not hold")
801 %************************************************************************
803 \subsection[TcDeriv-fixpoint]{Finding the fixed point of \tr{deriving} equations}
805 %************************************************************************
807 A ``solution'' (to one of the equations) is a list of (k,TyVarTy tv)
808 terms, which is the final correct RHS for the corresponding original
812 Each (k,TyVarTy tv) in a solution constrains only a type
816 The (k,TyVarTy tv) pairs in a solution are canonically
817 ordered by sorting on type varible, tv, (major key) and then class, k,
822 solveDerivEqns :: OverlapFlag
824 -> TcM [Instance]-- Solns in same order as eqns.
825 -- This bunch is Absolutely minimal...
827 solveDerivEqns overlap_flag orig_eqns
828 = do { traceTc (text "solveDerivEqns" <+> vcat (map pprDerivEqn orig_eqns))
829 ; iterateDeriv 1 initial_solutions }
831 -- The initial solutions for the equations claim that each
832 -- instance has an empty context; this solution is certainly
833 -- in canonical form.
834 initial_solutions :: [DerivSoln]
835 initial_solutions = [ [] | _ <- orig_eqns ]
837 ------------------------------------------------------------------
838 -- iterateDeriv calculates the next batch of solutions,
839 -- compares it with the current one; finishes if they are the
840 -- same, otherwise recurses with the new solutions.
841 -- It fails if any iteration fails
842 iterateDeriv :: Int -> [DerivSoln] -> TcM [Instance]
843 iterateDeriv n current_solns
844 | n > 20 -- Looks as if we are in an infinite loop
845 -- This can happen if we have -fallow-undecidable-instances
846 -- (See TcSimplify.tcSimplifyDeriv.)
847 = pprPanic "solveDerivEqns: probable loop"
848 (vcat (map pprDerivEqn orig_eqns) $$ ppr current_solns)
851 inst_specs = zipWithEqual "add_solns" mk_inst_spec
852 orig_eqns current_solns
855 -- Extend the inst info from the explicit instance decls
856 -- with the current set of solutions, and simplify each RHS
857 extendLocalInstEnv inst_specs $
858 mappM gen_soln orig_eqns
859 ) `thenM` \ new_solns ->
860 if (current_solns == new_solns) then
863 iterateDeriv (n+1) new_solns
865 ------------------------------------------------------------------
866 gen_soln :: DerivEqn -> TcM [PredType]
867 gen_soln (loc, orig, _, tyvars, clas, inst_ty, deriv_rhs)
869 do { theta <- tcSimplifyDeriv orig tyvars deriv_rhs
870 ; addErrCtxt (derivInstCtxt theta clas [inst_ty]) $
871 do { checkNoErrs (checkValidInstance tyvars theta clas [inst_ty])
872 -- See Note [Deriving context]
873 -- If this fails, don't continue
875 -- Check for a bizarre corner case, when the derived instance decl should
876 -- have form instance C a b => D (T a) where ...
877 -- Note that 'b' isn't a parameter of T. This gives rise to all sorts
878 -- of problems; in particular, it's hard to compare solutions for
879 -- equality when finding the fixpoint. So I just rule it out for now.
880 ; let tv_set = mkVarSet tyvars
881 weird_preds = [pred | pred <- theta, not (tyVarsOfPred pred `subVarSet` tv_set)]
882 ; mapM_ (addErrTc . badDerivedPred) weird_preds
884 -- Claim: the result instance declaration is guaranteed valid
885 -- Hence no need to call:
886 -- checkValidInstance tyvars theta clas inst_tys
887 ; return (sortLe (<=) theta) } } -- Canonicalise before returning the solution
889 ------------------------------------------------------------------
890 mk_inst_spec :: DerivEqn -> DerivSoln -> Instance
891 mk_inst_spec (loc, orig, dfun_name, tyvars, clas, inst_ty, _) theta
892 = mkLocalInstance dfun overlap_flag
894 dfun = mkDictFunId dfun_name tyvars theta clas [inst_ty]
896 extendLocalInstEnv :: [Instance] -> TcM a -> TcM a
897 -- Add new locally-defined instances; don't bother to check
898 -- for functional dependency errors -- that'll happen in TcInstDcls
899 extendLocalInstEnv dfuns thing_inside
900 = do { env <- getGblEnv
901 ; let inst_env' = extendInstEnvList (tcg_inst_env env) dfuns
902 env' = env { tcg_inst_env = inst_env' }
903 ; setGblEnv env' thing_inside }
906 Note [Deriving context]
907 ~~~~~~~~~~~~~~~~~~~~~~~
908 With -fglasgow-exts, we allow things like (C Int a) in the simplified
909 context for a derived instance declaration, because at a use of this
910 instance, we might know that a=Bool, and have an instance for (C Int
913 We nevertheless insist that each predicate meets the termination
914 conditions. If not, the deriving mechanism generates larger and larger
915 constraints. Example:
917 data Seq a = Cons a (Seq (Succ a)) | Nil deriving Show
919 Note the lack of a Show instance for Succ. First we'll generate
920 instance (Show (Succ a), Show a) => Show (Seq a)
922 instance (Show (Succ (Succ a)), Show (Succ a), Show a) => Show (Seq a)
923 and so on. Instead we want to complain of no instance for (Show (Succ a)).
926 %************************************************************************
928 \subsection[TcDeriv-normal-binds]{Bindings for the various classes}
930 %************************************************************************
932 After all the trouble to figure out the required context for the
933 derived instance declarations, all that's left is to chug along to
934 produce them. They will then be shoved into @tcInstDecls2@, which
935 will do all its usual business.
937 There are lots of possibilities for code to generate. Here are
938 various general remarks.
943 We want derived instances of @Eq@ and @Ord@ (both v common) to be
944 ``you-couldn't-do-better-by-hand'' efficient.
947 Deriving @Show@---also pretty common--- should also be reasonable good code.
950 Deriving for the other classes isn't that common or that big a deal.
957 Deriving @Ord@ is done mostly with the 1.3 @compare@ method.
960 Deriving @Eq@ also uses @compare@, if we're deriving @Ord@, too.
963 We {\em normally} generate code only for the non-defaulted methods;
964 there are some exceptions for @Eq@ and (especially) @Ord@...
967 Sometimes we use a @_con2tag_<tycon>@ function, which returns a data
968 constructor's numeric (@Int#@) tag. These are generated by
969 @gen_tag_n_con_binds@, and the heuristic for deciding if one of
970 these is around is given by @hasCon2TagFun@.
972 The examples under the different sections below will make this
976 Much less often (really just for deriving @Ix@), we use a
977 @_tag2con_<tycon>@ function. See the examples.
980 We use the renamer!!! Reason: we're supposed to be
981 producing @LHsBinds Name@ for the methods, but that means
982 producing correctly-uniquified code on the fly. This is entirely
983 possible (the @TcM@ monad has a @UniqueSupply@), but it is painful.
984 So, instead, we produce @MonoBinds RdrName@ then heave 'em through
985 the renamer. What a great hack!
989 -- Generate the InstInfo for the required instance paired with the
990 -- *representation* tycon for that instance,
991 -- plus any auxiliary bindings required
993 -- Representation tycons differ from the tycon in the instance signature in
994 -- case of instances for indexed families.
996 genInst :: Instance -> TcM ((InstInfo, TyCon), LHsBinds RdrName)
998 = do { fix_env <- getFixityEnv
1000 (tyvars,_,clas,[ty]) = instanceHead spec
1001 clas_nm = className clas
1002 (visible_tycon, tyArgs) = tcSplitTyConApp ty
1004 -- In case of a family instance, we need to use the representation
1005 -- tycon (after all, it has the data constructors)
1006 ; (tycon, _) <- tcLookupFamInstExact visible_tycon tyArgs
1007 ; let (meth_binds, aux_binds) = genDerivBinds clas fix_env tycon
1009 -- Bring the right type variables into
1010 -- scope, and rename the method binds
1011 -- It's a bit yukky that we return *renamed* InstInfo, but
1012 -- *non-renamed* auxiliary bindings
1013 ; (rn_meth_binds, _fvs) <- discardWarnings $
1014 bindLocalNames (map Var.varName tyvars) $
1015 rnMethodBinds clas_nm (\n -> []) [] meth_binds
1017 -- Build the InstInfo
1018 ; return ((InstInfo { iSpec = spec,
1019 iBinds = VanillaInst rn_meth_binds [] }, tycon),
1023 genDerivBinds clas fix_env tycon
1024 | className clas `elem` typeableClassNames
1025 = (gen_Typeable_binds tycon, emptyLHsBinds)
1028 = case assocMaybe gen_list (getUnique clas) of
1029 Just gen_fn -> gen_fn fix_env tycon
1030 Nothing -> pprPanic "genDerivBinds: bad derived class" (ppr clas)
1032 gen_list :: [(Unique, FixityEnv -> TyCon -> (LHsBinds RdrName, LHsBinds RdrName))]
1033 gen_list = [(eqClassKey, no_aux_binds (ignore_fix_env gen_Eq_binds))
1034 ,(ordClassKey, no_aux_binds (ignore_fix_env gen_Ord_binds))
1035 ,(enumClassKey, no_aux_binds (ignore_fix_env gen_Enum_binds))
1036 ,(boundedClassKey, no_aux_binds (ignore_fix_env gen_Bounded_binds))
1037 ,(ixClassKey, no_aux_binds (ignore_fix_env gen_Ix_binds))
1038 ,(typeableClassKey,no_aux_binds (ignore_fix_env gen_Typeable_binds))
1039 ,(showClassKey, no_aux_binds gen_Show_binds)
1040 ,(readClassKey, no_aux_binds gen_Read_binds)
1041 ,(dataClassKey, gen_Data_binds)
1044 -- no_aux_binds is used for generators that don't
1045 -- need to produce any auxiliary bindings
1046 no_aux_binds f fix_env tc = (f fix_env tc, emptyLHsBinds)
1047 ignore_fix_env f fix_env tc = f tc
1051 %************************************************************************
1053 \subsection[TcDeriv-taggery-Names]{What con2tag/tag2con functions are available?}
1055 %************************************************************************
1060 con2tag_Foo :: Foo ... -> Int#
1061 tag2con_Foo :: Int -> Foo ... -- easier if Int, not Int#
1062 maxtag_Foo :: Int -- ditto (NB: not unlifted)
1065 We have a @con2tag@ function for a tycon if:
1068 We're deriving @Eq@ and the tycon has nullary data constructors.
1071 Or: we're deriving @Ord@ (unless single-constructor), @Enum@, @Ix@
1072 (enum type only????)
1075 We have a @tag2con@ function for a tycon if:
1078 We're deriving @Enum@, or @Ix@ (enum type only???)
1081 If we have a @tag2con@ function, we also generate a @maxtag@ constant.
1084 genTaggeryBinds :: [(InstInfo, TyCon)] -> TcM (LHsBinds RdrName)
1085 genTaggeryBinds infos
1086 = do { names_so_far <- foldlM do_con2tag [] tycons_of_interest
1087 ; nm_alist_etc <- foldlM do_tag2con names_so_far tycons_of_interest
1088 ; return (listToBag (map gen_tag_n_con_monobind nm_alist_etc)) }
1090 all_CTs = [ (fst (simpleInstInfoClsTy info), tc)
1091 | (info, tc) <- infos]
1092 all_tycons = map snd all_CTs
1093 (tycons_of_interest, _) = removeDups compare all_tycons
1095 do_con2tag acc_Names tycon
1096 | isDataTyCon tycon &&
1097 ((we_are_deriving eqClassKey tycon
1098 && any isNullarySrcDataCon (tyConDataCons tycon))
1099 || (we_are_deriving ordClassKey tycon
1100 && not (isProductTyCon tycon))
1101 || (we_are_deriving enumClassKey tycon)
1102 || (we_are_deriving ixClassKey tycon))
1104 = returnM ((con2tag_RDR tycon, tycon, GenCon2Tag)
1109 do_tag2con acc_Names tycon
1110 | isDataTyCon tycon &&
1111 (we_are_deriving enumClassKey tycon ||
1112 we_are_deriving ixClassKey tycon
1113 && isEnumerationTyCon tycon)
1114 = returnM ( (tag2con_RDR tycon, tycon, GenTag2Con)
1115 : (maxtag_RDR tycon, tycon, GenMaxTag)
1120 we_are_deriving clas_key tycon
1121 = is_in_eqns clas_key tycon all_CTs
1123 is_in_eqns clas_key tycon [] = False
1124 is_in_eqns clas_key tycon ((c,t):cts)
1125 = (clas_key == classKey c && tycon == t)
1126 || is_in_eqns clas_key tycon cts
1130 derivingThingErr clas tys ty why
1131 = sep [hsep [ptext SLIT("Can't make a derived instance of"),
1133 nest 2 (parens why)]
1135 pred = mkClassPred clas (tys ++ [ty])
1137 standaloneCtxt :: LHsType Name -> SDoc
1138 standaloneCtxt ty = ptext SLIT("In the stand-alone deriving instance for") <+> quotes (ppr ty)
1140 derivInstCtxt theta clas inst_tys
1141 = hang (ptext SLIT("In the derived instance:"))
1142 2 (pprThetaArrow theta <+> pprClassPred clas inst_tys)
1143 -- Used for the ...Thetas variants; all top level
1146 = vcat [ptext SLIT("Can't derive instances where the instance context mentions"),
1147 ptext SLIT("type variables that are not data type parameters"),
1148 nest 2 (ptext SLIT("Offending constraint:") <+> ppr pred)]