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 TcGenDeriv -- Deriv stuff
50 %************************************************************************
52 \subsection[TcDeriv-intro]{Introduction to how we do deriving}
54 %************************************************************************
58 data T a b = C1 (Foo a) (Bar b)
63 [NOTE: See end of these comments for what to do with
64 data (C a, D b) => T a b = ...
67 We want to come up with an instance declaration of the form
69 instance (Ping a, Pong b, ...) => Eq (T a b) where
72 It is pretty easy, albeit tedious, to fill in the code "...". The
73 trick is to figure out what the context for the instance decl is,
74 namely @Ping@, @Pong@ and friends.
76 Let's call the context reqd for the T instance of class C at types
77 (a,b, ...) C (T a b). Thus:
79 Eq (T a b) = (Ping a, Pong b, ...)
81 Now we can get a (recursive) equation from the @data@ decl:
83 Eq (T a b) = Eq (Foo a) u Eq (Bar b) -- From C1
84 u Eq (T b a) u Eq Int -- From C2
85 u Eq (T a a) -- From C3
87 Foo and Bar may have explicit instances for @Eq@, in which case we can
88 just substitute for them. Alternatively, either or both may have
89 their @Eq@ instances given by @deriving@ clauses, in which case they
90 form part of the system of equations.
92 Now all we need do is simplify and solve the equations, iterating to
93 find the least fixpoint. Notice that the order of the arguments can
94 switch around, as here in the recursive calls to T.
96 Let's suppose Eq (Foo a) = Eq a, and Eq (Bar b) = Ping b.
100 Eq (T a b) = {} -- The empty set
103 Eq (T a b) = Eq (Foo a) u Eq (Bar b) -- From C1
104 u Eq (T b a) u Eq Int -- From C2
105 u Eq (T a a) -- From C3
107 After simplification:
108 = Eq a u Ping b u {} u {} u {}
113 Eq (T a b) = Eq (Foo a) u Eq (Bar b) -- From C1
114 u Eq (T b a) u Eq Int -- From C2
115 u Eq (T a a) -- From C3
117 After simplification:
122 = Eq a u Ping b u Eq b u Ping a
124 The next iteration gives the same result, so this is the fixpoint. We
125 need to make a canonical form of the RHS to ensure convergence. We do
126 this by simplifying the RHS to a form in which
128 - the classes constrain only tyvars
129 - the list is sorted by tyvar (major key) and then class (minor key)
130 - no duplicates, of course
132 So, here are the synonyms for the ``equation'' structures:
135 type DerivEqn = (SrcSpan, InstOrigin, Name, Class, TyCon, [TyVar], DerivRhs)
136 -- The Name is the name for the DFun we'll build
137 -- The tyvars bind all the variables in the RHS
139 pprDerivEqn :: DerivEqn -> SDoc
140 pprDerivEqn (l,_,n,c,tc,tvs,rhs)
141 = parens (hsep [ppr l, ppr n, ppr c, ppr tc, ppr tvs] <+> equals <+> ppr rhs)
143 type DerivRhs = ThetaType
144 type DerivSoln = DerivRhs
148 [Data decl contexts] A note about contexts on data decls
149 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
152 data (RealFloat a) => Complex a = !a :+ !a deriving( Read )
154 We will need an instance decl like:
156 instance (Read a, RealFloat a) => Read (Complex a) where
159 The RealFloat in the context is because the read method for Complex is bound
160 to construct a Complex, and doing that requires that the argument type is
163 But this ain't true for Show, Eq, Ord, etc, since they don't construct
164 a Complex; they only take them apart.
166 Our approach: identify the offending classes, and add the data type
167 context to the instance decl. The "offending classes" are
171 FURTHER NOTE ADDED March 2002. In fact, Haskell98 now requires that
172 pattern matching against a constructor from a data type with a context
173 gives rise to the constraints for that context -- or at least the thinned
174 version. So now all classes are "offending".
181 newtype T = T Char deriving( C [a] )
183 Notice the free 'a' in the deriving. We have to fill this out to
184 newtype T = T Char deriving( forall a. C [a] )
186 And then translate it to:
187 instance C [a] Char => C [a] T where ...
192 %************************************************************************
194 \subsection[TcDeriv-driver]{Top-level function for \tr{derivings}}
196 %************************************************************************
199 tcDeriving :: [LTyClDecl Name] -- All type constructors
200 -> [LDerivDecl Name] -- All stand-alone deriving declarations
201 -> TcM ([InstInfo], -- The generated "instance decls"
202 HsValBinds Name) -- Extra generated top-level bindings
204 tcDeriving tycl_decls deriv_decls
205 = recoverM (returnM ([], emptyValBindsOut)) $
206 do { -- Fish the "deriving"-related information out of the TcEnv
207 -- and make the necessary "equations".
208 overlap_flag <- getOverlapFlag
209 ; (ordinary_eqns, newtype_inst_info)
210 <- makeDerivEqns overlap_flag tycl_decls deriv_decls
212 ; (ordinary_inst_info, deriv_binds)
213 <- extendLocalInstEnv (map iSpec newtype_inst_info) $
214 deriveOrdinaryStuff overlap_flag ordinary_eqns
215 -- Add the newtype-derived instances to the inst env
216 -- before tacking the "ordinary" ones
218 ; let inst_info = newtype_inst_info ++ ordinary_inst_info
220 -- If we are compiling a hs-boot file,
221 -- don't generate any derived bindings
222 ; is_boot <- tcIsHsBoot
224 return (inst_info, emptyValBindsOut)
228 -- Generate the generic to/from functions from each type declaration
229 ; gen_binds <- mkGenericBinds tycl_decls
231 -- Rename these extra bindings, discarding warnings about unused bindings etc
232 -- Set -fglasgow exts so that we can have type signatures in patterns,
233 -- which is used in the generic binds
235 <- discardWarnings $ setOptM Opt_GlasgowExts $ do
236 { (rn_deriv, _dus1) <- rnTopBinds (ValBindsIn deriv_binds [])
237 ; (rn_gen, dus_gen) <- rnTopBinds (ValBindsIn gen_binds [])
238 ; keepAliveSetTc (duDefs dus_gen) -- Mark these guys to
240 ; return (rn_deriv `plusHsValBinds` rn_gen) }
244 ; ioToTcRn (dumpIfSet_dyn dflags Opt_D_dump_deriv "Derived instances"
245 (ddump_deriving inst_info rn_binds))
247 ; returnM (inst_info, rn_binds)
250 ddump_deriving :: [InstInfo] -> HsValBinds Name -> SDoc
251 ddump_deriving inst_infos extra_binds
252 = vcat (map pprInstInfoDetails inst_infos) $$ ppr extra_binds
254 -----------------------------------------
255 deriveOrdinaryStuff overlap_flag [] -- Short cut
256 = returnM ([], emptyLHsBinds)
258 deriveOrdinaryStuff overlap_flag eqns
259 = do { -- Take the equation list and solve it, to deliver a list of
260 -- solutions, a.k.a. the contexts for the instance decls
261 -- required for the corresponding equations.
262 inst_specs <- solveDerivEqns overlap_flag eqns
264 -- Generate the InstInfo for each dfun,
265 -- plus any auxiliary bindings it needs
266 ; (inst_infos, aux_binds_s) <- mapAndUnzipM genInst inst_specs
268 -- Generate any extra not-one-inst-decl-specific binds,
269 -- notably "con2tag" and/or "tag2con" functions.
270 ; extra_binds <- genTaggeryBinds inst_infos
273 ; returnM (inst_infos, unionManyBags (extra_binds : aux_binds_s))
276 -----------------------------------------
277 mkGenericBinds tycl_decls
278 = do { tcs <- mapM tcLookupTyCon
280 L _ (TyData { tcdLName = L _ tc_name }) <- tycl_decls]
281 -- We are only interested in the data type declarations
282 ; return (unionManyBags [ mkTyConGenericBinds tc |
283 tc <- tcs, tyConHasGenerics tc ]) }
284 -- And then only in the ones whose 'has-generics' flag is on
288 %************************************************************************
290 \subsection[TcDeriv-eqns]{Forming the equations}
292 %************************************************************************
294 @makeDerivEqns@ fishes around to find the info about needed derived
295 instances. Complicating factors:
298 We can only derive @Enum@ if the data type is an enumeration
299 type (all nullary data constructors).
302 We can only derive @Ix@ if the data type is an enumeration {\em
303 or} has just one data constructor (e.g., tuples).
306 [See Appendix~E in the Haskell~1.2 report.] This code here deals w/
309 Note [Newtype deriving superclasses]
310 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
311 The 'tys' here come from the partial application in the deriving
312 clause. The last arg is the new instance type.
314 We must pass the superclasses; the newtype might be an instance
315 of them in a different way than the representation type
316 E.g. newtype Foo a = Foo a deriving( Show, Num, Eq )
317 Then the Show instance is not done via isomorphism; it shows
319 The Num instance is derived via isomorphism, but the Show superclass
320 dictionary must the Show instance for Foo, *not* the Show dictionary
321 gotten from the Num dictionary. So we must build a whole new dictionary
322 not just use the Num one. The instance we want is something like:
323 instance (Num a, Show (Foo a), Eq (Foo a)) => Num (Foo a) where
326 There may be a coercion needed which we get from the tycon for the newtype
327 when the dict is constructed in TcInstDcls.tcInstDecl2
331 makeDerivEqns :: OverlapFlag
334 -> TcM ([DerivEqn], -- Ordinary derivings
335 [InstInfo]) -- Special newtype derivings
337 makeDerivEqns overlap_flag tycl_decls deriv_decls
338 = do derive_these_top_level <- mapM top_level_deriv deriv_decls >>= return . catMaybes
339 (maybe_ordinaries, maybe_newtypes)
340 <- mapAndUnzipM mk_eqn (derive_these ++ derive_these_top_level)
341 return (catMaybes maybe_ordinaries, catMaybes maybe_newtypes)
343 ------------------------------------------------------------------
344 derive_these :: [(SrcSpan, InstOrigin, NewOrData, Name, LHsType Name)]
345 -- Find the (nd, TyCon, Pred) pairs that must be `derived'
346 derive_these = [ (srcLocSpan (getSrcLoc tycon), DerivOrigin, nd, tycon, pred)
347 | L _ (TyData { tcdND = nd, tcdLName = L _ tycon,
348 tcdDerivs = Just preds }) <- tycl_decls,
351 top_level_deriv :: LDerivDecl Name -> TcM (Maybe (SrcSpan, InstOrigin, NewOrData, Name, LHsType Name))
352 top_level_deriv d@(L l (DerivDecl inst ty_name)) = recoverM (returnM Nothing) $ setSrcSpan l $
353 do tycon <- tcLookupLocatedTyCon ty_name
354 let new_or_data = if isNewTyCon tycon then NewType else DataType
355 traceTc (text "Stand-alone deriving:" <+> ppr (new_or_data, unLoc ty_name, inst))
356 return $ Just (l, StandAloneDerivOrigin, new_or_data, unLoc ty_name, inst)
358 ------------------------------------------------------------------
359 -- takes (whether newtype or data, name of data type, partially applied type class)
360 mk_eqn :: (SrcSpan, InstOrigin, NewOrData, Name, LHsType Name) -> TcM (Maybe DerivEqn, Maybe InstInfo)
361 -- We swizzle the tyvars and datacons out of the tycon
362 -- to make the rest of the equation
364 -- The "deriv_ty" is a LHsType to take account of the fact that for newtype derivign
365 -- we allow deriving (forall a. C [a]).
367 mk_eqn (loc, orig, new_or_data, tycon_name, hs_deriv_ty)
368 = tcLookupTyCon tycon_name `thenM` \ tycon ->
370 addErrCtxt (derivCtxt tycon) $
371 tcExtendTyVarEnv (tyConTyVars tycon) $ -- Deriving preds may (now) mention
372 -- the type variables for the type constructor
373 tcHsDeriv hs_deriv_ty `thenM` \ (deriv_tvs, clas, tys) ->
374 doptM Opt_GlasgowExts `thenM` \ gla_exts ->
375 mk_eqn_help loc orig gla_exts new_or_data tycon deriv_tvs clas tys
377 ------------------------------------------------------------------
378 -- data/newtype T a = ... deriving( C t1 t2 )
379 -- leads to a call to mk_eqn_help with
380 -- tycon = T, deriv_tvs = ftv(t1,t2), clas = C, tys = [t1,t2]
382 mk_eqn_help loc orig gla_exts DataType tycon deriv_tvs clas tys
383 | Just err <- checkSideConditions gla_exts tycon deriv_tvs clas tys
384 = bale_out (derivingThingErr clas tys tycon (tyConTyVars tycon) err)
386 = do { eqn <- mkDataTypeEqn loc orig tycon clas
387 ; returnM (Just eqn, Nothing) }
389 mk_eqn_help loc orig gla_exts NewType tycon deriv_tvs clas tys
390 | can_derive_via_isomorphism && (gla_exts || std_class_via_iso clas)
391 = do { traceTc (text "newtype deriving:" <+> ppr tycon <+> ppr rep_tys)
392 ; -- Go ahead and use the isomorphism
393 dfun_name <- new_dfun_name clas tycon
394 ; return (Nothing, Just (InstInfo { iSpec = mk_inst_spec dfun_name,
395 iBinds = NewTypeDerived ntd_info })) }
396 | std_class gla_exts clas
397 = mk_eqn_help loc orig gla_exts DataType tycon deriv_tvs clas tys -- Go via bale-out route
399 | otherwise -- Non-standard instance
400 = bale_out (if gla_exts then
401 cant_derive_err -- Too hard
403 non_std_err) -- Just complain about being a non-std instance
405 -- Here is the plan for newtype derivings. We see
406 -- newtype T a1...an = MkT (t ak+1...an) deriving (.., C s1 .. sm, ...)
407 -- where t is a type,
408 -- ak+1...an is a suffix of a1..an
409 -- ak+1...an do not occur free in t, nor in the s1..sm
410 -- (C s1 ... sm) is a *partial applications* of class C
411 -- with the last parameter missing
412 -- (T a1 .. ak) matches the kind of C's last argument
413 -- (and hence so does t)
415 -- We generate the instance
416 -- instance forall ({a1..ak} u fvs(s1..sm)).
417 -- C s1 .. sm t => C s1 .. sm (T a1...ak)
418 -- where T a1...ap is the partial application of
419 -- the LHS of the correct kind and p >= k
421 -- NB: the variables below are:
422 -- tc_tvs = [a1, ..., an]
423 -- tyvars_to_keep = [a1, ..., ak]
424 -- rep_ty = t ak .. an
425 -- deriv_tvs = fvs(s1..sm) \ tc_tvs
426 -- tys = [s1, ..., sm]
429 -- Running example: newtype T s a = MkT (ST s a) deriving( Monad )
430 -- We generate the instance
431 -- instance Monad (ST s) => Monad (T s) where
433 clas_tyvars = classTyVars clas
434 kind = tyVarKind (last clas_tyvars)
435 -- Kind of the thing we want to instance
436 -- e.g. argument kind of Monad, *->*
438 (arg_kinds, _) = splitKindFunTys kind
439 n_args_to_drop = length arg_kinds
440 -- Want to drop 1 arg from (T s a) and (ST s a)
441 -- to get instance Monad (ST s) => Monad (T s)
443 -- Note [newtype representation]
444 -- Need newTyConRhs *not* newTyConRep to get the representation
445 -- type, because the latter looks through all intermediate newtypes
447 -- newtype B = MkB Int
448 -- newtype A = MkA B deriving( Num )
449 -- We want the Num instance of B, *not* the Num instance of Int,
450 -- when making the Num instance of A!
451 (tc_tvs, rep_ty) = newTyConRhs tycon
452 (rep_fn, rep_ty_args) = tcSplitAppTys rep_ty
454 n_tyvars_to_keep = tyConArity tycon - n_args_to_drop
455 tyvars_to_drop = drop n_tyvars_to_keep tc_tvs
456 tyvars_to_keep = take n_tyvars_to_keep tc_tvs
458 n_args_to_keep = length rep_ty_args - n_args_to_drop
459 args_to_drop = drop n_args_to_keep rep_ty_args
460 args_to_keep = take n_args_to_keep rep_ty_args
462 rep_fn' = mkAppTys rep_fn args_to_keep
463 rep_tys = tys ++ [rep_fn']
464 rep_pred = mkClassPred clas rep_tys
465 -- rep_pred is the representation dictionary, from where
466 -- we are gong to get all the methods for the newtype dictionary
468 -- Next we figure out what superclass dictionaries to use
469 -- See Note [Newtype deriving superclasses] above
471 inst_tys = tys ++ [mkTyConApp tycon (mkTyVarTys tyvars_to_keep)]
472 sc_theta = substTheta (zipOpenTvSubst clas_tyvars inst_tys)
475 -- If there are no tyvars, there's no need
476 -- to abstract over the dictionaries we need
477 -- Example: newtype T = MkT Int deriving( C )
478 -- We get the derived instance
481 -- instance C Int => C T
482 dict_tvs = deriv_tvs ++ tyvars_to_keep
483 all_preds = rep_pred : sc_theta -- NB: rep_pred comes first
484 (dict_args, ntd_info) | null dict_tvs = ([], Just all_preds)
485 | otherwise = (all_preds, Nothing)
487 -- Finally! Here's where we build the dictionary Id
488 mk_inst_spec dfun_name = mkLocalInstance dfun overlap_flag
490 dfun = mkDictFunId dfun_name dict_tvs dict_args clas inst_tys
492 -------------------------------------------------------------------
493 -- Figuring out whether we can only do this newtype-deriving thing
495 right_arity = length tys + 1 == classArity clas
497 -- Never derive Read,Show,Typeable,Data this way
498 non_iso_classes = [readClassKey, showClassKey, typeableClassKey, dataClassKey]
499 can_derive_via_isomorphism
500 = not (getUnique clas `elem` non_iso_classes)
501 && right_arity -- Well kinded;
502 -- eg not: newtype T ... deriving( ST )
503 -- because ST needs *2* type params
504 && n_tyvars_to_keep >= 0 -- Type constructor has right kind:
505 -- eg not: newtype T = T Int deriving( Monad )
506 && n_args_to_keep >= 0 -- Rep type has right kind:
507 -- eg not: newtype T a = T Int deriving( Monad )
508 && eta_ok -- Eta reduction works
509 && not (isRecursiveTyCon tycon) -- Does not work for recursive tycons:
510 -- newtype A = MkA [A]
512 -- instance Eq [A] => Eq A !!
513 -- Here's a recursive newtype that's actually OK
514 -- newtype S1 = S1 [T1 ()]
515 -- newtype T1 a = T1 (StateT S1 IO a ) deriving( Monad )
516 -- It's currently rejected. Oh well.
517 -- In fact we generate an instance decl that has method of form
518 -- meth @ instTy = meth @ repTy
519 -- (no coerce's). We'd need a coerce if we wanted to handle
520 -- recursive newtypes too
522 -- Check that eta reduction is OK
523 -- (a) the dropped-off args are identical
524 -- (b) the remaining type args do not mention any of teh dropped type variables
525 -- (c) the type class args do not mention any of teh dropped type variables
526 dropped_tvs = mkVarSet tyvars_to_drop
527 eta_ok = (args_to_drop `tcEqTypes` mkTyVarTys tyvars_to_drop)
528 && (tyVarsOfType rep_fn' `disjointVarSet` dropped_tvs)
529 && (tyVarsOfTypes tys `disjointVarSet` dropped_tvs)
531 cant_derive_err = derivingThingErr clas tys tycon tyvars_to_keep
532 (vcat [ptext SLIT("even with cunning newtype deriving:"),
533 if isRecursiveTyCon tycon then
534 ptext SLIT("the newtype is recursive")
536 if not right_arity then
537 quotes (ppr (mkClassPred clas tys)) <+> ptext SLIT("does not have arity 1")
539 if not (n_tyvars_to_keep >= 0) then
540 ptext SLIT("the type constructor has wrong kind")
541 else if not (n_args_to_keep >= 0) then
542 ptext SLIT("the representation type has wrong kind")
543 else if not eta_ok then
544 ptext SLIT("the eta-reduction property does not hold")
548 non_std_err = derivingThingErr clas tys tycon tyvars_to_keep
549 (vcat [non_std_why clas,
550 ptext SLIT("Try -fglasgow-exts for GHC's newtype-deriving extension")])
552 bale_out err = addErrTc err `thenM_` returnM (Nothing, Nothing)
554 std_class gla_exts clas
555 = key `elem` derivableClassKeys
556 || (gla_exts && (key == typeableClassKey || key == dataClassKey))
560 std_class_via_iso clas -- These standard classes can be derived for a newtype
561 -- using the isomorphism trick *even if no -fglasgow-exts*
562 = classKey clas `elem` [eqClassKey, ordClassKey, ixClassKey, boundedClassKey]
563 -- Not Read/Show because they respect the type
564 -- Not Enum, becuase newtypes are never in Enum
567 new_dfun_name clas tycon -- Just a simple wrapper
568 = newDFunName clas [mkTyConApp tycon []] (getSrcLoc tycon)
569 -- The type passed to newDFunName is only used to generate
570 -- a suitable string; hence the empty type arg list
572 ------------------------------------------------------------------
573 mkDataTypeEqn :: SrcSpan -> InstOrigin -> TyCon -> Class -> TcM DerivEqn
574 mkDataTypeEqn loc orig tycon clas
575 | clas `hasKey` typeableClassKey
576 = -- The Typeable class is special in several ways
577 -- data T a b = ... deriving( Typeable )
579 -- instance Typeable2 T where ...
581 -- 1. There are no constraints in the instance
582 -- 2. There are no type variables either
583 -- 3. The actual class we want to generate isn't necessarily
584 -- Typeable; it depends on the arity of the type
585 do { real_clas <- tcLookupClass (typeableClassNames !! tyConArity tycon)
586 ; dfun_name <- new_dfun_name real_clas tycon
587 ; return (loc, orig, dfun_name, real_clas, tycon, [], []) }
590 = do { dfun_name <- new_dfun_name clas tycon
591 ; return (loc, orig, dfun_name, clas, tycon, tyvars, constraints) }
593 tyvars = tyConTyVars tycon
594 constraints = extra_constraints ++ ordinary_constraints
595 extra_constraints = tyConStupidTheta tycon
596 -- "extra_constraints": see note [Data decl contexts] above
599 = [ mkClassPred clas [arg_ty]
600 | data_con <- tyConDataCons tycon,
601 arg_ty <- dataConInstOrigArgTys data_con (map mkTyVarTy (tyConTyVars tycon)),
602 not (isUnLiftedType arg_ty) -- No constraints for unlifted types?
606 ------------------------------------------------------------------
607 -- Check side conditions that dis-allow derivability for particular classes
608 -- This is *apart* from the newtype-deriving mechanism
610 checkSideConditions :: Bool -> TyCon -> [TyVar] -> Class -> [TcType] -> Maybe SDoc
611 checkSideConditions gla_exts tycon deriv_tvs clas tys
612 | notNull deriv_tvs || notNull tys
613 = Just ty_args_why -- e.g. deriving( Foo s )
615 = case [cond | (key,cond) <- sideConditions, key == getUnique clas] of
616 [] -> Just (non_std_why clas)
617 [cond] -> cond (gla_exts, tycon)
618 other -> pprPanic "checkSideConditions" (ppr clas)
620 ty_args_why = quotes (ppr (mkClassPred clas tys)) <+> ptext SLIT("is not a class")
622 non_std_why clas = quotes (ppr clas) <+> ptext SLIT("is not a derivable class")
624 sideConditions :: [(Unique, Condition)]
626 = [ (eqClassKey, cond_std),
627 (ordClassKey, cond_std),
628 (readClassKey, cond_std),
629 (showClassKey, cond_std),
630 (enumClassKey, cond_std `andCond` cond_isEnumeration),
631 (ixClassKey, cond_std `andCond` (cond_isEnumeration `orCond` cond_isProduct)),
632 (boundedClassKey, cond_std `andCond` (cond_isEnumeration `orCond` cond_isProduct)),
633 (typeableClassKey, cond_glaExts `andCond` cond_typeableOK),
634 (dataClassKey, cond_glaExts `andCond` cond_std)
637 type Condition = (Bool, TyCon) -> Maybe SDoc -- Nothing => OK
639 orCond :: Condition -> Condition -> Condition
642 Nothing -> Nothing -- c1 succeeds
643 Just x -> case c2 tc of -- c1 fails
645 Just y -> Just (x $$ ptext SLIT(" and") $$ y)
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
653 cond_std (gla_exts, tycon)
654 | any (not . isVanillaDataCon) data_cons = Just existential_why
655 | null data_cons = Just no_cons_why
656 | otherwise = Nothing
658 data_cons = tyConDataCons tycon
659 no_cons_why = quotes (ppr tycon) <+> ptext SLIT("has no data constructors")
660 existential_why = quotes (ppr tycon) <+> ptext SLIT("has non-Haskell-98 constructor(s)")
662 cond_isEnumeration :: Condition
663 cond_isEnumeration (gla_exts, tycon)
664 | isEnumerationTyCon tycon = Nothing
665 | otherwise = Just why
667 why = quotes (ppr tycon) <+> ptext SLIT("has non-nullary constructors")
669 cond_isProduct :: Condition
670 cond_isProduct (gla_exts, tycon)
671 | isProductTyCon tycon = Nothing
672 | otherwise = Just why
674 why = quotes (ppr tycon) <+> ptext SLIT("has more than one constructor")
676 cond_typeableOK :: Condition
677 -- OK for Typeable class
678 -- Currently: (a) args all of kind *
679 -- (b) 7 or fewer args
680 cond_typeableOK (gla_exts, tycon)
681 | tyConArity tycon > 7 = Just too_many
682 | not (all (isSubArgTypeKind . tyVarKind) (tyConTyVars tycon)) = Just bad_kind
683 | otherwise = Nothing
685 too_many = quotes (ppr tycon) <+> ptext SLIT("has too many arguments")
686 bad_kind = quotes (ppr tycon) <+> ptext SLIT("has arguments of kind other than `*'")
688 cond_glaExts :: Condition
689 cond_glaExts (gla_exts, tycon) | gla_exts = Nothing
690 | otherwise = Just why
692 why = ptext SLIT("You need -fglasgow-exts to derive an instance for this class")
695 %************************************************************************
697 \subsection[TcDeriv-fixpoint]{Finding the fixed point of \tr{deriving} equations}
699 %************************************************************************
701 A ``solution'' (to one of the equations) is a list of (k,TyVarTy tv)
702 terms, which is the final correct RHS for the corresponding original
706 Each (k,TyVarTy tv) in a solution constrains only a type
710 The (k,TyVarTy tv) pairs in a solution are canonically
711 ordered by sorting on type varible, tv, (major key) and then class, k,
716 solveDerivEqns :: OverlapFlag
718 -> TcM [Instance]-- Solns in same order as eqns.
719 -- This bunch is Absolutely minimal...
721 solveDerivEqns overlap_flag orig_eqns
722 = iterateDeriv 1 initial_solutions
724 -- The initial solutions for the equations claim that each
725 -- instance has an empty context; this solution is certainly
726 -- in canonical form.
727 initial_solutions :: [DerivSoln]
728 initial_solutions = [ [] | _ <- orig_eqns ]
730 ------------------------------------------------------------------
731 -- iterateDeriv calculates the next batch of solutions,
732 -- compares it with the current one; finishes if they are the
733 -- same, otherwise recurses with the new solutions.
734 -- It fails if any iteration fails
735 iterateDeriv :: Int -> [DerivSoln] -> TcM [Instance]
736 iterateDeriv n current_solns
737 | n > 20 -- Looks as if we are in an infinite loop
738 -- This can happen if we have -fallow-undecidable-instances
739 -- (See TcSimplify.tcSimplifyDeriv.)
740 = pprPanic "solveDerivEqns: probable loop"
741 (vcat (map pprDerivEqn orig_eqns) $$ ppr current_solns)
744 inst_specs = zipWithEqual "add_solns" mk_inst_spec
745 orig_eqns current_solns
748 -- Extend the inst info from the explicit instance decls
749 -- with the current set of solutions, and simplify each RHS
750 extendLocalInstEnv inst_specs $
751 mappM gen_soln orig_eqns
752 ) `thenM` \ new_solns ->
753 if (current_solns == new_solns) then
756 iterateDeriv (n+1) new_solns
758 ------------------------------------------------------------------
759 gen_soln :: DerivEqn -> TcM [PredType]
760 gen_soln (loc, orig, _, clas, tc,tyvars,deriv_rhs)
762 do { let inst_tys = [mkTyConApp tc (mkTyVarTys tyvars)]
763 ; theta <- addErrCtxt (derivInstCtxt1 clas inst_tys) $
764 tcSimplifyDeriv orig tc tyvars deriv_rhs
765 -- Claim: the result instance declaration is guaranteed valid
766 -- Hence no need to call:
767 -- checkValidInstance tyvars theta clas inst_tys
768 ; return (sortLe (<=) theta) } -- Canonicalise before returning the solution
772 ------------------------------------------------------------------
773 mk_inst_spec :: DerivEqn -> DerivSoln -> Instance
774 mk_inst_spec (loc, orig, dfun_name, clas, tycon, tyvars, _) theta
775 = mkLocalInstance dfun overlap_flag
777 dfun = mkDictFunId dfun_name tyvars theta clas
778 [mkTyConApp tycon (mkTyVarTys tyvars)]
780 extendLocalInstEnv :: [Instance] -> TcM a -> TcM a
781 -- Add new locally-defined instances; don't bother to check
782 -- for functional dependency errors -- that'll happen in TcInstDcls
783 extendLocalInstEnv dfuns thing_inside
784 = do { env <- getGblEnv
785 ; let inst_env' = extendInstEnvList (tcg_inst_env env) dfuns
786 env' = env { tcg_inst_env = inst_env' }
787 ; setGblEnv env' thing_inside }
790 %************************************************************************
792 \subsection[TcDeriv-normal-binds]{Bindings for the various classes}
794 %************************************************************************
796 After all the trouble to figure out the required context for the
797 derived instance declarations, all that's left is to chug along to
798 produce them. They will then be shoved into @tcInstDecls2@, which
799 will do all its usual business.
801 There are lots of possibilities for code to generate. Here are
802 various general remarks.
807 We want derived instances of @Eq@ and @Ord@ (both v common) to be
808 ``you-couldn't-do-better-by-hand'' efficient.
811 Deriving @Show@---also pretty common--- should also be reasonable good code.
814 Deriving for the other classes isn't that common or that big a deal.
821 Deriving @Ord@ is done mostly with the 1.3 @compare@ method.
824 Deriving @Eq@ also uses @compare@, if we're deriving @Ord@, too.
827 We {\em normally} generate code only for the non-defaulted methods;
828 there are some exceptions for @Eq@ and (especially) @Ord@...
831 Sometimes we use a @_con2tag_<tycon>@ function, which returns a data
832 constructor's numeric (@Int#@) tag. These are generated by
833 @gen_tag_n_con_binds@, and the heuristic for deciding if one of
834 these is around is given by @hasCon2TagFun@.
836 The examples under the different sections below will make this
840 Much less often (really just for deriving @Ix@), we use a
841 @_tag2con_<tycon>@ function. See the examples.
844 We use the renamer!!! Reason: we're supposed to be
845 producing @LHsBinds Name@ for the methods, but that means
846 producing correctly-uniquified code on the fly. This is entirely
847 possible (the @TcM@ monad has a @UniqueSupply@), but it is painful.
848 So, instead, we produce @MonoBinds RdrName@ then heave 'em through
849 the renamer. What a great hack!
853 -- Generate the InstInfo for the required instance,
854 -- plus any auxiliary bindings required
855 genInst :: Instance -> TcM (InstInfo, LHsBinds RdrName)
857 = do { fix_env <- getFixityEnv
859 (tyvars,_,clas,[ty]) = instanceHead spec
860 clas_nm = className clas
861 tycon = tcTyConAppTyCon ty
862 (meth_binds, aux_binds) = genDerivBinds clas fix_env tycon
864 -- Bring the right type variables into
865 -- scope, and rename the method binds
866 -- It's a bit yukky that we return *renamed* InstInfo, but
867 -- *non-renamed* auxiliary bindings
868 ; (rn_meth_binds, _fvs) <- discardWarnings $
869 bindLocalNames (map Var.varName tyvars) $
870 rnMethodBinds clas_nm (\n -> []) [] meth_binds
872 -- Build the InstInfo
873 ; return (InstInfo { iSpec = spec,
874 iBinds = VanillaInst rn_meth_binds [] },
878 genDerivBinds clas fix_env tycon
879 | className clas `elem` typeableClassNames
880 = (gen_Typeable_binds tycon, emptyLHsBinds)
883 = case assocMaybe gen_list (getUnique clas) of
884 Just gen_fn -> gen_fn fix_env tycon
885 Nothing -> pprPanic "genDerivBinds: bad derived class" (ppr clas)
887 gen_list :: [(Unique, FixityEnv -> TyCon -> (LHsBinds RdrName, LHsBinds RdrName))]
888 gen_list = [(eqClassKey, no_aux_binds (ignore_fix_env gen_Eq_binds))
889 ,(ordClassKey, no_aux_binds (ignore_fix_env gen_Ord_binds))
890 ,(enumClassKey, no_aux_binds (ignore_fix_env gen_Enum_binds))
891 ,(boundedClassKey, no_aux_binds (ignore_fix_env gen_Bounded_binds))
892 ,(ixClassKey, no_aux_binds (ignore_fix_env gen_Ix_binds))
893 ,(typeableClassKey,no_aux_binds (ignore_fix_env gen_Typeable_binds))
894 ,(showClassKey, no_aux_binds gen_Show_binds)
895 ,(readClassKey, no_aux_binds gen_Read_binds)
896 ,(dataClassKey, gen_Data_binds)
899 -- no_aux_binds is used for generators that don't
900 -- need to produce any auxiliary bindings
901 no_aux_binds f fix_env tc = (f fix_env tc, emptyLHsBinds)
902 ignore_fix_env f fix_env tc = f tc
906 %************************************************************************
908 \subsection[TcDeriv-taggery-Names]{What con2tag/tag2con functions are available?}
910 %************************************************************************
915 con2tag_Foo :: Foo ... -> Int#
916 tag2con_Foo :: Int -> Foo ... -- easier if Int, not Int#
917 maxtag_Foo :: Int -- ditto (NB: not unlifted)
920 We have a @con2tag@ function for a tycon if:
923 We're deriving @Eq@ and the tycon has nullary data constructors.
926 Or: we're deriving @Ord@ (unless single-constructor), @Enum@, @Ix@
930 We have a @tag2con@ function for a tycon if:
933 We're deriving @Enum@, or @Ix@ (enum type only???)
936 If we have a @tag2con@ function, we also generate a @maxtag@ constant.
939 genTaggeryBinds :: [InstInfo] -> TcM (LHsBinds RdrName)
940 genTaggeryBinds infos
941 = do { names_so_far <- foldlM do_con2tag [] tycons_of_interest
942 ; nm_alist_etc <- foldlM do_tag2con names_so_far tycons_of_interest
943 ; return (listToBag (map gen_tag_n_con_monobind nm_alist_etc)) }
945 all_CTs = [ (cls, tcTyConAppTyCon ty)
947 let (cls,ty) = simpleInstInfoClsTy info ]
948 all_tycons = map snd all_CTs
949 (tycons_of_interest, _) = removeDups compare all_tycons
951 do_con2tag acc_Names tycon
952 | isDataTyCon tycon &&
953 ((we_are_deriving eqClassKey tycon
954 && any isNullarySrcDataCon (tyConDataCons tycon))
955 || (we_are_deriving ordClassKey tycon
956 && not (isProductTyCon tycon))
957 || (we_are_deriving enumClassKey tycon)
958 || (we_are_deriving ixClassKey tycon))
960 = returnM ((con2tag_RDR tycon, tycon, GenCon2Tag)
965 do_tag2con acc_Names tycon
966 | isDataTyCon tycon &&
967 (we_are_deriving enumClassKey tycon ||
968 we_are_deriving ixClassKey tycon
969 && isEnumerationTyCon tycon)
970 = returnM ( (tag2con_RDR tycon, tycon, GenTag2Con)
971 : (maxtag_RDR tycon, tycon, GenMaxTag)
976 we_are_deriving clas_key tycon
977 = is_in_eqns clas_key tycon all_CTs
979 is_in_eqns clas_key tycon [] = False
980 is_in_eqns clas_key tycon ((c,t):cts)
981 = (clas_key == classKey c && tycon == t)
982 || is_in_eqns clas_key tycon cts
986 derivingThingErr clas tys tycon tyvars why
987 = sep [hsep [ptext SLIT("Can't make a derived instance of"), quotes (ppr pred)],
990 pred = mkClassPred clas (tys ++ [mkTyConApp tycon (mkTyVarTys tyvars)])
992 derivCtxt :: TyCon -> SDoc
994 = ptext SLIT("When deriving instances for") <+> quotes (ppr tycon)
996 derivInstCtxt1 clas inst_tys
997 = ptext SLIT("When deriving the instance for") <+> quotes (pprClassPred clas inst_tys)