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