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
138 -- For family indexes, the tycon is the representation tycon
140 pprDerivEqn :: DerivEqn -> SDoc
141 pprDerivEqn (l, _, n, c, tc, tvs, rhs)
142 = parens (hsep [ppr l, ppr n, ppr c, ppr origTc, ppr tys] <+> equals <+>
145 (origTc, tys) = tyConOrigHead tc
147 type DerivRhs = ThetaType
148 type DerivSoln = DerivRhs
152 [Data decl contexts] A note about contexts on data decls
153 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
156 data (RealFloat a) => Complex a = !a :+ !a deriving( Read )
158 We will need an instance decl like:
160 instance (Read a, RealFloat a) => Read (Complex a) where
163 The RealFloat in the context is because the read method for Complex is bound
164 to construct a Complex, and doing that requires that the argument type is
167 But this ain't true for Show, Eq, Ord, etc, since they don't construct
168 a Complex; they only take them apart.
170 Our approach: identify the offending classes, and add the data type
171 context to the instance decl. The "offending classes" are
175 FURTHER NOTE ADDED March 2002. In fact, Haskell98 now requires that
176 pattern matching against a constructor from a data type with a context
177 gives rise to the constraints for that context -- or at least the thinned
178 version. So now all classes are "offending".
185 newtype T = T Char deriving( C [a] )
187 Notice the free 'a' in the deriving. We have to fill this out to
188 newtype T = T Char deriving( forall a. C [a] )
190 And then translate it to:
191 instance C [a] Char => C [a] T where ...
196 %************************************************************************
198 \subsection[TcDeriv-driver]{Top-level function for \tr{derivings}}
200 %************************************************************************
203 tcDeriving :: [LTyClDecl Name] -- All type constructors
204 -> [LDerivDecl Name] -- All stand-alone deriving declarations
205 -> TcM ([InstInfo], -- The generated "instance decls"
206 HsValBinds Name) -- Extra generated top-level bindings
208 tcDeriving tycl_decls deriv_decls
209 = recoverM (returnM ([], emptyValBindsOut)) $
210 do { -- Fish the "deriving"-related information out of the TcEnv
211 -- and make the necessary "equations".
212 overlap_flag <- getOverlapFlag
213 ; (ordinary_eqns, newtype_inst_info)
214 <- makeDerivEqns overlap_flag tycl_decls deriv_decls
216 ; (ordinary_inst_info, deriv_binds)
217 <- extendLocalInstEnv (map iSpec newtype_inst_info) $
218 deriveOrdinaryStuff overlap_flag ordinary_eqns
219 -- Add the newtype-derived instances to the inst env
220 -- before tacking the "ordinary" ones
222 ; let inst_info = newtype_inst_info ++ ordinary_inst_info
224 -- If we are compiling a hs-boot file,
225 -- don't generate any derived bindings
226 ; is_boot <- tcIsHsBoot
228 return (inst_info, emptyValBindsOut)
232 -- Generate the generic to/from functions from each type declaration
233 ; gen_binds <- mkGenericBinds tycl_decls
235 -- Rename these extra bindings, discarding warnings about unused bindings etc
236 -- Set -fglasgow exts so that we can have type signatures in patterns,
237 -- which is used in the generic binds
239 <- discardWarnings $ setOptM Opt_GlasgowExts $ do
240 { (rn_deriv, _dus1) <- rnTopBinds (ValBindsIn deriv_binds [])
241 ; (rn_gen, dus_gen) <- rnTopBinds (ValBindsIn gen_binds [])
242 ; keepAliveSetTc (duDefs dus_gen) -- Mark these guys to
244 ; return (rn_deriv `plusHsValBinds` rn_gen) }
248 ; ioToTcRn (dumpIfSet_dyn dflags Opt_D_dump_deriv "Derived instances"
249 (ddump_deriving inst_info rn_binds))
251 ; returnM (inst_info, rn_binds)
254 ddump_deriving :: [InstInfo] -> HsValBinds Name -> SDoc
255 ddump_deriving inst_infos extra_binds
256 = vcat (map pprInstInfoDetails inst_infos) $$ ppr extra_binds
258 -----------------------------------------
259 deriveOrdinaryStuff overlap_flag [] -- Short cut
260 = returnM ([], emptyLHsBinds)
262 deriveOrdinaryStuff overlap_flag eqns
263 = do { -- Take the equation list and solve it, to deliver a list of
264 -- solutions, a.k.a. the contexts for the instance decls
265 -- required for the corresponding equations.
266 inst_specs <- solveDerivEqns overlap_flag eqns
268 -- Generate the InstInfo for each dfun,
269 -- plus any auxiliary bindings it needs
270 ; (inst_infos, aux_binds_s) <- mapAndUnzipM genInst inst_specs
272 -- Generate any extra not-one-inst-decl-specific binds,
273 -- notably "con2tag" and/or "tag2con" functions.
274 ; extra_binds <- genTaggeryBinds inst_infos
277 ; returnM (map fst inst_infos,
278 unionManyBags (extra_binds : aux_binds_s))
281 -----------------------------------------
282 mkGenericBinds tycl_decls
283 = do { tcs <- mapM tcLookupTyCon
285 L _ (TyData { tcdLName = L _ tc_name }) <- tycl_decls]
286 -- We are only interested in the data type declarations
287 ; return (unionManyBags [ mkTyConGenericBinds tc |
288 tc <- tcs, tyConHasGenerics tc ]) }
289 -- And then only in the ones whose 'has-generics' flag is on
293 %************************************************************************
295 \subsection[TcDeriv-eqns]{Forming the equations}
297 %************************************************************************
299 @makeDerivEqns@ fishes around to find the info about needed derived
300 instances. Complicating factors:
303 We can only derive @Enum@ if the data type is an enumeration
304 type (all nullary data constructors).
307 We can only derive @Ix@ if the data type is an enumeration {\em
308 or} has just one data constructor (e.g., tuples).
311 [See Appendix~E in the Haskell~1.2 report.] This code here deals w/
314 Note [Newtype deriving superclasses]
315 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
316 The 'tys' here come from the partial application in the deriving
317 clause. The last arg is the new instance type.
319 We must pass the superclasses; the newtype might be an instance
320 of them in a different way than the representation type
321 E.g. newtype Foo a = Foo a deriving( Show, Num, Eq )
322 Then the Show instance is not done via isomorphism; it shows
324 The Num instance is derived via isomorphism, but the Show superclass
325 dictionary must the Show instance for Foo, *not* the Show dictionary
326 gotten from the Num dictionary. So we must build a whole new dictionary
327 not just use the Num one. The instance we want is something like:
328 instance (Num a, Show (Foo a), Eq (Foo a)) => Num (Foo a) where
331 There may be a coercion needed which we get from the tycon for the newtype
332 when the dict is constructed in TcInstDcls.tcInstDecl2
336 type DerivSpec = (SrcSpan, -- location of the deriving clause
337 InstOrigin, -- deriving at data decl or standalone?
338 NewOrData, -- newtype or data type
339 Name, -- Type constructor for which we derive
340 [LHsTyVarBndr Name], -- Type variables
341 Maybe [LHsType Name], -- Type indexes if indexed type
342 LHsType Name) -- Class instance to be generated
344 makeDerivEqns :: OverlapFlag
347 -> TcM ([DerivEqn], -- Ordinary derivings
348 [InstInfo]) -- Special newtype derivings
350 makeDerivEqns overlap_flag tycl_decls deriv_decls
351 = do derive_top_level <- mapM top_level_deriv deriv_decls
352 (maybe_ordinaries, maybe_newtypes)
353 <- mapAndUnzipM mk_eqn (derive_data ++ catMaybes derive_top_level)
354 return (catMaybes maybe_ordinaries, catMaybes maybe_newtypes)
356 ------------------------------------------------------------------
357 -- Deriving clauses at data declarations
358 derive_data :: [DerivSpec]
359 derive_data = [ (loc, DerivOrigin, nd, tycon, tyVars, tyPats, pred)
360 | L loc (TyData { tcdND = nd, tcdLName = L _ tycon,
361 tcdTyVars = tyVars, tcdTyPats = tyPats,
362 tcdDerivs = Just preds }) <- tycl_decls,
365 -- Standalone deriving declarations
366 top_level_deriv :: LDerivDecl Name -> TcM (Maybe DerivSpec)
367 top_level_deriv d@(L loc (DerivDecl inst ty_name)) =
368 recoverM (returnM Nothing) $ setSrcSpan loc $
369 do tycon <- tcLookupLocatedTyCon ty_name
370 let new_or_data = if isNewTyCon tycon then NewType else DataType
371 let tyVars = [ noLoc $ KindedTyVar (tyVarName tv) (tyVarKind tv)
372 | tv <- tyConTyVars tycon] -- Yuk!!!
373 traceTc (text "Stand-alone deriving:" <+>
374 ppr (new_or_data, unLoc ty_name, inst))
375 return $ Just (loc, StandAloneDerivOrigin, new_or_data,
376 unLoc ty_name, tyVars, Nothing, inst)
378 ------------------------------------------------------------------
379 -- Derive equation/inst info for one deriving clause (data or standalone)
380 mk_eqn :: DerivSpec -> TcM (Maybe DerivEqn, Maybe InstInfo)
381 -- We swizzle the datacons out of the tycon to make the rest of the
382 -- equation. We can't get the tyvars out of the constructor in case
383 -- of family instances, as we already need to them to lookup the
384 -- representation tycon (only that has the right set of type
385 -- variables, the type variables of the family constructor are
388 -- The "deriv_ty" is a LHsType to take account of the fact that for
389 -- newtype deriving we allow deriving (forall a. C [a]).
391 mk_eqn (loc, orig, new_or_data, tycon_name, tyvars, mb_tys, hs_deriv_ty)
393 addErrCtxt (derivCtxt tycon_name mb_tys) $
394 do { named_tycon <- tcLookupTyCon tycon_name
396 -- Enable deriving preds to mention the type variables in the
398 ; tcTyVarBndrs tyvars $ \tvs -> do
399 { traceTc (text "TcDeriv.mk_eqn: tyvars:" <+> ppr tvs)
401 -- Lookup representation tycon in case of a family instance
402 -- NB: We already need the type variables in scope here for the
403 -- call to `dsHsType'.
404 ; tycon <- case mb_tys of
405 Nothing -> return named_tycon
407 tys <- mapM dsHsType hsTys
408 tcLookupFamInst named_tycon tys
410 ; (deriv_tvs, clas, tys) <- tcHsDeriv hs_deriv_ty
411 ; gla_exts <- doptM Opt_GlasgowExts
412 ; mk_eqn_help loc orig gla_exts new_or_data tycon deriv_tvs clas tys
415 ------------------------------------------------------------------
416 -- data/newtype T a = ... deriving( C t1 t2 )
417 -- leads to a call to mk_eqn_help with
418 -- tycon = T, deriv_tvs = ftv(t1,t2), clas = C, tys = [t1,t2]
420 mk_eqn_help loc orig gla_exts DataType tycon deriv_tvs clas tys
421 | Just err <- checkSideConditions gla_exts tycon deriv_tvs clas tys
422 = bale_out (derivingThingErr clas tys origTyCon ttys err)
424 = do { eqn <- mkDataTypeEqn loc orig tycon clas
425 ; returnM (Just eqn, Nothing) }
427 (origTyCon, ttys) = tyConOrigHead tycon
429 mk_eqn_help loc orig gla_exts NewType tycon deriv_tvs clas tys
430 | can_derive_via_isomorphism && (gla_exts || std_class_via_iso clas)
431 = do { traceTc (text "newtype deriving:" <+> ppr tycon <+> ppr rep_tys)
432 ; -- Go ahead and use the isomorphism
433 dfun_name <- new_dfun_name clas tycon
434 ; return (Nothing, Just (InstInfo { iSpec = mk_inst_spec dfun_name,
435 iBinds = NewTypeDerived ntd_info })) }
436 | std_class gla_exts clas
437 = mk_eqn_help loc orig gla_exts DataType tycon deriv_tvs clas tys -- Go via bale-out route
439 | otherwise -- Non-standard instance
440 = bale_out (if gla_exts then
441 cant_derive_err -- Too hard
443 non_std_err) -- Just complain about being a non-std instance
445 -- Here is the plan for newtype derivings. We see
446 -- newtype T a1...an = MkT (t ak+1...an) deriving (.., C s1 .. sm, ...)
447 -- where t is a type,
448 -- ak+1...an is a suffix of a1..an
449 -- ak+1...an do not occur free in t, nor in the s1..sm
450 -- (C s1 ... sm) is a *partial applications* of class C
451 -- with the last parameter missing
452 -- (T a1 .. ak) matches the kind of C's last argument
453 -- (and hence so does t)
455 -- We generate the instance
456 -- instance forall ({a1..ak} u fvs(s1..sm)).
457 -- C s1 .. sm t => C s1 .. sm (T a1...ak)
458 -- where T a1...ap is the partial application of
459 -- the LHS of the correct kind and p >= k
461 -- NB: the variables below are:
462 -- tc_tvs = [a1, ..., an]
463 -- tyvars_to_keep = [a1, ..., ak]
464 -- rep_ty = t ak .. an
465 -- deriv_tvs = fvs(s1..sm) \ tc_tvs
466 -- tys = [s1, ..., sm]
469 -- Running example: newtype T s a = MkT (ST s a) deriving( Monad )
470 -- We generate the instance
471 -- instance Monad (ST s) => Monad (T s) where
473 clas_tyvars = classTyVars clas
474 kind = tyVarKind (last clas_tyvars)
475 -- Kind of the thing we want to instance
476 -- e.g. argument kind of Monad, *->*
478 (arg_kinds, _) = splitKindFunTys kind
479 n_args_to_drop = length arg_kinds
480 -- Want to drop 1 arg from (T s a) and (ST s a)
481 -- to get instance Monad (ST s) => Monad (T s)
483 -- Note [newtype representation]
484 -- Need newTyConRhs *not* newTyConRep to get the representation
485 -- type, because the latter looks through all intermediate newtypes
487 -- newtype B = MkB Int
488 -- newtype A = MkA B deriving( Num )
489 -- We want the Num instance of B, *not* the Num instance of Int,
490 -- when making the Num instance of A!
491 (tc_tvs, rep_ty) = newTyConRhs tycon
492 (rep_fn, rep_ty_args) = tcSplitAppTys rep_ty
494 n_tyvars_to_keep = tyConArity tycon - n_args_to_drop
495 tyvars_to_drop = drop n_tyvars_to_keep tc_tvs
496 tyvars_to_keep = take n_tyvars_to_keep tc_tvs
498 n_args_to_keep = length rep_ty_args - n_args_to_drop
499 args_to_drop = drop n_args_to_keep rep_ty_args
500 args_to_keep = take n_args_to_keep rep_ty_args
502 rep_fn' = mkAppTys rep_fn args_to_keep
503 rep_tys = tys ++ [rep_fn']
504 rep_pred = mkClassPred clas rep_tys
505 -- rep_pred is the representation dictionary, from where
506 -- we are gong to get all the methods for the newtype
509 -- To account for newtype family instance, we need to get the family
510 -- tycon and its index types when costructing the type at which we
511 -- construct the class instance. The dropped class parameters must of
512 -- course all be variables (not more complex indexes).
515 (origTyCon, tyArgs) = tyConOrigHead tycon
516 in mkTyConApp origTyCon (take n_tyvars_to_keep tyArgs)
518 -- Next we figure out what superclass dictionaries to use
519 -- See Note [Newtype deriving superclasses] above
521 inst_tys = tys ++ [origHead]
522 sc_theta = substTheta (zipOpenTvSubst clas_tyvars inst_tys)
525 -- If there are no tyvars, there's no need
526 -- to abstract over the dictionaries we need
527 -- Example: newtype T = MkT Int deriving( C )
528 -- We get the derived instance
531 -- instance C Int => C T
532 dict_tvs = deriv_tvs ++ tyvars_to_keep
533 all_preds = rep_pred : sc_theta -- NB: rep_pred comes first
534 (dict_args, ntd_info) | null dict_tvs = ([], Just all_preds)
535 | otherwise = (all_preds, Nothing)
537 -- Finally! Here's where we build the dictionary Id
538 mk_inst_spec dfun_name = mkLocalInstance dfun overlap_flag
540 dfun = mkDictFunId dfun_name dict_tvs dict_args clas inst_tys
542 -------------------------------------------------------------------
543 -- Figuring out whether we can only do this newtype-deriving thing
545 right_arity = length tys + 1 == classArity clas
547 -- Never derive Read,Show,Typeable,Data this way
548 non_iso_classes = [readClassKey, showClassKey, typeableClassKey, dataClassKey]
549 can_derive_via_isomorphism
550 = not (getUnique clas `elem` non_iso_classes)
551 && right_arity -- Well kinded;
552 -- eg not: newtype T ... deriving( ST )
553 -- because ST needs *2* type params
554 && n_tyvars_to_keep >= 0 -- Type constructor has right kind:
555 -- eg not: newtype T = T Int deriving( Monad )
556 && n_args_to_keep >= 0 -- Rep type has right kind:
557 -- eg not: newtype T a = T Int deriving( Monad )
558 && eta_ok -- Eta reduction works
559 && not (isRecursiveTyCon tycon) -- Does not work for recursive tycons:
560 -- newtype A = MkA [A]
562 -- instance Eq [A] => Eq A !!
563 -- Here's a recursive newtype that's actually OK
564 -- newtype S1 = S1 [T1 ()]
565 -- newtype T1 a = T1 (StateT S1 IO a ) deriving( Monad )
566 -- It's currently rejected. Oh well.
567 -- In fact we generate an instance decl that has method of form
568 -- meth @ instTy = meth @ repTy
569 -- (no coerce's). We'd need a coerce if we wanted to handle
570 -- recursive newtypes too
572 -- Check that eta reduction is OK
573 -- (a) the dropped-off args are identical
574 -- (b) the remaining type args do not mention any of teh dropped
576 -- (c) the type class args do not mention any of teh dropped type
578 -- (d) in case of newtype family instances, the eta-dropped
579 -- arguments must be type variables (not more complex indexes)
580 dropped_tvs = mkVarSet tyvars_to_drop
581 eta_ok = (args_to_drop `tcEqTypes` mkTyVarTys tyvars_to_drop)
582 && (tyVarsOfType rep_fn' `disjointVarSet` dropped_tvs)
583 && (tyVarsOfTypes tys `disjointVarSet` dropped_tvs)
584 && droppedIndexesAreVariables
586 droppedIndexesAreVariables =
587 case tyConFamInst_maybe tycon of
589 Just (famTyCon, tyIdxs) ->
590 all isTyVarTy $ drop (tyConArity famTyCon - n_args_to_drop) tyIdxs
592 cant_derive_err = derivingThingErr clas tys tycon (mkTyVarTys tyvars_to_keep)
593 (vcat [ptext SLIT("even with cunning newtype deriving:"),
594 if isRecursiveTyCon tycon then
595 ptext SLIT("the newtype is recursive")
597 if not right_arity then
598 quotes (ppr (mkClassPred clas tys)) <+> ptext SLIT("does not have arity 1")
600 if not (n_tyvars_to_keep >= 0) then
601 ptext SLIT("the type constructor has wrong kind")
602 else if not (n_args_to_keep >= 0) then
603 ptext SLIT("the representation type has wrong kind")
604 else if not eta_ok then
605 ptext SLIT("the eta-reduction property does not hold")
609 non_std_err = derivingThingErr clas tys tycon (mkTyVarTys tyvars_to_keep)
610 (vcat [non_std_why clas,
611 ptext SLIT("Try -fglasgow-exts for GHC's newtype-deriving extension")])
613 bale_out err = addErrTc err `thenM_` returnM (Nothing, Nothing)
615 std_class gla_exts clas
616 = key `elem` derivableClassKeys
617 || (gla_exts && (key == typeableClassKey || key == dataClassKey))
621 std_class_via_iso clas -- These standard classes can be derived for a newtype
622 -- using the isomorphism trick *even if no -fglasgow-exts*
623 = classKey clas `elem` [eqClassKey, ordClassKey, ixClassKey, boundedClassKey]
624 -- Not Read/Show because they respect the type
625 -- Not Enum, becuase newtypes are never in Enum
628 new_dfun_name clas tycon -- Just a simple wrapper
629 = newDFunName clas [mkTyConApp tycon []] (getSrcLoc tycon)
630 -- The type passed to newDFunName is only used to generate
631 -- a suitable string; hence the empty type arg list
633 ------------------------------------------------------------------
634 mkDataTypeEqn :: SrcSpan -> InstOrigin -> TyCon -> Class -> TcM DerivEqn
635 mkDataTypeEqn loc orig tycon clas
636 | clas `hasKey` typeableClassKey
637 = -- The Typeable class is special in several ways
638 -- data T a b = ... deriving( Typeable )
640 -- instance Typeable2 T where ...
642 -- 1. There are no constraints in the instance
643 -- 2. There are no type variables either
644 -- 3. The actual class we want to generate isn't necessarily
645 -- Typeable; it depends on the arity of the type
646 do { real_clas <- tcLookupClass (typeableClassNames !! tyConArity tycon)
647 ; dfun_name <- new_dfun_name real_clas tycon
648 ; return (loc, orig, dfun_name, real_clas, tycon, [], []) }
651 = do { dfun_name <- new_dfun_name clas tycon
652 ; return (loc, orig, dfun_name, clas, tycon, tyvars, constraints)
655 tyvars = tyConTyVars tycon
656 constraints = extra_constraints ++ ordinary_constraints
657 extra_constraints = tyConStupidTheta tycon
658 -- "extra_constraints": see note [Data decl contexts] above
661 = [ mkClassPred clas [arg_ty]
662 | data_con <- tyConDataCons tycon,
663 arg_ty <- dataConInstOrigArgTys data_con (mkTyVarTys tyvars),
664 not (isUnLiftedType arg_ty) -- No constraints for unlifted types?
668 ------------------------------------------------------------------
669 -- Check side conditions that dis-allow derivability for particular classes
670 -- This is *apart* from the newtype-deriving mechanism
672 checkSideConditions :: Bool -> TyCon -> [TyVar] -> Class -> [TcType] -> Maybe SDoc
673 checkSideConditions gla_exts tycon deriv_tvs clas tys
674 | notNull deriv_tvs || notNull tys
675 = Just ty_args_why -- e.g. deriving( Foo s )
677 = case [cond | (key,cond) <- sideConditions, key == getUnique clas] of
678 [] -> Just (non_std_why clas)
679 [cond] -> cond (gla_exts, tycon)
680 other -> pprPanic "checkSideConditions" (ppr clas)
682 ty_args_why = quotes (ppr (mkClassPred clas tys)) <+> ptext SLIT("is not a class")
684 non_std_why clas = quotes (ppr clas) <+> ptext SLIT("is not a derivable class")
686 sideConditions :: [(Unique, Condition)]
688 = [ (eqClassKey, cond_std),
689 (ordClassKey, cond_std),
690 (readClassKey, cond_std),
691 (showClassKey, cond_std),
692 (enumClassKey, cond_std `andCond` cond_isEnumeration),
693 (ixClassKey, cond_std `andCond` (cond_isEnumeration `orCond` cond_isProduct)),
694 (boundedClassKey, cond_std `andCond` (cond_isEnumeration `orCond` cond_isProduct)),
695 (typeableClassKey, cond_glaExts `andCond` cond_typeableOK),
696 (dataClassKey, cond_glaExts `andCond` cond_std)
699 type Condition = (Bool, TyCon) -> Maybe SDoc -- Nothing => OK
701 orCond :: Condition -> Condition -> Condition
704 Nothing -> Nothing -- c1 succeeds
705 Just x -> case c2 tc of -- c1 fails
707 Just y -> Just (x $$ ptext SLIT(" and") $$ y)
710 andCond c1 c2 tc = case c1 tc of
711 Nothing -> c2 tc -- c1 succeeds
712 Just x -> Just x -- c1 fails
714 cond_std :: Condition
715 cond_std (gla_exts, tycon)
716 | any (not . isVanillaDataCon) data_cons = Just existential_why
717 | null data_cons = Just no_cons_why
718 | otherwise = Nothing
720 data_cons = tyConDataCons tycon
721 no_cons_why = quotes (ppr tycon) <+> ptext SLIT("has no data constructors")
722 existential_why = quotes (ppr tycon) <+> ptext SLIT("has non-Haskell-98 constructor(s)")
724 cond_isEnumeration :: Condition
725 cond_isEnumeration (gla_exts, tycon)
726 | isEnumerationTyCon tycon = Nothing
727 | otherwise = Just why
729 why = quotes (ppr tycon) <+> ptext SLIT("has non-nullary constructors")
731 cond_isProduct :: Condition
732 cond_isProduct (gla_exts, tycon)
733 | isProductTyCon tycon = Nothing
734 | otherwise = Just why
736 why = quotes (ppr tycon) <+> ptext SLIT("has more than one constructor")
738 cond_typeableOK :: Condition
739 -- OK for Typeable class
740 -- Currently: (a) args all of kind *
741 -- (b) 7 or fewer args
742 cond_typeableOK (gla_exts, tycon)
743 | tyConArity tycon > 7 = Just too_many
744 | not (all (isSubArgTypeKind . tyVarKind) (tyConTyVars tycon))
746 | isFamInstTyCon tycon = Just fam_inst -- no Typable for family insts
747 | otherwise = Nothing
749 too_many = quotes (ppr tycon) <+> ptext SLIT("has too many arguments")
750 bad_kind = quotes (ppr tycon) <+>
751 ptext SLIT("has arguments of kind other than `*'")
752 fam_inst = quotes (ppr tycon) <+> ptext SLIT("is a type family")
754 cond_glaExts :: Condition
755 cond_glaExts (gla_exts, tycon) | gla_exts = Nothing
756 | otherwise = Just why
758 why = ptext SLIT("You need -fglasgow-exts to derive an instance for this class")
761 %************************************************************************
763 \subsection[TcDeriv-fixpoint]{Finding the fixed point of \tr{deriving} equations}
765 %************************************************************************
767 A ``solution'' (to one of the equations) is a list of (k,TyVarTy tv)
768 terms, which is the final correct RHS for the corresponding original
772 Each (k,TyVarTy tv) in a solution constrains only a type
776 The (k,TyVarTy tv) pairs in a solution are canonically
777 ordered by sorting on type varible, tv, (major key) and then class, k,
782 solveDerivEqns :: OverlapFlag
784 -> TcM [Instance]-- Solns in same order as eqns.
785 -- This bunch is Absolutely minimal...
787 solveDerivEqns overlap_flag orig_eqns
788 = iterateDeriv 1 initial_solutions
790 -- The initial solutions for the equations claim that each
791 -- instance has an empty context; this solution is certainly
792 -- in canonical form.
793 initial_solutions :: [DerivSoln]
794 initial_solutions = [ [] | _ <- orig_eqns ]
796 ------------------------------------------------------------------
797 -- iterateDeriv calculates the next batch of solutions,
798 -- compares it with the current one; finishes if they are the
799 -- same, otherwise recurses with the new solutions.
800 -- It fails if any iteration fails
801 iterateDeriv :: Int -> [DerivSoln] -> TcM [Instance]
802 iterateDeriv n current_solns
803 | n > 20 -- Looks as if we are in an infinite loop
804 -- This can happen if we have -fallow-undecidable-instances
805 -- (See TcSimplify.tcSimplifyDeriv.)
806 = pprPanic "solveDerivEqns: probable loop"
807 (vcat (map pprDerivEqn orig_eqns) $$ ppr current_solns)
810 inst_specs = zipWithEqual "add_solns" mk_inst_spec
811 orig_eqns current_solns
814 -- Extend the inst info from the explicit instance decls
815 -- with the current set of solutions, and simplify each RHS
816 extendLocalInstEnv inst_specs $
817 mappM gen_soln orig_eqns
818 ) `thenM` \ new_solns ->
819 if (current_solns == new_solns) then
822 iterateDeriv (n+1) new_solns
824 ------------------------------------------------------------------
825 gen_soln :: DerivEqn -> TcM [PredType]
826 gen_soln (loc, orig, _, clas, tc, tyvars, deriv_rhs)
828 do { let inst_tys = [origHead]
829 ; theta <- addErrCtxt (derivInstCtxt1 clas inst_tys) $
830 tcSimplifyDeriv orig tc tyvars deriv_rhs
831 -- Claim: the result instance declaration is guaranteed valid
832 -- Hence no need to call:
833 -- checkValidInstance tyvars theta clas inst_tys
834 ; return (sortLe (<=) theta) } -- Canonicalise before returning the solution
836 origHead = uncurry mkTyConApp (tyConOrigHead tc)
838 ------------------------------------------------------------------
839 mk_inst_spec :: DerivEqn -> DerivSoln -> Instance
840 mk_inst_spec (loc, orig, dfun_name, clas, tycon, tyvars, _) theta
841 = mkLocalInstance dfun overlap_flag
843 dfun = mkDictFunId dfun_name tyvars theta clas [origHead]
844 origHead = uncurry mkTyConApp (tyConOrigHead tycon)
846 extendLocalInstEnv :: [Instance] -> TcM a -> TcM a
847 -- Add new locally-defined instances; don't bother to check
848 -- for functional dependency errors -- that'll happen in TcInstDcls
849 extendLocalInstEnv dfuns thing_inside
850 = do { env <- getGblEnv
851 ; let inst_env' = extendInstEnvList (tcg_inst_env env) dfuns
852 env' = env { tcg_inst_env = inst_env' }
853 ; setGblEnv env' thing_inside }
856 %************************************************************************
858 \subsection[TcDeriv-normal-binds]{Bindings for the various classes}
860 %************************************************************************
862 After all the trouble to figure out the required context for the
863 derived instance declarations, all that's left is to chug along to
864 produce them. They will then be shoved into @tcInstDecls2@, which
865 will do all its usual business.
867 There are lots of possibilities for code to generate. Here are
868 various general remarks.
873 We want derived instances of @Eq@ and @Ord@ (both v common) to be
874 ``you-couldn't-do-better-by-hand'' efficient.
877 Deriving @Show@---also pretty common--- should also be reasonable good code.
880 Deriving for the other classes isn't that common or that big a deal.
887 Deriving @Ord@ is done mostly with the 1.3 @compare@ method.
890 Deriving @Eq@ also uses @compare@, if we're deriving @Ord@, too.
893 We {\em normally} generate code only for the non-defaulted methods;
894 there are some exceptions for @Eq@ and (especially) @Ord@...
897 Sometimes we use a @_con2tag_<tycon>@ function, which returns a data
898 constructor's numeric (@Int#@) tag. These are generated by
899 @gen_tag_n_con_binds@, and the heuristic for deciding if one of
900 these is around is given by @hasCon2TagFun@.
902 The examples under the different sections below will make this
906 Much less often (really just for deriving @Ix@), we use a
907 @_tag2con_<tycon>@ function. See the examples.
910 We use the renamer!!! Reason: we're supposed to be
911 producing @LHsBinds Name@ for the methods, but that means
912 producing correctly-uniquified code on the fly. This is entirely
913 possible (the @TcM@ monad has a @UniqueSupply@), but it is painful.
914 So, instead, we produce @MonoBinds RdrName@ then heave 'em through
915 the renamer. What a great hack!
919 -- Generate the InstInfo for the required instance paired with the
920 -- *representation* tycon for that instance,
921 -- plus any auxiliary bindings required
923 -- Representation tycons differ from the tycon in the instance signature in
924 -- case of instances for indexed families.
926 genInst :: Instance -> TcM ((InstInfo, TyCon), LHsBinds RdrName)
928 = do { fix_env <- getFixityEnv
930 (tyvars,_,clas,[ty]) = instanceHead spec
931 clas_nm = className clas
932 (visible_tycon, tyArgs) = tcSplitTyConApp ty
934 -- In case of a family instance, we need to use the representation
935 -- tycon (after all it has the data constructors)
936 ; tycon <- if isOpenTyCon visible_tycon
937 then tcLookupFamInst visible_tycon tyArgs
938 else return visible_tycon
939 ; let (meth_binds, aux_binds) = genDerivBinds clas fix_env tycon
941 -- Bring the right type variables into
942 -- scope, and rename the method binds
943 -- It's a bit yukky that we return *renamed* InstInfo, but
944 -- *non-renamed* auxiliary bindings
945 ; (rn_meth_binds, _fvs) <- discardWarnings $
946 bindLocalNames (map Var.varName tyvars) $
947 rnMethodBinds clas_nm (\n -> []) [] meth_binds
949 -- Build the InstInfo
950 ; return ((InstInfo { iSpec = spec,
951 iBinds = VanillaInst rn_meth_binds [] }, tycon),
955 genDerivBinds clas fix_env tycon
956 | className clas `elem` typeableClassNames
957 = (gen_Typeable_binds tycon, emptyLHsBinds)
960 = case assocMaybe gen_list (getUnique clas) of
961 Just gen_fn -> gen_fn fix_env tycon
962 Nothing -> pprPanic "genDerivBinds: bad derived class" (ppr clas)
964 gen_list :: [(Unique, FixityEnv -> TyCon -> (LHsBinds RdrName, LHsBinds RdrName))]
965 gen_list = [(eqClassKey, no_aux_binds (ignore_fix_env gen_Eq_binds))
966 ,(ordClassKey, no_aux_binds (ignore_fix_env gen_Ord_binds))
967 ,(enumClassKey, no_aux_binds (ignore_fix_env gen_Enum_binds))
968 ,(boundedClassKey, no_aux_binds (ignore_fix_env gen_Bounded_binds))
969 ,(ixClassKey, no_aux_binds (ignore_fix_env gen_Ix_binds))
970 ,(typeableClassKey,no_aux_binds (ignore_fix_env gen_Typeable_binds))
971 ,(showClassKey, no_aux_binds gen_Show_binds)
972 ,(readClassKey, no_aux_binds gen_Read_binds)
973 ,(dataClassKey, gen_Data_binds)
976 -- no_aux_binds is used for generators that don't
977 -- need to produce any auxiliary bindings
978 no_aux_binds f fix_env tc = (f fix_env tc, emptyLHsBinds)
979 ignore_fix_env f fix_env tc = f tc
983 %************************************************************************
985 \subsection[TcDeriv-taggery-Names]{What con2tag/tag2con functions are available?}
987 %************************************************************************
992 con2tag_Foo :: Foo ... -> Int#
993 tag2con_Foo :: Int -> Foo ... -- easier if Int, not Int#
994 maxtag_Foo :: Int -- ditto (NB: not unlifted)
997 We have a @con2tag@ function for a tycon if:
1000 We're deriving @Eq@ and the tycon has nullary data constructors.
1003 Or: we're deriving @Ord@ (unless single-constructor), @Enum@, @Ix@
1004 (enum type only????)
1007 We have a @tag2con@ function for a tycon if:
1010 We're deriving @Enum@, or @Ix@ (enum type only???)
1013 If we have a @tag2con@ function, we also generate a @maxtag@ constant.
1016 genTaggeryBinds :: [(InstInfo, TyCon)] -> TcM (LHsBinds RdrName)
1017 genTaggeryBinds infos
1018 = do { names_so_far <- foldlM do_con2tag [] tycons_of_interest
1019 ; nm_alist_etc <- foldlM do_tag2con names_so_far tycons_of_interest
1020 ; return (listToBag (map gen_tag_n_con_monobind nm_alist_etc)) }
1022 all_CTs = [ (fst (simpleInstInfoClsTy info), tc)
1023 | (info, tc) <- infos]
1024 all_tycons = map snd all_CTs
1025 (tycons_of_interest, _) = removeDups compare all_tycons
1027 do_con2tag acc_Names tycon
1028 | isDataTyCon tycon &&
1029 ((we_are_deriving eqClassKey tycon
1030 && any isNullarySrcDataCon (tyConDataCons tycon))
1031 || (we_are_deriving ordClassKey tycon
1032 && not (isProductTyCon tycon))
1033 || (we_are_deriving enumClassKey tycon)
1034 || (we_are_deriving ixClassKey tycon))
1036 = returnM ((con2tag_RDR tycon, tycon, GenCon2Tag)
1041 do_tag2con acc_Names tycon
1042 | isDataTyCon tycon &&
1043 (we_are_deriving enumClassKey tycon ||
1044 we_are_deriving ixClassKey tycon
1045 && isEnumerationTyCon tycon)
1046 = returnM ( (tag2con_RDR tycon, tycon, GenTag2Con)
1047 : (maxtag_RDR tycon, tycon, GenMaxTag)
1052 we_are_deriving clas_key tycon
1053 = is_in_eqns clas_key tycon all_CTs
1055 is_in_eqns clas_key tycon [] = False
1056 is_in_eqns clas_key tycon ((c,t):cts)
1057 = (clas_key == classKey c && tycon == t)
1058 || is_in_eqns clas_key tycon cts
1062 derivingThingErr clas tys tycon ttys why
1063 = sep [hsep [ptext SLIT("Can't make a derived instance of"),
1065 nest 2 (parens why)]
1067 pred = mkClassPred clas (tys ++ [mkTyConApp tycon ttys])
1069 derivCtxt :: Name -> Maybe [LHsType Name] -> SDoc
1070 derivCtxt tycon mb_tys
1071 = ptext SLIT("When deriving instances for") <+> quotes typeInst
1073 typeInst = case mb_tys of
1074 Nothing -> ppr tycon
1075 Just tys -> ppr tycon <+>
1076 hsep (map (pprParendHsType . unLoc) tys)
1078 derivInstCtxt1 clas inst_tys
1079 = ptext SLIT("When deriving the instance for") <+>
1080 quotes (pprClassPred clas inst_tys)