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