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 %************************************************************************
56 %************************************************************************
60 1. Convert the decls (i.e. data/newtype deriving clauses,
61 plus standalone deriving) to [EarlyDerivSpec]
63 2. Infer the missing contexts for the Left DerivSpecs
65 3. Add the derived bindings, generating InstInfos
68 -- DerivSpec is purely local to this module
69 data DerivSpec = DS { ds_loc :: SrcSpan
70 , ds_orig :: InstOrigin
73 , ds_theta :: ThetaType
76 , ds_newtype :: Bool }
77 -- This spec implies a dfun declaration of the form
78 -- df :: forall tvs. theta => C tys
79 -- The Name is the name for the DFun we'll build
80 -- The tyvars bind all the variables in the theta
81 -- For family indexes, the tycon is the *family* tycon
82 -- (not the representation tycon)
84 -- ds_newtype = True <=> Newtype deriving
85 -- False <=> Vanilla deriving
87 type EarlyDerivSpec = Either DerivSpec DerivSpec
88 -- Left ds => the context for the instance should be inferred
89 -- In this case ds_theta is the list of all the
90 -- constraints needed, such as (Eq [a], Eq a)
91 -- The inference process is to reduce this to a
92 -- simpler form (e.g. Eq a)
94 -- Right ds => the exact context for the instance is supplied
95 -- by the programmer; it is ds_theta
97 pprDerivSpec :: DerivSpec -> SDoc
98 pprDerivSpec (DS { ds_loc = l, ds_name = n, ds_tvs = tvs,
99 ds_cls = c, ds_tys = tys, ds_theta = rhs })
100 = parens (hsep [ppr l, ppr n, ppr tvs, ppr c, ppr tys]
101 <+> equals <+> ppr rhs)
105 Inferring missing contexts
106 ~~~~~~~~~~~~~~~~~~~~~~~~~~
109 data T a b = C1 (Foo a) (Bar b)
114 [NOTE: See end of these comments for what to do with
115 data (C a, D b) => T a b = ...
118 We want to come up with an instance declaration of the form
120 instance (Ping a, Pong b, ...) => Eq (T a b) where
123 It is pretty easy, albeit tedious, to fill in the code "...". The
124 trick is to figure out what the context for the instance decl is,
125 namely @Ping@, @Pong@ and friends.
127 Let's call the context reqd for the T instance of class C at types
128 (a,b, ...) C (T a b). Thus:
130 Eq (T a b) = (Ping a, Pong b, ...)
132 Now we can get a (recursive) equation from the @data@ decl:
134 Eq (T a b) = Eq (Foo a) u Eq (Bar b) -- From C1
135 u Eq (T b a) u Eq Int -- From C2
136 u Eq (T a a) -- From C3
138 Foo and Bar may have explicit instances for @Eq@, in which case we can
139 just substitute for them. Alternatively, either or both may have
140 their @Eq@ instances given by @deriving@ clauses, in which case they
141 form part of the system of equations.
143 Now all we need do is simplify and solve the equations, iterating to
144 find the least fixpoint. Notice that the order of the arguments can
145 switch around, as here in the recursive calls to T.
147 Let's suppose Eq (Foo a) = Eq a, and Eq (Bar b) = Ping b.
151 Eq (T a b) = {} -- The empty set
154 Eq (T a b) = Eq (Foo a) u Eq (Bar b) -- From C1
155 u Eq (T b a) u Eq Int -- From C2
156 u Eq (T a a) -- From C3
158 After simplification:
159 = Eq a u Ping b u {} u {} u {}
164 Eq (T a b) = Eq (Foo a) u Eq (Bar b) -- From C1
165 u Eq (T b a) u Eq Int -- From C2
166 u Eq (T a a) -- From C3
168 After simplification:
173 = Eq a u Ping b u Eq b u Ping a
175 The next iteration gives the same result, so this is the fixpoint. We
176 need to make a canonical form of the RHS to ensure convergence. We do
177 this by simplifying the RHS to a form in which
179 - the classes constrain only tyvars
180 - the list is sorted by tyvar (major key) and then class (minor key)
181 - no duplicates, of course
183 So, here are the synonyms for the ``equation'' structures:
186 Note [Data decl contexts]
187 ~~~~~~~~~~~~~~~~~~~~~~~~~
190 data (RealFloat a) => Complex a = !a :+ !a deriving( Read )
192 We will need an instance decl like:
194 instance (Read a, RealFloat a) => Read (Complex a) where
197 The RealFloat in the context is because the read method for Complex is bound
198 to construct a Complex, and doing that requires that the argument type is
201 But this ain't true for Show, Eq, Ord, etc, since they don't construct
202 a Complex; they only take them apart.
204 Our approach: identify the offending classes, and add the data type
205 context to the instance decl. The "offending classes" are
209 FURTHER NOTE ADDED March 2002. In fact, Haskell98 now requires that
210 pattern matching against a constructor from a data type with a context
211 gives rise to the constraints for that context -- or at least the thinned
212 version. So now all classes are "offending".
214 Note [Newtype deriving]
215 ~~~~~~~~~~~~~~~~~~~~~~~
219 newtype T = T Char deriving( C [a] )
221 Notice the free 'a' in the deriving. We have to fill this out to
222 newtype T = T Char deriving( forall a. C [a] )
224 And then translate it to:
225 instance C [a] Char => C [a] T where ...
228 Note [Newtype deriving superclasses]
229 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
230 (See also Trac #1220 for an interesting exchange on newtype
231 deriving and superclasses.)
233 The 'tys' here come from the partial application in the deriving
234 clause. The last arg is the new instance type.
236 We must pass the superclasses; the newtype might be an instance
237 of them in a different way than the representation type
238 E.g. newtype Foo a = Foo a deriving( Show, Num, Eq )
239 Then the Show instance is not done via isomorphism; it shows
241 The Num instance is derived via isomorphism, but the Show superclass
242 dictionary must the Show instance for Foo, *not* the Show dictionary
243 gotten from the Num dictionary. So we must build a whole new dictionary
244 not just use the Num one. The instance we want is something like:
245 instance (Num a, Show (Foo a), Eq (Foo a)) => Num (Foo a) where
248 There may be a coercion needed which we get from the tycon for the newtype
249 when the dict is constructed in TcInstDcls.tcInstDecl2
254 %************************************************************************
256 \subsection[TcDeriv-driver]{Top-level function for \tr{derivings}}
258 %************************************************************************
261 tcDeriving :: [LTyClDecl Name] -- All type constructors
262 -> [LInstDecl Name] -- All instance declarations
263 -> [LDerivDecl Name] -- All stand-alone deriving declarations
264 -> TcM ([InstInfo], -- The generated "instance decls"
265 HsValBinds Name) -- Extra generated top-level bindings
267 tcDeriving tycl_decls inst_decls deriv_decls
268 = recoverM (returnM ([], emptyValBindsOut)) $
269 do { -- Fish the "deriving"-related information out of the TcEnv
270 -- And make the necessary "equations".
271 ; early_specs <- makeDerivSpecs tycl_decls inst_decls deriv_decls
273 ; overlap_flag <- getOverlapFlag
274 ; let (infer_specs, given_specs) = splitEithers early_specs
275 ; (insts1, aux_binds1) <- mapAndUnzipM (genInst overlap_flag) given_specs
277 ; final_specs <- extendLocalInstEnv (map iSpec insts1) $
278 inferInstanceContexts overlap_flag infer_specs
280 ; (insts2, aux_binds2) <- mapAndUnzipM (genInst overlap_flag) final_specs
282 ; is_boot <- tcIsHsBoot
283 ; rn_binds <- makeAuxBinds is_boot tycl_decls
284 (concat aux_binds1 ++ concat aux_binds2)
286 ; let inst_info = insts1 ++ insts2
289 ; ioToTcRn (dumpIfSet_dyn dflags Opt_D_dump_deriv "Derived instances"
290 (ddump_deriving inst_info rn_binds))
292 ; return (inst_info, rn_binds) }
294 ddump_deriving :: [InstInfo] -> HsValBinds Name -> SDoc
295 ddump_deriving inst_infos extra_binds
296 = vcat (map pprInstInfoDetails inst_infos) $$ ppr extra_binds
298 makeAuxBinds :: Bool -> [LTyClDecl Name] -> DerivAuxBinds -> TcM (HsValBinds Name)
299 makeAuxBinds is_boot tycl_decls deriv_aux_binds
300 | is_boot -- If we are compiling a hs-boot file,
301 -- don't generate any derived bindings
302 = return emptyValBindsOut
305 = do { let aux_binds = listToBag (map genAuxBind (rm_dups [] deriv_aux_binds))
306 -- Generate any extra not-one-inst-decl-specific binds,
307 -- notably "con2tag" and/or "tag2con" functions.
309 -- Generate the generic to/from functions from each type declaration
310 ; gen_binds <- mkGenericBinds tycl_decls
312 -- Rename these extra bindings, discarding warnings about unused bindings etc
313 -- Type signatures in patterns are used in the generic binds
315 setOptM Opt_PatternSignatures $
316 do { (rn_deriv, _dus1) <- rnTopBinds (ValBindsIn aux_binds [])
317 ; (rn_gen, dus_gen) <- rnTopBinds (ValBindsIn gen_binds [])
318 ; keepAliveSetTc (duDefs dus_gen) -- Mark these guys to
320 ; return (rn_deriv `plusHsValBinds` rn_gen) } }
322 -- Remove duplicate requests for auxilliary bindings
324 rm_dups acc (b:bs) | any (isDupAux b) acc = rm_dups acc bs
325 | otherwise = rm_dups (b:acc) bs
327 -----------------------------------------
328 mkGenericBinds :: [LTyClDecl Name] -> TcM (LHsBinds RdrName)
329 mkGenericBinds tycl_decls
330 = do { tcs <- mapM tcLookupTyCon
332 L _ (TyData { tcdLName = L _ tc_name }) <- tycl_decls]
333 -- We are only interested in the data type declarations
334 ; return (unionManyBags [ mkTyConGenericBinds tc |
335 tc <- tcs, tyConHasGenerics tc ]) }
336 -- And then only in the ones whose 'has-generics' flag is on
340 %************************************************************************
342 From HsSyn to DerivSpec
344 %************************************************************************
346 @makeDerivSpecs@ fishes around to find the info about needed derived
347 instances. Complicating factors:
350 We can only derive @Enum@ if the data type is an enumeration
351 type (all nullary data constructors).
354 We can only derive @Ix@ if the data type is an enumeration {\em
355 or} has just one data constructor (e.g., tuples).
358 [See Appendix~E in the Haskell~1.2 report.] This code here deals w/
362 makeDerivSpecs :: [LTyClDecl Name]
365 -> TcM [EarlyDerivSpec]
367 makeDerivSpecs tycl_decls inst_decls deriv_decls
368 = do { eqns1 <- mapAndRecoverM deriveTyData $
369 extractTyDataPreds tycl_decls ++
370 [ pd -- traverse assoc data families
371 | L _ (InstDecl _ _ _ ats) <- inst_decls
372 , pd <- extractTyDataPreds ats ]
373 ; eqns2 <- mapAndRecoverM deriveStandalone deriv_decls
374 ; return (catMaybes (eqns1 ++ eqns2)) }
376 extractTyDataPreds decls =
377 [(p, d) | d@(L _ (TyData {tcdDerivs = Just preds})) <- decls, p <- preds]
380 ------------------------------------------------------------------
381 deriveStandalone :: LDerivDecl Name -> TcM (Maybe EarlyDerivSpec)
382 -- Standalone deriving declarations
383 -- e.g. deriving instance show a => Show (T a)
384 -- Rather like tcLocalInstDecl
385 deriveStandalone (L loc (DerivDecl deriv_ty))
387 addErrCtxt (standaloneCtxt deriv_ty) $
388 do { traceTc (text "standalone deriving decl for" <+> ppr deriv_ty)
389 ; (tvs, theta, tau) <- tcHsInstHead deriv_ty
390 ; traceTc (text "standalone deriving;"
391 <+> text "tvs:" <+> ppr tvs
392 <+> text "theta:" <+> ppr theta
393 <+> text "tau:" <+> ppr tau)
394 ; (cls, inst_tys) <- checkValidInstHead tau
395 ; let cls_tys = take (length inst_tys - 1) inst_tys
396 inst_ty = last inst_tys
398 ; traceTc (text "standalone deriving;"
399 <+> text "class:" <+> ppr cls
400 <+> text "class types:" <+> ppr cls_tys
401 <+> text "type:" <+> ppr inst_ty)
402 ; mkEqnHelp StandAloneDerivOrigin tvs cls cls_tys inst_ty
405 ------------------------------------------------------------------
406 deriveTyData :: (LHsType Name, LTyClDecl Name) -> TcM (Maybe EarlyDerivSpec)
407 deriveTyData (deriv_pred, L loc decl@(TyData { tcdLName = L _ tycon_name,
408 tcdTyVars = tv_names,
409 tcdTyPats = ty_pats }))
412 do { let hs_ty_args = ty_pats `orElse` map (nlHsTyVar . hsLTyVarName) tv_names
413 hs_app = nlHsTyConApp tycon_name hs_ty_args
414 -- We get kinding info for the tyvars by typechecking (T a b)
415 -- Hence forming a tycon application and then dis-assembling it
416 ; (tvs, tc_app) <- tcHsQuantifiedType tv_names hs_app
417 ; tcExtendTyVarEnv tvs $ -- Deriving preds may (now) mention
418 -- the type variables for the type constructor
419 do { (deriv_tvs, cls, cls_tys) <- tcHsDeriv deriv_pred
420 -- The "deriv_pred" is a LHsType to take account of the fact that for
421 -- newtype deriving we allow deriving (forall a. C [a]).
422 ; mkEqnHelp DerivOrigin (tvs++deriv_tvs) cls cls_tys tc_app Nothing } }
425 = panic "derivTyData" -- Caller ensures that only TyData can happen
427 ------------------------------------------------------------------
428 mkEqnHelp :: InstOrigin -> [TyVar] -> Class -> [Type] -> Type
429 -> Maybe ThetaType -- Just => context supplied (standalone deriving)
430 -- Nothing => context inferred (deriving on data decl)
431 -> TcRn (Maybe EarlyDerivSpec)
432 mkEqnHelp orig tvs cls cls_tys tc_app mtheta
433 | Just (tycon, tc_args) <- tcSplitTyConApp_maybe tc_app
434 = do { (rep_tc, rep_tc_args) <- tcLookupFamInstExact tycon tc_args
436 ; mayDeriveDataTypeable <- doptM Opt_DeriveDataTypeable
437 ; newtype_deriving <- doptM Opt_GeneralizedNewtypeDeriving
439 -- Be careful to test rep_tc here: in the case of families, we want
440 -- to check the instance tycon, not the family tycon
441 ; if isDataTyCon rep_tc then
442 mkDataTypeEqn orig mayDeriveDataTypeable tvs cls cls_tys
443 tycon tc_args rep_tc rep_tc_args mtheta
445 mkNewTypeEqn orig mayDeriveDataTypeable newtype_deriving
447 tycon tc_args rep_tc rep_tc_args mtheta }
449 = baleOut (derivingThingErr cls cls_tys tc_app
450 (ptext SLIT("Last argument of the instance must be a type application")))
452 baleOut :: Message -> TcM (Maybe a)
453 baleOut err = do { addErrTc err; return Nothing }
456 Auxiliary lookup wrapper which requires that looked up family instances are
457 not type instances. If called with a vanilla tycon, the old type application
461 tcLookupFamInstExact :: TyCon -> [Type] -> TcM (TyCon, [Type])
462 tcLookupFamInstExact tycon tys
463 | not (isOpenTyCon tycon)
464 = return (tycon, tys)
466 = do { maybeFamInst <- tcLookupFamInst tycon tys
467 ; case maybeFamInst of
468 Nothing -> famInstNotFound tycon tys False
469 Just famInst@(_, rep_tys)
470 | not variable_only_subst -> famInstNotFound tycon tys True
471 | otherwise -> return famInst
473 tvs = map (Type.getTyVar
474 "TcDeriv.tcLookupFamInstExact")
476 variable_only_subst = all Type.isTyVarTy rep_tys &&
477 sizeVarSet (mkVarSet tvs) == length tvs
478 -- renaming may have no repetitions
483 %************************************************************************
487 %************************************************************************
490 mkDataTypeEqn :: InstOrigin -> Bool -> [Var] -> Class -> [Type]
491 -> TyCon -> [Type] -> TyCon -> [Type] -> Maybe ThetaType
492 -> TcRn (Maybe EarlyDerivSpec) -- Return 'Nothing' if error
494 mkDataTypeEqn orig mayDeriveDataTypeable tvs cls cls_tys
495 tycon tc_args rep_tc rep_tc_args mtheta
496 | Just err <- checkSideConditions mayDeriveDataTypeable cls cls_tys rep_tc
497 -- NB: pass the *representation* tycon to checkSideConditions
498 = baleOut (derivingThingErr cls cls_tys (mkTyConApp tycon tc_args) err)
501 = ASSERT( null cls_tys )
502 mk_data_eqn orig tvs cls tycon tc_args rep_tc rep_tc_args mtheta
504 mk_data_eqn, mk_typeable_eqn
505 :: InstOrigin -> [TyVar] -> Class
506 -> TyCon -> [TcType] -> TyCon -> [TcType] -> Maybe ThetaType
507 -> TcM (Maybe EarlyDerivSpec)
508 mk_data_eqn orig tvs cls tycon tc_args rep_tc rep_tc_args mtheta
509 | getName cls `elem` typeableClassNames
510 = mk_typeable_eqn orig tvs cls tycon tc_args rep_tc rep_tc_args mtheta
513 = do { dfun_name <- new_dfun_name cls tycon
515 ; let ordinary_constraints
516 = [ mkClassPred cls [arg_ty]
517 | data_con <- tyConDataCons rep_tc,
518 arg_ty <- ASSERT( isVanillaDataCon data_con )
519 dataConInstOrigArgTys data_con rep_tc_args,
520 not (isUnLiftedType arg_ty) ] -- No constraints for unlifted types?
522 stupid_subst = zipTopTvSubst (tyConTyVars rep_tc) rep_tc_args
523 stupid_constraints = substTheta stupid_subst (tyConStupidTheta rep_tc)
524 all_constraints = stupid_constraints ++ ordinary_constraints
525 -- see Note [Data decl contexts] above
527 spec = DS { ds_loc = loc, ds_orig = orig
528 , ds_name = dfun_name, ds_tvs = tvs
529 , ds_cls = cls, ds_tys = [mkTyConApp tycon tc_args]
530 , ds_theta = mtheta `orElse` all_constraints
531 , ds_newtype = False }
533 ; return (if isJust mtheta then Just (Right spec) -- Specified context
534 else Just (Left spec)) } -- Infer context
537 mk_typeable_eqn orig tvs cls tycon tc_args rep_tc _rep_tc_args mtheta
538 -- The Typeable class is special in several ways
539 -- data T a b = ... deriving( Typeable )
541 -- instance Typeable2 T where ...
543 -- 1. There are no constraints in the instance
544 -- 2. There are no type variables either
545 -- 3. The actual class we want to generate isn't necessarily
546 -- Typeable; it depends on the arity of the type
547 | isNothing mtheta -- deriving on a data type decl
548 = do { checkTc (cls `hasKey` typeableClassKey)
549 (ptext SLIT("Use deriving( Typeable ) on a data type declaration"))
550 ; real_cls <- tcLookupClass (typeableClassNames !! tyConArity tycon)
551 ; mk_typeable_eqn orig tvs real_cls tycon [] rep_tc [] (Just []) }
553 | otherwise -- standaone deriving
554 = do { checkTc (null tc_args)
555 (ptext SLIT("Derived typeable instance must be of form (Typeable")
556 <> int (tyConArity tycon) <+> ppr tycon <> rparen)
557 ; dfun_name <- new_dfun_name cls tycon
559 ; return (Just $ Right $
560 DS { ds_loc = loc, ds_orig = orig, ds_name = dfun_name, ds_tvs = []
561 , ds_cls = cls, ds_tys = [mkTyConApp tycon []]
562 , ds_theta = mtheta `orElse` [], ds_newtype = False }) }
564 ------------------------------------------------------------------
565 -- Check side conditions that dis-allow derivability for particular classes
566 -- This is *apart* from the newtype-deriving mechanism
568 -- Here we get the representation tycon in case of family instances as it has
569 -- the data constructors - but we need to be careful to fall back to the
570 -- family tycon (with indexes) in error messages.
572 checkSideConditions :: Bool -> Class -> [TcType] -> TyCon -> Maybe SDoc
573 checkSideConditions mayDeriveDataTypeable cls cls_tys rep_tc
575 = Just ty_args_why -- e.g. deriving( Foo s )
577 = case sideConditions cls of
578 Just cond -> cond (mayDeriveDataTypeable, rep_tc)
579 Nothing -> Just non_std_why
581 ty_args_why = quotes (ppr (mkClassPred cls cls_tys)) <+> ptext SLIT("is not a class")
582 non_std_why = quotes (ppr cls) <+> ptext SLIT("is not a derivable class")
584 sideConditions :: Class -> Maybe Condition
586 | cls_key == eqClassKey = Just cond_std
587 | cls_key == ordClassKey = Just cond_std
588 | cls_key == readClassKey = Just cond_std
589 | cls_key == showClassKey = Just cond_std
590 | cls_key == enumClassKey = Just (cond_std `andCond` cond_isEnumeration)
591 | cls_key == ixClassKey = Just (cond_std `andCond` (cond_isEnumeration `orCond` cond_isProduct))
592 | cls_key == boundedClassKey = Just (cond_std `andCond` (cond_isEnumeration `orCond` cond_isProduct))
593 | cls_key == dataClassKey = Just (cond_mayDeriveDataTypeable `andCond` cond_std)
594 | getName cls `elem` typeableClassNames = Just (cond_mayDeriveDataTypeable `andCond` cond_typeableOK)
595 | otherwise = Nothing
597 cls_key = getUnique cls
599 type Condition = (Bool, TyCon) -> Maybe SDoc
600 -- Bool is whether or not we are allowed to derive Data and Typeable
601 -- TyCon is the *representation* tycon if the
602 -- data type is an indexed one
605 orCond :: Condition -> Condition -> Condition
608 Nothing -> Nothing -- c1 succeeds
609 Just x -> case c2 tc of -- c1 fails
611 Just y -> Just (x $$ ptext SLIT(" and") $$ y)
614 andCond :: Condition -> Condition -> Condition
615 andCond c1 c2 tc = case c1 tc of
616 Nothing -> c2 tc -- c1 succeeds
617 Just x -> Just x -- c1 fails
619 cond_std :: Condition
621 | any (not . isVanillaDataCon) data_cons = Just existential_why
622 | null data_cons = Just no_cons_why
623 | otherwise = Nothing
625 data_cons = tyConDataCons rep_tc
626 no_cons_why = quotes (pprSourceTyCon rep_tc) <+>
627 ptext SLIT("has no data constructors")
628 existential_why = quotes (pprSourceTyCon rep_tc) <+>
629 ptext SLIT("has non-Haskell-98 constructor(s)")
631 cond_isEnumeration :: Condition
632 cond_isEnumeration (_, rep_tc)
633 | isEnumerationTyCon rep_tc = Nothing
634 | otherwise = Just why
636 why = quotes (pprSourceTyCon rep_tc) <+>
637 ptext SLIT("has non-nullary constructors")
639 cond_isProduct :: Condition
640 cond_isProduct (_, rep_tc)
641 | isProductTyCon rep_tc = Nothing
642 | otherwise = Just why
644 why = quotes (pprSourceTyCon rep_tc) <+>
645 ptext SLIT("has more than one constructor")
647 cond_typeableOK :: Condition
648 -- OK for Typeable class
649 -- Currently: (a) args all of kind *
650 -- (b) 7 or fewer args
651 cond_typeableOK (_, rep_tc)
652 | tyConArity rep_tc > 7 = Just too_many
653 | not (all (isSubArgTypeKind . tyVarKind) (tyConTyVars rep_tc))
655 | isFamInstTyCon rep_tc = Just fam_inst -- no Typable for family insts
656 | otherwise = Nothing
658 too_many = quotes (pprSourceTyCon rep_tc) <+>
659 ptext SLIT("has too many arguments")
660 bad_kind = quotes (pprSourceTyCon rep_tc) <+>
661 ptext SLIT("has arguments of kind other than `*'")
662 fam_inst = quotes (pprSourceTyCon rep_tc) <+>
663 ptext SLIT("is a type family")
665 cond_mayDeriveDataTypeable :: Condition
666 cond_mayDeriveDataTypeable (mayDeriveDataTypeable, _)
667 | mayDeriveDataTypeable = Nothing
668 | otherwise = Just why
670 why = ptext SLIT("You need -XDeriveDataTypeable to derive an instance for this class")
672 std_class_via_iso :: Class -> Bool
673 std_class_via_iso clas -- These standard classes can be derived for a newtype
674 -- using the isomorphism trick *even if no -fglasgow-exts*
675 = classKey clas `elem` [eqClassKey, ordClassKey, ixClassKey, boundedClassKey]
676 -- Not Read/Show because they respect the type
677 -- Not Enum, because newtypes are never in Enum
680 new_dfun_name :: Class -> TyCon -> TcM Name
681 new_dfun_name clas tycon -- Just a simple wrapper
682 = newDFunName clas [mkTyConApp tycon []] (getSrcSpan tycon)
683 -- The type passed to newDFunName is only used to generate
684 -- a suitable string; hence the empty type arg list
688 %************************************************************************
692 %************************************************************************
695 mkNewTypeEqn :: InstOrigin -> Bool -> Bool -> [Var] -> Class
696 -> [Type] -> TyCon -> [Type] -> TyCon -> [Type]
698 -> TcRn (Maybe EarlyDerivSpec)
699 mkNewTypeEqn orig mayDeriveDataTypeable newtype_deriving tvs
700 cls cls_tys tycon tc_args rep_tycon rep_tc_args mtheta
701 | can_derive_via_isomorphism && (newtype_deriving || std_class_via_iso cls)
702 = do { traceTc (text "newtype deriving:" <+> ppr tycon <+> ppr rep_tys)
703 ; dfun_name <- new_dfun_name cls tycon
705 ; let spec = DS { ds_loc = loc, ds_orig = orig
706 , ds_name = dfun_name, ds_tvs = dict_tvs
707 , ds_cls = cls, ds_tys = inst_tys
708 , ds_theta = mtheta `orElse` all_preds
709 , ds_newtype = True }
710 ; return (if isJust mtheta then Just (Right spec)
711 else Just (Left spec)) }
713 | isNothing mb_std_err -- Use the standard H98 method
714 = mk_data_eqn orig tvs cls tycon tc_args rep_tycon rep_tc_args mtheta
716 -- Otherwise we can't derive
717 | newtype_deriving = baleOut cant_derive_err -- Too hard
718 | otherwise = baleOut std_err -- Just complain about being a non-std instance
720 mb_std_err = checkSideConditions mayDeriveDataTypeable cls cls_tys rep_tycon
721 std_err = derivingThingErr cls cls_tys tc_app $
722 vcat [fromJust mb_std_err,
723 ptext SLIT("Try -XGeneralizedNewtypeDeriving for GHC's newtype-deriving extension")]
725 -- Here is the plan for newtype derivings. We see
726 -- newtype T a1...an = MkT (t ak+1...an) deriving (.., C s1 .. sm, ...)
727 -- where t is a type,
728 -- ak+1...an is a suffix of a1..an, and are all tyars
729 -- ak+1...an do not occur free in t, nor in the s1..sm
730 -- (C s1 ... sm) is a *partial applications* of class C
731 -- with the last parameter missing
732 -- (T a1 .. ak) matches the kind of C's last argument
733 -- (and hence so does t)
735 -- We generate the instance
736 -- instance forall ({a1..ak} u fvs(s1..sm)).
737 -- C s1 .. sm t => C s1 .. sm (T a1...ak)
738 -- where T a1...ap is the partial application of
739 -- the LHS of the correct kind and p >= k
741 -- NB: the variables below are:
742 -- tc_tvs = [a1, ..., an]
743 -- tyvars_to_keep = [a1, ..., ak]
744 -- rep_ty = t ak .. an
745 -- deriv_tvs = fvs(s1..sm) \ tc_tvs
746 -- tys = [s1, ..., sm]
749 -- Running example: newtype T s a = MkT (ST s a) deriving( Monad )
750 -- We generate the instance
751 -- instance Monad (ST s) => Monad (T s) where
753 cls_tyvars = classTyVars cls
754 kind = tyVarKind (last cls_tyvars)
755 -- Kind of the thing we want to instance
756 -- e.g. argument kind of Monad, *->*
758 (arg_kinds, _) = splitKindFunTys kind
759 n_args_to_drop = length arg_kinds
760 -- Want to drop 1 arg from (T s a) and (ST s a)
761 -- to get instance Monad (ST s) => Monad (T s)
763 -- Note [newtype representation]
764 -- Need newTyConRhs *not* newTyConRep to get the representation
765 -- type, because the latter looks through all intermediate newtypes
767 -- newtype B = MkB Int
768 -- newtype A = MkA B deriving( Num )
769 -- We want the Num instance of B, *not* the Num instance of Int,
770 -- when making the Num instance of A!
771 rep_ty = newTyConInstRhs rep_tycon rep_tc_args
772 (rep_fn, rep_ty_args) = tcSplitAppTys rep_ty
774 n_tyargs_to_keep = tyConArity tycon - n_args_to_drop
775 dropped_tc_args = drop n_tyargs_to_keep tc_args
776 dropped_tvs = tyVarsOfTypes dropped_tc_args
778 n_args_to_keep = length rep_ty_args - n_args_to_drop
779 args_to_drop = drop n_args_to_keep rep_ty_args
780 args_to_keep = take n_args_to_keep rep_ty_args
782 rep_fn' = mkAppTys rep_fn args_to_keep
783 rep_tys = cls_tys ++ [rep_fn']
784 rep_pred = mkClassPred cls rep_tys
785 -- rep_pred is the representation dictionary, from where
786 -- we are gong to get all the methods for the newtype
789 tc_app = mkTyConApp tycon (take n_tyargs_to_keep tc_args)
791 -- Next we figure out what superclass dictionaries to use
792 -- See Note [Newtype deriving superclasses] above
794 inst_tys = cls_tys ++ [tc_app]
795 sc_theta = substTheta (zipOpenTvSubst cls_tyvars inst_tys)
798 -- If there are no tyvars, there's no need
799 -- to abstract over the dictionaries we need
800 -- Example: newtype T = MkT Int deriving( C )
801 -- We get the derived instance
804 -- instance C Int => C T
805 dict_tvs = filterOut (`elemVarSet` dropped_tvs) tvs
806 all_preds = rep_pred : sc_theta -- NB: rep_pred comes first
808 -------------------------------------------------------------------
809 -- Figuring out whether we can only do this newtype-deriving thing
811 right_arity = length cls_tys + 1 == classArity cls
813 -- Never derive Read,Show,Typeable,Data this way
814 non_iso_classes = [readClassKey, showClassKey, typeableClassKey, dataClassKey]
815 can_derive_via_isomorphism
816 = not (getUnique cls `elem` non_iso_classes)
817 && right_arity -- Well kinded;
818 -- eg not: newtype T ... deriving( ST )
819 -- because ST needs *2* type params
820 && n_tyargs_to_keep >= 0 -- Type constructor has right kind:
821 -- eg not: newtype T = T Int deriving( Monad )
822 && n_args_to_keep >= 0 -- Rep type has right kind:
823 -- eg not: newtype T a = T Int deriving( Monad )
824 && eta_ok -- Eta reduction works
825 && not (isRecursiveTyCon tycon) -- Does not work for recursive tycons:
826 -- newtype A = MkA [A]
828 -- instance Eq [A] => Eq A !!
829 -- Here's a recursive newtype that's actually OK
830 -- newtype S1 = S1 [T1 ()]
831 -- newtype T1 a = T1 (StateT S1 IO a ) deriving( Monad )
832 -- It's currently rejected. Oh well.
833 -- In fact we generate an instance decl that has method of form
834 -- meth @ instTy = meth @ repTy
835 -- (no coerce's). We'd need a coerce if we wanted to handle
836 -- recursive newtypes too
838 -- Check that eta reduction is OK
839 eta_ok = (args_to_drop `tcEqTypes` dropped_tc_args)
840 -- (a) the dropped-off args are identical in the source and rep type
841 -- newtype T a b = MkT (S [a] b) deriving( Monad )
842 -- Here the 'b' must be the same in the rep type (S [a] b)
844 && (tyVarsOfType rep_fn' `disjointVarSet` dropped_tvs)
845 -- (b) the remaining type args do not mention any of the dropped
848 && (tyVarsOfTypes cls_tys `disjointVarSet` dropped_tvs)
849 -- (c) the type class args do not mention any of the dropped type
852 && all isTyVarTy dropped_tc_args
853 -- (d) in case of newtype family instances, the eta-dropped
854 -- arguments must be type variables (not more complex indexes)
856 cant_derive_err = derivingThingErr cls cls_tys tc_app
857 (vcat [ptext SLIT("even with cunning newtype deriving:"),
858 if isRecursiveTyCon tycon then
859 ptext SLIT("the newtype may be recursive")
861 if not right_arity then
862 quotes (ppr (mkClassPred cls cls_tys)) <+> ptext SLIT("does not have arity 1")
864 if not (n_tyargs_to_keep >= 0) then
865 ptext SLIT("the type constructor has wrong kind")
866 else if not (n_args_to_keep >= 0) then
867 ptext SLIT("the representation type has wrong kind")
868 else if not eta_ok then
869 ptext SLIT("the eta-reduction property does not hold")
875 %************************************************************************
877 \subsection[TcDeriv-fixpoint]{Finding the fixed point of \tr{deriving} equations}
879 %************************************************************************
881 A ``solution'' (to one of the equations) is a list of (k,TyVarTy tv)
882 terms, which is the final correct RHS for the corresponding original
886 Each (k,TyVarTy tv) in a solution constrains only a type
890 The (k,TyVarTy tv) pairs in a solution are canonically
891 ordered by sorting on type varible, tv, (major key) and then class, k,
896 inferInstanceContexts :: OverlapFlag -> [DerivSpec] -> TcM [DerivSpec]
898 inferInstanceContexts _ [] = return []
900 inferInstanceContexts oflag infer_specs
901 = do { traceTc (text "inferInstanceContexts" <+> vcat (map pprDerivSpec infer_specs))
902 ; iterate_deriv 1 initial_solutions }
904 ------------------------------------------------------------------
905 -- The initial solutions for the equations claim that each
906 -- instance has an empty context; this solution is certainly
907 -- in canonical form.
908 initial_solutions :: [ThetaType]
909 initial_solutions = [ [] | _ <- infer_specs ]
911 ------------------------------------------------------------------
912 -- iterate_deriv calculates the next batch of solutions,
913 -- compares it with the current one; finishes if they are the
914 -- same, otherwise recurses with the new solutions.
915 -- It fails if any iteration fails
916 iterate_deriv :: Int -> [ThetaType] -> TcM [DerivSpec]
917 iterate_deriv n current_solns
918 | n > 20 -- Looks as if we are in an infinite loop
919 -- This can happen if we have -fallow-undecidable-instances
920 -- (See TcSimplify.tcSimplifyDeriv.)
921 = pprPanic "solveDerivEqns: probable loop"
922 (vcat (map pprDerivSpec infer_specs) $$ ppr current_solns)
924 = do { -- Extend the inst info from the explicit instance decls
925 -- with the current set of solutions, and simplify each RHS
926 let inst_specs = zipWithEqual "add_solns" (mkInstance2 oflag)
927 current_solns infer_specs
928 ; new_solns <- checkNoErrs $
929 extendLocalInstEnv inst_specs $
930 mapM gen_soln infer_specs
932 ; if (current_solns == new_solns) then
933 return [ spec { ds_theta = soln }
934 | (spec, soln) <- zip infer_specs current_solns ]
936 iterate_deriv (n+1) new_solns }
938 ------------------------------------------------------------------
939 gen_soln :: DerivSpec -> TcM [PredType]
940 gen_soln (DS { ds_loc = loc, ds_orig = orig, ds_tvs = tyvars
941 , ds_cls = clas, ds_tys = inst_tys, ds_theta = deriv_rhs })
943 addErrCtxt (derivInstCtxt clas inst_tys) $
944 do { theta <- tcSimplifyDeriv orig tyvars deriv_rhs
945 -- checkValidInstance tyvars theta clas inst_tys
946 -- Not necessary; see Note [Exotic derived instance contexts]
949 -- Check for a bizarre corner case, when the derived instance decl should
950 -- have form instance C a b => D (T a) where ...
951 -- Note that 'b' isn't a parameter of T. This gives rise to all sorts
952 -- of problems; in particular, it's hard to compare solutions for
953 -- equality when finding the fixpoint. So I just rule it out for now.
954 ; let tv_set = mkVarSet tyvars
955 weird_preds = [pred | pred <- theta, not (tyVarsOfPred pred `subVarSet` tv_set)]
956 ; mapM_ (addErrTc . badDerivedPred) weird_preds
958 -- Claim: the result instance declaration is guaranteed valid
959 -- Hence no need to call:
960 -- checkValidInstance tyvars theta clas inst_tys
961 ; return (sortLe (<=) theta) } -- Canonicalise before returning the solution
963 ------------------------------------------------------------------
964 mkInstance1 :: OverlapFlag -> DerivSpec -> Instance
965 mkInstance1 overlap_flag spec = mkInstance2 overlap_flag (ds_theta spec) spec
967 mkInstance2 :: OverlapFlag -> ThetaType -> DerivSpec -> Instance
968 mkInstance2 overlap_flag theta
969 (DS { ds_name = dfun_name
970 , ds_tvs = tyvars, ds_cls = clas, ds_tys = tys })
971 = mkLocalInstance dfun overlap_flag
973 dfun = mkDictFunId dfun_name tyvars theta clas tys
976 extendLocalInstEnv :: [Instance] -> TcM a -> TcM a
977 -- Add new locally-defined instances; don't bother to check
978 -- for functional dependency errors -- that'll happen in TcInstDcls
979 extendLocalInstEnv dfuns thing_inside
980 = do { env <- getGblEnv
981 ; let inst_env' = extendInstEnvList (tcg_inst_env env) dfuns
982 env' = env { tcg_inst_env = inst_env' }
983 ; setGblEnv env' thing_inside }
987 %************************************************************************
989 \subsection[TcDeriv-normal-binds]{Bindings for the various classes}
991 %************************************************************************
993 After all the trouble to figure out the required context for the
994 derived instance declarations, all that's left is to chug along to
995 produce them. They will then be shoved into @tcInstDecls2@, which
996 will do all its usual business.
998 There are lots of possibilities for code to generate. Here are
999 various general remarks.
1004 We want derived instances of @Eq@ and @Ord@ (both v common) to be
1005 ``you-couldn't-do-better-by-hand'' efficient.
1008 Deriving @Show@---also pretty common--- should also be reasonable good code.
1011 Deriving for the other classes isn't that common or that big a deal.
1018 Deriving @Ord@ is done mostly with the 1.3 @compare@ method.
1021 Deriving @Eq@ also uses @compare@, if we're deriving @Ord@, too.
1024 We {\em normally} generate code only for the non-defaulted methods;
1025 there are some exceptions for @Eq@ and (especially) @Ord@...
1028 Sometimes we use a @_con2tag_<tycon>@ function, which returns a data
1029 constructor's numeric (@Int#@) tag. These are generated by
1030 @gen_tag_n_con_binds@, and the heuristic for deciding if one of
1031 these is around is given by @hasCon2TagFun@.
1033 The examples under the different sections below will make this
1037 Much less often (really just for deriving @Ix@), we use a
1038 @_tag2con_<tycon>@ function. See the examples.
1041 We use the renamer!!! Reason: we're supposed to be
1042 producing @LHsBinds Name@ for the methods, but that means
1043 producing correctly-uniquified code on the fly. This is entirely
1044 possible (the @TcM@ monad has a @UniqueSupply@), but it is painful.
1045 So, instead, we produce @MonoBinds RdrName@ then heave 'em through
1046 the renamer. What a great hack!
1050 -- Generate the InstInfo for the required instance paired with the
1051 -- *representation* tycon for that instance,
1052 -- plus any auxiliary bindings required
1054 -- Representation tycons differ from the tycon in the instance signature in
1055 -- case of instances for indexed families.
1057 genInst :: OverlapFlag -> DerivSpec -> TcM (InstInfo, DerivAuxBinds)
1060 = return (InstInfo { iSpec = mkInstance1 oflag spec
1061 , iBinds = NewTypeDerived }, [])
1064 = do { fix_env <- getFixityEnv
1066 inst = mkInstance1 oflag spec
1067 (tyvars,_,clas,[ty]) = instanceHead inst
1068 clas_nm = className clas
1069 (visible_tycon, tyArgs) = tcSplitTyConApp ty
1071 -- In case of a family instance, we need to use the representation
1072 -- tycon (after all, it has the data constructors)
1073 ; (tycon, _) <- tcLookupFamInstExact visible_tycon tyArgs
1074 ; let (meth_binds, aux_binds) = genDerivBinds clas fix_env tycon
1076 -- Bring the right type variables into
1077 -- scope, and rename the method binds
1078 -- It's a bit yukky that we return *renamed* InstInfo, but
1079 -- *non-renamed* auxiliary bindings
1080 ; (rn_meth_binds, _fvs) <- discardWarnings $
1081 bindLocalNames (map Var.varName tyvars) $
1082 rnMethodBinds clas_nm (\_ -> []) [] meth_binds
1084 -- Build the InstInfo
1085 ; return (InstInfo { iSpec = inst,
1086 iBinds = VanillaInst rn_meth_binds [] },
1090 genDerivBinds :: Class -> FixityEnv -> TyCon -> (LHsBinds RdrName, DerivAuxBinds)
1091 genDerivBinds clas fix_env tycon
1092 | className clas `elem` typeableClassNames
1093 = (gen_Typeable_binds tycon, [])
1096 = case assocMaybe gen_list (getUnique clas) of
1097 Just gen_fn -> gen_fn tycon
1098 Nothing -> pprPanic "genDerivBinds: bad derived class" (ppr clas)
1100 gen_list :: [(Unique, TyCon -> (LHsBinds RdrName, DerivAuxBinds))]
1101 gen_list = [(eqClassKey, gen_Eq_binds)
1102 ,(ordClassKey, gen_Ord_binds)
1103 ,(enumClassKey, gen_Enum_binds)
1104 ,(boundedClassKey, gen_Bounded_binds)
1105 ,(ixClassKey, gen_Ix_binds)
1106 ,(showClassKey, gen_Show_binds fix_env)
1107 ,(readClassKey, gen_Read_binds fix_env)
1108 ,(dataClassKey, gen_Data_binds fix_env)
1113 %************************************************************************
1115 \subsection[TcDeriv-taggery-Names]{What con2tag/tag2con functions are available?}
1117 %************************************************************************
1120 derivingThingErr :: Class -> [Type] -> Type -> Message -> Message
1121 derivingThingErr clas tys ty why
1122 = sep [hsep [ptext SLIT("Can't make a derived instance of"),
1124 nest 2 (parens why)]
1126 pred = mkClassPred clas (tys ++ [ty])
1128 standaloneCtxt :: LHsType Name -> SDoc
1129 standaloneCtxt ty = hang (ptext SLIT("In the stand-alone deriving instance for"))
1132 derivInstCtxt :: Class -> [Type] -> Message
1133 derivInstCtxt clas inst_tys
1134 = ptext SLIT("When deriving the instance for") <+> parens (pprClassPred clas inst_tys)
1136 badDerivedPred :: PredType -> Message
1138 = vcat [ptext SLIT("Can't derive instances where the instance context mentions"),
1139 ptext SLIT("type variables that are not data type parameters"),
1140 nest 2 (ptext SLIT("Offending constraint:") <+> ppr pred)]
1142 famInstNotFound :: TyCon -> [Type] -> Bool -> TcM a
1143 famInstNotFound tycon tys notExact
1144 = failWithTc (msg <+> quotes (pprTypeApp tycon (ppr tycon) tys))
1146 msg = ptext $ if notExact
1147 then SLIT("No family instance exactly matching")
1148 else SLIT("More than one family instance for")