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 %************************************************************************
58 %************************************************************************
62 1. Convert the decls (i.e. data/newtype deriving clauses,
63 plus standalone deriving) to [EarlyDerivSpec]
65 2. Infer the missing contexts for the Left DerivSpecs
67 3. Add the derived bindings, generating InstInfos
70 -- DerivSpec is purely local to this module
71 data DerivSpec = DS { ds_loc :: SrcSpan
72 , ds_orig :: InstOrigin
75 , ds_theta :: ThetaType
79 , ds_tc_args :: [Type]
80 , ds_newtype :: Bool }
81 -- This spec implies a dfun declaration of the form
82 -- df :: forall tvs. theta => C tys
83 -- The Name is the name for the DFun we'll build
84 -- The tyvars bind all the variables in the theta
85 -- For family indexes, the tycon in
86 -- in ds_tys is the *family* tycon
87 -- in ds_tc, ds_tc_args is the *representation* tycon
88 -- For non-family tycons, both are the same
90 -- ds_newtype = True <=> Newtype deriving
91 -- False <=> Vanilla deriving
93 type EarlyDerivSpec = Either DerivSpec DerivSpec
94 -- Left ds => the context for the instance should be inferred
95 -- In this case ds_theta is the list of all the
96 -- constraints needed, such as (Eq [a], Eq a)
97 -- The inference process is to reduce this to a
98 -- simpler form (e.g. Eq a)
100 -- Right ds => the exact context for the instance is supplied
101 -- by the programmer; it is ds_theta
103 pprDerivSpec :: DerivSpec -> SDoc
104 pprDerivSpec (DS { ds_loc = l, ds_name = n, ds_tvs = tvs,
105 ds_cls = c, ds_tys = tys, ds_theta = rhs })
106 = parens (hsep [ppr l, ppr n, ppr tvs, ppr c, ppr tys]
107 <+> equals <+> ppr rhs)
111 Inferring missing contexts
112 ~~~~~~~~~~~~~~~~~~~~~~~~~~
115 data T a b = C1 (Foo a) (Bar b)
120 [NOTE: See end of these comments for what to do with
121 data (C a, D b) => T a b = ...
124 We want to come up with an instance declaration of the form
126 instance (Ping a, Pong b, ...) => Eq (T a b) where
129 It is pretty easy, albeit tedious, to fill in the code "...". The
130 trick is to figure out what the context for the instance decl is,
131 namely @Ping@, @Pong@ and friends.
133 Let's call the context reqd for the T instance of class C at types
134 (a,b, ...) C (T a b). Thus:
136 Eq (T a b) = (Ping a, Pong b, ...)
138 Now we can get a (recursive) equation from the @data@ decl:
140 Eq (T a b) = Eq (Foo a) u Eq (Bar b) -- From C1
141 u Eq (T b a) u Eq Int -- From C2
142 u Eq (T a a) -- From C3
144 Foo and Bar may have explicit instances for @Eq@, in which case we can
145 just substitute for them. Alternatively, either or both may have
146 their @Eq@ instances given by @deriving@ clauses, in which case they
147 form part of the system of equations.
149 Now all we need do is simplify and solve the equations, iterating to
150 find the least fixpoint. Notice that the order of the arguments can
151 switch around, as here in the recursive calls to T.
153 Let's suppose Eq (Foo a) = Eq a, and Eq (Bar b) = Ping b.
157 Eq (T a b) = {} -- The empty set
160 Eq (T a b) = Eq (Foo a) u Eq (Bar b) -- From C1
161 u Eq (T b a) u Eq Int -- From C2
162 u Eq (T a a) -- From C3
164 After simplification:
165 = Eq a u Ping b u {} u {} u {}
170 Eq (T a b) = Eq (Foo a) u Eq (Bar b) -- From C1
171 u Eq (T b a) u Eq Int -- From C2
172 u Eq (T a a) -- From C3
174 After simplification:
179 = Eq a u Ping b u Eq b u Ping a
181 The next iteration gives the same result, so this is the fixpoint. We
182 need to make a canonical form of the RHS to ensure convergence. We do
183 this by simplifying the RHS to a form in which
185 - the classes constrain only tyvars
186 - the list is sorted by tyvar (major key) and then class (minor key)
187 - no duplicates, of course
189 So, here are the synonyms for the ``equation'' structures:
192 Note [Data decl contexts]
193 ~~~~~~~~~~~~~~~~~~~~~~~~~
196 data (RealFloat a) => Complex a = !a :+ !a deriving( Read )
198 We will need an instance decl like:
200 instance (Read a, RealFloat a) => Read (Complex a) where
203 The RealFloat in the context is because the read method for Complex is bound
204 to construct a Complex, and doing that requires that the argument type is
207 But this ain't true for Show, Eq, Ord, etc, since they don't construct
208 a Complex; they only take them apart.
210 Our approach: identify the offending classes, and add the data type
211 context to the instance decl. The "offending classes" are
215 FURTHER NOTE ADDED March 2002. In fact, Haskell98 now requires that
216 pattern matching against a constructor from a data type with a context
217 gives rise to the constraints for that context -- or at least the thinned
218 version. So now all classes are "offending".
220 Note [Newtype deriving]
221 ~~~~~~~~~~~~~~~~~~~~~~~
225 newtype T = T Char deriving( C [a] )
227 Notice the free 'a' in the deriving. We have to fill this out to
228 newtype T = T Char deriving( forall a. C [a] )
230 And then translate it to:
231 instance C [a] Char => C [a] T where ...
234 Note [Newtype deriving superclasses]
235 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
236 (See also Trac #1220 for an interesting exchange on newtype
237 deriving and superclasses.)
239 The 'tys' here come from the partial application in the deriving
240 clause. The last arg is the new instance type.
242 We must pass the superclasses; the newtype might be an instance
243 of them in a different way than the representation type
244 E.g. newtype Foo a = Foo a deriving( Show, Num, Eq )
245 Then the Show instance is not done via isomorphism; it shows
247 The Num instance is derived via isomorphism, but the Show superclass
248 dictionary must the Show instance for Foo, *not* the Show dictionary
249 gotten from the Num dictionary. So we must build a whole new dictionary
250 not just use the Num one. The instance we want is something like:
251 instance (Num a, Show (Foo a), Eq (Foo a)) => Num (Foo a) where
254 There may be a coercion needed which we get from the tycon for the newtype
255 when the dict is constructed in TcInstDcls.tcInstDecl2
260 %************************************************************************
262 \subsection[TcDeriv-driver]{Top-level function for \tr{derivings}}
264 %************************************************************************
267 tcDeriving :: [LTyClDecl Name] -- All type constructors
268 -> [LInstDecl Name] -- All instance declarations
269 -> [LDerivDecl Name] -- All stand-alone deriving declarations
270 -> TcM ([InstInfo Name], -- The generated "instance decls"
271 HsValBinds Name) -- Extra generated top-level bindings
273 tcDeriving tycl_decls inst_decls deriv_decls
274 = recoverM (return ([], emptyValBindsOut)) $
275 do { -- Fish the "deriving"-related information out of the TcEnv
276 -- And make the necessary "equations".
277 is_boot <- tcIsHsBoot
278 ; traceTc (text "tcDeriving" <+> ppr is_boot)
279 ; early_specs <- makeDerivSpecs is_boot tycl_decls inst_decls deriv_decls
281 ; overlap_flag <- getOverlapFlag
282 ; let (infer_specs, given_specs) = splitEithers early_specs
283 ; insts1 <- mapM (genInst overlap_flag) given_specs
285 ; final_specs <- extendLocalInstEnv (map (iSpec . fst) insts1) $
286 inferInstanceContexts overlap_flag infer_specs
288 ; insts2 <- mapM (genInst overlap_flag) final_specs
290 -- Generate the generic to/from functions from each type declaration
291 ; gen_binds <- mkGenericBinds is_boot
292 ; (inst_info, rn_binds) <- renameDeriv is_boot gen_binds (insts1 ++ insts2)
295 ; liftIO (dumpIfSet_dyn dflags Opt_D_dump_deriv "Derived instances"
296 (ddump_deriving inst_info rn_binds))
298 ; return (inst_info, rn_binds) }
300 ddump_deriving :: [InstInfo Name] -> HsValBinds Name -> SDoc
301 ddump_deriving inst_infos extra_binds
302 = vcat (map pprInstInfoDetails inst_infos) $$ ppr extra_binds
304 renameDeriv :: Bool -> LHsBinds RdrName
305 -> [(InstInfo RdrName, DerivAuxBinds)]
306 -> TcM ([InstInfo Name], HsValBinds Name)
307 renameDeriv is_boot gen_binds insts
308 | is_boot -- If we are compiling a hs-boot file, don't generate any derived bindings
309 -- The inst-info bindings will all be empty, but it's easier to
310 -- just use rn_inst_info to change the type appropriately
311 = do { rn_inst_infos <- mapM rn_inst_info inst_infos
312 ; return (rn_inst_infos, emptyValBindsOut) }
315 = discardWarnings $ -- Discard warnings about unused bindings etc
316 do { (rn_gen, dus_gen) <- setOptM Opt_ScopedTypeVariables $ -- Type signatures in patterns
317 -- are used in the generic binds
318 rnTopBinds (ValBindsIn gen_binds [])
319 ; keepAliveSetTc (duDefs dus_gen) -- Mark these guys to be kept alive
321 -- Generate and rename any extra not-one-inst-decl-specific binds,
322 -- notably "con2tag" and/or "tag2con" functions.
323 -- Bring those names into scope before renaming the instances themselves
324 ; loc <- getSrcSpanM -- Generic loc for shared bindings
325 ; let aux_binds = listToBag $ map (genAuxBind loc) $
326 rm_dups [] $ concat deriv_aux_binds
327 ; rn_aux_lhs <- rnTopBindsLHS emptyFsEnv (ValBindsIn aux_binds [])
328 ; let aux_names = map unLoc (collectHsValBinders rn_aux_lhs)
330 ; bindLocalNames aux_names $
331 do { (rn_aux, _dus) <- rnTopBindsRHS (mkNameSet aux_names) rn_aux_lhs
332 ; rn_inst_infos <- mapM rn_inst_info inst_infos
333 ; return (rn_inst_infos, rn_aux `plusHsValBinds` rn_gen) } }
336 (inst_infos, deriv_aux_binds) = unzip insts
338 -- Remove duplicate requests for auxilliary bindings
340 rm_dups acc (b:bs) | any (isDupAux b) acc = rm_dups acc bs
341 | otherwise = rm_dups (b:acc) bs
344 rn_inst_info (InstInfo { iSpec = inst, iBinds = NewTypeDerived co })
345 = return (InstInfo { iSpec = inst, iBinds = NewTypeDerived co })
347 rn_inst_info (InstInfo { iSpec = inst, iBinds = VanillaInst binds sigs })
348 = -- Bring the right type variables into
349 -- scope (yuk), and rename the method binds
351 bindLocalNames (map Var.varName tyvars) $
352 do { (rn_binds, _fvs) <- rnMethodBinds clas_nm (\_ -> []) [] binds
353 ; return (InstInfo { iSpec = inst, iBinds = VanillaInst rn_binds [] }) }
355 (tyvars,_,clas,_) = instanceHead inst
356 clas_nm = className clas
358 -----------------------------------------
359 mkGenericBinds :: Bool -> TcM (LHsBinds RdrName)
360 mkGenericBinds is_boot
364 = do { gbl_env <- getGblEnv
365 ; let tcs = typeEnvTyCons (tcg_type_env gbl_env)
366 ; return (unionManyBags [ mkTyConGenericBinds tc |
367 tc <- tcs, tyConHasGenerics tc ]) }
368 -- We are only interested in the data type declarations,
369 -- and then only in the ones whose 'has-generics' flag is on
370 -- The predicate tyConHasGenerics finds both of these
374 %************************************************************************
376 From HsSyn to DerivSpec
378 %************************************************************************
380 @makeDerivSpecs@ fishes around to find the info about needed derived instances.
383 makeDerivSpecs :: Bool
387 -> TcM [EarlyDerivSpec]
389 makeDerivSpecs is_boot tycl_decls inst_decls deriv_decls
390 | is_boot -- No 'deriving' at all in hs-boot files
391 = do { mapM_ add_deriv_err deriv_locs
394 = do { eqns1 <- mapAndRecoverM deriveTyData all_tydata
395 ; eqns2 <- mapAndRecoverM deriveStandalone deriv_decls
396 ; return (eqns1 ++ eqns2) }
398 extractTyDataPreds decls
399 = [(p, d) | d@(L _ (TyData {tcdDerivs = Just preds})) <- decls, p <- preds]
401 all_tydata :: [(LHsType Name, LTyClDecl Name)]
402 -- Derived predicate paired with its data type declaration
403 all_tydata = extractTyDataPreds tycl_decls ++
404 [ pd -- Traverse assoc data families
405 | L _ (InstDecl _ _ _ ats) <- inst_decls
406 , pd <- extractTyDataPreds ats ]
408 deriv_locs = map (getLoc . snd) all_tydata
409 ++ map getLoc deriv_decls
411 add_deriv_err loc = setSrcSpan loc $
412 addErr (hang (ptext (sLit "Deriving not permitted in hs-boot file"))
413 2 (ptext (sLit "Use an instance declaration instead")))
415 ------------------------------------------------------------------
416 deriveStandalone :: LDerivDecl Name -> TcM EarlyDerivSpec
417 -- Standalone deriving declarations
418 -- e.g. deriving instance Show a => Show (T a)
419 -- Rather like tcLocalInstDecl
420 deriveStandalone (L loc (DerivDecl deriv_ty))
422 addErrCtxt (standaloneCtxt deriv_ty) $
423 do { traceTc (text "standalone deriving decl for" <+> ppr deriv_ty)
424 ; (tvs, theta, tau) <- tcHsInstHead deriv_ty
425 ; traceTc (text "standalone deriving;"
426 <+> text "tvs:" <+> ppr tvs
427 <+> text "theta:" <+> ppr theta
428 <+> text "tau:" <+> ppr tau)
429 ; (cls, inst_tys) <- checkValidInstHead tau
430 ; checkValidInstance tvs theta cls inst_tys
431 -- C.f. TcInstDcls.tcLocalInstDecl1
433 ; let cls_tys = take (length inst_tys - 1) inst_tys
434 inst_ty = last inst_tys
435 ; traceTc (text "standalone deriving;"
436 <+> text "class:" <+> ppr cls
437 <+> text "class types:" <+> ppr cls_tys
438 <+> text "type:" <+> ppr inst_ty)
439 ; mkEqnHelp StandAloneDerivOrigin tvs cls cls_tys inst_ty
442 ------------------------------------------------------------------
443 deriveTyData :: (LHsType Name, LTyClDecl Name) -> TcM EarlyDerivSpec
444 deriveTyData (L loc deriv_pred, L _ decl@(TyData { tcdLName = L _ tycon_name,
445 tcdTyVars = tv_names,
446 tcdTyPats = ty_pats }))
447 = setSrcSpan loc $ -- Use the location of the 'deriving' item
449 do { (tvs, tc, tc_args) <- get_lhs ty_pats
450 ; tcExtendTyVarEnv tvs $ -- Deriving preds may (now) mention
451 -- the type variables for the type constructor
453 do { (deriv_tvs, cls, cls_tys) <- tcHsDeriv deriv_pred
454 -- The "deriv_pred" is a LHsType to take account of the fact that for
455 -- newtype deriving we allow deriving (forall a. C [a]).
457 -- Given data T a b c = ... deriving( C d ),
458 -- we want to drop type variables from T so that (C d (T a)) is well-kinded
459 ; let cls_tyvars = classTyVars cls
460 kind = tyVarKind (last cls_tyvars)
461 (arg_kinds, _) = splitKindFunTys kind
462 n_args_to_drop = length arg_kinds
463 n_args_to_keep = tyConArity tc - n_args_to_drop
464 args_to_drop = drop n_args_to_keep tc_args
465 inst_ty = mkTyConApp tc (take n_args_to_keep tc_args)
466 inst_ty_kind = typeKind inst_ty
467 dropped_tvs = mkVarSet (mapCatMaybes getTyVar_maybe args_to_drop)
468 univ_tvs = (mkVarSet tvs `extendVarSetList` deriv_tvs)
469 `minusVarSet` dropped_tvs
471 -- Check that the result really is well-kinded
472 ; checkTc (n_args_to_keep >= 0 && (inst_ty_kind `eqKind` kind))
473 (derivingKindErr tc cls cls_tys kind)
475 ; checkTc (sizeVarSet dropped_tvs == n_args_to_drop && -- (a)
476 tyVarsOfTypes (inst_ty:cls_tys) `subVarSet` univ_tvs) -- (b)
477 (derivingEtaErr cls cls_tys inst_ty)
479 -- (a) The data type can be eta-reduced; eg reject:
480 -- data instance T a a = ... deriving( Monad )
481 -- (b) The type class args do not mention any of the dropped type
483 -- newtype T a s = ... deriving( ST s )
485 -- Type families can't be partially applied
486 -- e.g. newtype instance T Int a = MkT [a] deriving( Monad )
487 -- Note [Deriving, type families, and partial applications]
488 ; checkTc (not (isOpenTyCon tc) || n_args_to_drop == 0)
489 (typeFamilyPapErr tc cls cls_tys inst_ty)
491 ; mkEqnHelp DerivOrigin (varSetElems univ_tvs) cls cls_tys inst_ty Nothing } }
493 -- Tiresomely we must figure out the "lhs", which is awkward for type families
494 -- E.g. data T a b = .. deriving( Eq )
495 -- Here, the lhs is (T a b)
496 -- data instance TF Int b = ... deriving( Eq )
497 -- Here, the lhs is (TF Int b)
498 -- But if we just look up the tycon_name, we get is the *family*
499 -- tycon, but not pattern types -- they are in the *rep* tycon.
500 get_lhs Nothing = do { tc <- tcLookupTyCon tycon_name
501 ; let tvs = tyConTyVars tc
502 ; return (tvs, tc, mkTyVarTys tvs) }
503 get_lhs (Just pats) = do { let hs_app = nlHsTyConApp tycon_name pats
504 ; (tvs, tc_app) <- tcHsQuantifiedType tv_names hs_app
505 ; let (tc, tc_args) = tcSplitTyConApp tc_app
506 ; return (tvs, tc, tc_args) }
509 = panic "derivTyData" -- Caller ensures that only TyData can happen
512 Note [Deriving, type families, and partial applications]
513 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
514 When there are no type families, it's quite easy:
516 newtype S a = MkS [a]
517 -- :CoS :: S ~ [] -- Eta-reduced
519 instance Eq [a] => Eq (S a) -- by coercion sym (Eq (coMkS a)) : Eq [a] ~ Eq (S a)
520 instance Monad [] => Monad S -- by coercion sym (Monad coMkS) : Monad [] ~ Monad S
522 When type familes are involved it's trickier:
525 newtype instance T Int a = MkT [a] deriving( Eq, Monad )
526 -- :RT is the representation type for (T Int a)
527 -- :CoF:R1T a :: T Int a ~ :RT a -- Not eta reduced
528 -- :Co:R1T :: :RT ~ [] -- Eta-reduced
530 instance Eq [a] => Eq (T Int a) -- easy by coercion
531 instance Monad [] => Monad (T Int) -- only if we can eta reduce???
533 The "???" bit is that we don't build the :CoF thing in eta-reduced form
534 Henc the current typeFamilyPapErr, even though the instance makes sense.
535 After all, we can write it out
536 instance Monad [] => Monad (T Int) -- only if we can eta reduce???
541 mkEqnHelp :: InstOrigin -> [TyVar] -> Class -> [Type] -> Type
542 -> Maybe ThetaType -- Just => context supplied (standalone deriving)
543 -- Nothing => context inferred (deriving on data decl)
544 -> TcRn EarlyDerivSpec
545 -- Make the EarlyDerivSpec for an instance
546 -- forall tvs. theta => cls (tys ++ [ty])
547 -- where the 'theta' is optional (that's the Maybe part)
548 -- Assumes that this declaration is well-kinded
550 mkEqnHelp orig tvs cls cls_tys tc_app mtheta
551 | Just (tycon, tc_args) <- tcSplitTyConApp_maybe tc_app
552 , isAlgTyCon tycon -- Check for functions, primitive types etc
553 = do { (rep_tc, rep_tc_args) <- tcLookupFamInstExact tycon tc_args
554 -- Be careful to test rep_tc here: in the case of families,
555 -- we want to check the instance tycon, not the family tycon
557 -- For standalone deriving (mtheta /= Nothing),
558 -- check that all the data constructors are in scope.
559 -- No need for this when deriving Typeable, becuase we don't need
560 -- the constructors for that.
561 ; rdr_env <- getGlobalRdrEnv
562 ; let hidden_data_cons = isAbstractTyCon rep_tc || any not_in_scope (tyConDataCons rep_tc)
563 not_in_scope dc = null (lookupGRE_Name rdr_env (dataConName dc))
564 ; checkTc (isNothing mtheta ||
565 not hidden_data_cons ||
566 className cls `elem` typeableClassNames)
567 (derivingHiddenErr tycon)
569 ; mayDeriveDataTypeable <- doptM Opt_DeriveDataTypeable
570 ; newtype_deriving <- doptM Opt_GeneralizedNewtypeDeriving
572 ; if isDataTyCon rep_tc then
573 mkDataTypeEqn orig mayDeriveDataTypeable tvs cls cls_tys
574 tycon tc_args rep_tc rep_tc_args mtheta
576 mkNewTypeEqn orig mayDeriveDataTypeable newtype_deriving
578 tycon tc_args rep_tc rep_tc_args mtheta }
580 = failWithTc (derivingThingErr cls cls_tys tc_app
581 (ptext (sLit "The last argument of the instance must be a data or newtype application")))
584 Note [Looking up family instances for deriving]
585 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
586 tcLookupFamInstExact is an auxiliary lookup wrapper which requires
587 that looked-up family instances exist. If called with a vanilla
588 tycon, the old type application is simply returned.
591 data instance F () = ... deriving Eq
592 data instance F () = ... deriving Eq
593 then tcLookupFamInstExact will be confused by the two matches;
594 but that can't happen because tcInstDecls1 doesn't call tcDeriving
595 if there are any overlaps.
597 There are two other things that might go wrong with the lookup.
598 First, we might see a standalone deriving clause
600 when there is no data instance F () in scope.
602 Note that it's OK to have
603 data instance F [a] = ...
604 deriving Eq (F [(a,b)])
605 where the match is not exact; the same holds for ordinary data types
606 with standalone deriving declrations.
609 tcLookupFamInstExact :: TyCon -> [Type] -> TcM (TyCon, [Type])
610 tcLookupFamInstExact tycon tys
611 | not (isOpenTyCon tycon)
612 = return (tycon, tys)
614 = do { maybeFamInst <- tcLookupFamInst tycon tys
615 ; case maybeFamInst of
616 Nothing -> famInstNotFound tycon tys
617 Just famInst -> return famInst
620 famInstNotFound :: TyCon -> [Type] -> TcM a
621 famInstNotFound tycon tys
622 = failWithTc (ptext (sLit "No family instance for")
623 <+> quotes (pprTypeApp tycon tys))
627 %************************************************************************
631 %************************************************************************
634 mkDataTypeEqn :: InstOrigin -> Bool -> [Var] -> Class -> [Type]
635 -> TyCon -> [Type] -> TyCon -> [Type] -> Maybe ThetaType
636 -> TcRn EarlyDerivSpec -- Return 'Nothing' if error
638 mkDataTypeEqn orig mayDeriveDataTypeable tvs cls cls_tys
639 tycon tc_args rep_tc rep_tc_args mtheta
640 = case checkSideConditions mayDeriveDataTypeable cls cls_tys rep_tc of
641 -- NB: pass the *representation* tycon to checkSideConditions
642 CanDerive -> mk_data_eqn orig tvs cls tycon tc_args rep_tc rep_tc_args mtheta
643 NonDerivableClass -> bale_out (nonStdErr cls)
644 DerivableClassError msg -> bale_out msg
646 bale_out msg = failWithTc (derivingThingErr cls cls_tys (mkTyConApp tycon tc_args) msg)
648 mk_data_eqn, mk_typeable_eqn
649 :: InstOrigin -> [TyVar] -> Class
650 -> TyCon -> [TcType] -> TyCon -> [TcType] -> Maybe ThetaType
651 -> TcM EarlyDerivSpec
652 mk_data_eqn orig tvs cls tycon tc_args rep_tc rep_tc_args mtheta
653 | getName cls `elem` typeableClassNames
654 = mk_typeable_eqn orig tvs cls tycon tc_args rep_tc rep_tc_args mtheta
657 = do { dfun_name <- new_dfun_name cls tycon
659 ; let ordinary_constraints
660 = [ mkClassPred cls [arg_ty]
661 | data_con <- tyConDataCons rep_tc,
662 arg_ty <- ASSERT( isVanillaDataCon data_con )
663 dataConInstOrigArgTys data_con rep_tc_args,
664 not (isUnLiftedType arg_ty) ]
665 -- No constraints for unlifted types
666 -- Where they are legal we generate specilised function calls
668 -- See Note [Superclasses of derived instance]
669 sc_constraints = substTheta (zipOpenTvSubst (classTyVars cls) inst_tys)
671 inst_tys = [mkTyConApp tycon tc_args]
673 stupid_subst = zipTopTvSubst (tyConTyVars rep_tc) rep_tc_args
674 stupid_constraints = substTheta stupid_subst (tyConStupidTheta rep_tc)
675 all_constraints = stupid_constraints ++ sc_constraints ++ ordinary_constraints
677 spec = DS { ds_loc = loc, ds_orig = orig
678 , ds_name = dfun_name, ds_tvs = tvs
679 , ds_cls = cls, ds_tys = inst_tys
680 , ds_tc = rep_tc, ds_tc_args = rep_tc_args
681 , ds_theta = mtheta `orElse` all_constraints
682 , ds_newtype = False }
684 ; return (if isJust mtheta then Right spec -- Specified context
685 else Left spec) } -- Infer context
687 mk_typeable_eqn orig tvs cls tycon tc_args rep_tc rep_tc_args mtheta
688 -- The Typeable class is special in several ways
689 -- data T a b = ... deriving( Typeable )
691 -- instance Typeable2 T where ...
693 -- 1. There are no constraints in the instance
694 -- 2. There are no type variables either
695 -- 3. The actual class we want to generate isn't necessarily
696 -- Typeable; it depends on the arity of the type
697 | isNothing mtheta -- deriving on a data type decl
698 = do { checkTc (cls `hasKey` typeableClassKey)
699 (ptext (sLit "Use deriving( Typeable ) on a data type declaration"))
700 ; real_cls <- tcLookupClass (typeableClassNames !! tyConArity tycon)
701 ; mk_typeable_eqn orig tvs real_cls tycon [] rep_tc [] (Just []) }
703 | otherwise -- standaone deriving
704 = do { checkTc (null tc_args)
705 (ptext (sLit "Derived typeable instance must be of form (Typeable")
706 <> int (tyConArity tycon) <+> ppr tycon <> rparen)
707 ; dfun_name <- new_dfun_name cls tycon
710 DS { ds_loc = loc, ds_orig = orig, ds_name = dfun_name, ds_tvs = []
711 , ds_cls = cls, ds_tys = [mkTyConApp tycon []]
712 , ds_tc = rep_tc, ds_tc_args = rep_tc_args
713 , ds_theta = mtheta `orElse` [], ds_newtype = False }) }
715 ------------------------------------------------------------------
716 -- Check side conditions that dis-allow derivability for particular classes
717 -- This is *apart* from the newtype-deriving mechanism
719 -- Here we get the representation tycon in case of family instances as it has
720 -- the data constructors - but we need to be careful to fall back to the
721 -- family tycon (with indexes) in error messages.
723 data DerivStatus = CanDerive
724 | DerivableClassError SDoc -- Standard class, but can't do it
725 | NonDerivableClass -- Non-standard class
727 checkSideConditions :: Bool -> Class -> [TcType] -> TyCon -> DerivStatus
728 checkSideConditions mayDeriveDataTypeable cls cls_tys rep_tc
729 | Just cond <- sideConditions cls
730 = case (cond (mayDeriveDataTypeable, rep_tc)) of
731 Just err -> DerivableClassError err -- Class-specific error
732 Nothing | null cls_tys -> CanDerive
733 | otherwise -> DerivableClassError ty_args_why -- e.g. deriving( Eq s )
734 | otherwise = NonDerivableClass -- Not a standard class
736 ty_args_why = quotes (ppr (mkClassPred cls cls_tys)) <+> ptext (sLit "is not a class")
738 nonStdErr :: Class -> SDoc
739 nonStdErr cls = quotes (ppr cls) <+> ptext (sLit "is not a derivable class")
741 sideConditions :: Class -> Maybe Condition
743 | cls_key == eqClassKey = Just cond_std
744 | cls_key == ordClassKey = Just cond_std
745 | cls_key == showClassKey = Just cond_std
746 | cls_key == readClassKey = Just (cond_std `andCond` cond_noUnliftedArgs)
747 | cls_key == enumClassKey = Just (cond_std `andCond` cond_isEnumeration)
748 | cls_key == ixClassKey = Just (cond_std `andCond` cond_enumOrProduct)
749 | cls_key == boundedClassKey = Just (cond_std `andCond` cond_enumOrProduct)
750 | cls_key == dataClassKey = Just (cond_mayDeriveDataTypeable `andCond` cond_std `andCond` cond_noUnliftedArgs)
751 | getName cls `elem` typeableClassNames = Just (cond_mayDeriveDataTypeable `andCond` cond_typeableOK)
752 | otherwise = Nothing
754 cls_key = getUnique cls
756 type Condition = (Bool, TyCon) -> Maybe SDoc
757 -- Bool is whether or not we are allowed to derive Data and Typeable
758 -- TyCon is the *representation* tycon if the
759 -- data type is an indexed one
762 orCond :: Condition -> Condition -> Condition
765 Nothing -> Nothing -- c1 succeeds
766 Just x -> case c2 tc of -- c1 fails
768 Just y -> Just (x $$ ptext (sLit " and") $$ y)
771 andCond :: Condition -> Condition -> Condition
772 andCond c1 c2 tc = case c1 tc of
773 Nothing -> c2 tc -- c1 succeeds
774 Just x -> Just x -- c1 fails
776 cond_std :: Condition
778 | any (not . isVanillaDataCon) data_cons = Just existential_why
779 | null data_cons = Just no_cons_why
780 | otherwise = Nothing
782 data_cons = tyConDataCons rep_tc
783 no_cons_why = quotes (pprSourceTyCon rep_tc) <+>
784 ptext (sLit "has no data constructors")
785 existential_why = quotes (pprSourceTyCon rep_tc) <+>
786 ptext (sLit "has non-Haskell-98 constructor(s)")
788 cond_enumOrProduct :: Condition
789 cond_enumOrProduct = cond_isEnumeration `orCond`
790 (cond_isProduct `andCond` cond_noUnliftedArgs)
792 cond_noUnliftedArgs :: Condition
793 -- For some classes (eg Eq, Ord) we allow unlifted arg types
794 -- by generating specilaised code. For others (eg Data) we don't.
795 cond_noUnliftedArgs (_, tc)
796 | null bad_cons = Nothing
797 | otherwise = Just why
799 bad_cons = [ con | con <- tyConDataCons tc
800 , any isUnLiftedType (dataConOrigArgTys con) ]
801 why = ptext (sLit "Constructor") <+> quotes (ppr (head bad_cons))
802 <+> ptext (sLit "has arguments of unlifted type")
804 cond_isEnumeration :: Condition
805 cond_isEnumeration (_, rep_tc)
806 | isEnumerationTyCon rep_tc = Nothing
807 | otherwise = Just why
809 why = quotes (pprSourceTyCon rep_tc) <+>
810 ptext (sLit "has non-nullary constructors")
812 cond_isProduct :: Condition
813 cond_isProduct (_, rep_tc)
814 | isProductTyCon rep_tc = Nothing
815 | otherwise = Just why
817 why = quotes (pprSourceTyCon rep_tc) <+>
818 ptext (sLit "has more than one constructor")
820 cond_typeableOK :: Condition
821 -- OK for Typeable class
822 -- Currently: (a) args all of kind *
823 -- (b) 7 or fewer args
824 cond_typeableOK (_, rep_tc)
825 | tyConArity rep_tc > 7 = Just too_many
826 | not (all (isSubArgTypeKind . tyVarKind) (tyConTyVars rep_tc))
828 | isFamInstTyCon rep_tc = Just fam_inst -- no Typable for family insts
829 | otherwise = Nothing
831 too_many = quotes (pprSourceTyCon rep_tc) <+>
832 ptext (sLit "has too many arguments")
833 bad_kind = quotes (pprSourceTyCon rep_tc) <+>
834 ptext (sLit "has arguments of kind other than `*'")
835 fam_inst = quotes (pprSourceTyCon rep_tc) <+>
836 ptext (sLit "is a type family")
838 cond_mayDeriveDataTypeable :: Condition
839 cond_mayDeriveDataTypeable (mayDeriveDataTypeable, _)
840 | mayDeriveDataTypeable = Nothing
841 | otherwise = Just why
843 why = ptext (sLit "You need -XDeriveDataTypeable to derive an instance for this class")
845 std_class_via_iso :: Class -> Bool
846 std_class_via_iso clas -- These standard classes can be derived for a newtype
847 -- using the isomorphism trick *even if no -fglasgow-exts*
848 = classKey clas `elem` [eqClassKey, ordClassKey, ixClassKey, boundedClassKey]
849 -- Not Read/Show because they respect the type
850 -- Not Enum, because newtypes are never in Enum
853 new_dfun_name :: Class -> TyCon -> TcM Name
854 new_dfun_name clas tycon -- Just a simple wrapper
855 = do { loc <- getSrcSpanM -- The location of the instance decl, not of the tycon
856 ; newDFunName clas [mkTyConApp tycon []] loc }
857 -- The type passed to newDFunName is only used to generate
858 -- a suitable string; hence the empty type arg list
861 Note [Superclasses of derived instance]
862 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
863 In general, a derived instance decl needs the superclasses of the derived
864 class too. So if we have
865 data T a = ...deriving( Ord )
866 then the initial context for Ord (T a) should include Eq (T a). Often this is
867 redundant; we'll also generate an Ord constraint for each constructor argument,
868 and that will probably generate enough constraints to make the Eq (T a) constraint
869 be satisfied too. But not always; consider:
875 data T a = MkT (S a) deriving( Ord )
876 instance Num a => Eq (T a)
878 The derived instance for (Ord (T a)) must have a (Num a) constraint!
880 data T a = MkT deriving( Data, Typeable )
881 Here there *is* no argument field, but we must nevertheless generate
882 a context for the Data instances:
883 instance Typable a => Data (T a) where ...
886 %************************************************************************
890 %************************************************************************
893 mkNewTypeEqn :: InstOrigin -> Bool -> Bool -> [Var] -> Class
894 -> [Type] -> TyCon -> [Type] -> TyCon -> [Type]
896 -> TcRn EarlyDerivSpec
897 mkNewTypeEqn orig mayDeriveDataTypeable newtype_deriving tvs
898 cls cls_tys tycon tc_args rep_tycon rep_tc_args mtheta
899 -- Want: instance (...) => cls (cls_tys ++ [tycon tc_args]) where ...
900 | can_derive_via_isomorphism && (newtype_deriving || std_class_via_iso cls)
901 = do { traceTc (text "newtype deriving:" <+> ppr tycon <+> ppr rep_tys)
902 ; dfun_name <- new_dfun_name cls tycon
904 ; let spec = DS { ds_loc = loc, ds_orig = orig
905 , ds_name = dfun_name, ds_tvs = varSetElems dfun_tvs
906 , ds_cls = cls, ds_tys = inst_tys
907 , ds_tc = rep_tycon, ds_tc_args = rep_tc_args
908 , ds_theta = mtheta `orElse` all_preds
909 , ds_newtype = True }
910 ; return (if isJust mtheta then Right spec
914 = case check_conditions of
915 CanDerive -> mk_data_eqn orig tvs cls tycon tc_args rep_tycon rep_tc_args mtheta
916 -- Use the standard H98 method
917 DerivableClassError msg -> bale_out msg -- Error with standard class
918 NonDerivableClass -- Must use newtype deriving
919 | newtype_deriving -> bale_out cant_derive_err -- Too hard, even with newtype deriving
920 | otherwise -> bale_out non_std_err -- Try newtype deriving!
922 check_conditions = checkSideConditions mayDeriveDataTypeable cls cls_tys rep_tycon
923 bale_out msg = failWithTc (derivingThingErr cls cls_tys inst_ty msg)
925 non_std_err = nonStdErr cls $$
926 ptext (sLit "Try -XGeneralizedNewtypeDeriving for GHC's newtype-deriving extension")
928 -- Here is the plan for newtype derivings. We see
929 -- newtype T a1...an = MkT (t ak+1...an) deriving (.., C s1 .. sm, ...)
930 -- where t is a type,
931 -- ak+1...an is a suffix of a1..an, and are all tyars
932 -- ak+1...an do not occur free in t, nor in the s1..sm
933 -- (C s1 ... sm) is a *partial applications* of class C
934 -- with the last parameter missing
935 -- (T a1 .. ak) matches the kind of C's last argument
936 -- (and hence so does t)
937 -- The latter kind-check has been done by deriveTyData already,
938 -- and tc_args are already trimmed
940 -- We generate the instance
941 -- instance forall ({a1..ak} u fvs(s1..sm)).
942 -- C s1 .. sm t => C s1 .. sm (T a1...ak)
943 -- where T a1...ap is the partial application of
944 -- the LHS of the correct kind and p >= k
946 -- NB: the variables below are:
947 -- tc_tvs = [a1, ..., an]
948 -- tyvars_to_keep = [a1, ..., ak]
949 -- rep_ty = t ak .. an
950 -- deriv_tvs = fvs(s1..sm) \ tc_tvs
951 -- tys = [s1, ..., sm]
954 -- Running example: newtype T s a = MkT (ST s a) deriving( Monad )
955 -- We generate the instance
956 -- instance Monad (ST s) => Monad (T s) where
958 nt_eta_arity = length (fst (newTyConEtadRhs rep_tycon))
959 -- For newtype T a b = MkT (S a a b), the TyCon machinery already
960 -- eta-reduces the representation type, so we know that
962 -- That's convenient here, because we may have to apply
963 -- it to fewer than its original complement of arguments
965 -- Note [Newtype representation]
966 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
967 -- Need newTyConRhs (*not* a recursive representation finder)
968 -- to get the representation type. For example
969 -- newtype B = MkB Int
970 -- newtype A = MkA B deriving( Num )
971 -- We want the Num instance of B, *not* the Num instance of Int,
972 -- when making the Num instance of A!
973 rep_inst_ty = newTyConInstRhs rep_tycon rep_tc_args
974 rep_tys = cls_tys ++ [rep_inst_ty]
975 rep_pred = mkClassPred cls rep_tys
976 -- rep_pred is the representation dictionary, from where
977 -- we are gong to get all the methods for the newtype
981 -- Next we figure out what superclass dictionaries to use
982 -- See Note [Newtype deriving superclasses] above
984 cls_tyvars = classTyVars cls
985 dfun_tvs = tyVarsOfTypes inst_tys
986 inst_ty = mkTyConApp tycon tc_args
987 inst_tys = cls_tys ++ [inst_ty]
988 sc_theta = substTheta (zipOpenTvSubst cls_tyvars inst_tys)
991 -- If there are no tyvars, there's no need
992 -- to abstract over the dictionaries we need
993 -- Example: newtype T = MkT Int deriving( C )
994 -- We get the derived instance
997 -- instance C Int => C T
998 all_preds = rep_pred : sc_theta -- NB: rep_pred comes first
1000 -------------------------------------------------------------------
1001 -- Figuring out whether we can only do this newtype-deriving thing
1003 can_derive_via_isomorphism
1004 = not (non_iso_class cls)
1008 -- && not (isRecursiveTyCon tycon) -- Note [Recursive newtypes]
1010 -- Never derive Read,Show,Typeable,Data by isomorphism
1011 non_iso_class cls = className cls `elem` ([readClassName, showClassName, dataClassName] ++
1014 arity_ok = length cls_tys + 1 == classArity cls
1015 -- Well kinded; eg not: newtype T ... deriving( ST )
1016 -- because ST needs *2* type params
1018 -- Check that eta reduction is OK
1019 eta_ok = nt_eta_arity <= length rep_tc_args
1020 -- The newtype can be eta-reduced to match the number
1021 -- of type argument actually supplied
1022 -- newtype T a b = MkT (S [a] b) deriving( Monad )
1023 -- Here the 'b' must be the same in the rep type (S [a] b)
1024 -- And the [a] must not mention 'b'. That's all handled
1027 ats_ok = null (classATs cls)
1028 -- No associated types for the class, because we don't
1029 -- currently generate type 'instance' decls; and cannot do
1030 -- so for 'data' instance decls
1033 = vcat [ ptext (sLit "even with cunning newtype deriving:")
1034 , if arity_ok then empty else arity_msg
1035 , if eta_ok then empty else eta_msg
1036 , if ats_ok then empty else ats_msg ]
1037 arity_msg = quotes (ppr (mkClassPred cls cls_tys)) <+> ptext (sLit "does not have arity 1")
1038 eta_msg = ptext (sLit "cannot eta-reduce the representation type enough")
1039 ats_msg = ptext (sLit "the class has associated types")
1042 Note [Recursive newtypes]
1043 ~~~~~~~~~~~~~~~~~~~~~~~~~
1044 Newtype deriving works fine, even if the newtype is recursive.
1045 e.g. newtype S1 = S1 [T1 ()]
1046 newtype T1 a = T1 (StateT S1 IO a ) deriving( Monad )
1047 Remember, too, that type families are curretly (conservatively) given
1048 a recursive flag, so this also allows newtype deriving to work
1051 We used to exclude recursive types, because we had a rather simple
1052 minded way of generating the instance decl:
1054 instance Eq [A] => Eq A -- Makes typechecker loop!
1055 But now we require a simple context, so it's ok.
1058 %************************************************************************
1060 \subsection[TcDeriv-fixpoint]{Finding the fixed point of \tr{deriving} equations}
1062 %************************************************************************
1064 A ``solution'' (to one of the equations) is a list of (k,TyVarTy tv)
1065 terms, which is the final correct RHS for the corresponding original
1069 Each (k,TyVarTy tv) in a solution constrains only a type
1073 The (k,TyVarTy tv) pairs in a solution are canonically
1074 ordered by sorting on type varible, tv, (major key) and then class, k,
1079 inferInstanceContexts :: OverlapFlag -> [DerivSpec] -> TcM [DerivSpec]
1081 inferInstanceContexts _ [] = return []
1083 inferInstanceContexts oflag infer_specs
1084 = do { traceTc (text "inferInstanceContexts" <+> vcat (map pprDerivSpec infer_specs))
1085 ; iterate_deriv 1 initial_solutions }
1087 ------------------------------------------------------------------
1088 -- The initial solutions for the equations claim that each
1089 -- instance has an empty context; this solution is certainly
1090 -- in canonical form.
1091 initial_solutions :: [ThetaType]
1092 initial_solutions = [ [] | _ <- infer_specs ]
1094 ------------------------------------------------------------------
1095 -- iterate_deriv calculates the next batch of solutions,
1096 -- compares it with the current one; finishes if they are the
1097 -- same, otherwise recurses with the new solutions.
1098 -- It fails if any iteration fails
1099 iterate_deriv :: Int -> [ThetaType] -> TcM [DerivSpec]
1100 iterate_deriv n current_solns
1101 | n > 20 -- Looks as if we are in an infinite loop
1102 -- This can happen if we have -XUndecidableInstances
1103 -- (See TcSimplify.tcSimplifyDeriv.)
1104 = pprPanic "solveDerivEqns: probable loop"
1105 (vcat (map pprDerivSpec infer_specs) $$ ppr current_solns)
1107 = do { -- Extend the inst info from the explicit instance decls
1108 -- with the current set of solutions, and simplify each RHS
1109 let inst_specs = zipWithEqual "add_solns" (mkInstance oflag)
1110 current_solns infer_specs
1111 ; new_solns <- checkNoErrs $
1112 extendLocalInstEnv inst_specs $
1113 mapM gen_soln infer_specs
1115 ; if (current_solns == new_solns) then
1116 return [ spec { ds_theta = soln }
1117 | (spec, soln) <- zip infer_specs current_solns ]
1119 iterate_deriv (n+1) new_solns }
1121 ------------------------------------------------------------------
1122 gen_soln :: DerivSpec -> TcM [PredType]
1123 gen_soln (DS { ds_loc = loc, ds_orig = orig, ds_tvs = tyvars
1124 , ds_cls = clas, ds_tys = inst_tys, ds_theta = deriv_rhs })
1126 addErrCtxt (derivInstCtxt clas inst_tys) $
1127 do { theta <- tcSimplifyDeriv orig tyvars deriv_rhs
1128 -- checkValidInstance tyvars theta clas inst_tys
1129 -- Not necessary; see Note [Exotic derived instance contexts]
1132 -- Check for a bizarre corner case, when the derived instance decl should
1133 -- have form instance C a b => D (T a) where ...
1134 -- Note that 'b' isn't a parameter of T. This gives rise to all sorts
1135 -- of problems; in particular, it's hard to compare solutions for
1136 -- equality when finding the fixpoint. So I just rule it out for now.
1137 ; let tv_set = mkVarSet tyvars
1138 weird_preds = [pred | pred <- theta, not (tyVarsOfPred pred `subVarSet` tv_set)]
1139 ; mapM_ (addErrTc . badDerivedPred) weird_preds
1141 -- Claim: the result instance declaration is guaranteed valid
1142 -- Hence no need to call:
1143 -- checkValidInstance tyvars theta clas inst_tys
1144 ; return (sortLe (<=) theta) } -- Canonicalise before returning the solution
1146 ------------------------------------------------------------------
1147 mkInstance :: OverlapFlag -> ThetaType -> DerivSpec -> Instance
1148 mkInstance overlap_flag theta
1149 (DS { ds_name = dfun_name
1150 , ds_tvs = tyvars, ds_cls = clas, ds_tys = tys })
1151 = mkLocalInstance dfun overlap_flag
1153 dfun = mkDictFunId dfun_name tyvars theta clas tys
1156 extendLocalInstEnv :: [Instance] -> TcM a -> TcM a
1157 -- Add new locally-defined instances; don't bother to check
1158 -- for functional dependency errors -- that'll happen in TcInstDcls
1159 extendLocalInstEnv dfuns thing_inside
1160 = do { env <- getGblEnv
1161 ; let inst_env' = extendInstEnvList (tcg_inst_env env) dfuns
1162 env' = env { tcg_inst_env = inst_env' }
1163 ; setGblEnv env' thing_inside }
1167 %************************************************************************
1169 \subsection[TcDeriv-normal-binds]{Bindings for the various classes}
1171 %************************************************************************
1173 After all the trouble to figure out the required context for the
1174 derived instance declarations, all that's left is to chug along to
1175 produce them. They will then be shoved into @tcInstDecls2@, which
1176 will do all its usual business.
1178 There are lots of possibilities for code to generate. Here are
1179 various general remarks.
1184 We want derived instances of @Eq@ and @Ord@ (both v common) to be
1185 ``you-couldn't-do-better-by-hand'' efficient.
1188 Deriving @Show@---also pretty common--- should also be reasonable good code.
1191 Deriving for the other classes isn't that common or that big a deal.
1198 Deriving @Ord@ is done mostly with the 1.3 @compare@ method.
1201 Deriving @Eq@ also uses @compare@, if we're deriving @Ord@, too.
1204 We {\em normally} generate code only for the non-defaulted methods;
1205 there are some exceptions for @Eq@ and (especially) @Ord@...
1208 Sometimes we use a @_con2tag_<tycon>@ function, which returns a data
1209 constructor's numeric (@Int#@) tag. These are generated by
1210 @gen_tag_n_con_binds@, and the heuristic for deciding if one of
1211 these is around is given by @hasCon2TagFun@.
1213 The examples under the different sections below will make this
1217 Much less often (really just for deriving @Ix@), we use a
1218 @_tag2con_<tycon>@ function. See the examples.
1221 We use the renamer!!! Reason: we're supposed to be
1222 producing @LHsBinds Name@ for the methods, but that means
1223 producing correctly-uniquified code on the fly. This is entirely
1224 possible (the @TcM@ monad has a @UniqueSupply@), but it is painful.
1225 So, instead, we produce @MonoBinds RdrName@ then heave 'em through
1226 the renamer. What a great hack!
1230 -- Generate the InstInfo for the required instance paired with the
1231 -- *representation* tycon for that instance,
1232 -- plus any auxiliary bindings required
1234 -- Representation tycons differ from the tycon in the instance signature in
1235 -- case of instances for indexed families.
1237 genInst :: OverlapFlag -> DerivSpec -> TcM (InstInfo RdrName, DerivAuxBinds)
1240 = return (InstInfo { iSpec = mkInstance oflag (ds_theta spec) spec
1241 , iBinds = NewTypeDerived co }, [])
1244 = do { let loc = getSrcSpan (ds_name spec)
1245 inst = mkInstance oflag (ds_theta spec) spec
1248 -- In case of a family instance, we need to use the representation
1249 -- tycon (after all, it has the data constructors)
1250 ; fix_env <- getFixityEnv
1251 ; let (meth_binds, aux_binds) = genDerivBinds loc fix_env clas rep_tycon
1253 -- Build the InstInfo
1254 ; return (InstInfo { iSpec = inst,
1255 iBinds = VanillaInst meth_binds [] },
1259 rep_tycon = ds_tc spec
1260 rep_tc_args = ds_tc_args spec
1261 co1 = case tyConFamilyCoercion_maybe rep_tycon of
1263 Just co_con -> ACo (mkTyConApp co_con rep_tc_args)
1264 co2 = case newTyConCo_maybe rep_tycon of
1265 Nothing -> IdCo -- The newtype is transparent; no need for a cast
1266 Just co_con -> ACo (mkTyConApp co_con rep_tc_args)
1267 co = co1 `mkTransCoI` co2
1269 -- Example: newtype instance N [a] = N1 (Tree a)
1270 -- deriving instance Eq b => Eq (N [(b,b)])
1271 -- From the instance, we get an implicit newtype R1:N a = N1 (Tree a)
1272 -- When dealing with the deriving clause
1273 -- co1 : N [(b,b)] ~ R1:N (b,b)
1274 -- co2 : R1:N (b,b) ~ Tree (b,b)
1276 genDerivBinds :: SrcSpan -> FixityEnv -> Class -> TyCon -> (LHsBinds RdrName, DerivAuxBinds)
1277 genDerivBinds loc fix_env clas tycon
1278 | className clas `elem` typeableClassNames
1279 = (gen_Typeable_binds loc tycon, [])
1282 = case assocMaybe gen_list (getUnique clas) of
1283 Just gen_fn -> gen_fn loc tycon
1284 Nothing -> pprPanic "genDerivBinds: bad derived class" (ppr clas)
1286 gen_list :: [(Unique, SrcSpan -> TyCon -> (LHsBinds RdrName, DerivAuxBinds))]
1287 gen_list = [(eqClassKey, gen_Eq_binds)
1288 ,(ordClassKey, gen_Ord_binds)
1289 ,(enumClassKey, gen_Enum_binds)
1290 ,(boundedClassKey, gen_Bounded_binds)
1291 ,(ixClassKey, gen_Ix_binds)
1292 ,(showClassKey, gen_Show_binds fix_env)
1293 ,(readClassKey, gen_Read_binds fix_env)
1294 ,(dataClassKey, gen_Data_binds)
1299 %************************************************************************
1301 \subsection[TcDeriv-taggery-Names]{What con2tag/tag2con functions are available?}
1303 %************************************************************************
1306 derivingKindErr :: TyCon -> Class -> [Type] -> Kind -> Message
1307 derivingKindErr tc cls cls_tys cls_kind
1308 = hang (ptext (sLit "Cannot derive well-kinded instance of form")
1309 <+> quotes (pprClassPred cls cls_tys <+> parens (ppr tc <+> ptext (sLit "..."))))
1310 2 (ptext (sLit "Class") <+> quotes (ppr cls)
1311 <+> ptext (sLit "expects an argument of kind") <+> quotes (pprKind cls_kind))
1313 derivingEtaErr :: Class -> [Type] -> Type -> Message
1314 derivingEtaErr cls cls_tys inst_ty
1315 = sep [ptext (sLit "Cannot eta-reduce to an instance of form"),
1316 nest 2 (ptext (sLit "instance (...) =>")
1317 <+> pprClassPred cls (cls_tys ++ [inst_ty]))]
1319 typeFamilyPapErr :: TyCon -> Class -> [Type] -> Type -> Message
1320 typeFamilyPapErr tc cls cls_tys inst_ty
1321 = hang (ptext (sLit "Derived instance") <+> quotes (pprClassPred cls (cls_tys ++ [inst_ty])))
1322 2 (ptext (sLit "requires illegal partial application of data type family") <+> ppr tc)
1324 derivingThingErr :: Class -> [Type] -> Type -> Message -> Message
1325 derivingThingErr clas tys ty why
1326 = sep [hsep [ptext (sLit "Can't make a derived instance of"),
1328 nest 2 (parens why)]
1330 pred = mkClassPred clas (tys ++ [ty])
1332 derivingHiddenErr :: TyCon -> SDoc
1333 derivingHiddenErr tc
1334 = hang (ptext (sLit "The data constructors of") <+> quotes (ppr tc) <+> ptext (sLit "are not all in scope"))
1335 2 (ptext (sLit "so you cannot derive an instance for it"))
1337 standaloneCtxt :: LHsType Name -> SDoc
1338 standaloneCtxt ty = hang (ptext (sLit "In the stand-alone deriving instance for"))
1341 derivInstCtxt :: Class -> [Type] -> Message
1342 derivInstCtxt clas inst_tys
1343 = ptext (sLit "When deriving the instance for") <+> parens (pprClassPred clas inst_tys)
1345 badDerivedPred :: PredType -> Message
1347 = vcat [ptext (sLit "Can't derive instances where the instance context mentions"),
1348 ptext (sLit "type variables that are not data type parameters"),
1349 nest 2 (ptext (sLit "Offending constraint:") <+> ppr pred)]