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 <- ASSERT( isVanillaDataCon data_con )
483 dataConInstOrigArgTys data_con rep_tc_args,
484 not (isUnLiftedType arg_ty) ] -- No constraints for unlifted types?
486 tiresome_subst = zipTopTvSubst (tyConTyVars rep_tc) rep_tc_args
487 stupid_constraints = substTheta tiresome_subst (tyConStupidTheta rep_tc)
488 -- see note [Data decl contexts] above
490 ; return (loc, orig, dfun_name, tvs, cls, mkTyConApp tycon tc_args,
491 stupid_constraints ++ ordinary_constraints)
494 ------------------------------------------------------------------
495 -- Check side conditions that dis-allow derivability for particular classes
496 -- This is *apart* from the newtype-deriving mechanism
498 -- Here we get the representation tycon in case of family instances as it has
499 -- the data constructors - but we need to be careful to fall back to the
500 -- family tycon (with indexes) in error messages.
502 checkSideConditions :: Bool -> Class -> [TcType] -> TyCon -> Maybe SDoc
503 checkSideConditions gla_exts cls cls_tys rep_tc
505 = Just ty_args_why -- e.g. deriving( Foo s )
507 = case [cond | (key,cond) <- sideConditions, key == getUnique cls] of
508 [] -> Just (non_std_why cls)
509 [cond] -> cond (gla_exts, rep_tc)
510 other -> pprPanic "checkSideConditions" (ppr cls)
512 ty_args_why = quotes (ppr (mkClassPred cls cls_tys)) <+> ptext SLIT("is not a class")
514 non_std_why cls = quotes (ppr cls) <+> ptext SLIT("is not a derivable class")
516 sideConditions :: [(Unique, Condition)]
518 = [ (eqClassKey, cond_std),
519 (ordClassKey, cond_std),
520 (readClassKey, cond_std),
521 (showClassKey, cond_std),
522 (enumClassKey, cond_std `andCond` cond_isEnumeration),
523 (ixClassKey, cond_std `andCond` (cond_isEnumeration `orCond` cond_isProduct)),
524 (boundedClassKey, cond_std `andCond` (cond_isEnumeration `orCond` cond_isProduct)),
525 (typeableClassKey, cond_glaExts `andCond` cond_typeableOK),
526 (dataClassKey, cond_glaExts `andCond` cond_std)
529 type Condition = (Bool, TyCon) -> Maybe SDoc
530 -- Bool is gla-exts flag
531 -- TyCon is the *representation* tycon if the
532 -- data type is an indexed one
535 orCond :: Condition -> Condition -> Condition
538 Nothing -> Nothing -- c1 succeeds
539 Just x -> case c2 tc of -- c1 fails
541 Just y -> Just (x $$ ptext SLIT(" and") $$ y)
544 andCond c1 c2 tc = case c1 tc of
545 Nothing -> c2 tc -- c1 succeeds
546 Just x -> Just x -- c1 fails
548 cond_std :: Condition
549 cond_std (gla_exts, rep_tc)
550 | any (not . isVanillaDataCon) data_cons = Just existential_why
551 | null data_cons = Just no_cons_why
552 | otherwise = Nothing
554 data_cons = tyConDataCons rep_tc
555 no_cons_why = quotes (pprSourceTyCon rep_tc) <+>
556 ptext SLIT("has no data constructors")
557 existential_why = quotes (pprSourceTyCon rep_tc) <+>
558 ptext SLIT("has non-Haskell-98 constructor(s)")
560 cond_isEnumeration :: Condition
561 cond_isEnumeration (gla_exts, rep_tc)
562 | isEnumerationTyCon rep_tc = Nothing
563 | otherwise = Just why
565 why = quotes (pprSourceTyCon rep_tc) <+>
566 ptext SLIT("has non-nullary constructors")
568 cond_isProduct :: Condition
569 cond_isProduct (gla_exts, rep_tc)
570 | isProductTyCon rep_tc = Nothing
571 | otherwise = Just why
573 why = quotes (pprSourceTyCon rep_tc) <+>
574 ptext SLIT("has more than one constructor")
576 cond_typeableOK :: Condition
577 -- OK for Typeable class
578 -- Currently: (a) args all of kind *
579 -- (b) 7 or fewer args
580 cond_typeableOK (gla_exts, rep_tc)
581 | tyConArity rep_tc > 7 = Just too_many
582 | not (all (isSubArgTypeKind . tyVarKind) (tyConTyVars rep_tc))
584 | isFamInstTyCon rep_tc = Just fam_inst -- no Typable for family insts
585 | otherwise = Nothing
587 too_many = quotes (pprSourceTyCon rep_tc) <+>
588 ptext SLIT("has too many arguments")
589 bad_kind = quotes (pprSourceTyCon rep_tc) <+>
590 ptext SLIT("has arguments of kind other than `*'")
591 fam_inst = quotes (pprSourceTyCon rep_tc) <+>
592 ptext SLIT("is a type family")
594 cond_glaExts :: Condition
595 cond_glaExts (gla_exts, _rep_tc) | gla_exts = Nothing
596 | otherwise = Just why
598 why = ptext SLIT("You need -fglasgow-exts to derive an instance for this class")
600 std_class_via_iso clas -- These standard classes can be derived for a newtype
601 -- using the isomorphism trick *even if no -fglasgow-exts*
602 = classKey clas `elem` [eqClassKey, ordClassKey, ixClassKey, boundedClassKey]
603 -- Not Read/Show because they respect the type
604 -- Not Enum, because newtypes are never in Enum
607 new_dfun_name clas tycon -- Just a simple wrapper
608 = newDFunName clas [mkTyConApp tycon []] (getSrcSpan tycon)
609 -- The type passed to newDFunName is only used to generate
610 -- a suitable string; hence the empty type arg list
614 %************************************************************************
618 %************************************************************************
621 mkNewTypeEqn orig gla_exts overlap_flag tvs cls cls_tys
623 rep_tycon rep_tc_args
624 | can_derive_via_isomorphism && (gla_exts || std_class_via_iso cls)
625 = do { traceTc (text "newtype deriving:" <+> ppr tycon <+> ppr rep_tys)
626 ; -- Go ahead and use the isomorphism
627 dfun_name <- new_dfun_name cls tycon
628 ; return (Nothing, Just (InstInfo { iSpec = mk_inst_spec dfun_name,
629 iBinds = NewTypeDerived ntd_info })) }
631 | isNothing mb_std_err -- Use the standard H98 method
632 = do { loc <- getSrcSpanM
633 ; eqn <- mk_data_eqn loc orig tvs cls tycon tc_args rep_tycon rep_tc_args
634 ; return (Just eqn, Nothing) }
636 -- Otherwise we can't derive
637 | gla_exts = baleOut cant_derive_err -- Too hard
638 | otherwise = baleOut std_err -- Just complain about being a non-std instance
640 mb_std_err = checkSideConditions gla_exts cls cls_tys rep_tycon
641 std_err = derivingThingErr cls cls_tys tc_app $
642 vcat [fromJust mb_std_err,
643 ptext SLIT("Try -fglasgow-exts for GHC's newtype-deriving extension")]
645 -- Here is the plan for newtype derivings. We see
646 -- newtype T a1...an = MkT (t ak+1...an) deriving (.., C s1 .. sm, ...)
647 -- where t is a type,
648 -- ak+1...an is a suffix of a1..an, and are all tyars
649 -- ak+1...an do not occur free in t, nor in the s1..sm
650 -- (C s1 ... sm) is a *partial applications* of class C
651 -- with the last parameter missing
652 -- (T a1 .. ak) matches the kind of C's last argument
653 -- (and hence so does t)
655 -- We generate the instance
656 -- instance forall ({a1..ak} u fvs(s1..sm)).
657 -- C s1 .. sm t => C s1 .. sm (T a1...ak)
658 -- where T a1...ap is the partial application of
659 -- the LHS of the correct kind and p >= k
661 -- NB: the variables below are:
662 -- tc_tvs = [a1, ..., an]
663 -- tyvars_to_keep = [a1, ..., ak]
664 -- rep_ty = t ak .. an
665 -- deriv_tvs = fvs(s1..sm) \ tc_tvs
666 -- tys = [s1, ..., sm]
669 -- Running example: newtype T s a = MkT (ST s a) deriving( Monad )
670 -- We generate the instance
671 -- instance Monad (ST s) => Monad (T s) where
673 cls_tyvars = classTyVars cls
674 kind = tyVarKind (last cls_tyvars)
675 -- Kind of the thing we want to instance
676 -- e.g. argument kind of Monad, *->*
678 (arg_kinds, _) = splitKindFunTys kind
679 n_args_to_drop = length arg_kinds
680 -- Want to drop 1 arg from (T s a) and (ST s a)
681 -- to get instance Monad (ST s) => Monad (T s)
683 -- Note [newtype representation]
684 -- Need newTyConRhs *not* newTyConRep to get the representation
685 -- type, because the latter looks through all intermediate newtypes
687 -- newtype B = MkB Int
688 -- newtype A = MkA B deriving( Num )
689 -- We want the Num instance of B, *not* the Num instance of Int,
690 -- when making the Num instance of A!
691 rep_ty = newTyConInstRhs rep_tycon rep_tc_args
692 (rep_fn, rep_ty_args) = tcSplitAppTys rep_ty
694 n_tyargs_to_keep = tyConArity tycon - n_args_to_drop
695 dropped_tc_args = drop n_tyargs_to_keep tc_args
696 dropped_tvs = tyVarsOfTypes dropped_tc_args
698 n_args_to_keep = length rep_ty_args - n_args_to_drop
699 args_to_drop = drop n_args_to_keep rep_ty_args
700 args_to_keep = take n_args_to_keep rep_ty_args
702 rep_fn' = mkAppTys rep_fn args_to_keep
703 rep_tys = cls_tys ++ [rep_fn']
704 rep_pred = mkClassPred cls rep_tys
705 -- rep_pred is the representation dictionary, from where
706 -- we are gong to get all the methods for the newtype
709 tc_app = mkTyConApp tycon (take n_tyargs_to_keep tc_args)
711 -- Next we figure out what superclass dictionaries to use
712 -- See Note [Newtype deriving superclasses] above
714 inst_tys = cls_tys ++ [tc_app]
715 sc_theta = substTheta (zipOpenTvSubst cls_tyvars inst_tys)
718 -- If there are no tyvars, there's no need
719 -- to abstract over the dictionaries we need
720 -- Example: newtype T = MkT Int deriving( C )
721 -- We get the derived instance
724 -- instance C Int => C T
725 dict_tvs = filterOut (`elemVarSet` dropped_tvs) tvs
726 all_preds = rep_pred : sc_theta -- NB: rep_pred comes first
727 (dict_args, ntd_info) | null dict_tvs = ([], Just all_preds)
728 | otherwise = (all_preds, Nothing)
730 -- Finally! Here's where we build the dictionary Id
731 mk_inst_spec dfun_name = mkLocalInstance dfun overlap_flag
733 dfun = mkDictFunId dfun_name dict_tvs dict_args cls inst_tys
735 -------------------------------------------------------------------
736 -- Figuring out whether we can only do this newtype-deriving thing
738 right_arity = length cls_tys + 1 == classArity cls
740 -- Never derive Read,Show,Typeable,Data this way
741 non_iso_classes = [readClassKey, showClassKey, typeableClassKey, dataClassKey]
742 can_derive_via_isomorphism
743 = not (getUnique cls `elem` non_iso_classes)
744 && right_arity -- Well kinded;
745 -- eg not: newtype T ... deriving( ST )
746 -- because ST needs *2* type params
747 && n_tyargs_to_keep >= 0 -- Type constructor has right kind:
748 -- eg not: newtype T = T Int deriving( Monad )
749 && n_args_to_keep >= 0 -- Rep type has right kind:
750 -- eg not: newtype T a = T Int deriving( Monad )
751 && eta_ok -- Eta reduction works
752 && not (isRecursiveTyCon tycon) -- Does not work for recursive tycons:
753 -- newtype A = MkA [A]
755 -- instance Eq [A] => Eq A !!
756 -- Here's a recursive newtype that's actually OK
757 -- newtype S1 = S1 [T1 ()]
758 -- newtype T1 a = T1 (StateT S1 IO a ) deriving( Monad )
759 -- It's currently rejected. Oh well.
760 -- In fact we generate an instance decl that has method of form
761 -- meth @ instTy = meth @ repTy
762 -- (no coerce's). We'd need a coerce if we wanted to handle
763 -- recursive newtypes too
765 -- Check that eta reduction is OK
766 eta_ok = (args_to_drop `tcEqTypes` dropped_tc_args)
767 -- (a) the dropped-off args are identical in the source and rep type
768 -- newtype T a b = MkT (S [a] b) deriving( Monad )
769 -- Here the 'b' must be the same in the rep type (S [a] b)
771 && (tyVarsOfType rep_fn' `disjointVarSet` dropped_tvs)
772 -- (b) the remaining type args do not mention any of the dropped
775 && (tyVarsOfTypes cls_tys `disjointVarSet` dropped_tvs)
776 -- (c) the type class args do not mention any of the dropped type
779 && all isTyVarTy dropped_tc_args
780 -- (d) in case of newtype family instances, the eta-dropped
781 -- arguments must be type variables (not more complex indexes)
783 cant_derive_err = derivingThingErr cls cls_tys tc_app
784 (vcat [ptext SLIT("even with cunning newtype deriving:"),
785 if isRecursiveTyCon tycon then
786 ptext SLIT("the newtype may be recursive")
788 if not right_arity then
789 quotes (ppr (mkClassPred cls cls_tys)) <+> ptext SLIT("does not have arity 1")
791 if not (n_tyargs_to_keep >= 0) then
792 ptext SLIT("the type constructor has wrong kind")
793 else if not (n_args_to_keep >= 0) then
794 ptext SLIT("the representation type has wrong kind")
795 else if not eta_ok then
796 ptext SLIT("the eta-reduction property does not hold")
802 %************************************************************************
804 \subsection[TcDeriv-fixpoint]{Finding the fixed point of \tr{deriving} equations}
806 %************************************************************************
808 A ``solution'' (to one of the equations) is a list of (k,TyVarTy tv)
809 terms, which is the final correct RHS for the corresponding original
813 Each (k,TyVarTy tv) in a solution constrains only a type
817 The (k,TyVarTy tv) pairs in a solution are canonically
818 ordered by sorting on type varible, tv, (major key) and then class, k,
823 solveDerivEqns :: OverlapFlag
825 -> TcM [Instance]-- Solns in same order as eqns.
826 -- This bunch is Absolutely minimal...
828 solveDerivEqns overlap_flag orig_eqns
829 = do { traceTc (text "solveDerivEqns" <+> vcat (map pprDerivEqn orig_eqns))
830 ; iterateDeriv 1 initial_solutions }
832 -- The initial solutions for the equations claim that each
833 -- instance has an empty context; this solution is certainly
834 -- in canonical form.
835 initial_solutions :: [DerivSoln]
836 initial_solutions = [ [] | _ <- orig_eqns ]
838 ------------------------------------------------------------------
839 -- iterateDeriv calculates the next batch of solutions,
840 -- compares it with the current one; finishes if they are the
841 -- same, otherwise recurses with the new solutions.
842 -- It fails if any iteration fails
843 iterateDeriv :: Int -> [DerivSoln] -> TcM [Instance]
844 iterateDeriv n current_solns
845 | n > 20 -- Looks as if we are in an infinite loop
846 -- This can happen if we have -fallow-undecidable-instances
847 -- (See TcSimplify.tcSimplifyDeriv.)
848 = pprPanic "solveDerivEqns: probable loop"
849 (vcat (map pprDerivEqn orig_eqns) $$ ppr current_solns)
852 inst_specs = zipWithEqual "add_solns" mk_inst_spec
853 orig_eqns current_solns
856 -- Extend the inst info from the explicit instance decls
857 -- with the current set of solutions, and simplify each RHS
858 extendLocalInstEnv inst_specs $
859 mappM gen_soln orig_eqns
860 ) `thenM` \ new_solns ->
861 if (current_solns == new_solns) then
864 iterateDeriv (n+1) new_solns
866 ------------------------------------------------------------------
867 gen_soln :: DerivEqn -> TcM [PredType]
868 gen_soln (loc, orig, _, tyvars, clas, inst_ty, deriv_rhs)
870 addErrCtxt (derivInstCtxt clas [inst_ty]) $
871 do { theta <- tcSimplifyDeriv orig tyvars deriv_rhs
872 -- checkValidInstance tyvars theta clas [inst_ty]
873 -- Not necessary; see Note [Exotic derived instance contexts]
876 -- Check for a bizarre corner case, when the derived instance decl should
877 -- have form instance C a b => D (T a) where ...
878 -- Note that 'b' isn't a parameter of T. This gives rise to all sorts
879 -- of problems; in particular, it's hard to compare solutions for
880 -- equality when finding the fixpoint. So I just rule it out for now.
881 ; let tv_set = mkVarSet tyvars
882 weird_preds = [pred | pred <- theta, not (tyVarsOfPred pred `subVarSet` tv_set)]
883 ; mapM_ (addErrTc . badDerivedPred) weird_preds
885 -- Claim: the result instance declaration is guaranteed valid
886 -- Hence no need to call:
887 -- checkValidInstance tyvars theta clas inst_tys
888 ; return (sortLe (<=) theta) } -- Canonicalise before returning the solution
890 ------------------------------------------------------------------
891 mk_inst_spec :: DerivEqn -> DerivSoln -> Instance
892 mk_inst_spec (loc, orig, dfun_name, tyvars, clas, inst_ty, _) theta
893 = mkLocalInstance dfun overlap_flag
895 dfun = mkDictFunId dfun_name tyvars theta clas [inst_ty]
897 extendLocalInstEnv :: [Instance] -> TcM a -> TcM a
898 -- Add new locally-defined instances; don't bother to check
899 -- for functional dependency errors -- that'll happen in TcInstDcls
900 extendLocalInstEnv dfuns thing_inside
901 = do { env <- getGblEnv
902 ; let inst_env' = extendInstEnvList (tcg_inst_env env) dfuns
903 env' = env { tcg_inst_env = inst_env' }
904 ; setGblEnv env' thing_inside }
908 %************************************************************************
910 \subsection[TcDeriv-normal-binds]{Bindings for the various classes}
912 %************************************************************************
914 After all the trouble to figure out the required context for the
915 derived instance declarations, all that's left is to chug along to
916 produce them. They will then be shoved into @tcInstDecls2@, which
917 will do all its usual business.
919 There are lots of possibilities for code to generate. Here are
920 various general remarks.
925 We want derived instances of @Eq@ and @Ord@ (both v common) to be
926 ``you-couldn't-do-better-by-hand'' efficient.
929 Deriving @Show@---also pretty common--- should also be reasonable good code.
932 Deriving for the other classes isn't that common or that big a deal.
939 Deriving @Ord@ is done mostly with the 1.3 @compare@ method.
942 Deriving @Eq@ also uses @compare@, if we're deriving @Ord@, too.
945 We {\em normally} generate code only for the non-defaulted methods;
946 there are some exceptions for @Eq@ and (especially) @Ord@...
949 Sometimes we use a @_con2tag_<tycon>@ function, which returns a data
950 constructor's numeric (@Int#@) tag. These are generated by
951 @gen_tag_n_con_binds@, and the heuristic for deciding if one of
952 these is around is given by @hasCon2TagFun@.
954 The examples under the different sections below will make this
958 Much less often (really just for deriving @Ix@), we use a
959 @_tag2con_<tycon>@ function. See the examples.
962 We use the renamer!!! Reason: we're supposed to be
963 producing @LHsBinds Name@ for the methods, but that means
964 producing correctly-uniquified code on the fly. This is entirely
965 possible (the @TcM@ monad has a @UniqueSupply@), but it is painful.
966 So, instead, we produce @MonoBinds RdrName@ then heave 'em through
967 the renamer. What a great hack!
971 -- Generate the InstInfo for the required instance paired with the
972 -- *representation* tycon for that instance,
973 -- plus any auxiliary bindings required
975 -- Representation tycons differ from the tycon in the instance signature in
976 -- case of instances for indexed families.
978 genInst :: Instance -> TcM ((InstInfo, TyCon), LHsBinds RdrName)
980 = do { fix_env <- getFixityEnv
982 (tyvars,_,clas,[ty]) = instanceHead spec
983 clas_nm = className clas
984 (visible_tycon, tyArgs) = tcSplitTyConApp ty
986 -- In case of a family instance, we need to use the representation
987 -- tycon (after all, it has the data constructors)
988 ; (tycon, _) <- tcLookupFamInstExact visible_tycon tyArgs
989 ; let (meth_binds, aux_binds) = genDerivBinds clas fix_env tycon
991 -- Bring the right type variables into
992 -- scope, and rename the method binds
993 -- It's a bit yukky that we return *renamed* InstInfo, but
994 -- *non-renamed* auxiliary bindings
995 ; (rn_meth_binds, _fvs) <- discardWarnings $
996 bindLocalNames (map Var.varName tyvars) $
997 rnMethodBinds clas_nm (\n -> []) [] meth_binds
999 -- Build the InstInfo
1000 ; return ((InstInfo { iSpec = spec,
1001 iBinds = VanillaInst rn_meth_binds [] }, tycon),
1005 genDerivBinds clas fix_env tycon
1006 | className clas `elem` typeableClassNames
1007 = (gen_Typeable_binds tycon, emptyLHsBinds)
1010 = case assocMaybe gen_list (getUnique clas) of
1011 Just gen_fn -> gen_fn fix_env tycon
1012 Nothing -> pprPanic "genDerivBinds: bad derived class" (ppr clas)
1014 gen_list :: [(Unique, FixityEnv -> TyCon -> (LHsBinds RdrName, LHsBinds RdrName))]
1015 gen_list = [(eqClassKey, no_aux_binds (ignore_fix_env gen_Eq_binds))
1016 ,(ordClassKey, no_aux_binds (ignore_fix_env gen_Ord_binds))
1017 ,(enumClassKey, no_aux_binds (ignore_fix_env gen_Enum_binds))
1018 ,(boundedClassKey, no_aux_binds (ignore_fix_env gen_Bounded_binds))
1019 ,(ixClassKey, no_aux_binds (ignore_fix_env gen_Ix_binds))
1020 ,(typeableClassKey,no_aux_binds (ignore_fix_env gen_Typeable_binds))
1021 ,(showClassKey, no_aux_binds gen_Show_binds)
1022 ,(readClassKey, no_aux_binds gen_Read_binds)
1023 ,(dataClassKey, gen_Data_binds)
1026 -- no_aux_binds is used for generators that don't
1027 -- need to produce any auxiliary bindings
1028 no_aux_binds f fix_env tc = (f fix_env tc, emptyLHsBinds)
1029 ignore_fix_env f fix_env tc = f tc
1033 %************************************************************************
1035 \subsection[TcDeriv-taggery-Names]{What con2tag/tag2con functions are available?}
1037 %************************************************************************
1042 con2tag_Foo :: Foo ... -> Int#
1043 tag2con_Foo :: Int -> Foo ... -- easier if Int, not Int#
1044 maxtag_Foo :: Int -- ditto (NB: not unlifted)
1047 We have a @con2tag@ function for a tycon if:
1050 We're deriving @Eq@ and the tycon has nullary data constructors.
1053 Or: we're deriving @Ord@ (unless single-constructor), @Enum@, @Ix@
1054 (enum type only????)
1057 We have a @tag2con@ function for a tycon if:
1060 We're deriving @Enum@, or @Ix@ (enum type only???)
1063 If we have a @tag2con@ function, we also generate a @maxtag@ constant.
1066 genTaggeryBinds :: [(InstInfo, TyCon)] -> TcM (LHsBinds RdrName)
1067 genTaggeryBinds infos
1068 = do { names_so_far <- foldlM do_con2tag [] tycons_of_interest
1069 ; nm_alist_etc <- foldlM do_tag2con names_so_far tycons_of_interest
1070 ; return (listToBag (map gen_tag_n_con_monobind nm_alist_etc)) }
1072 all_CTs = [ (fst (simpleInstInfoClsTy info), tc)
1073 | (info, tc) <- infos]
1074 all_tycons = map snd all_CTs
1075 (tycons_of_interest, _) = removeDups compare all_tycons
1077 do_con2tag acc_Names tycon
1078 | isDataTyCon tycon &&
1079 ((we_are_deriving eqClassKey tycon
1080 && any isNullarySrcDataCon (tyConDataCons tycon))
1081 || (we_are_deriving ordClassKey tycon
1082 && not (isProductTyCon tycon))
1083 || (we_are_deriving enumClassKey tycon)
1084 || (we_are_deriving ixClassKey tycon))
1086 = returnM ((con2tag_RDR tycon, tycon, GenCon2Tag)
1091 do_tag2con acc_Names tycon
1092 | isDataTyCon tycon &&
1093 (we_are_deriving enumClassKey tycon ||
1094 we_are_deriving ixClassKey tycon
1095 && isEnumerationTyCon tycon)
1096 = returnM ( (tag2con_RDR tycon, tycon, GenTag2Con)
1097 : (maxtag_RDR tycon, tycon, GenMaxTag)
1102 we_are_deriving clas_key tycon
1103 = is_in_eqns clas_key tycon all_CTs
1105 is_in_eqns clas_key tycon [] = False
1106 is_in_eqns clas_key tycon ((c,t):cts)
1107 = (clas_key == classKey c && tycon == t)
1108 || is_in_eqns clas_key tycon cts
1112 derivingThingErr clas tys ty why
1113 = sep [hsep [ptext SLIT("Can't make a derived instance of"),
1115 nest 2 (parens why)]
1117 pred = mkClassPred clas (tys ++ [ty])
1119 standaloneCtxt :: LHsType Name -> SDoc
1120 standaloneCtxt ty = ptext SLIT("In the stand-alone deriving instance for") <+> quotes (ppr ty)
1122 derivInstCtxt clas inst_tys
1123 = ptext SLIT("When deriving the instance for") <+> parens (pprClassPred clas inst_tys)
1126 = vcat [ptext SLIT("Can't derive instances where the instance context mentions"),
1127 ptext SLIT("type variables that are not data type parameters"),
1128 nest 2 (ptext SLIT("Offending constraint:") <+> ppr pred)]