552274392cc24595ebcabe304cbadaac1ee49178
[ghc-hetmet.git] / ghc / compiler / typecheck / TcDeriv.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[TcDeriv]{Deriving}
5
6 Handles @deriving@ clauses on @data@ declarations.
7
8 \begin{code}
9 module TcDeriv ( tcDeriving ) where
10
11 #include "HsVersions.h"
12
13 import HsSyn            ( HsBinds(..), MonoBinds(..), TyClDecl(..),
14                           collectMonoBinders )
15 import RdrHsSyn         ( RdrNameMonoBinds )
16 import RnHsSyn          ( RenamedHsBinds, RenamedMonoBinds, RenamedTyClDecl, RenamedHsPred )
17 import CmdLineOpts      ( DynFlag(..) )
18
19 import TcRnMonad
20 import TcEnv            ( tcExtendTempInstEnv, newDFunName, 
21                           InstInfo(..), pprInstInfo, InstBindings(..),
22                           pprInstInfoDetails, tcLookupTyCon, tcExtendTyVarEnv
23                         )
24 import TcGenDeriv       -- Deriv stuff
25 import InstEnv          ( simpleDFunClassTyCon )
26 import TcMonoType       ( tcHsPred )
27 import TcSimplify       ( tcSimplifyDeriv )
28
29 import RnBinds          ( rnMethodBinds, rnTopMonoBinds )
30 import RnEnv            ( bindLocalsFV, extendTyVarEnvFVRn )
31 import TcRnMonad        ( thenM, returnM, mapAndUnzipM )
32 import HscTypes         ( DFunId )
33
34 import BasicTypes       ( NewOrData(..) )
35 import Class            ( className, classArity, classKey, classTyVars, classSCTheta, Class )
36 import Subst            ( mkTyVarSubst, substTheta )
37 import ErrUtils         ( dumpIfSet_dyn )
38 import MkId             ( mkDictFunId )
39 import DataCon          ( dataConOrigArgTys, isNullaryDataCon, isExistentialDataCon )
40 import Maybes           ( maybeToBool, catMaybes )
41 import Name             ( Name, getSrcLoc, nameUnique )
42 import NameSet
43 import RdrName          ( RdrName )
44
45 import TyCon            ( tyConTyVars, tyConDataCons, tyConArity, 
46                           tyConTheta, maybeTyConSingleCon, isDataTyCon,
47                           isEnumerationTyCon, isRecursiveTyCon, TyCon
48                         )
49 import TcType           ( TcType, ThetaType, mkTyVarTy, mkTyVarTys, mkTyConApp, 
50                           getClassPredTys_maybe,
51                           isUnLiftedType, mkClassPred, tyVarsOfTypes, tcSplitFunTys, isTypeKind,
52                           tcEqTypes, tcSplitAppTys, mkAppTys, tcSplitDFunTy )
53 import Var              ( TyVar, tyVarKind, idType, varName )
54 import VarSet           ( mkVarSet, subVarSet )
55 import PrelNames
56 import Util             ( zipWithEqual, sortLt, notNull )
57 import ListSetOps       ( removeDups,  assoc )
58 import Outputable
59 \end{code}
60
61 %************************************************************************
62 %*                                                                      *
63 \subsection[TcDeriv-intro]{Introduction to how we do deriving}
64 %*                                                                      *
65 %************************************************************************
66
67 Consider
68
69         data T a b = C1 (Foo a) (Bar b)
70                    | C2 Int (T b a)
71                    | C3 (T a a)
72                    deriving (Eq)
73
74 [NOTE: See end of these comments for what to do with 
75         data (C a, D b) => T a b = ...
76 ]
77
78 We want to come up with an instance declaration of the form
79
80         instance (Ping a, Pong b, ...) => Eq (T a b) where
81                 x == y = ...
82
83 It is pretty easy, albeit tedious, to fill in the code "...".  The
84 trick is to figure out what the context for the instance decl is,
85 namely @Ping@, @Pong@ and friends.
86
87 Let's call the context reqd for the T instance of class C at types
88 (a,b, ...)  C (T a b).  Thus:
89
90         Eq (T a b) = (Ping a, Pong b, ...)
91
92 Now we can get a (recursive) equation from the @data@ decl:
93
94         Eq (T a b) = Eq (Foo a) u Eq (Bar b)    -- From C1
95                    u Eq (T b a) u Eq Int        -- From C2
96                    u Eq (T a a)                 -- From C3
97
98 Foo and Bar may have explicit instances for @Eq@, in which case we can
99 just substitute for them.  Alternatively, either or both may have
100 their @Eq@ instances given by @deriving@ clauses, in which case they
101 form part of the system of equations.
102
103 Now all we need do is simplify and solve the equations, iterating to
104 find the least fixpoint.  Notice that the order of the arguments can
105 switch around, as here in the recursive calls to T.
106
107 Let's suppose Eq (Foo a) = Eq a, and Eq (Bar b) = Ping b.
108
109 We start with:
110
111         Eq (T a b) = {}         -- The empty set
112
113 Next iteration:
114         Eq (T a b) = Eq (Foo a) u Eq (Bar b)    -- From C1
115                    u Eq (T b a) u Eq Int        -- From C2
116                    u Eq (T a a)                 -- From C3
117
118         After simplification:
119                    = Eq a u Ping b u {} u {} u {}
120                    = Eq a u Ping b
121
122 Next iteration:
123
124         Eq (T a b) = Eq (Foo a) u Eq (Bar b)    -- From C1
125                    u Eq (T b a) u Eq Int        -- From C2
126                    u Eq (T a a)                 -- From C3
127
128         After simplification:
129                    = Eq a u Ping b
130                    u (Eq b u Ping a)
131                    u (Eq a u Ping a)
132
133                    = Eq a u Ping b u Eq b u Ping a
134
135 The next iteration gives the same result, so this is the fixpoint.  We
136 need to make a canonical form of the RHS to ensure convergence.  We do
137 this by simplifying the RHS to a form in which
138
139         - the classes constrain only tyvars
140         - the list is sorted by tyvar (major key) and then class (minor key)
141         - no duplicates, of course
142
143 So, here are the synonyms for the ``equation'' structures:
144
145 \begin{code}
146 type DerivEqn = (Name, Class, TyCon, [TyVar], DerivRhs)
147                 -- The Name is the name for the DFun we'll build
148                 -- The tyvars bind all the variables in the RHS
149
150 pprDerivEqn (n,c,tc,tvs,rhs)
151   = parens (hsep [ppr n, ppr c, ppr tc, ppr tvs] <+> equals <+> ppr rhs)
152
153 type DerivRhs  = ThetaType
154 type DerivSoln = DerivRhs
155 \end{code}
156
157
158 [Data decl contexts] A note about contexts on data decls
159 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
160 Consider
161
162         data (RealFloat a) => Complex a = !a :+ !a deriving( Read )
163
164 We will need an instance decl like:
165
166         instance (Read a, RealFloat a) => Read (Complex a) where
167           ...
168
169 The RealFloat in the context is because the read method for Complex is bound
170 to construct a Complex, and doing that requires that the argument type is
171 in RealFloat. 
172
173 But this ain't true for Show, Eq, Ord, etc, since they don't construct
174 a Complex; they only take them apart.
175
176 Our approach: identify the offending classes, and add the data type
177 context to the instance decl.  The "offending classes" are
178
179         Read, Enum?
180
181 FURTHER NOTE ADDED March 2002.  In fact, Haskell98 now requires that
182 pattern matching against a constructor from a data type with a context
183 gives rise to the constraints for that context -- or at least the thinned
184 version.  So now all classes are "offending".
185
186
187
188 %************************************************************************
189 %*                                                                      *
190 \subsection[TcDeriv-driver]{Top-level function for \tr{derivings}}
191 %*                                                                      *
192 %************************************************************************
193
194 \begin{code}
195 tcDeriving  :: [RenamedTyClDecl]        -- All type constructors
196             -> TcM ([InstInfo],         -- The generated "instance decls".
197                     RenamedHsBinds,     -- Extra generated bindings
198                     FreeVars)           -- These are free in the generated bindings
199
200 tcDeriving tycl_decls
201   = recoverM (returnM ([], EmptyBinds, emptyFVs)) $
202     getDOpts                    `thenM` \ dflags ->
203
204         -- Fish the "deriving"-related information out of the TcEnv
205         -- and make the necessary "equations".
206     makeDerivEqns tycl_decls                            `thenM` \ (ordinary_eqns, newtype_inst_info) ->
207     tcExtendTempInstEnv (map iDFunId newtype_inst_info) $
208         -- Add the newtype-derived instances to the inst env
209         -- before tacking the "ordinary" ones
210
211     deriveOrdinaryStuff ordinary_eqns                   `thenM` \ (ordinary_inst_info, binds, fvs) ->
212     let
213         inst_info  = newtype_inst_info ++ ordinary_inst_info
214     in
215
216     ioToTcRn (dumpIfSet_dyn dflags Opt_D_dump_deriv "Derived instances" 
217              (ddump_deriving inst_info binds))          `thenM_`
218
219     returnM (inst_info, binds, fvs)
220
221   where
222     ddump_deriving :: [InstInfo] -> RenamedHsBinds -> SDoc
223     ddump_deriving inst_infos extra_binds
224       = vcat (map ppr_info inst_infos) $$ ppr extra_binds
225
226     ppr_info inst_info = pprInstInfo inst_info $$ 
227                          nest 4 (pprInstInfoDetails inst_info)
228         -- pprInstInfo doesn't print much: only the type
229
230 -----------------------------------------
231 deriveOrdinaryStuff []  -- Short cut
232   = returnM ([], EmptyBinds, emptyFVs)
233
234 deriveOrdinaryStuff eqns
235   =     -- Take the equation list and solve it, to deliver a list of
236         -- solutions, a.k.a. the contexts for the instance decls
237         -- required for the corresponding equations.
238     solveDerivEqns eqns                 `thenM` \ new_dfuns ->
239
240         -- Now augment the InstInfos, adding in the rather boring
241         -- actual-code-to-do-the-methods binds.  We may also need to
242         -- generate extra not-one-inst-decl-specific binds, notably
243         -- "con2tag" and/or "tag2con" functions.  We do these
244         -- separately.
245     gen_taggery_Names new_dfuns         `thenM` \ nm_alist_etc ->
246
247     let
248         extra_mbind_list = map gen_tag_n_con_monobind nm_alist_etc
249         extra_mbinds     = foldr AndMonoBinds EmptyMonoBinds extra_mbind_list
250         mbinders         = collectMonoBinders extra_mbinds
251     in
252     mappM gen_bind new_dfuns            `thenM` \ rdr_name_inst_infos ->
253         
254     traceTc (text "tcDeriv" <+> vcat (map ppr rdr_name_inst_infos))     `thenM_`
255     getModule                           `thenM` \ this_mod ->
256     initRn (InterfaceMode this_mod) (
257         -- Rename to get RenamedBinds.
258         -- The only tricky bit is that the extra_binds must scope 
259         -- over the method bindings for the instances.
260         bindLocalsFV (ptext (SLIT("deriving"))) mbinders        $ \ _ ->
261         rnTopMonoBinds extra_mbinds []                  `thenM` \ (rn_extra_binds, dus) ->
262         mapAndUnzipM rn_inst_info rdr_name_inst_infos   `thenM` \ (rn_inst_infos, fvs_s) ->
263         returnM ((rn_inst_infos, rn_extra_binds), 
264                   duUses dus `plusFV` plusFVs fvs_s)
265     )                           `thenM` \ ((rn_inst_infos, rn_extra_binds), fvs) ->
266    returnM (rn_inst_infos, rn_extra_binds, fvs)
267
268   where
269     rn_inst_info (dfun, binds) 
270         = extendTyVarEnvFVRn (map varName tyvars)       $
271                 -- Bring the right type variables into scope
272           rnMethodBinds (className cls) [] binds        `thenM` \ (rn_binds, fvs) ->
273           return (InstInfo { iDFunId = dfun, iBinds = VanillaInst rn_binds [] }, fvs)
274         where
275           (tyvars, _, cls, _) = tcSplitDFunTy (idType dfun)
276 \end{code}
277
278
279 %************************************************************************
280 %*                                                                      *
281 \subsection[TcDeriv-eqns]{Forming the equations}
282 %*                                                                      *
283 %************************************************************************
284
285 @makeDerivEqns@ fishes around to find the info about needed derived
286 instances.  Complicating factors:
287 \begin{itemize}
288 \item
289 We can only derive @Enum@ if the data type is an enumeration
290 type (all nullary data constructors).
291
292 \item
293 We can only derive @Ix@ if the data type is an enumeration {\em
294 or} has just one data constructor (e.g., tuples).
295 \end{itemize}
296
297 [See Appendix~E in the Haskell~1.2 report.] This code here deals w/
298 all those.
299
300 \begin{code}
301 makeDerivEqns :: [RenamedTyClDecl] 
302               -> TcM ([DerivEqn],       -- Ordinary derivings
303                       [InstInfo])       -- Special newtype derivings
304
305 makeDerivEqns tycl_decls
306   = mapAndUnzipM mk_eqn derive_these            `thenM` \ (maybe_ordinaries, maybe_newtypes) ->
307     returnM (catMaybes maybe_ordinaries, catMaybes maybe_newtypes)
308   where
309     ------------------------------------------------------------------
310     derive_these :: [(NewOrData, Name, RenamedHsPred)]
311         -- Find the (nd, TyCon, Pred) pairs that must be `derived'
312         -- NB: only source-language decls have deriving, no imported ones do
313     derive_these = [ (nd, tycon, pred) 
314                    | TyData {tcdND = nd, tcdName = tycon, tcdDerivs = Just preds} <- tycl_decls,
315                      pred <- preds ]
316
317     ------------------------------------------------------------------
318     mk_eqn :: (NewOrData, Name, RenamedHsPred) -> TcM (Maybe DerivEqn, Maybe InstInfo)
319         -- We swizzle the tyvars and datacons out of the tycon
320         -- to make the rest of the equation
321
322     mk_eqn (new_or_data, tycon_name, pred)
323       = tcLookupTyCon tycon_name                `thenM` \ tycon ->
324         addSrcLoc (getSrcLoc tycon)             $
325         addErrCtxt (derivCtxt Nothing tycon)    $
326         tcExtendTyVarEnv (tyConTyVars tycon)    $       -- Deriving preds may (now) mention
327                                                         -- the type variables for the type constructor
328         tcHsPred pred                           `thenM` \ pred' ->
329         case getClassPredTys_maybe pred' of
330            Nothing          -> bale_out (malformedPredErr tycon pred)
331            Just (clas, tys) -> doptM Opt_GlasgowExts                    `thenM` \ gla_exts ->
332                                mk_eqn_help gla_exts new_or_data tycon clas tys
333
334     ------------------------------------------------------------------
335     mk_eqn_help gla_exts DataType tycon clas tys
336       | Just err <- chk_out gla_exts clas tycon tys
337       = bale_out (derivingThingErr clas tys tycon tyvars err)
338       | otherwise 
339       = new_dfun_name clas tycon         `thenM` \ dfun_name ->
340         returnM (Just (dfun_name, clas, tycon, tyvars, constraints), Nothing)
341       where
342         tyvars    = tyConTyVars tycon
343         data_cons = tyConDataCons tycon
344         constraints = extra_constraints ++ ordinary_constraints
345                  -- "extra_constraints": see note [Data decl contexts] above
346         extra_constraints = tyConTheta tycon
347
348         ordinary_constraints
349           | clas `hasKey` typeableClassKey      -- For the Typeable class, the constraints
350                                                 -- don't involve the constructor ags, only 
351                                                 -- the tycon tyvars
352                                                 -- e.g.   data T a b = ...
353                                                 -- we want
354                                                 --      instance (Typeable a, Typable b)
355                                                 --               => Typeable (T a b) where
356           = [mkClassPred clas [mkTyVarTy tv] | tv <- tyvars]
357           | otherwise
358           = [ mkClassPred clas [arg_ty] 
359             | data_con <- tyConDataCons tycon,
360               arg_ty   <- dataConOrigArgTys data_con,
361                         -- Use the same type variables
362                         -- as the type constructor,
363                         -- hence no need to instantiate
364               not (isUnLiftedType arg_ty)       -- No constraints for unlifted types?
365             ]
366
367     mk_eqn_help gla_exts NewType tycon clas tys
368       | can_derive_via_isomorphism && (gla_exts || standard_class gla_exts clas)
369       =         -- Go ahead and use the isomorphism
370            traceTc (text "newtype deriving:" <+> ppr tycon <+> ppr rep_tys)     `thenM_`
371            new_dfun_name clas tycon             `thenM` \ dfun_name ->
372            returnM (Nothing, Just (InstInfo { iDFunId = mk_dfun dfun_name,
373                                               iBinds = NewTypeDerived rep_tys }))
374       | standard_class gla_exts clas
375       = mk_eqn_help gla_exts DataType tycon clas tys    -- Go via bale-out route
376
377       | otherwise                               -- Non-standard instance
378       = bale_out (if gla_exts then      
379                         cant_derive_err -- Too hard
380                   else
381                         non_std_err)    -- Just complain about being a non-std instance
382       where
383         -- Here is the plan for newtype derivings.  We see
384         --        newtype T a1...an = T (t ak...an) deriving (.., C s1 .. sm, ...)
385         -- where aj...an do not occur free in t, and the (C s1 ... sm) is a 
386         -- *partial applications* of class C with the last parameter missing
387         --
388         -- We generate the instances
389         --       instance C s1 .. sm (t ak...aj) => C s1 .. sm (T a1...aj)
390         -- where T a1...aj is the partial application of the LHS of the correct kind
391         --
392         -- Running example: newtype T s a = MkT (ST s a) deriving( Monad )
393         --      instance Monad (ST s) => Monad (T s) where 
394         --        fail = coerce ... (fail @ ST s)
395
396         clas_tyvars = classTyVars clas
397         kind = tyVarKind (last clas_tyvars)
398                 -- Kind of the thing we want to instance
399                 --   e.g. argument kind of Monad, *->*
400
401         (arg_kinds, _) = tcSplitFunTys kind
402         n_args_to_drop = length arg_kinds       
403                 -- Want to drop 1 arg from (T s a) and (ST s a)
404                 -- to get       instance Monad (ST s) => Monad (T s)
405
406         -- Note [newtype representation]
407         -- We must not use newTyConRep to get the representation 
408         -- type, because that looks through all intermediate newtypes
409         -- To get the RHS of *this* newtype, just look at the data
410         -- constructor.  For example
411         --      newtype B = MkB Int
412         --      newtype A = MkA B deriving( Num )
413         -- We want the Num instance of B, *not* the Num instance of Int,
414         -- when making the Num instance of A!
415         tyvars                = tyConTyVars tycon
416         rep_ty                = head (dataConOrigArgTys (head (tyConDataCons tycon)))
417         (rep_fn, rep_ty_args) = tcSplitAppTys rep_ty
418
419         n_tyvars_to_keep = tyConArity tycon  - n_args_to_drop
420         tyvars_to_drop   = drop n_tyvars_to_keep tyvars
421         tyvars_to_keep   = take n_tyvars_to_keep tyvars
422
423         n_args_to_keep = length rep_ty_args - n_args_to_drop
424         args_to_drop   = drop n_args_to_keep rep_ty_args
425         args_to_keep   = take n_args_to_keep rep_ty_args
426
427         rep_tys  = tys ++ [mkAppTys rep_fn args_to_keep]
428         rep_pred = mkClassPred clas rep_tys
429                 -- rep_pred is the representation dictionary, from where
430                 -- we are gong to get all the methods for the newtype dictionary
431
432         inst_tys = (tys ++ [mkTyConApp tycon (mkTyVarTys tyvars_to_keep)])
433                 -- The 'tys' here come from the partial application
434                 -- in the deriving clause. The last arg is the new
435                 -- instance type.
436
437                 -- We must pass the superclasses; the newtype might be an instance
438                 -- of them in a different way than the representation type
439                 -- E.g.         newtype Foo a = Foo a deriving( Show, Num, Eq )
440                 -- Then the Show instance is not done via isomprphism; it shows
441                 --      Foo 3 as "Foo 3"
442                 -- The Num instance is derived via isomorphism, but the Show superclass
443                 -- dictionary must the Show instance for Foo, *not* the Show dictionary
444                 -- gotten from the Num dictionary. So we must build a whole new dictionary
445                 -- not just use the Num one.  The instance we want is something like:
446                 --      instance (Num a, Show (Foo a), Eq (Foo a)) => Num (Foo a) where
447                 --              (+) = ((+)@a)
448                 --              ...etc...
449                 -- There's no 'corece' needed because after the type checker newtypes
450                 -- are transparent.
451
452         sc_theta = substTheta (mkTyVarSubst clas_tyvars inst_tys)
453                               (classSCTheta clas)
454
455                 -- If there are no tyvars, there's no need
456                 -- to abstract over the dictionaries we need
457         dict_args | null tyvars = []
458                   | otherwise   = rep_pred : sc_theta
459
460                 -- Finally! Here's where we build the dictionary Id
461         mk_dfun dfun_name = mkDictFunId dfun_name tyvars dict_args clas inst_tys
462
463         -------------------------------------------------------------------
464         --  Figuring out whether we can only do this newtype-deriving thing
465
466         right_arity = length tys + 1 == classArity clas
467
468         can_derive_via_isomorphism
469            =  not (clas `hasKey` readClassKey)  -- Never derive Read,Show,Typeable this way 
470            && not (clas `hasKey` showClassKey)
471            && not (clas `hasKey` typeableClassKey)
472            && right_arity                       -- Well kinded;
473                                                 -- eg not: newtype T ... deriving( ST )
474                                                 --      because ST needs *2* type params
475            && n_tyvars_to_keep >= 0             -- Type constructor has right kind:
476                                                 -- eg not: newtype T = T Int deriving( Monad )
477            && n_args_to_keep   >= 0             -- Rep type has right kind: 
478                                                 -- eg not: newtype T a = T Int deriving( Monad )
479            && eta_ok                            -- Eta reduction works
480            && not (isRecursiveTyCon tycon)      -- Does not work for recursive tycons:
481                                                 --      newtype A = MkA [A]
482                                                 -- Don't want
483                                                 --      instance Eq [A] => Eq A !!
484
485         -- Check that eta reduction is OK
486         --      (a) the dropped-off args are identical
487         --      (b) the remaining type args mention 
488         --          only the remaining type variables
489         eta_ok = (args_to_drop `tcEqTypes` mkTyVarTys tyvars_to_drop)
490               && (tyVarsOfTypes args_to_keep `subVarSet` mkVarSet tyvars_to_keep) 
491
492         cant_derive_err = derivingThingErr clas tys tycon tyvars_to_keep
493                                 (vcat [ptext SLIT("even with cunning newtype deriving:"),
494                                         if isRecursiveTyCon tycon then
495                                           ptext SLIT("the newtype is recursive")
496                                         else empty,
497                                         if not right_arity then 
498                                           quotes (ppr (mkClassPred clas tys)) <+> ptext SLIT("does not have arity 1")
499                                         else empty,
500                                         if not (n_tyvars_to_keep >= 0) then 
501                                           ptext SLIT("the type constructor has wrong kind")
502                                         else if not (n_args_to_keep >= 0) then
503                                           ptext SLIT("the representation type has wrong kind")
504                                         else if not eta_ok then 
505                                           ptext SLIT("the eta-reduction property does not hold")
506                                         else empty
507                                       ])
508
509         non_std_err = derivingThingErr clas tys tycon tyvars_to_keep
510                                 (vcat [non_std_why clas,
511                                        ptext SLIT("Try -fglasgow-exts for GHC's newtype-deriving extension")])
512
513     bale_out err = addErrTc err `thenM_` returnM (Nothing, Nothing) 
514
515     standard_class gla_exts clas =  key `elem` derivableClassKeys
516                                  || (gla_exts && (key == typeableClassKey || key == traverseClassKey))
517         where
518           key = classKey clas
519     ------------------------------------------------------------------
520     chk_out :: Bool -> Class -> TyCon -> [TcType] -> Maybe SDoc
521     chk_out gla_exts clas tycon tys
522         | notNull tys                                                   = Just ty_args_why
523         | not (standard_class gla_exts clas)                            = Just (non_std_why clas)
524         | clas `hasKey` enumClassKey    && not is_enumeration           = Just nullary_why
525         | clas `hasKey` boundedClassKey && not is_enumeration_or_single = Just single_nullary_why
526         | clas `hasKey` ixClassKey      && not is_enumeration_or_single = Just single_nullary_why
527         | clas `hasKey` typeableClassKey && not all_type_kind           = Just not_type_kind_why
528         | null data_cons                                                = Just no_cons_why
529         | any isExistentialDataCon data_cons                            = Just existential_why     
530         | otherwise                                                     = Nothing
531         where
532             data_cons = tyConDataCons tycon
533             is_enumeration = isEnumerationTyCon tycon
534             is_single_con  = maybeToBool (maybeTyConSingleCon tycon)
535             is_enumeration_or_single = is_enumeration || is_single_con
536             all_type_kind = all (isTypeKind . tyVarKind) (tyConTyVars tycon)
537
538             single_nullary_why = ptext SLIT("one constructor data type or type with all nullary constructors expected")
539             nullary_why        = quotes (ppr tycon) <+> ptext SLIT("has non-nullary constructors")
540             no_cons_why        = quotes (ppr tycon) <+> ptext SLIT("has no data constructors")
541             ty_args_why        = quotes (ppr pred) <+> ptext SLIT("is not a class")
542             existential_why    = quotes (ppr tycon) <+> ptext SLIT("has existentially-quantified constructor(s)")
543             not_type_kind_why  = quotes (ppr tycon) <+> ptext SLIT("is parameterised over arguments of kind other than `*'")
544
545             pred = mkClassPred clas tys
546
547 non_std_why clas = quotes (ppr clas) <+> ptext SLIT("is not a derivable class")
548
549 new_dfun_name clas tycon        -- Just a simple wrapper
550   = newDFunName clas [mkTyConApp tycon []] (getSrcLoc tycon)
551         -- The type passed to newDFunName is only used to generate
552         -- a suitable string; hence the empty type arg list
553 \end{code}
554
555 %************************************************************************
556 %*                                                                      *
557 \subsection[TcDeriv-fixpoint]{Finding the fixed point of \tr{deriving} equations}
558 %*                                                                      *
559 %************************************************************************
560
561 A ``solution'' (to one of the equations) is a list of (k,TyVarTy tv)
562 terms, which is the final correct RHS for the corresponding original
563 equation.
564 \begin{itemize}
565 \item
566 Each (k,TyVarTy tv) in a solution constrains only a type
567 variable, tv.
568
569 \item
570 The (k,TyVarTy tv) pairs in a solution are canonically
571 ordered by sorting on type varible, tv, (major key) and then class, k,
572 (minor key)
573 \end{itemize}
574
575 \begin{code}
576 solveDerivEqns :: [DerivEqn]
577                -> TcM [DFunId]  -- Solns in same order as eqns.
578                                 -- This bunch is Absolutely minimal...
579
580 solveDerivEqns orig_eqns
581   = iterateDeriv 1 initial_solutions
582   where
583         -- The initial solutions for the equations claim that each
584         -- instance has an empty context; this solution is certainly
585         -- in canonical form.
586     initial_solutions :: [DerivSoln]
587     initial_solutions = [ [] | _ <- orig_eqns ]
588
589     ------------------------------------------------------------------
590         -- iterateDeriv calculates the next batch of solutions,
591         -- compares it with the current one; finishes if they are the
592         -- same, otherwise recurses with the new solutions.
593         -- It fails if any iteration fails
594     iterateDeriv :: Int -> [DerivSoln] ->TcM [DFunId]
595     iterateDeriv n current_solns
596       | n > 20  -- Looks as if we are in an infinite loop
597                 -- This can happen if we have -fallow-undecidable-instances
598                 -- (See TcSimplify.tcSimplifyDeriv.)
599       = pprPanic "solveDerivEqns: probable loop" 
600                  (vcat (map pprDerivEqn orig_eqns) $$ ppr current_solns)
601       | otherwise
602       = let 
603             dfuns = zipWithEqual "add_solns" mk_deriv_dfun orig_eqns current_solns
604         in
605         checkNoErrs (
606                   -- Extend the inst info from the explicit instance decls
607                   -- with the current set of solutions, and simplify each RHS
608             tcExtendTempInstEnv dfuns $
609             mappM gen_soln orig_eqns
610         )                               `thenM` \ new_solns ->
611         if (current_solns == new_solns) then
612             returnM dfuns
613         else
614             iterateDeriv (n+1) new_solns
615
616     ------------------------------------------------------------------
617
618     gen_soln (_, clas, tc,tyvars,deriv_rhs)
619       = addSrcLoc (getSrcLoc tc)                $
620         addErrCtxt (derivCtxt (Just clas) tc)   $
621         tcSimplifyDeriv tyvars deriv_rhs        `thenM` \ theta ->
622         returnM (sortLt (<) theta)      -- Canonicalise before returning the soluction
623
624 mk_deriv_dfun (dfun_name, clas, tycon, tyvars, _) theta
625   = mkDictFunId dfun_name tyvars theta
626                 clas [mkTyConApp tycon (mkTyVarTys tyvars)] 
627 \end{code}
628
629 %************************************************************************
630 %*                                                                      *
631 \subsection[TcDeriv-normal-binds]{Bindings for the various classes}
632 %*                                                                      *
633 %************************************************************************
634
635 After all the trouble to figure out the required context for the
636 derived instance declarations, all that's left is to chug along to
637 produce them.  They will then be shoved into @tcInstDecls2@, which
638 will do all its usual business.
639
640 There are lots of possibilities for code to generate.  Here are
641 various general remarks.
642
643 PRINCIPLES:
644 \begin{itemize}
645 \item
646 We want derived instances of @Eq@ and @Ord@ (both v common) to be
647 ``you-couldn't-do-better-by-hand'' efficient.
648
649 \item
650 Deriving @Show@---also pretty common--- should also be reasonable good code.
651
652 \item
653 Deriving for the other classes isn't that common or that big a deal.
654 \end{itemize}
655
656 PRAGMATICS:
657
658 \begin{itemize}
659 \item
660 Deriving @Ord@ is done mostly with the 1.3 @compare@ method.
661
662 \item
663 Deriving @Eq@ also uses @compare@, if we're deriving @Ord@, too.
664
665 \item
666 We {\em normally} generate code only for the non-defaulted methods;
667 there are some exceptions for @Eq@ and (especially) @Ord@...
668
669 \item
670 Sometimes we use a @_con2tag_<tycon>@ function, which returns a data
671 constructor's numeric (@Int#@) tag.  These are generated by
672 @gen_tag_n_con_binds@, and the heuristic for deciding if one of
673 these is around is given by @hasCon2TagFun@.
674
675 The examples under the different sections below will make this
676 clearer.
677
678 \item
679 Much less often (really just for deriving @Ix@), we use a
680 @_tag2con_<tycon>@ function.  See the examples.
681
682 \item
683 We use the renamer!!!  Reason: we're supposed to be
684 producing @RenamedMonoBinds@ for the methods, but that means
685 producing correctly-uniquified code on the fly.  This is entirely
686 possible (the @TcM@ monad has a @UniqueSupply@), but it is painful.
687 So, instead, we produce @RdrNameMonoBinds@ then heave 'em through
688 the renamer.  What a great hack!
689 \end{itemize}
690
691 \begin{code}
692 -- Generate the method bindings for the required instance
693 -- (paired with DFunId, as we need that when renaming
694 --  the method binds)
695 gen_bind :: DFunId -> TcM (DFunId, RdrNameMonoBinds)
696 gen_bind dfun
697   = getFixityEnv                `thenM` \ fix_env -> 
698     let
699         (clas, tycon) = simpleDFunClassTyCon dfun
700         gen_binds_fn  = assoc "gen_bind:bad derived class"
701                               gen_list (getUnique clas)
702     
703         gen_list = [(eqClassKey,      gen_Eq_binds)
704                    ,(ordClassKey,     gen_Ord_binds)
705                    ,(enumClassKey,    gen_Enum_binds)
706                    ,(boundedClassKey, gen_Bounded_binds)
707                    ,(ixClassKey,      gen_Ix_binds)
708                    ,(showClassKey,    gen_Show_binds fix_env)
709                    ,(readClassKey,    gen_Read_binds fix_env)
710                    ,(typeableClassKey,gen_Typeable_binds)
711                    ]
712     in
713     returnM (dfun, gen_binds_fn tycon)
714 \end{code}
715
716
717 %************************************************************************
718 %*                                                                      *
719 \subsection[TcDeriv-taggery-Names]{What con2tag/tag2con functions are available?}
720 %*                                                                      *
721 %************************************************************************
722
723
724 data Foo ... = ...
725
726 con2tag_Foo :: Foo ... -> Int#
727 tag2con_Foo :: Int -> Foo ...   -- easier if Int, not Int#
728 maxtag_Foo  :: Int              -- ditto (NB: not unlifted)
729
730
731 We have a @con2tag@ function for a tycon if:
732 \begin{itemize}
733 \item
734 We're deriving @Eq@ and the tycon has nullary data constructors.
735
736 \item
737 Or: we're deriving @Ord@ (unless single-constructor), @Enum@, @Ix@
738 (enum type only????)
739 \end{itemize}
740
741 We have a @tag2con@ function for a tycon if:
742 \begin{itemize}
743 \item
744 We're deriving @Enum@, or @Ix@ (enum type only???)
745 \end{itemize}
746
747 If we have a @tag2con@ function, we also generate a @maxtag@ constant.
748
749 \begin{code}
750 gen_taggery_Names :: [DFunId]
751                   -> TcM [(RdrName,     -- for an assoc list
752                            TyCon,       -- related tycon
753                            TagThingWanted)]
754
755 gen_taggery_Names dfuns
756   = foldlM do_con2tag []           tycons_of_interest `thenM` \ names_so_far ->
757     foldlM do_tag2con names_so_far tycons_of_interest
758   where
759     all_CTs = map simpleDFunClassTyCon dfuns
760     all_tycons              = map snd all_CTs
761     (tycons_of_interest, _) = removeDups compare all_tycons
762     
763     do_con2tag acc_Names tycon
764       | isDataTyCon tycon &&
765         ((we_are_deriving eqClassKey tycon
766             && any isNullaryDataCon (tyConDataCons tycon))
767          || (we_are_deriving ordClassKey  tycon
768             && not (maybeToBool (maybeTyConSingleCon tycon)))
769          || (we_are_deriving enumClassKey tycon)
770          || (we_are_deriving ixClassKey   tycon))
771         
772       = returnM ((con2tag_RDR tycon, tycon, GenCon2Tag)
773                    : acc_Names)
774       | otherwise
775       = returnM acc_Names
776
777     do_tag2con acc_Names tycon
778       | isDataTyCon tycon &&
779          (we_are_deriving enumClassKey tycon ||
780           we_are_deriving ixClassKey   tycon
781           && isEnumerationTyCon tycon)
782       = returnM ( (tag2con_RDR tycon, tycon, GenTag2Con)
783                  : (maxtag_RDR  tycon, tycon, GenMaxTag)
784                  : acc_Names)
785       | otherwise
786       = returnM acc_Names
787
788     we_are_deriving clas_key tycon
789       = is_in_eqns clas_key tycon all_CTs
790       where
791         is_in_eqns clas_key tycon [] = False
792         is_in_eqns clas_key tycon ((c,t):cts)
793           =  (clas_key == classKey c && tycon == t)
794           || is_in_eqns clas_key tycon cts
795 \end{code}
796
797 \begin{code}
798 derivingThingErr clas tys tycon tyvars why
799   = sep [hsep [ptext SLIT("Can't make a derived instance of"), quotes (ppr pred)],
800          parens why]
801   where
802     pred = mkClassPred clas (tys ++ [mkTyConApp tycon (mkTyVarTys tyvars)])
803
804 malformedPredErr tycon pred = ptext SLIT("Illegal deriving item") <+> ppr pred
805
806 derivCtxt :: Maybe Class -> TyCon -> SDoc
807 derivCtxt maybe_cls tycon
808   = ptext SLIT("When deriving") <+> cls <+> ptext SLIT("for type") <+> quotes (ppr tycon)
809   where
810     cls = case maybe_cls of
811             Nothing -> ptext SLIT("instances")
812             Just c  -> ptext SLIT("the") <+> quotes (ppr c) <+> ptext SLIT("instance")
813 \end{code}
814