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
52 %************************************************************************
54 \subsection[TcDeriv-intro]{Introduction to how we do deriving}
56 %************************************************************************
60 data T a b = C1 (Foo a) (Bar b)
65 [NOTE: See end of these comments for what to do with
66 data (C a, D b) => T a b = ...
69 We want to come up with an instance declaration of the form
71 instance (Ping a, Pong b, ...) => Eq (T a b) where
74 It is pretty easy, albeit tedious, to fill in the code "...". The
75 trick is to figure out what the context for the instance decl is,
76 namely @Ping@, @Pong@ and friends.
78 Let's call the context reqd for the T instance of class C at types
79 (a,b, ...) C (T a b). Thus:
81 Eq (T a b) = (Ping a, Pong b, ...)
83 Now we can get a (recursive) equation from the @data@ decl:
85 Eq (T a b) = Eq (Foo a) u Eq (Bar b) -- From C1
86 u Eq (T b a) u Eq Int -- From C2
87 u Eq (T a a) -- From C3
89 Foo and Bar may have explicit instances for @Eq@, in which case we can
90 just substitute for them. Alternatively, either or both may have
91 their @Eq@ instances given by @deriving@ clauses, in which case they
92 form part of the system of equations.
94 Now all we need do is simplify and solve the equations, iterating to
95 find the least fixpoint. Notice that the order of the arguments can
96 switch around, as here in the recursive calls to T.
98 Let's suppose Eq (Foo a) = Eq a, and Eq (Bar b) = Ping b.
102 Eq (T a b) = {} -- The empty set
105 Eq (T a b) = Eq (Foo a) u Eq (Bar b) -- From C1
106 u Eq (T b a) u Eq Int -- From C2
107 u Eq (T a a) -- From C3
109 After simplification:
110 = Eq a u Ping b u {} u {} u {}
115 Eq (T a b) = Eq (Foo a) u Eq (Bar b) -- From C1
116 u Eq (T b a) u Eq Int -- From C2
117 u Eq (T a a) -- From C3
119 After simplification:
124 = Eq a u Ping b u Eq b u Ping a
126 The next iteration gives the same result, so this is the fixpoint. We
127 need to make a canonical form of the RHS to ensure convergence. We do
128 this by simplifying the RHS to a form in which
130 - the classes constrain only tyvars
131 - the list is sorted by tyvar (major key) and then class (minor key)
132 - no duplicates, of course
134 So, here are the synonyms for the ``equation'' structures:
137 type DerivRhs = ThetaType
138 type DerivSoln = DerivRhs
139 type DerivEqn = (SrcSpan, InstOrigin, Name, [TyVar], Class, Type, DerivRhs)
140 -- (span, orig, df, tvs, C, ty, rhs)
141 -- implies a dfun declaration of the form
142 -- df :: forall tvs. rhs => C ty
143 -- The Name is the name for the DFun we'll build
144 -- The tyvars bind all the variables in the RHS
145 -- For family indexes, the tycon is the *family* tycon
146 -- (not the representation tycon)
148 pprDerivEqn :: DerivEqn -> SDoc
149 pprDerivEqn (l, _, n, tvs, c, ty, rhs)
150 = parens (hsep [ppr l, ppr n, ppr tvs, ppr c, ppr ty]
151 <+> equals <+> ppr rhs)
155 [Data decl contexts] A note about contexts on data decls
156 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
159 data (RealFloat a) => Complex a = !a :+ !a deriving( Read )
161 We will need an instance decl like:
163 instance (Read a, RealFloat a) => Read (Complex a) where
166 The RealFloat in the context is because the read method for Complex is bound
167 to construct a Complex, and doing that requires that the argument type is
170 But this ain't true for Show, Eq, Ord, etc, since they don't construct
171 a Complex; they only take them apart.
173 Our approach: identify the offending classes, and add the data type
174 context to the instance decl. The "offending classes" are
178 FURTHER NOTE ADDED March 2002. In fact, Haskell98 now requires that
179 pattern matching against a constructor from a data type with a context
180 gives rise to the constraints for that context -- or at least the thinned
181 version. So now all classes are "offending".
188 newtype T = T Char deriving( C [a] )
190 Notice the free 'a' in the deriving. We have to fill this out to
191 newtype T = T Char deriving( forall a. C [a] )
193 And then translate it to:
194 instance C [a] Char => C [a] T where ...
199 %************************************************************************
201 \subsection[TcDeriv-driver]{Top-level function for \tr{derivings}}
203 %************************************************************************
206 tcDeriving :: [LTyClDecl Name] -- All type constructors
207 -> [LDerivDecl Name] -- All stand-alone deriving declarations
208 -> TcM ([InstInfo], -- The generated "instance decls"
209 HsValBinds Name) -- Extra generated top-level bindings
211 tcDeriving tycl_decls deriv_decls
212 = recoverM (returnM ([], emptyValBindsOut)) $
213 do { -- Fish the "deriving"-related information out of the TcEnv
214 -- and make the necessary "equations".
215 ; (ordinary_eqns, newtype_inst_info) <- makeDerivEqns tycl_decls deriv_decls
217 ; (ordinary_inst_info, deriv_binds)
218 <- extendLocalInstEnv (map iSpec newtype_inst_info) $
219 deriveOrdinaryStuff ordinary_eqns
220 -- Add the newtype-derived instances to the inst env
221 -- before tacking the "ordinary" ones
223 ; let inst_info = newtype_inst_info ++ ordinary_inst_info
225 -- If we are compiling a hs-boot file,
226 -- don't generate any derived bindings
227 ; is_boot <- tcIsHsBoot
229 return (inst_info, emptyValBindsOut)
233 -- Generate the generic to/from functions from each type declaration
234 ; gen_binds <- mkGenericBinds tycl_decls
236 -- Rename these extra bindings, discarding warnings about unused bindings etc
237 -- Set -fglasgow exts so that we can have type signatures in patterns,
238 -- which is used in the generic binds
240 <- discardWarnings $ setOptM Opt_GlasgowExts $ do
241 { (rn_deriv, _dus1) <- rnTopBinds (ValBindsIn deriv_binds [])
242 ; (rn_gen, dus_gen) <- rnTopBinds (ValBindsIn gen_binds [])
243 ; keepAliveSetTc (duDefs dus_gen) -- Mark these guys to
245 ; return (rn_deriv `plusHsValBinds` rn_gen) }
249 ; ioToTcRn (dumpIfSet_dyn dflags Opt_D_dump_deriv "Derived instances"
250 (ddump_deriving inst_info rn_binds))
252 ; returnM (inst_info, rn_binds)
255 ddump_deriving :: [InstInfo] -> HsValBinds Name -> SDoc
256 ddump_deriving inst_infos extra_binds
257 = vcat (map pprInstInfoDetails inst_infos) $$ ppr extra_binds
259 -----------------------------------------
260 deriveOrdinaryStuff [] -- Short cut
261 = returnM ([], emptyLHsBinds)
263 deriveOrdinaryStuff eqns
264 = do { -- Take the equation list and solve it, to deliver a list of
265 -- solutions, a.k.a. the contexts for the instance decls
266 -- required for the corresponding equations.
267 overlap_flag <- getOverlapFlag
268 ; inst_specs <- solveDerivEqns overlap_flag eqns
270 -- Generate the InstInfo for each dfun,
271 -- plus any auxiliary bindings it needs
272 ; (inst_infos, aux_binds_s) <- mapAndUnzipM genInst inst_specs
274 -- Generate any extra not-one-inst-decl-specific binds,
275 -- notably "con2tag" and/or "tag2con" functions.
276 ; extra_binds <- genTaggeryBinds inst_infos
279 ; returnM (map fst inst_infos,
280 unionManyBags (extra_binds : aux_binds_s))
283 -----------------------------------------
284 mkGenericBinds tycl_decls
285 = do { tcs <- mapM tcLookupTyCon
287 L _ (TyData { tcdLName = L _ tc_name }) <- tycl_decls]
288 -- We are only interested in the data type declarations
289 ; return (unionManyBags [ mkTyConGenericBinds tc |
290 tc <- tcs, tyConHasGenerics tc ]) }
291 -- And then only in the ones whose 'has-generics' flag is on
295 %************************************************************************
297 \subsection[TcDeriv-eqns]{Forming the equations}
299 %************************************************************************
301 @makeDerivEqns@ fishes around to find the info about needed derived
302 instances. Complicating factors:
305 We can only derive @Enum@ if the data type is an enumeration
306 type (all nullary data constructors).
309 We can only derive @Ix@ if the data type is an enumeration {\em
310 or} has just one data constructor (e.g., tuples).
313 [See Appendix~E in the Haskell~1.2 report.] This code here deals w/
316 Note [Newtype deriving superclasses]
317 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
318 The 'tys' here come from the partial application in the deriving
319 clause. The last arg is the new instance type.
321 We must pass the superclasses; the newtype might be an instance
322 of them in a different way than the representation type
323 E.g. newtype Foo a = Foo a deriving( Show, Num, Eq )
324 Then the Show instance is not done via isomorphism; it shows
326 The Num instance is derived via isomorphism, but the Show superclass
327 dictionary must the Show instance for Foo, *not* the Show dictionary
328 gotten from the Num dictionary. So we must build a whole new dictionary
329 not just use the Num one. The instance we want is something like:
330 instance (Num a, Show (Foo a), Eq (Foo a)) => Num (Foo a) where
333 There may be a coercion needed which we get from the tycon for the newtype
334 when the dict is constructed in TcInstDcls.tcInstDecl2
338 makeDerivEqns :: [LTyClDecl Name]
340 -> TcM ([DerivEqn], -- Ordinary derivings
341 [InstInfo]) -- Special newtype derivings
343 makeDerivEqns tycl_decls deriv_decls
344 = do { eqns1 <- mapM deriveTyData $
345 [ (p,d) | d@(L _ (TyData {tcdDerivs = Just preds})) <- tycl_decls
347 ; eqns2 <- mapM deriveStandalone deriv_decls
348 ; return ([eqn | (Just eqn, _) <- eqns1 ++ eqns2],
349 [inst | (_, Just inst) <- eqns1 ++ eqns2]) }
351 ------------------------------------------------------------------
352 deriveStandalone :: LDerivDecl Name -> TcM (Maybe DerivEqn, Maybe InstInfo)
353 -- Standalone deriving declarations
354 -- e.g. derive instance Show T
355 -- Rather like tcLocalInstDecl
356 deriveStandalone (L loc (DerivDecl deriv_ty))
358 addErrCtxt (standaloneCtxt deriv_ty) $
359 do { (tvs, theta, tau) <- tcHsInstHead deriv_ty
360 ; (cls, inst_tys) <- checkValidInstHead tau
361 ; let cls_tys = take (length inst_tys - 1) inst_tys
362 inst_ty = last inst_tys
364 ; mkEqnHelp StandAloneDerivOrigin tvs cls cls_tys inst_ty }
366 ------------------------------------------------------------------
367 deriveTyData :: (LHsType Name, LTyClDecl Name) -> TcM (Maybe DerivEqn, Maybe InstInfo)
368 deriveTyData (deriv_pred, L loc decl@(TyData { tcdLName = L _ tycon_name,
369 tcdTyVars = tv_names,
370 tcdTyPats = ty_pats }))
373 do { let hs_ty_args = ty_pats `orElse` map (nlHsTyVar . hsLTyVarName) tv_names
374 hs_app = nlHsTyConApp tycon_name hs_ty_args
375 -- We get kinding info for the tyvars by typechecking (T a b)
376 -- Hence forming a tycon application and then dis-assembling it
377 ; (tvs, tc_app) <- tcHsQuantifiedType tv_names hs_app
378 ; tcExtendTyVarEnv tvs $ -- Deriving preds may (now) mention
379 -- the type variables for the type constructor
380 do { (deriv_tvs, cls, cls_tys) <- tcHsDeriv deriv_pred
381 -- The "deriv_pred" is a LHsType to take account of the fact that for
382 -- newtype deriving we allow deriving (forall a. C [a]).
383 ; mkEqnHelp DerivOrigin (tvs++deriv_tvs) cls cls_tys tc_app } }
385 ------------------------------------------------------------------
386 mkEqnHelp orig tvs cls cls_tys tc_app
387 | Just (tycon, tc_args) <- tcSplitTyConApp_maybe tc_app
388 = do { -- Make tc_app saturated, because that's what the
389 -- mkDataTypeEqn things expect
390 -- It might not be saturated in the standalone deriving case
391 -- derive instance Monad (T a)
392 let extra_tvs = dropList tc_args (tyConTyVars tycon)
393 full_tc_args = tc_args ++ mkTyVarTys extra_tvs
394 full_tvs = tvs ++ extra_tvs
396 ; (rep_tc, rep_tc_args) <- tcLookupFamInst tycon full_tc_args
398 ; gla_exts <- doptM Opt_GlasgowExts
399 ; overlap_flag <- getOverlapFlag
400 ; if isDataTyCon tycon then
401 mkDataTypeEqn orig gla_exts full_tvs cls cls_tys
402 tycon full_tc_args rep_tc rep_tc_args
404 mkNewTypeEqn orig gla_exts overlap_flag full_tvs cls cls_tys
405 tycon full_tc_args rep_tc rep_tc_args }
407 = baleOut (derivingThingErr cls cls_tys tc_app
408 (ptext SLIT("Last argument of the instance must be a type application")))
410 baleOut err = addErrTc err >> returnM (Nothing, Nothing)
414 %************************************************************************
418 %************************************************************************
421 mkDataTypeEqn orig gla_exts tvs cls cls_tys tycon tc_args rep_tc rep_tc_args
422 | Just err <- checkSideConditions gla_exts cls cls_tys tycon tc_args
423 = baleOut (derivingThingErr cls cls_tys (mkTyConApp tycon tc_args) err)
426 = ASSERT( null cls_tys )
427 do { loc <- getSrcSpanM
428 ; eqn <- mk_data_eqn loc orig tvs cls tycon tc_args rep_tc rep_tc_args
429 ; return (Just eqn, Nothing) }
431 mk_data_eqn :: SrcSpan -> InstOrigin -> [TyVar] -> Class
432 -> TyCon -> [TcType] -> TyCon -> [TcType] -> TcM DerivEqn
433 mk_data_eqn loc orig tvs cls tycon tc_args rep_tc rep_tc_args
434 | cls `hasKey` typeableClassKey
435 = -- The Typeable class is special in several ways
436 -- data T a b = ... deriving( Typeable )
438 -- instance Typeable2 T where ...
440 -- 1. There are no constraints in the instance
441 -- 2. There are no type variables either
442 -- 3. The actual class we want to generate isn't necessarily
443 -- Typeable; it depends on the arity of the type
444 do { real_clas <- tcLookupClass (typeableClassNames !! tyConArity tycon)
445 ; dfun_name <- new_dfun_name real_clas tycon
446 ; return (loc, orig, dfun_name, [], real_clas, mkTyConApp tycon [], []) }
449 = do { dfun_name <- new_dfun_name cls tycon
450 ; let ordinary_constraints
451 = [ mkClassPred cls [arg_ty]
452 | data_con <- tyConDataCons rep_tc,
453 arg_ty <- dataConInstOrigArgTys data_con rep_tc_args,
454 not (isUnLiftedType arg_ty) ] -- No constraints for unlifted types?
456 tiresome_subst = zipTopTvSubst (tyConTyVars rep_tc) rep_tc_args
457 stupid_constraints = substTheta tiresome_subst (tyConStupidTheta rep_tc)
458 -- see note [Data decl contexts] above
460 ; return (loc, orig, dfun_name, tvs, cls, mkTyConApp tycon tc_args,
461 stupid_constraints ++ ordinary_constraints)
464 ------------------------------------------------------------------
465 -- Check side conditions that dis-allow derivability for particular classes
466 -- This is *apart* from the newtype-deriving mechanism
468 checkSideConditions :: Bool -> Class -> [TcType] -> TyCon -> [TcType] -> Maybe SDoc
469 checkSideConditions gla_exts cls cls_tys tycon tc_tys
471 = Just ty_args_why -- e.g. deriving( Foo s )
473 = case [cond | (key,cond) <- sideConditions, key == getUnique cls] of
474 [] -> Just (non_std_why cls)
475 [cond] -> cond (gla_exts, tycon)
476 other -> pprPanic "checkSideConditions" (ppr cls)
478 ty_args_why = quotes (ppr (mkClassPred cls cls_tys)) <+> ptext SLIT("is not a class")
480 non_std_why cls = quotes (ppr cls) <+> ptext SLIT("is not a derivable class")
482 sideConditions :: [(Unique, Condition)]
484 = [ (eqClassKey, cond_std),
485 (ordClassKey, cond_std),
486 (readClassKey, cond_std),
487 (showClassKey, cond_std),
488 (enumClassKey, cond_std `andCond` cond_isEnumeration),
489 (ixClassKey, cond_std `andCond` (cond_isEnumeration `orCond` cond_isProduct)),
490 (boundedClassKey, cond_std `andCond` (cond_isEnumeration `orCond` cond_isProduct)),
491 (typeableClassKey, cond_glaExts `andCond` cond_typeableOK),
492 (dataClassKey, cond_glaExts `andCond` cond_std)
495 type Condition = (Bool, TyCon) -> Maybe SDoc -- Nothing => OK
497 orCond :: Condition -> Condition -> Condition
500 Nothing -> Nothing -- c1 succeeds
501 Just x -> case c2 tc of -- c1 fails
503 Just y -> Just (x $$ ptext SLIT(" and") $$ y)
506 andCond c1 c2 tc = case c1 tc of
507 Nothing -> c2 tc -- c1 succeeds
508 Just x -> Just x -- c1 fails
510 cond_std :: Condition
511 cond_std (gla_exts, tycon)
512 | any (not . isVanillaDataCon) data_cons = Just existential_why
513 | null data_cons = Just no_cons_why
514 | otherwise = Nothing
516 data_cons = tyConDataCons tycon
517 no_cons_why = quotes (ppr tycon) <+> ptext SLIT("has no data constructors")
518 existential_why = quotes (ppr tycon) <+> ptext SLIT("has non-Haskell-98 constructor(s)")
520 cond_isEnumeration :: Condition
521 cond_isEnumeration (gla_exts, tycon)
522 | isEnumerationTyCon tycon = Nothing
523 | otherwise = Just why
525 why = quotes (ppr tycon) <+> ptext SLIT("has non-nullary constructors")
527 cond_isProduct :: Condition
528 cond_isProduct (gla_exts, tycon)
529 | isProductTyCon tycon = Nothing
530 | otherwise = Just why
532 why = quotes (ppr tycon) <+> ptext SLIT("has more than one constructor")
534 cond_typeableOK :: Condition
535 -- OK for Typeable class
536 -- Currently: (a) args all of kind *
537 -- (b) 7 or fewer args
538 cond_typeableOK (gla_exts, tycon)
539 | tyConArity tycon > 7 = Just too_many
540 | not (all (isSubArgTypeKind . tyVarKind) (tyConTyVars tycon))
542 | isFamInstTyCon tycon = Just fam_inst -- no Typable for family insts
543 | otherwise = Nothing
545 too_many = quotes (ppr tycon) <+> ptext SLIT("has too many arguments")
546 bad_kind = quotes (ppr tycon) <+>
547 ptext SLIT("has arguments of kind other than `*'")
548 fam_inst = quotes (ppr tycon) <+> ptext SLIT("is a type family")
550 cond_glaExts :: Condition
551 cond_glaExts (gla_exts, tycon) | gla_exts = Nothing
552 | otherwise = Just why
554 why = ptext SLIT("You need -fglasgow-exts to derive an instance for this class")
556 std_class gla_exts clas
557 = key `elem` derivableClassKeys
558 || (gla_exts && (key == typeableClassKey || key == dataClassKey))
562 std_class_via_iso clas -- These standard classes can be derived for a newtype
563 -- using the isomorphism trick *even if no -fglasgow-exts*
564 = classKey clas `elem` [eqClassKey, ordClassKey, ixClassKey, boundedClassKey]
565 -- Not Read/Show because they respect the type
566 -- Not Enum, becuase newtypes are never in Enum
569 new_dfun_name clas tycon -- Just a simple wrapper
570 = newDFunName clas [mkTyConApp tycon []] (getSrcLoc tycon)
571 -- The type passed to newDFunName is only used to generate
572 -- a suitable string; hence the empty type arg list
576 %************************************************************************
580 %************************************************************************
583 mkNewTypeEqn orig gla_exts overlap_flag tvs cls cls_tys
585 rep_tycon rep_tc_args
586 | can_derive_via_isomorphism && (gla_exts || std_class_via_iso cls)
587 = do { traceTc (text "newtype deriving:" <+> ppr tycon <+> ppr rep_tys)
588 ; -- Go ahead and use the isomorphism
589 dfun_name <- new_dfun_name cls tycon
590 ; return (Nothing, Just (InstInfo { iSpec = mk_inst_spec dfun_name,
591 iBinds = NewTypeDerived ntd_info })) }
592 | std_class gla_exts cls
593 = mkDataTypeEqn orig gla_exts tvs cls cls_tys tycon tc_args rep_tycon rep_tc_args -- Go via bale-out route
595 -- Otherwise its a non-standard instance
596 | gla_exts = baleOut cant_derive_err -- Too hard
597 | otherwise = baleOut non_std_err -- Just complain about being a non-std instance
599 -- Here is the plan for newtype derivings. We see
600 -- newtype T a1...an = MkT (t ak+1...an) deriving (.., C s1 .. sm, ...)
601 -- where t is a type,
602 -- ak+1...an is a suffix of a1..an, and are all tyars
603 -- ak+1...an do not occur free in t, nor in the s1..sm
604 -- (C s1 ... sm) is a *partial applications* of class C
605 -- with the last parameter missing
606 -- (T a1 .. ak) matches the kind of C's last argument
607 -- (and hence so does t)
609 -- We generate the instance
610 -- instance forall ({a1..ak} u fvs(s1..sm)).
611 -- C s1 .. sm t => C s1 .. sm (T a1...ak)
612 -- where T a1...ap is the partial application of
613 -- the LHS of the correct kind and p >= k
615 -- NB: the variables below are:
616 -- tc_tvs = [a1, ..., an]
617 -- tyvars_to_keep = [a1, ..., ak]
618 -- rep_ty = t ak .. an
619 -- deriv_tvs = fvs(s1..sm) \ tc_tvs
620 -- tys = [s1, ..., sm]
623 -- Running example: newtype T s a = MkT (ST s a) deriving( Monad )
624 -- We generate the instance
625 -- instance Monad (ST s) => Monad (T s) where
627 cls_tyvars = classTyVars cls
628 kind = tyVarKind (last cls_tyvars)
629 -- Kind of the thing we want to instance
630 -- e.g. argument kind of Monad, *->*
632 (arg_kinds, _) = splitKindFunTys kind
633 n_args_to_drop = length arg_kinds
634 -- Want to drop 1 arg from (T s a) and (ST s a)
635 -- to get instance Monad (ST s) => Monad (T s)
637 -- Note [newtype representation]
638 -- Need newTyConRhs *not* newTyConRep to get the representation
639 -- type, because the latter looks through all intermediate newtypes
641 -- newtype B = MkB Int
642 -- newtype A = MkA B deriving( Num )
643 -- We want the Num instance of B, *not* the Num instance of Int,
644 -- when making the Num instance of A!
645 rep_ty = newTyConInstRhs rep_tycon rep_tc_args
646 (rep_fn, rep_ty_args) = tcSplitAppTys rep_ty
648 n_tyargs_to_keep = tyConArity tycon - n_args_to_drop
649 dropped_tc_args = drop n_tyargs_to_keep tc_args
650 dropped_tvs = tyVarsOfTypes dropped_tc_args
652 n_args_to_keep = length rep_ty_args - n_args_to_drop
653 args_to_drop = drop n_args_to_keep rep_ty_args
654 args_to_keep = take n_args_to_keep rep_ty_args
656 rep_fn' = mkAppTys rep_fn args_to_keep
657 rep_tys = cls_tys ++ [rep_fn']
658 rep_pred = mkClassPred cls rep_tys
659 -- rep_pred is the representation dictionary, from where
660 -- we are gong to get all the methods for the newtype
663 tc_app = mkTyConApp tycon (take n_tyargs_to_keep tc_args)
665 -- Next we figure out what superclass dictionaries to use
666 -- See Note [Newtype deriving superclasses] above
668 inst_tys = cls_tys ++ [tc_app]
669 sc_theta = substTheta (zipOpenTvSubst cls_tyvars inst_tys)
672 -- If there are no tyvars, there's no need
673 -- to abstract over the dictionaries we need
674 -- Example: newtype T = MkT Int deriving( C )
675 -- We get the derived instance
678 -- instance C Int => C T
679 dict_tvs = filterOut (`elemVarSet` dropped_tvs) tvs
680 all_preds = rep_pred : sc_theta -- NB: rep_pred comes first
681 (dict_args, ntd_info) | null dict_tvs = ([], Just all_preds)
682 | otherwise = (all_preds, Nothing)
684 -- Finally! Here's where we build the dictionary Id
685 mk_inst_spec dfun_name = mkLocalInstance dfun overlap_flag
687 dfun = mkDictFunId dfun_name dict_tvs dict_args cls inst_tys
689 -------------------------------------------------------------------
690 -- Figuring out whether we can only do this newtype-deriving thing
692 right_arity = length cls_tys + 1 == classArity cls
694 -- Never derive Read,Show,Typeable,Data this way
695 non_iso_classes = [readClassKey, showClassKey, typeableClassKey, dataClassKey]
696 can_derive_via_isomorphism
697 = not (getUnique cls `elem` non_iso_classes)
698 && right_arity -- Well kinded;
699 -- eg not: newtype T ... deriving( ST )
700 -- because ST needs *2* type params
701 && n_tyargs_to_keep >= 0 -- Type constructor has right kind:
702 -- eg not: newtype T = T Int deriving( Monad )
703 && n_args_to_keep >= 0 -- Rep type has right kind:
704 -- eg not: newtype T a = T Int deriving( Monad )
705 && eta_ok -- Eta reduction works
706 && not (isRecursiveTyCon tycon) -- Does not work for recursive tycons:
707 -- newtype A = MkA [A]
709 -- instance Eq [A] => Eq A !!
710 -- Here's a recursive newtype that's actually OK
711 -- newtype S1 = S1 [T1 ()]
712 -- newtype T1 a = T1 (StateT S1 IO a ) deriving( Monad )
713 -- It's currently rejected. Oh well.
714 -- In fact we generate an instance decl that has method of form
715 -- meth @ instTy = meth @ repTy
716 -- (no coerce's). We'd need a coerce if we wanted to handle
717 -- recursive newtypes too
719 -- Check that eta reduction is OK
720 eta_ok = (args_to_drop `tcEqTypes` dropped_tc_args)
721 -- (a) the dropped-off args are identical in the source and rep type
722 -- newtype T a b = MkT (S [a] b) deriving( Monad )
723 -- Here the 'b' must be the same in the rep type (S [a] b)
725 && (tyVarsOfType rep_fn' `disjointVarSet` dropped_tvs)
726 -- (b) the remaining type args do not mention any of the dropped
729 && (tyVarsOfTypes cls_tys `disjointVarSet` dropped_tvs)
730 -- (c) the type class args do not mention any of the dropped type
733 && all isTyVarTy dropped_tc_args
734 -- (d) in case of newtype family instances, the eta-dropped
735 -- arguments must be type variables (not more complex indexes)
737 cant_derive_err = derivingThingErr cls cls_tys tc_app
738 (vcat [ptext SLIT("even with cunning newtype deriving:"),
739 if isRecursiveTyCon tycon then
740 ptext SLIT("the newtype is recursive")
742 if not right_arity then
743 quotes (ppr (mkClassPred cls cls_tys)) <+> ptext SLIT("does not have arity 1")
745 if not (n_tyargs_to_keep >= 0) then
746 ptext SLIT("the type constructor has wrong kind")
747 else if not (n_args_to_keep >= 0) then
748 ptext SLIT("the representation type has wrong kind")
749 else if not eta_ok then
750 ptext SLIT("the eta-reduction property does not hold")
754 non_std_err = derivingThingErr cls cls_tys tc_app
755 (vcat [non_std_why cls,
756 ptext SLIT("Try -fglasgow-exts for GHC's newtype-deriving extension")])
760 %************************************************************************
762 \subsection[TcDeriv-fixpoint]{Finding the fixed point of \tr{deriving} equations}
764 %************************************************************************
766 A ``solution'' (to one of the equations) is a list of (k,TyVarTy tv)
767 terms, which is the final correct RHS for the corresponding original
771 Each (k,TyVarTy tv) in a solution constrains only a type
775 The (k,TyVarTy tv) pairs in a solution are canonically
776 ordered by sorting on type varible, tv, (major key) and then class, k,
781 solveDerivEqns :: OverlapFlag
783 -> TcM [Instance]-- Solns in same order as eqns.
784 -- This bunch is Absolutely minimal...
786 solveDerivEqns overlap_flag orig_eqns
787 = do { traceTc (text "solveDerivEqns" <+> vcat (map pprDerivEqn orig_eqns))
788 ; iterateDeriv 1 initial_solutions }
790 -- The initial solutions for the equations claim that each
791 -- instance has an empty context; this solution is certainly
792 -- in canonical form.
793 initial_solutions :: [DerivSoln]
794 initial_solutions = [ [] | _ <- orig_eqns ]
796 ------------------------------------------------------------------
797 -- iterateDeriv calculates the next batch of solutions,
798 -- compares it with the current one; finishes if they are the
799 -- same, otherwise recurses with the new solutions.
800 -- It fails if any iteration fails
801 iterateDeriv :: Int -> [DerivSoln] -> TcM [Instance]
802 iterateDeriv n current_solns
803 | n > 20 -- Looks as if we are in an infinite loop
804 -- This can happen if we have -fallow-undecidable-instances
805 -- (See TcSimplify.tcSimplifyDeriv.)
806 = pprPanic "solveDerivEqns: probable loop"
807 (vcat (map pprDerivEqn orig_eqns) $$ ppr current_solns)
810 inst_specs = zipWithEqual "add_solns" mk_inst_spec
811 orig_eqns current_solns
814 -- Extend the inst info from the explicit instance decls
815 -- with the current set of solutions, and simplify each RHS
816 extendLocalInstEnv inst_specs $
817 mappM gen_soln orig_eqns
818 ) `thenM` \ new_solns ->
819 if (current_solns == new_solns) then
822 iterateDeriv (n+1) new_solns
824 ------------------------------------------------------------------
825 gen_soln :: DerivEqn -> TcM [PredType]
826 gen_soln (loc, orig, _, tyvars, clas, inst_ty, deriv_rhs)
828 do { theta <- tcSimplifyDeriv orig tyvars deriv_rhs
829 ; addErrCtxt (derivInstCtxt theta clas [inst_ty]) $
830 do { checkNoErrs (checkValidInstance tyvars theta clas [inst_ty])
831 -- See Note [Deriving context]
832 -- If this fails, don't continue
834 -- Check for a bizarre corner case, when the derived instance decl should
835 -- have form instance C a b => D (T a) where ...
836 -- Note that 'b' isn't a parameter of T. This gives rise to all sorts
837 -- of problems; in particular, it's hard to compare solutions for
838 -- equality when finding the fixpoint. So I just rule it out for now.
839 ; let tv_set = mkVarSet tyvars
840 weird_preds = [pred | pred <- theta, not (tyVarsOfPred pred `subVarSet` tv_set)]
841 ; mapM_ (addErrTc . badDerivedPred) weird_preds
843 -- Claim: the result instance declaration is guaranteed valid
844 -- Hence no need to call:
845 -- checkValidInstance tyvars theta clas inst_tys
846 ; return (sortLe (<=) theta) } } -- Canonicalise before returning the solution
848 ------------------------------------------------------------------
849 mk_inst_spec :: DerivEqn -> DerivSoln -> Instance
850 mk_inst_spec (loc, orig, dfun_name, tyvars, clas, inst_ty, _) theta
851 = mkLocalInstance dfun overlap_flag
853 dfun = mkDictFunId dfun_name tyvars theta clas [inst_ty]
855 extendLocalInstEnv :: [Instance] -> TcM a -> TcM a
856 -- Add new locally-defined instances; don't bother to check
857 -- for functional dependency errors -- that'll happen in TcInstDcls
858 extendLocalInstEnv dfuns thing_inside
859 = do { env <- getGblEnv
860 ; let inst_env' = extendInstEnvList (tcg_inst_env env) dfuns
861 env' = env { tcg_inst_env = inst_env' }
862 ; setGblEnv env' thing_inside }
865 %************************************************************************
867 \subsection[TcDeriv-normal-binds]{Bindings for the various classes}
869 %************************************************************************
871 After all the trouble to figure out the required context for the
872 derived instance declarations, all that's left is to chug along to
873 produce them. They will then be shoved into @tcInstDecls2@, which
874 will do all its usual business.
876 There are lots of possibilities for code to generate. Here are
877 various general remarks.
882 We want derived instances of @Eq@ and @Ord@ (both v common) to be
883 ``you-couldn't-do-better-by-hand'' efficient.
886 Deriving @Show@---also pretty common--- should also be reasonable good code.
889 Deriving for the other classes isn't that common or that big a deal.
896 Deriving @Ord@ is done mostly with the 1.3 @compare@ method.
899 Deriving @Eq@ also uses @compare@, if we're deriving @Ord@, too.
902 We {\em normally} generate code only for the non-defaulted methods;
903 there are some exceptions for @Eq@ and (especially) @Ord@...
906 Sometimes we use a @_con2tag_<tycon>@ function, which returns a data
907 constructor's numeric (@Int#@) tag. These are generated by
908 @gen_tag_n_con_binds@, and the heuristic for deciding if one of
909 these is around is given by @hasCon2TagFun@.
911 The examples under the different sections below will make this
915 Much less often (really just for deriving @Ix@), we use a
916 @_tag2con_<tycon>@ function. See the examples.
919 We use the renamer!!! Reason: we're supposed to be
920 producing @LHsBinds Name@ for the methods, but that means
921 producing correctly-uniquified code on the fly. This is entirely
922 possible (the @TcM@ monad has a @UniqueSupply@), but it is painful.
923 So, instead, we produce @MonoBinds RdrName@ then heave 'em through
924 the renamer. What a great hack!
928 -- Generate the InstInfo for the required instance paired with the
929 -- *representation* tycon for that instance,
930 -- plus any auxiliary bindings required
932 -- Representation tycons differ from the tycon in the instance signature in
933 -- case of instances for indexed families.
935 genInst :: Instance -> TcM ((InstInfo, TyCon), LHsBinds RdrName)
937 = do { fix_env <- getFixityEnv
939 (tyvars,_,clas,[ty]) = instanceHead spec
940 clas_nm = className clas
941 (visible_tycon, tyArgs) = tcSplitTyConApp ty
943 -- In case of a family instance, we need to use the representation
944 -- tycon (after all, it has the data constructors)
945 ; (tycon, _) <- tcLookupFamInst visible_tycon tyArgs
946 ; let (meth_binds, aux_binds) = genDerivBinds clas fix_env tycon
948 -- Bring the right type variables into
949 -- scope, and rename the method binds
950 -- It's a bit yukky that we return *renamed* InstInfo, but
951 -- *non-renamed* auxiliary bindings
952 ; (rn_meth_binds, _fvs) <- discardWarnings $
953 bindLocalNames (map Var.varName tyvars) $
954 rnMethodBinds clas_nm (\n -> []) [] meth_binds
956 -- Build the InstInfo
957 ; return ((InstInfo { iSpec = spec,
958 iBinds = VanillaInst rn_meth_binds [] }, tycon),
962 genDerivBinds clas fix_env tycon
963 | className clas `elem` typeableClassNames
964 = (gen_Typeable_binds tycon, emptyLHsBinds)
967 = case assocMaybe gen_list (getUnique clas) of
968 Just gen_fn -> gen_fn fix_env tycon
969 Nothing -> pprPanic "genDerivBinds: bad derived class" (ppr clas)
971 gen_list :: [(Unique, FixityEnv -> TyCon -> (LHsBinds RdrName, LHsBinds RdrName))]
972 gen_list = [(eqClassKey, no_aux_binds (ignore_fix_env gen_Eq_binds))
973 ,(ordClassKey, no_aux_binds (ignore_fix_env gen_Ord_binds))
974 ,(enumClassKey, no_aux_binds (ignore_fix_env gen_Enum_binds))
975 ,(boundedClassKey, no_aux_binds (ignore_fix_env gen_Bounded_binds))
976 ,(ixClassKey, no_aux_binds (ignore_fix_env gen_Ix_binds))
977 ,(typeableClassKey,no_aux_binds (ignore_fix_env gen_Typeable_binds))
978 ,(showClassKey, no_aux_binds gen_Show_binds)
979 ,(readClassKey, no_aux_binds gen_Read_binds)
980 ,(dataClassKey, gen_Data_binds)
983 -- no_aux_binds is used for generators that don't
984 -- need to produce any auxiliary bindings
985 no_aux_binds f fix_env tc = (f fix_env tc, emptyLHsBinds)
986 ignore_fix_env f fix_env tc = f tc
990 %************************************************************************
992 \subsection[TcDeriv-taggery-Names]{What con2tag/tag2con functions are available?}
994 %************************************************************************
999 con2tag_Foo :: Foo ... -> Int#
1000 tag2con_Foo :: Int -> Foo ... -- easier if Int, not Int#
1001 maxtag_Foo :: Int -- ditto (NB: not unlifted)
1004 We have a @con2tag@ function for a tycon if:
1007 We're deriving @Eq@ and the tycon has nullary data constructors.
1010 Or: we're deriving @Ord@ (unless single-constructor), @Enum@, @Ix@
1011 (enum type only????)
1014 We have a @tag2con@ function for a tycon if:
1017 We're deriving @Enum@, or @Ix@ (enum type only???)
1020 If we have a @tag2con@ function, we also generate a @maxtag@ constant.
1023 genTaggeryBinds :: [(InstInfo, TyCon)] -> TcM (LHsBinds RdrName)
1024 genTaggeryBinds infos
1025 = do { names_so_far <- foldlM do_con2tag [] tycons_of_interest
1026 ; nm_alist_etc <- foldlM do_tag2con names_so_far tycons_of_interest
1027 ; return (listToBag (map gen_tag_n_con_monobind nm_alist_etc)) }
1029 all_CTs = [ (fst (simpleInstInfoClsTy info), tc)
1030 | (info, tc) <- infos]
1031 all_tycons = map snd all_CTs
1032 (tycons_of_interest, _) = removeDups compare all_tycons
1034 do_con2tag acc_Names tycon
1035 | isDataTyCon tycon &&
1036 ((we_are_deriving eqClassKey tycon
1037 && any isNullarySrcDataCon (tyConDataCons tycon))
1038 || (we_are_deriving ordClassKey tycon
1039 && not (isProductTyCon tycon))
1040 || (we_are_deriving enumClassKey tycon)
1041 || (we_are_deriving ixClassKey tycon))
1043 = returnM ((con2tag_RDR tycon, tycon, GenCon2Tag)
1048 do_tag2con acc_Names tycon
1049 | isDataTyCon tycon &&
1050 (we_are_deriving enumClassKey tycon ||
1051 we_are_deriving ixClassKey tycon
1052 && isEnumerationTyCon tycon)
1053 = returnM ( (tag2con_RDR tycon, tycon, GenTag2Con)
1054 : (maxtag_RDR tycon, tycon, GenMaxTag)
1059 we_are_deriving clas_key tycon
1060 = is_in_eqns clas_key tycon all_CTs
1062 is_in_eqns clas_key tycon [] = False
1063 is_in_eqns clas_key tycon ((c,t):cts)
1064 = (clas_key == classKey c && tycon == t)
1065 || is_in_eqns clas_key tycon cts
1069 derivingThingErr clas tys ty why
1070 = sep [hsep [ptext SLIT("Can't make a derived instance of"),
1072 nest 2 (parens why)]
1074 pred = mkClassPred clas (tys ++ [ty])
1076 standaloneCtxt :: LHsType Name -> SDoc
1077 standaloneCtxt ty = ptext SLIT("In the stand-alone deriving instance for") <+> quotes (ppr ty)
1079 derivInstCtxt theta clas inst_tys
1080 = hang (ptext SLIT("In the derived instance:"))
1081 2 (pprThetaArrow theta <+> pprClassPred clas inst_tys)
1082 -- Used for the ...Thetas variants; all top level
1085 = vcat [ptext SLIT("Can't derive instances where the instance context mentions"),
1086 ptext SLIT("type variables that are not data type parameters"),
1087 nest 2 (ptext SLIT("Offending constraint:") <+> ppr pred)]