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