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
53 %************************************************************************
57 %************************************************************************
61 1. Convert the decls (i.e. data/newtype deriving clauses,
62 plus standalone deriving) to [EarlyDerivSpec]
64 2. Infer the missing contexts for the Left DerivSpecs
66 3. Add the derived bindings, generating InstInfos
69 -- DerivSpec is purely local to this module
70 data DerivSpec = DS { ds_loc :: SrcSpan
71 , ds_orig :: InstOrigin
74 , ds_theta :: ThetaType
77 , ds_newtype :: Bool }
78 -- This spec implies a dfun declaration of the form
79 -- df :: forall tvs. theta => C tys
80 -- The Name is the name for the DFun we'll build
81 -- The tyvars bind all the variables in the theta
82 -- For family indexes, the tycon is the *family* tycon
83 -- (not the representation tycon)
85 -- ds_newtype = True <=> Newtype deriving
86 -- False <=> Vanilla deriving
88 type EarlyDerivSpec = Either DerivSpec DerivSpec
89 -- Left ds => the context for the instance should be inferred
90 -- In this case ds_theta is the list of all the
91 -- constraints needed, such as (Eq [a], Eq a)
92 -- The inference process is to reduce this to a
93 -- simpler form (e.g. Eq a)
95 -- Right ds => the exact context for the instance is supplied
96 -- by the programmer; it is ds_theta
98 pprDerivSpec :: DerivSpec -> SDoc
99 pprDerivSpec (DS { ds_loc = l, ds_name = n, ds_tvs = tvs,
100 ds_cls = c, ds_tys = tys, ds_theta = rhs })
101 = parens (hsep [ppr l, ppr n, ppr tvs, ppr c, ppr tys]
102 <+> equals <+> ppr rhs)
106 Inferring missing contexts
107 ~~~~~~~~~~~~~~~~~~~~~~~~~~
110 data T a b = C1 (Foo a) (Bar b)
115 [NOTE: See end of these comments for what to do with
116 data (C a, D b) => T a b = ...
119 We want to come up with an instance declaration of the form
121 instance (Ping a, Pong b, ...) => Eq (T a b) where
124 It is pretty easy, albeit tedious, to fill in the code "...". The
125 trick is to figure out what the context for the instance decl is,
126 namely @Ping@, @Pong@ and friends.
128 Let's call the context reqd for the T instance of class C at types
129 (a,b, ...) C (T a b). Thus:
131 Eq (T a b) = (Ping a, Pong b, ...)
133 Now we can get a (recursive) equation from the @data@ decl:
135 Eq (T a b) = Eq (Foo a) u Eq (Bar b) -- From C1
136 u Eq (T b a) u Eq Int -- From C2
137 u Eq (T a a) -- From C3
139 Foo and Bar may have explicit instances for @Eq@, in which case we can
140 just substitute for them. Alternatively, either or both may have
141 their @Eq@ instances given by @deriving@ clauses, in which case they
142 form part of the system of equations.
144 Now all we need do is simplify and solve the equations, iterating to
145 find the least fixpoint. Notice that the order of the arguments can
146 switch around, as here in the recursive calls to T.
148 Let's suppose Eq (Foo a) = Eq a, and Eq (Bar b) = Ping b.
152 Eq (T a b) = {} -- The empty set
155 Eq (T a b) = Eq (Foo a) u Eq (Bar b) -- From C1
156 u Eq (T b a) u Eq Int -- From C2
157 u Eq (T a a) -- From C3
159 After simplification:
160 = Eq a u Ping b u {} u {} u {}
165 Eq (T a b) = Eq (Foo a) u Eq (Bar b) -- From C1
166 u Eq (T b a) u Eq Int -- From C2
167 u Eq (T a a) -- From C3
169 After simplification:
174 = Eq a u Ping b u Eq b u Ping a
176 The next iteration gives the same result, so this is the fixpoint. We
177 need to make a canonical form of the RHS to ensure convergence. We do
178 this by simplifying the RHS to a form in which
180 - the classes constrain only tyvars
181 - the list is sorted by tyvar (major key) and then class (minor key)
182 - no duplicates, of course
184 So, here are the synonyms for the ``equation'' structures:
187 Note [Data decl contexts]
188 ~~~~~~~~~~~~~~~~~~~~~~~~~
191 data (RealFloat a) => Complex a = !a :+ !a deriving( Read )
193 We will need an instance decl like:
195 instance (Read a, RealFloat a) => Read (Complex a) where
198 The RealFloat in the context is because the read method for Complex is bound
199 to construct a Complex, and doing that requires that the argument type is
202 But this ain't true for Show, Eq, Ord, etc, since they don't construct
203 a Complex; they only take them apart.
205 Our approach: identify the offending classes, and add the data type
206 context to the instance decl. The "offending classes" are
210 FURTHER NOTE ADDED March 2002. In fact, Haskell98 now requires that
211 pattern matching against a constructor from a data type with a context
212 gives rise to the constraints for that context -- or at least the thinned
213 version. So now all classes are "offending".
215 Note [Newtype deriving]
216 ~~~~~~~~~~~~~~~~~~~~~~~
220 newtype T = T Char deriving( C [a] )
222 Notice the free 'a' in the deriving. We have to fill this out to
223 newtype T = T Char deriving( forall a. C [a] )
225 And then translate it to:
226 instance C [a] Char => C [a] T where ...
229 Note [Newtype deriving superclasses]
230 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
231 (See also Trac #1220 for an interesting exchange on newtype
232 deriving and superclasses.)
234 The 'tys' here come from the partial application in the deriving
235 clause. The last arg is the new instance type.
237 We must pass the superclasses; the newtype might be an instance
238 of them in a different way than the representation type
239 E.g. newtype Foo a = Foo a deriving( Show, Num, Eq )
240 Then the Show instance is not done via isomorphism; it shows
242 The Num instance is derived via isomorphism, but the Show superclass
243 dictionary must the Show instance for Foo, *not* the Show dictionary
244 gotten from the Num dictionary. So we must build a whole new dictionary
245 not just use the Num one. The instance we want is something like:
246 instance (Num a, Show (Foo a), Eq (Foo a)) => Num (Foo a) where
249 There may be a coercion needed which we get from the tycon for the newtype
250 when the dict is constructed in TcInstDcls.tcInstDecl2
255 %************************************************************************
257 \subsection[TcDeriv-driver]{Top-level function for \tr{derivings}}
259 %************************************************************************
262 tcDeriving :: [LTyClDecl Name] -- All type constructors
263 -> [LInstDecl Name] -- All instance declarations
264 -> [LDerivDecl Name] -- All stand-alone deriving declarations
265 -> TcM ([InstInfo], -- The generated "instance decls"
266 HsValBinds Name) -- Extra generated top-level bindings
268 tcDeriving tycl_decls inst_decls deriv_decls
269 = recoverM (return ([], emptyValBindsOut)) $
270 do { -- Fish the "deriving"-related information out of the TcEnv
271 -- And make the necessary "equations".
272 ; early_specs <- makeDerivSpecs tycl_decls inst_decls deriv_decls
274 ; overlap_flag <- getOverlapFlag
275 ; let (infer_specs, given_specs) = splitEithers early_specs
276 ; (insts1, aux_binds1) <- mapAndUnzipM (genInst overlap_flag) given_specs
278 ; final_specs <- extendLocalInstEnv (map iSpec insts1) $
279 inferInstanceContexts overlap_flag infer_specs
281 ; (insts2, aux_binds2) <- mapAndUnzipM (genInst overlap_flag) final_specs
283 ; is_boot <- tcIsHsBoot
284 ; rn_binds <- makeAuxBinds is_boot tycl_decls
285 (concat aux_binds1 ++ concat aux_binds2)
287 ; let inst_info = insts1 ++ insts2
290 ; liftIO (dumpIfSet_dyn dflags Opt_D_dump_deriv "Derived instances"
291 (ddump_deriving inst_info rn_binds))
293 ; return (inst_info, rn_binds) }
295 ddump_deriving :: [InstInfo] -> HsValBinds Name -> SDoc
296 ddump_deriving inst_infos extra_binds
297 = vcat (map pprInstInfoDetails inst_infos) $$ ppr extra_binds
299 makeAuxBinds :: Bool -> [LTyClDecl Name] -> DerivAuxBinds -> TcM (HsValBinds Name)
300 makeAuxBinds is_boot tycl_decls deriv_aux_binds
301 | is_boot -- If we are compiling a hs-boot file,
302 -- don't generate any derived bindings
303 = return emptyValBindsOut
306 = do { let aux_binds = listToBag (map genAuxBind (rm_dups [] deriv_aux_binds))
307 -- Generate any extra not-one-inst-decl-specific binds,
308 -- notably "con2tag" and/or "tag2con" functions.
310 -- Generate the generic to/from functions from each type declaration
311 ; gen_binds <- mkGenericBinds tycl_decls
313 -- Rename these extra bindings, discarding warnings about unused bindings etc
314 -- Type signatures in patterns are used in the generic binds
316 setOptM Opt_PatternSignatures $
317 do { (rn_deriv, _dus1) <- rnTopBinds (ValBindsIn aux_binds [])
318 ; (rn_gen, dus_gen) <- rnTopBinds (ValBindsIn gen_binds [])
319 ; keepAliveSetTc (duDefs dus_gen) -- Mark these guys to
321 ; return (rn_deriv `plusHsValBinds` rn_gen) } }
323 -- Remove duplicate requests for auxilliary bindings
325 rm_dups acc (b:bs) | any (isDupAux b) acc = rm_dups acc bs
326 | otherwise = rm_dups (b:acc) bs
328 -----------------------------------------
329 mkGenericBinds :: [LTyClDecl Name] -> TcM (LHsBinds RdrName)
330 mkGenericBinds tycl_decls
331 = do { tcs <- mapM tcLookupTyCon
333 L _ (TyData { tcdLName = L _ tc_name }) <- tycl_decls]
334 -- We are only interested in the data type declarations
335 ; return (unionManyBags [ mkTyConGenericBinds tc |
336 tc <- tcs, tyConHasGenerics tc ]) }
337 -- And then only in the ones whose 'has-generics' flag is on
341 %************************************************************************
343 From HsSyn to DerivSpec
345 %************************************************************************
347 @makeDerivSpecs@ fishes around to find the info about needed derived
348 instances. Complicating factors:
351 We can only derive @Enum@ if the data type is an enumeration
352 type (all nullary data constructors).
355 We can only derive @Ix@ if the data type is an enumeration {\em
356 or} has just one data constructor (e.g., tuples).
359 [See Appendix~E in the Haskell~1.2 report.] This code here deals w/
363 makeDerivSpecs :: [LTyClDecl Name]
366 -> TcM [EarlyDerivSpec]
368 makeDerivSpecs tycl_decls inst_decls deriv_decls
369 = do { eqns1 <- mapAndRecoverM deriveTyData $
370 extractTyDataPreds tycl_decls ++
371 [ pd -- traverse assoc data families
372 | L _ (InstDecl _ _ _ ats) <- inst_decls
373 , pd <- extractTyDataPreds ats ]
374 ; eqns2 <- mapAndRecoverM deriveStandalone deriv_decls
375 ; return (catMaybes (eqns1 ++ eqns2)) }
377 extractTyDataPreds decls =
378 [(p, d) | d@(L _ (TyData {tcdDerivs = Just preds})) <- decls, p <- preds]
381 ------------------------------------------------------------------
382 deriveStandalone :: LDerivDecl Name -> TcM (Maybe EarlyDerivSpec)
383 -- Standalone deriving declarations
384 -- e.g. deriving instance show a => Show (T a)
385 -- Rather like tcLocalInstDecl
386 deriveStandalone (L loc (DerivDecl deriv_ty))
388 addErrCtxt (standaloneCtxt deriv_ty) $
389 do { traceTc (text "standalone deriving decl for" <+> ppr deriv_ty)
390 ; (tvs, theta, tau) <- tcHsInstHead deriv_ty
391 ; traceTc (text "standalone deriving;"
392 <+> text "tvs:" <+> ppr tvs
393 <+> text "theta:" <+> ppr theta
394 <+> text "tau:" <+> ppr tau)
395 ; (cls, inst_tys) <- checkValidInstHead tau
396 ; checkValidInstance tvs theta cls inst_tys
397 -- C.f. TcInstDcls.tcLocalInstDecl1
399 ; let cls_tys = take (length inst_tys - 1) inst_tys
400 inst_ty = last inst_tys
401 ; traceTc (text "standalone deriving;"
402 <+> text "class:" <+> ppr cls
403 <+> text "class types:" <+> ppr cls_tys
404 <+> text "type:" <+> ppr inst_ty)
405 ; mkEqnHelp StandAloneDerivOrigin tvs cls cls_tys inst_ty
408 ------------------------------------------------------------------
409 deriveTyData :: (LHsType Name, LTyClDecl Name) -> TcM (Maybe EarlyDerivSpec)
410 deriveTyData (deriv_pred, L loc decl@(TyData { tcdLName = L _ tycon_name,
411 tcdTyVars = tv_names,
412 tcdTyPats = ty_pats }))
415 do { let hs_ty_args = ty_pats `orElse` map (nlHsTyVar . hsLTyVarName) tv_names
416 hs_app = nlHsTyConApp tycon_name hs_ty_args
417 -- We get kinding info for the tyvars by typechecking (T a b)
418 -- Hence forming a tycon application and then dis-assembling it
419 ; (tvs, tc_app) <- tcHsQuantifiedType tv_names hs_app
420 ; tcExtendTyVarEnv tvs $ -- Deriving preds may (now) mention
421 -- the type variables for the type constructor
422 do { (deriv_tvs, cls, cls_tys) <- tcHsDeriv deriv_pred
423 -- The "deriv_pred" is a LHsType to take account of the fact that for
424 -- newtype deriving we allow deriving (forall a. C [a]).
425 ; mkEqnHelp DerivOrigin (tvs++deriv_tvs) cls cls_tys tc_app Nothing } }
428 = panic "derivTyData" -- Caller ensures that only TyData can happen
430 ------------------------------------------------------------------
431 mkEqnHelp :: InstOrigin -> [TyVar] -> Class -> [Type] -> Type
432 -> Maybe ThetaType -- Just => context supplied (standalone deriving)
433 -- Nothing => context inferred (deriving on data decl)
434 -> TcRn (Maybe EarlyDerivSpec)
435 mkEqnHelp orig tvs cls cls_tys tc_app mtheta
436 | Just (tycon, tc_args) <- tcSplitTyConApp_maybe tc_app
437 , isAlgTyCon tycon -- Check for functions, primitive types etc
438 = do { (rep_tc, rep_tc_args) <- tcLookupFamInstExact tycon tc_args
439 -- Be careful to test rep_tc here: in the case of families,
440 -- we want to check the instance tycon, not the family tycon
442 -- For standalone deriving (mtheta /= Nothing),
443 -- check that all the data constructors are in scope
444 -- By this time we know that the thing is algebraic
445 -- because we've called checkInstHead in derivingStandalone
446 ; rdr_env <- getGlobalRdrEnv
447 ; let hidden_data_cons = isAbstractTyCon rep_tc || any not_in_scope (tyConDataCons rep_tc)
448 not_in_scope dc = null (lookupGRE_Name rdr_env (dataConName dc))
449 ; checkTc (isNothing mtheta || not hidden_data_cons)
450 (derivingHiddenErr tycon)
452 ; mayDeriveDataTypeable <- doptM Opt_DeriveDataTypeable
453 ; newtype_deriving <- doptM Opt_GeneralizedNewtypeDeriving
455 ; if isDataTyCon rep_tc then
456 mkDataTypeEqn orig mayDeriveDataTypeable tvs cls cls_tys
457 tycon tc_args rep_tc rep_tc_args mtheta
459 mkNewTypeEqn orig mayDeriveDataTypeable newtype_deriving
461 tycon tc_args rep_tc rep_tc_args mtheta }
463 = baleOut (derivingThingErr cls cls_tys tc_app
464 (ptext (sLit "The last argument of the instance must be a data or newtype application")))
466 baleOut :: Message -> TcM (Maybe a)
467 baleOut err = do { addErrTc err; return Nothing }
470 Note [Looking up family instances for deriving]
471 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
472 tcLookupFamInstExact is an auxiliary lookup wrapper which requires
473 that looked-up family instances exist. If called with a vanilla
474 tycon, the old type application is simply returned.
477 data instance F () = ... deriving Eq
478 data instance F () = ... deriving Eq
479 then tcLookupFamInstExact will be confused by the two matches;
480 but that can't happen because tcInstDecls1 doesn't call tcDeriving
481 if there are any overlaps.
483 There are two other things that might go wrong with the lookup.
484 First, we might see a standalone deriving clause
486 when there is no data instance F () in scope.
488 Note that it's OK to have
489 data instance F [a] = ...
490 deriving Eq (F [(a,b)])
491 where the match is not exact; the same holds for ordinary data types
492 with standalone deriving declrations.
495 tcLookupFamInstExact :: TyCon -> [Type] -> TcM (TyCon, [Type])
496 tcLookupFamInstExact tycon tys
497 | not (isOpenTyCon tycon)
498 = return (tycon, tys)
500 = do { maybeFamInst <- tcLookupFamInst tycon tys
501 ; case maybeFamInst of
502 Nothing -> famInstNotFound tycon tys
503 Just famInst -> return famInst
506 famInstNotFound :: TyCon -> [Type] -> TcM a
507 famInstNotFound tycon tys
508 = failWithTc (ptext (sLit "No family instance for")
509 <+> quotes (pprTypeApp tycon (ppr tycon) tys))
513 %************************************************************************
517 %************************************************************************
520 mkDataTypeEqn :: InstOrigin -> Bool -> [Var] -> Class -> [Type]
521 -> TyCon -> [Type] -> TyCon -> [Type] -> Maybe ThetaType
522 -> TcRn (Maybe EarlyDerivSpec) -- Return 'Nothing' if error
524 mkDataTypeEqn orig mayDeriveDataTypeable tvs cls cls_tys
525 tycon tc_args rep_tc rep_tc_args mtheta
526 | Just err <- checkSideConditions mayDeriveDataTypeable cls cls_tys rep_tc
527 -- NB: pass the *representation* tycon to checkSideConditions
528 = baleOut (derivingThingErr cls cls_tys (mkTyConApp tycon tc_args) err)
531 = ASSERT( null cls_tys )
532 mk_data_eqn orig tvs cls tycon tc_args rep_tc rep_tc_args mtheta
534 mk_data_eqn, mk_typeable_eqn
535 :: InstOrigin -> [TyVar] -> Class
536 -> TyCon -> [TcType] -> TyCon -> [TcType] -> Maybe ThetaType
537 -> TcM (Maybe EarlyDerivSpec)
538 mk_data_eqn orig tvs cls tycon tc_args rep_tc rep_tc_args mtheta
539 | getName cls `elem` typeableClassNames
540 = mk_typeable_eqn orig tvs cls tycon tc_args rep_tc rep_tc_args mtheta
543 = do { dfun_name <- new_dfun_name cls tycon
545 ; let ordinary_constraints
546 = [ mkClassPred cls [arg_ty]
547 | data_con <- tyConDataCons rep_tc,
548 arg_ty <- ASSERT( isVanillaDataCon data_con )
549 dataConInstOrigArgTys data_con rep_tc_args,
550 not (isUnLiftedType arg_ty) ] -- No constraints for unlifted types?
552 -- See Note [Superclasses of derived instance]
553 sc_constraints = substTheta (zipOpenTvSubst (classTyVars cls) inst_tys)
555 inst_tys = [mkTyConApp tycon tc_args]
557 stupid_subst = zipTopTvSubst (tyConTyVars rep_tc) rep_tc_args
558 stupid_constraints = substTheta stupid_subst (tyConStupidTheta rep_tc)
559 all_constraints = stupid_constraints ++ sc_constraints ++ ordinary_constraints
561 spec = DS { ds_loc = loc, ds_orig = orig
562 , ds_name = dfun_name, ds_tvs = tvs
563 , ds_cls = cls, ds_tys = inst_tys
564 , ds_theta = mtheta `orElse` all_constraints
565 , ds_newtype = False }
567 ; return (if isJust mtheta then Just (Right spec) -- Specified context
568 else Just (Left spec)) } -- Infer context
570 mk_typeable_eqn orig tvs cls tycon tc_args rep_tc _rep_tc_args mtheta
571 -- The Typeable class is special in several ways
572 -- data T a b = ... deriving( Typeable )
574 -- instance Typeable2 T where ...
576 -- 1. There are no constraints in the instance
577 -- 2. There are no type variables either
578 -- 3. The actual class we want to generate isn't necessarily
579 -- Typeable; it depends on the arity of the type
580 | isNothing mtheta -- deriving on a data type decl
581 = do { checkTc (cls `hasKey` typeableClassKey)
582 (ptext (sLit "Use deriving( Typeable ) on a data type declaration"))
583 ; real_cls <- tcLookupClass (typeableClassNames !! tyConArity tycon)
584 ; mk_typeable_eqn orig tvs real_cls tycon [] rep_tc [] (Just []) }
586 | otherwise -- standaone deriving
587 = do { checkTc (null tc_args)
588 (ptext (sLit "Derived typeable instance must be of form (Typeable")
589 <> int (tyConArity tycon) <+> ppr tycon <> rparen)
590 ; dfun_name <- new_dfun_name cls tycon
592 ; return (Just $ Right $
593 DS { ds_loc = loc, ds_orig = orig, ds_name = dfun_name, ds_tvs = []
594 , ds_cls = cls, ds_tys = [mkTyConApp tycon []]
595 , ds_theta = mtheta `orElse` [], ds_newtype = False }) }
597 ------------------------------------------------------------------
598 -- Check side conditions that dis-allow derivability for particular classes
599 -- This is *apart* from the newtype-deriving mechanism
601 -- Here we get the representation tycon in case of family instances as it has
602 -- the data constructors - but we need to be careful to fall back to the
603 -- family tycon (with indexes) in error messages.
605 checkSideConditions :: Bool -> Class -> [TcType] -> TyCon -> Maybe SDoc
606 checkSideConditions mayDeriveDataTypeable cls cls_tys rep_tc
608 = Just ty_args_why -- e.g. deriving( Foo s )
610 = case sideConditions cls of
611 Just cond -> cond (mayDeriveDataTypeable, rep_tc)
612 Nothing -> Just non_std_why
614 ty_args_why = quotes (ppr (mkClassPred cls cls_tys)) <+> ptext (sLit "is not a class")
615 non_std_why = quotes (ppr cls) <+> ptext (sLit "is not a derivable class")
617 sideConditions :: Class -> Maybe Condition
619 | cls_key == eqClassKey = Just cond_std
620 | cls_key == ordClassKey = Just cond_std
621 | cls_key == readClassKey = Just cond_std
622 | cls_key == showClassKey = Just cond_std
623 | cls_key == enumClassKey = Just (cond_std `andCond` cond_isEnumeration)
624 | cls_key == ixClassKey = Just (cond_std `andCond` (cond_isEnumeration `orCond` cond_isProduct))
625 | cls_key == boundedClassKey = Just (cond_std `andCond` (cond_isEnumeration `orCond` cond_isProduct))
626 | cls_key == dataClassKey = Just (cond_mayDeriveDataTypeable `andCond` cond_std)
627 | getName cls `elem` typeableClassNames = Just (cond_mayDeriveDataTypeable `andCond` cond_typeableOK)
628 | otherwise = Nothing
630 cls_key = getUnique cls
632 type Condition = (Bool, TyCon) -> Maybe SDoc
633 -- Bool is whether or not we are allowed to derive Data and Typeable
634 -- TyCon is the *representation* tycon if the
635 -- data type is an indexed one
638 orCond :: Condition -> Condition -> Condition
641 Nothing -> Nothing -- c1 succeeds
642 Just x -> case c2 tc of -- c1 fails
644 Just y -> Just (x $$ ptext (sLit " and") $$ y)
647 andCond :: Condition -> Condition -> Condition
648 andCond c1 c2 tc = case c1 tc of
649 Nothing -> c2 tc -- c1 succeeds
650 Just x -> Just x -- c1 fails
652 cond_std :: Condition
654 | any (not . isVanillaDataCon) data_cons = Just existential_why
655 | null data_cons = Just no_cons_why
656 | otherwise = Nothing
658 data_cons = tyConDataCons rep_tc
659 no_cons_why = quotes (pprSourceTyCon rep_tc) <+>
660 ptext (sLit "has no data constructors")
661 existential_why = quotes (pprSourceTyCon rep_tc) <+>
662 ptext (sLit "has non-Haskell-98 constructor(s)")
664 cond_isEnumeration :: Condition
665 cond_isEnumeration (_, rep_tc)
666 | isEnumerationTyCon rep_tc = Nothing
667 | otherwise = Just why
669 why = quotes (pprSourceTyCon rep_tc) <+>
670 ptext (sLit "has non-nullary constructors")
672 cond_isProduct :: Condition
673 cond_isProduct (_, rep_tc)
674 | isProductTyCon rep_tc = Nothing
675 | otherwise = Just why
677 why = quotes (pprSourceTyCon rep_tc) <+>
678 ptext (sLit "has more than one constructor")
680 cond_typeableOK :: Condition
681 -- OK for Typeable class
682 -- Currently: (a) args all of kind *
683 -- (b) 7 or fewer args
684 cond_typeableOK (_, rep_tc)
685 | tyConArity rep_tc > 7 = Just too_many
686 | not (all (isSubArgTypeKind . tyVarKind) (tyConTyVars rep_tc))
688 | isFamInstTyCon rep_tc = Just fam_inst -- no Typable for family insts
689 | otherwise = Nothing
691 too_many = quotes (pprSourceTyCon rep_tc) <+>
692 ptext (sLit "has too many arguments")
693 bad_kind = quotes (pprSourceTyCon rep_tc) <+>
694 ptext (sLit "has arguments of kind other than `*'")
695 fam_inst = quotes (pprSourceTyCon rep_tc) <+>
696 ptext (sLit "is a type family")
698 cond_mayDeriveDataTypeable :: Condition
699 cond_mayDeriveDataTypeable (mayDeriveDataTypeable, _)
700 | mayDeriveDataTypeable = Nothing
701 | otherwise = Just why
703 why = ptext (sLit "You need -XDeriveDataTypeable to derive an instance for this class")
705 std_class_via_iso :: Class -> Bool
706 std_class_via_iso clas -- These standard classes can be derived for a newtype
707 -- using the isomorphism trick *even if no -fglasgow-exts*
708 = classKey clas `elem` [eqClassKey, ordClassKey, ixClassKey, boundedClassKey]
709 -- Not Read/Show because they respect the type
710 -- Not Enum, because newtypes are never in Enum
713 new_dfun_name :: Class -> TyCon -> TcM Name
714 new_dfun_name clas tycon -- Just a simple wrapper
715 = newDFunName clas [mkTyConApp tycon []] (getSrcSpan tycon)
716 -- The type passed to newDFunName is only used to generate
717 -- a suitable string; hence the empty type arg list
720 Note [Superclasses of derived instance]
721 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
722 In general, a derived instance decl needs the superclasses of the derived
723 class too. So if we have
724 data T a = ...deriving( Ord )
725 then the initial context for Ord (T a) should include Eq (T a). Often this is
726 redundant; we'll also generate an Ord constraint for each constructor argument,
727 and that will probably generate enough constraints to make the Eq (T a) constraint
728 be satisfied too. But not always; consider:
734 data T a = MkT (S a) deriving( Ord )
735 instance Num a => Eq (T a)
737 The derived instance for (Ord (T a)) must have a (Num a) constraint!
739 data T a = MkT deriving( Data, Typeable )
740 Here there *is* no argument field, but we must nevertheless generate
741 a context for the Data instances:
742 instance Typable a => Data (T a) where ...
745 %************************************************************************
749 %************************************************************************
752 mkNewTypeEqn :: InstOrigin -> Bool -> Bool -> [Var] -> Class
753 -> [Type] -> TyCon -> [Type] -> TyCon -> [Type]
755 -> TcRn (Maybe EarlyDerivSpec)
756 mkNewTypeEqn orig mayDeriveDataTypeable newtype_deriving tvs
757 cls cls_tys tycon tc_args rep_tycon rep_tc_args mtheta
758 | can_derive_via_isomorphism && (newtype_deriving || std_class_via_iso cls)
759 = do { traceTc (text "newtype deriving:" <+> ppr tycon <+> ppr rep_tys)
760 ; dfun_name <- new_dfun_name cls tycon
762 ; let spec = DS { ds_loc = loc, ds_orig = orig
763 , ds_name = dfun_name, ds_tvs = dict_tvs
764 , ds_cls = cls, ds_tys = inst_tys
765 , ds_theta = mtheta `orElse` all_preds
766 , ds_newtype = True }
767 ; return (if isJust mtheta then Just (Right spec)
768 else Just (Left spec)) }
770 | isNothing mb_std_err -- Use the standard H98 method
771 = mk_data_eqn orig tvs cls tycon tc_args rep_tycon rep_tc_args mtheta
773 -- Otherwise we can't derive
774 | newtype_deriving = baleOut cant_derive_err -- Too hard
775 | otherwise = baleOut std_err -- Just complain about being a non-std instance
777 mb_std_err = checkSideConditions mayDeriveDataTypeable cls cls_tys rep_tycon
778 std_err = derivingThingErr cls cls_tys tc_app $
779 vcat [fromJust mb_std_err,
780 ptext (sLit "Try -XGeneralizedNewtypeDeriving for GHC's newtype-deriving extension")]
782 -- Here is the plan for newtype derivings. We see
783 -- newtype T a1...an = MkT (t ak+1...an) deriving (.., C s1 .. sm, ...)
784 -- where t is a type,
785 -- ak+1...an is a suffix of a1..an, and are all tyars
786 -- ak+1...an do not occur free in t, nor in the s1..sm
787 -- (C s1 ... sm) is a *partial applications* of class C
788 -- with the last parameter missing
789 -- (T a1 .. ak) matches the kind of C's last argument
790 -- (and hence so does t)
792 -- We generate the instance
793 -- instance forall ({a1..ak} u fvs(s1..sm)).
794 -- C s1 .. sm t => C s1 .. sm (T a1...ak)
795 -- where T a1...ap is the partial application of
796 -- the LHS of the correct kind and p >= k
798 -- NB: the variables below are:
799 -- tc_tvs = [a1, ..., an]
800 -- tyvars_to_keep = [a1, ..., ak]
801 -- rep_ty = t ak .. an
802 -- deriv_tvs = fvs(s1..sm) \ tc_tvs
803 -- tys = [s1, ..., sm]
806 -- Running example: newtype T s a = MkT (ST s a) deriving( Monad )
807 -- We generate the instance
808 -- instance Monad (ST s) => Monad (T s) where
810 cls_tyvars = classTyVars cls
811 kind = tyVarKind (last cls_tyvars)
812 -- Kind of the thing we want to instance
813 -- e.g. argument kind of Monad, *->*
815 (arg_kinds, _) = splitKindFunTys kind
816 n_args_to_drop = length arg_kinds
817 -- Want to drop 1 arg from (T s a) and (ST s a)
818 -- to get instance Monad (ST s) => Monad (T s)
820 -- Note [Newtype representation]
821 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
822 -- Need newTyConRhs (*not* a recursive representation finder)
823 -- to get the representation type. For example
824 -- newtype B = MkB Int
825 -- newtype A = MkA B deriving( Num )
826 -- We want the Num instance of B, *not* the Num instance of Int,
827 -- when making the Num instance of A!
828 rep_ty = newTyConInstRhs rep_tycon rep_tc_args
829 (rep_fn, rep_ty_args) = tcSplitAppTys rep_ty
831 n_tyargs_to_keep = tyConArity tycon - n_args_to_drop
832 dropped_tc_args = drop n_tyargs_to_keep tc_args
833 dropped_tvs = tyVarsOfTypes dropped_tc_args
835 n_args_to_keep = length rep_ty_args - n_args_to_drop
836 args_to_drop = drop n_args_to_keep rep_ty_args
837 args_to_keep = take n_args_to_keep rep_ty_args
839 rep_fn' = mkAppTys rep_fn args_to_keep
840 rep_tys = cls_tys ++ [rep_fn']
841 rep_pred = mkClassPred cls rep_tys
842 -- rep_pred is the representation dictionary, from where
843 -- we are gong to get all the methods for the newtype
846 tc_app = mkTyConApp tycon (take n_tyargs_to_keep tc_args)
848 -- Next we figure out what superclass dictionaries to use
849 -- See Note [Newtype deriving superclasses] above
851 inst_tys = cls_tys ++ [tc_app]
852 sc_theta = substTheta (zipOpenTvSubst cls_tyvars inst_tys)
855 -- If there are no tyvars, there's no need
856 -- to abstract over the dictionaries we need
857 -- Example: newtype T = MkT Int deriving( C )
858 -- We get the derived instance
861 -- instance C Int => C T
862 dict_tvs = filterOut (`elemVarSet` dropped_tvs) tvs
863 all_preds = rep_pred : sc_theta -- NB: rep_pred comes first
865 -------------------------------------------------------------------
866 -- Figuring out whether we can only do this newtype-deriving thing
868 right_arity = length cls_tys + 1 == classArity cls
870 -- Never derive Read,Show,Typeable,Data this way
871 non_iso_classes = [readClassKey, showClassKey, typeableClassKey, dataClassKey]
872 can_derive_via_isomorphism
873 = not (getUnique cls `elem` non_iso_classes)
874 && right_arity -- Well kinded;
875 -- eg not: newtype T ... deriving( ST )
876 -- because ST needs *2* type params
877 && n_tyargs_to_keep >= 0 -- Type constructor has right kind:
878 -- eg not: newtype T = T Int deriving( Monad )
879 && n_args_to_keep >= 0 -- Rep type has right kind:
880 -- eg not: newtype T a = T Int deriving( Monad )
881 && eta_ok -- Eta reduction works
882 && not (isRecursiveTyCon tycon) -- Does not work for recursive tycons:
883 -- newtype A = MkA [A]
885 -- instance Eq [A] => Eq A !!
886 -- Here's a recursive newtype that's actually OK
887 -- newtype S1 = S1 [T1 ()]
888 -- newtype T1 a = T1 (StateT S1 IO a ) deriving( Monad )
889 -- It's currently rejected. Oh well.
890 -- In fact we generate an instance decl that has method of form
891 -- meth @ instTy = meth @ repTy
892 -- (no coerce's). We'd need a coerce if we wanted to handle
893 -- recursive newtypes too
895 -- Check that eta reduction is OK
896 eta_ok = (args_to_drop `tcEqTypes` dropped_tc_args)
897 -- (a) the dropped-off args are identical in the source and rep type
898 -- newtype T a b = MkT (S [a] b) deriving( Monad )
899 -- Here the 'b' must be the same in the rep type (S [a] b)
901 && (tyVarsOfType rep_fn' `disjointVarSet` dropped_tvs)
902 -- (b) the remaining type args do not mention any of the dropped
905 && (tyVarsOfTypes cls_tys `disjointVarSet` dropped_tvs)
906 -- (c) the type class args do not mention any of the dropped type
909 && all isTyVarTy dropped_tc_args
910 -- (d) in case of newtype family instances, the eta-dropped
911 -- arguments must be type variables (not more complex indexes)
913 cant_derive_err = derivingThingErr cls cls_tys tc_app
914 (vcat [ptext (sLit "even with cunning newtype deriving:"),
915 if isRecursiveTyCon tycon then
916 ptext (sLit "the newtype may be recursive")
918 if not right_arity then
919 quotes (ppr (mkClassPred cls cls_tys)) <+> ptext (sLit "does not have arity 1")
921 if not (n_tyargs_to_keep >= 0) then
922 ptext (sLit "the type constructor has wrong kind")
923 else if not (n_args_to_keep >= 0) then
924 ptext (sLit "the representation type has wrong kind")
925 else if not eta_ok then
926 ptext (sLit "the eta-reduction property does not hold")
932 %************************************************************************
934 \subsection[TcDeriv-fixpoint]{Finding the fixed point of \tr{deriving} equations}
936 %************************************************************************
938 A ``solution'' (to one of the equations) is a list of (k,TyVarTy tv)
939 terms, which is the final correct RHS for the corresponding original
943 Each (k,TyVarTy tv) in a solution constrains only a type
947 The (k,TyVarTy tv) pairs in a solution are canonically
948 ordered by sorting on type varible, tv, (major key) and then class, k,
953 inferInstanceContexts :: OverlapFlag -> [DerivSpec] -> TcM [DerivSpec]
955 inferInstanceContexts _ [] = return []
957 inferInstanceContexts oflag infer_specs
958 = do { traceTc (text "inferInstanceContexts" <+> vcat (map pprDerivSpec infer_specs))
959 ; iterate_deriv 1 initial_solutions }
961 ------------------------------------------------------------------
962 -- The initial solutions for the equations claim that each
963 -- instance has an empty context; this solution is certainly
964 -- in canonical form.
965 initial_solutions :: [ThetaType]
966 initial_solutions = [ [] | _ <- infer_specs ]
968 ------------------------------------------------------------------
969 -- iterate_deriv calculates the next batch of solutions,
970 -- compares it with the current one; finishes if they are the
971 -- same, otherwise recurses with the new solutions.
972 -- It fails if any iteration fails
973 iterate_deriv :: Int -> [ThetaType] -> TcM [DerivSpec]
974 iterate_deriv n current_solns
975 | n > 20 -- Looks as if we are in an infinite loop
976 -- This can happen if we have -XUndecidableInstances
977 -- (See TcSimplify.tcSimplifyDeriv.)
978 = pprPanic "solveDerivEqns: probable loop"
979 (vcat (map pprDerivSpec infer_specs) $$ ppr current_solns)
981 = do { -- Extend the inst info from the explicit instance decls
982 -- with the current set of solutions, and simplify each RHS
983 let inst_specs = zipWithEqual "add_solns" (mkInstance2 oflag)
984 current_solns infer_specs
985 ; new_solns <- checkNoErrs $
986 extendLocalInstEnv inst_specs $
987 mapM gen_soln infer_specs
989 ; if (current_solns == new_solns) then
990 return [ spec { ds_theta = soln }
991 | (spec, soln) <- zip infer_specs current_solns ]
993 iterate_deriv (n+1) new_solns }
995 ------------------------------------------------------------------
996 gen_soln :: DerivSpec -> TcM [PredType]
997 gen_soln (DS { ds_loc = loc, ds_orig = orig, ds_tvs = tyvars
998 , ds_cls = clas, ds_tys = inst_tys, ds_theta = deriv_rhs })
1000 addErrCtxt (derivInstCtxt clas inst_tys) $
1001 do { theta <- tcSimplifyDeriv orig tyvars deriv_rhs
1002 -- checkValidInstance tyvars theta clas inst_tys
1003 -- Not necessary; see Note [Exotic derived instance contexts]
1006 -- Check for a bizarre corner case, when the derived instance decl should
1007 -- have form instance C a b => D (T a) where ...
1008 -- Note that 'b' isn't a parameter of T. This gives rise to all sorts
1009 -- of problems; in particular, it's hard to compare solutions for
1010 -- equality when finding the fixpoint. So I just rule it out for now.
1011 ; let tv_set = mkVarSet tyvars
1012 weird_preds = [pred | pred <- theta, not (tyVarsOfPred pred `subVarSet` tv_set)]
1013 ; mapM_ (addErrTc . badDerivedPred) weird_preds
1015 -- Claim: the result instance declaration is guaranteed valid
1016 -- Hence no need to call:
1017 -- checkValidInstance tyvars theta clas inst_tys
1018 ; return (sortLe (<=) theta) } -- Canonicalise before returning the solution
1020 ------------------------------------------------------------------
1021 mkInstance1 :: OverlapFlag -> DerivSpec -> Instance
1022 mkInstance1 overlap_flag spec = mkInstance2 overlap_flag (ds_theta spec) spec
1024 mkInstance2 :: OverlapFlag -> ThetaType -> DerivSpec -> Instance
1025 mkInstance2 overlap_flag theta
1026 (DS { ds_name = dfun_name
1027 , ds_tvs = tyvars, ds_cls = clas, ds_tys = tys })
1028 = mkLocalInstance dfun overlap_flag
1030 dfun = mkDictFunId dfun_name tyvars theta clas tys
1033 extendLocalInstEnv :: [Instance] -> TcM a -> TcM a
1034 -- Add new locally-defined instances; don't bother to check
1035 -- for functional dependency errors -- that'll happen in TcInstDcls
1036 extendLocalInstEnv dfuns thing_inside
1037 = do { env <- getGblEnv
1038 ; let inst_env' = extendInstEnvList (tcg_inst_env env) dfuns
1039 env' = env { tcg_inst_env = inst_env' }
1040 ; setGblEnv env' thing_inside }
1044 %************************************************************************
1046 \subsection[TcDeriv-normal-binds]{Bindings for the various classes}
1048 %************************************************************************
1050 After all the trouble to figure out the required context for the
1051 derived instance declarations, all that's left is to chug along to
1052 produce them. They will then be shoved into @tcInstDecls2@, which
1053 will do all its usual business.
1055 There are lots of possibilities for code to generate. Here are
1056 various general remarks.
1061 We want derived instances of @Eq@ and @Ord@ (both v common) to be
1062 ``you-couldn't-do-better-by-hand'' efficient.
1065 Deriving @Show@---also pretty common--- should also be reasonable good code.
1068 Deriving for the other classes isn't that common or that big a deal.
1075 Deriving @Ord@ is done mostly with the 1.3 @compare@ method.
1078 Deriving @Eq@ also uses @compare@, if we're deriving @Ord@, too.
1081 We {\em normally} generate code only for the non-defaulted methods;
1082 there are some exceptions for @Eq@ and (especially) @Ord@...
1085 Sometimes we use a @_con2tag_<tycon>@ function, which returns a data
1086 constructor's numeric (@Int#@) tag. These are generated by
1087 @gen_tag_n_con_binds@, and the heuristic for deciding if one of
1088 these is around is given by @hasCon2TagFun@.
1090 The examples under the different sections below will make this
1094 Much less often (really just for deriving @Ix@), we use a
1095 @_tag2con_<tycon>@ function. See the examples.
1098 We use the renamer!!! Reason: we're supposed to be
1099 producing @LHsBinds Name@ for the methods, but that means
1100 producing correctly-uniquified code on the fly. This is entirely
1101 possible (the @TcM@ monad has a @UniqueSupply@), but it is painful.
1102 So, instead, we produce @MonoBinds RdrName@ then heave 'em through
1103 the renamer. What a great hack!
1107 -- Generate the InstInfo for the required instance paired with the
1108 -- *representation* tycon for that instance,
1109 -- plus any auxiliary bindings required
1111 -- Representation tycons differ from the tycon in the instance signature in
1112 -- case of instances for indexed families.
1114 genInst :: OverlapFlag -> DerivSpec -> TcM (InstInfo, DerivAuxBinds)
1117 = return (InstInfo { iSpec = mkInstance1 oflag spec
1118 , iBinds = NewTypeDerived }, [])
1121 = do { fix_env <- getFixityEnv
1123 inst = mkInstance1 oflag spec
1124 (tyvars,_,clas,[ty]) = instanceHead inst
1125 clas_nm = className clas
1126 (visible_tycon, tyArgs) = tcSplitTyConApp ty
1128 -- In case of a family instance, we need to use the representation
1129 -- tycon (after all, it has the data constructors)
1130 ; (tycon, _) <- tcLookupFamInstExact visible_tycon tyArgs
1131 ; let (meth_binds, aux_binds) = genDerivBinds clas fix_env tycon
1133 -- Bring the right type variables into
1134 -- scope, and rename the method binds
1135 -- It's a bit yukky that we return *renamed* InstInfo, but
1136 -- *non-renamed* auxiliary bindings
1137 ; (rn_meth_binds, _fvs) <- discardWarnings $
1138 bindLocalNames (map Var.varName tyvars) $
1139 rnMethodBinds clas_nm (\_ -> []) [] meth_binds
1141 -- Build the InstInfo
1142 ; return (InstInfo { iSpec = inst,
1143 iBinds = VanillaInst rn_meth_binds [] },
1147 genDerivBinds :: Class -> FixityEnv -> TyCon -> (LHsBinds RdrName, DerivAuxBinds)
1148 genDerivBinds clas fix_env tycon
1149 | className clas `elem` typeableClassNames
1150 = (gen_Typeable_binds tycon, [])
1153 = case assocMaybe gen_list (getUnique clas) of
1154 Just gen_fn -> gen_fn tycon
1155 Nothing -> pprPanic "genDerivBinds: bad derived class" (ppr clas)
1157 gen_list :: [(Unique, TyCon -> (LHsBinds RdrName, DerivAuxBinds))]
1158 gen_list = [(eqClassKey, gen_Eq_binds)
1159 ,(ordClassKey, gen_Ord_binds)
1160 ,(enumClassKey, gen_Enum_binds)
1161 ,(boundedClassKey, gen_Bounded_binds)
1162 ,(ixClassKey, gen_Ix_binds)
1163 ,(showClassKey, gen_Show_binds fix_env)
1164 ,(readClassKey, gen_Read_binds fix_env)
1165 ,(dataClassKey, gen_Data_binds fix_env)
1170 %************************************************************************
1172 \subsection[TcDeriv-taggery-Names]{What con2tag/tag2con functions are available?}
1174 %************************************************************************
1177 derivingThingErr :: Class -> [Type] -> Type -> Message -> Message
1178 derivingThingErr clas tys ty why
1179 = sep [hsep [ptext (sLit "Can't make a derived instance of"),
1181 nest 2 (parens why)]
1183 pred = mkClassPred clas (tys ++ [ty])
1185 derivingHiddenErr :: TyCon -> SDoc
1186 derivingHiddenErr tc
1187 = hang (ptext (sLit "The data constructors of") <+> quotes (ppr tc) <+> ptext (sLit "are not all in scope"))
1188 2 (ptext (sLit "so you cannot derive an instance for it"))
1190 standaloneCtxt :: LHsType Name -> SDoc
1191 standaloneCtxt ty = hang (ptext (sLit "In the stand-alone deriving instance for"))
1194 derivInstCtxt :: Class -> [Type] -> Message
1195 derivInstCtxt clas inst_tys
1196 = ptext (sLit "When deriving the instance for") <+> parens (pprClassPred clas inst_tys)
1198 badDerivedPred :: PredType -> Message
1200 = vcat [ptext (sLit "Can't derive instances where the instance context mentions"),
1201 ptext (sLit "type variables that are not data type parameters"),
1202 nest 2 (ptext (sLit "Offending constraint:") <+> ppr pred)]