[project @ 2003-04-08 11:27:30 by simonpj]
[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 )
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, 
51                           tcEqTypes, tcSplitAppTys, mkAppTys )
52 import Var              ( TyVar, tyVarKind )
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` \ method_binds_s ->
252         
253     traceTc (text "tcDeriv" <+> ppr method_binds_s)     `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_meths method_binds_s            `thenM` \ (rn_method_binds_s, fvs_s) ->
262         returnM ((rn_method_binds_s, rn_extra_binds), 
263                   duUses dus `plusFV` plusFVs fvs_s)
264     )                           `thenM` \ ((rn_method_binds_s, rn_extra_binds), fvs) ->
265     let
266         new_inst_infos = zipWith gen_inst_info new_dfuns rn_method_binds_s
267     in
268     returnM (new_inst_infos, rn_extra_binds, fvs)
269
270   where
271         -- Make a Real dfun instead of the dummy one we have so far
272     gen_inst_info :: DFunId -> RenamedMonoBinds -> InstInfo
273     gen_inst_info dfun binds
274       = InstInfo { iDFunId = dfun, iBinds = VanillaInst binds [] }
275
276     rn_meths (cls, meths) = rnMethodBinds cls [] meths
277 \end{code}
278
279
280 %************************************************************************
281 %*                                                                      *
282 \subsection[TcDeriv-eqns]{Forming the equations}
283 %*                                                                      *
284 %************************************************************************
285
286 @makeDerivEqns@ fishes around to find the info about needed derived
287 instances.  Complicating factors:
288 \begin{itemize}
289 \item
290 We can only derive @Enum@ if the data type is an enumeration
291 type (all nullary data constructors).
292
293 \item
294 We can only derive @Ix@ if the data type is an enumeration {\em
295 or} has just one data constructor (e.g., tuples).
296 \end{itemize}
297
298 [See Appendix~E in the Haskell~1.2 report.] This code here deals w/
299 all those.
300
301 \begin{code}
302 makeDerivEqns :: [RenamedTyClDecl] 
303               -> TcM ([DerivEqn],       -- Ordinary derivings
304                       [InstInfo])       -- Special newtype derivings
305
306 makeDerivEqns tycl_decls
307   = mapAndUnzipM mk_eqn derive_these            `thenM` \ (maybe_ordinaries, maybe_newtypes) ->
308     returnM (catMaybes maybe_ordinaries, catMaybes maybe_newtypes)
309   where
310     ------------------------------------------------------------------
311     derive_these :: [(NewOrData, Name, RenamedHsPred)]
312         -- Find the (nd, TyCon, Pred) pairs that must be `derived'
313         -- NB: only source-language decls have deriving, no imported ones do
314     derive_these = [ (nd, tycon, pred) 
315                    | TyData {tcdND = nd, tcdName = tycon, tcdDerivs = Just preds} <- tycl_decls,
316                      pred <- preds ]
317
318     ------------------------------------------------------------------
319     mk_eqn :: (NewOrData, Name, RenamedHsPred) -> TcM (Maybe DerivEqn, Maybe InstInfo)
320         -- We swizzle the tyvars and datacons out of the tycon
321         -- to make the rest of the equation
322
323     mk_eqn (new_or_data, tycon_name, pred)
324       = tcLookupTyCon tycon_name                `thenM` \ tycon ->
325         addSrcLoc (getSrcLoc tycon)             $
326         addErrCtxt (derivCtxt Nothing tycon)    $
327         tcExtendTyVarEnv (tyConTyVars tycon)    $       -- Deriving preds may (now) mention
328                                                         -- the type variables for the type constructor
329         tcHsPred pred                           `thenM` \ pred' ->
330         case getClassPredTys_maybe pred' of
331            Nothing          -> bale_out (malformedPredErr tycon pred)
332            Just (clas, tys) -> mk_eqn_help new_or_data tycon clas tys
333
334     ------------------------------------------------------------------
335     mk_eqn_help DataType tycon clas tys
336       | Just err <- chk_out 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 ++ 
345                       [ mkClassPred clas [arg_ty] 
346                       | data_con <- tyConDataCons tycon,
347                         arg_ty   <- dataConOrigArgTys data_con,
348                                 -- Use the same type variables
349                                 -- as the type constructor,
350                                 -- hence no need to instantiate
351                         not (isUnLiftedType arg_ty)     -- No constraints for unlifted types?
352                       ]
353
354          -- "extra_constraints": see note [Data decl contexts] above
355         extra_constraints = tyConTheta tycon
356
357     mk_eqn_help NewType tycon clas tys
358       = doptM Opt_GlasgowExts                   `thenM` \ gla_exts ->
359         if can_derive_via_isomorphism && (gla_exts || standard_instance) then
360                 -- Go ahead and use the isomorphism
361            traceTc (text "newtype deriving:" <+> ppr tycon <+> ppr rep_tys)     `thenM_`
362            new_dfun_name clas tycon             `thenM` \ dfun_name ->
363            returnM (Nothing, Just (InstInfo { iDFunId = mk_dfun dfun_name,
364                                               iBinds = NewTypeDerived rep_tys }))
365         else
366         if standard_instance then
367                 mk_eqn_help DataType tycon clas []      -- Go via bale-out route
368         else
369         -- Non-standard instance
370         if gla_exts then
371                 -- Too hard
372                 bale_out cant_derive_err
373         else
374                 -- Just complain about being a non-std instance
375                 bale_out non_std_err
376       where
377         -- Here is the plan for newtype derivings.  We see
378         --        newtype T a1...an = T (t ak...an) deriving (.., C s1 .. sm, ...)
379         -- where aj...an do not occur free in t, and the (C s1 ... sm) is a 
380         -- *partial applications* of class C with the last parameter missing
381         --
382         -- We generate the instances
383         --       instance C s1 .. sm (t ak...aj) => C s1 .. sm (T a1...aj)
384         -- where T a1...aj is the partial application of the LHS of the correct kind
385         --
386         -- Running example: newtype T s a = MkT (ST s a) deriving( Monad )
387         --      instance Monad (ST s) => Monad (T s) where 
388         --        fail = coerce ... (fail @ ST s)
389
390         clas_tyvars = classTyVars clas
391         kind = tyVarKind (last clas_tyvars)
392                 -- Kind of the thing we want to instance
393                 --   e.g. argument kind of Monad, *->*
394
395         (arg_kinds, _) = tcSplitFunTys kind
396         n_args_to_drop = length arg_kinds       
397                 -- Want to drop 1 arg from (T s a) and (ST s a)
398                 -- to get       instance Monad (ST s) => Monad (T s)
399
400         -- Note [newtype representation]
401         -- We must not use newTyConRep to get the representation 
402         -- type, because that looks through all intermediate newtypes
403         -- To get the RHS of *this* newtype, just look at the data
404         -- constructor.  For example
405         --      newtype B = MkB Int
406         --      newtype A = MkA B deriving( Num )
407         -- We want the Num instance of B, *not* the Num instance of Int,
408         -- when making the Num instance of A!
409         tyvars                = tyConTyVars tycon
410         rep_ty                = head (dataConOrigArgTys (head (tyConDataCons tycon)))
411         (rep_fn, rep_ty_args) = tcSplitAppTys rep_ty
412
413         n_tyvars_to_keep = tyConArity tycon  - n_args_to_drop
414         tyvars_to_drop   = drop n_tyvars_to_keep tyvars
415         tyvars_to_keep   = take n_tyvars_to_keep tyvars
416
417         n_args_to_keep = length rep_ty_args - n_args_to_drop
418         args_to_drop   = drop n_args_to_keep rep_ty_args
419         args_to_keep   = take n_args_to_keep rep_ty_args
420
421         rep_tys  = tys ++ [mkAppTys rep_fn args_to_keep]
422         rep_pred = mkClassPred clas rep_tys
423                 -- rep_pred is the representation dictionary, from where
424                 -- we are gong to get all the methods for the newtype dictionary
425
426         inst_tys = (tys ++ [mkTyConApp tycon (mkTyVarTys tyvars_to_keep)])
427                 -- The 'tys' here come from the partial application
428                 -- in the deriving clause. The last arg is the new
429                 -- instance type.
430
431                 -- We must pass the superclasses; the newtype might be an instance
432                 -- of them in a different way than the representation type
433                 -- E.g.         newtype Foo a = Foo a deriving( Show, Num, Eq )
434                 -- Then the Show instance is not done via isomprphism; it shows
435                 --      Foo 3 as "Foo 3"
436                 -- The Num instance is derived via isomorphism, but the Show superclass
437                 -- dictionary must the Show instance for Foo, *not* the Show dictionary
438                 -- gotten from the Num dictionary. So we must build a whole new dictionary
439                 -- not just use the Num one.  The instance we want is something like:
440                 --      instance (Num a, Show (Foo a), Eq (Foo a)) => Num (Foo a) where
441                 --              (+) = ((+)@a)
442                 --              ...etc...
443                 -- There's no 'corece' needed because after the type checker newtypes
444                 -- are transparent.
445
446         sc_theta = substTheta (mkTyVarSubst clas_tyvars inst_tys)
447                               (classSCTheta clas)
448
449                 -- If there are no tyvars, there's no need
450                 -- to abstract over the dictionaries we need
451         dict_args | null tyvars = []
452                   | otherwise   = rep_pred : sc_theta
453
454                 -- Finally! Here's where we build the dictionary Id
455         mk_dfun dfun_name = mkDictFunId dfun_name tyvars dict_args clas inst_tys
456
457         -------------------------------------------------------------------
458         --  Figuring out whether we can only do this newtype-deriving thing
459
460         standard_instance = null tys && classKey clas `elem` derivableClassKeys
461         right_arity = length tys + 1 == classArity clas
462
463         can_derive_via_isomorphism
464            =  not (clas `hasKey` readClassKey)  -- Never derive Read,Show this way
465            && not (clas `hasKey` showClassKey)
466            && right_arity                       -- Well kinded;
467                                                 -- eg not: newtype T ... deriving( ST )
468                                                 --      because ST needs *2* type params
469            && n_tyvars_to_keep >= 0             -- Well kinded; 
470                                                 -- eg not: newtype T = T Int deriving( Monad )
471            && n_args_to_keep   >= 0             -- Well kinded: 
472                                                 -- eg not: newtype T a = T Int deriving( Monad )
473            && eta_ok                            -- Eta reduction works
474            && not (isRecursiveTyCon tycon)      -- Does not work for recursive tycons:
475                                                 --      newtype A = MkA [A]
476                                                 -- Don't want
477                                                 --      instance Eq [A] => Eq A !!
478
479         -- Check that eta reduction is OK
480         --      (a) the dropped-off args are identical
481         --      (b) the remaining type args mention 
482         --          only the remaining type variables
483         eta_ok = (args_to_drop `tcEqTypes` mkTyVarTys tyvars_to_drop)
484               && (tyVarsOfTypes args_to_keep `subVarSet` mkVarSet tyvars_to_keep) 
485
486         cant_derive_err = derivingThingErr clas tys tycon tyvars_to_keep
487                                 (vcat [ptext SLIT("even with cunning newtype deriving:"),
488                                         if right_arity then empty else
489                                         quotes (ppr (mkClassPred clas tys)) <+> ptext SLIT("does not have arity 1"),
490                                         if n_tyvars_to_keep >= 0 && n_args_to_keep >= 0 then empty else
491                                           ptext SLIT("the type constructor has wrong kind"),
492                                         if n_args_to_keep >= 0 then empty else
493                                           ptext SLIT("representation type has wrong kind"),
494                                         if eta_ok then empty else 
495                                           ptext SLIT("the eta-reduction property does not hold"),
496                                         if not (isRecursiveTyCon tycon) then empty else
497                                           ptext SLIT("the newtype is recursive")
498                                       ])
499
500         non_std_err = derivingThingErr clas tys tycon tyvars_to_keep
501                                 (vcat [non_std_why clas,
502                                        ptext SLIT("Try -fglasgow-exts for GHC's newtype-deriving extension")])
503
504     bale_out err = addErrTc err `thenM_` returnM (Nothing, Nothing) 
505
506     ------------------------------------------------------------------
507     chk_out :: Class -> TyCon -> [TcType] -> Maybe SDoc
508     chk_out clas tycon tys
509         | notNull tys                                                   = Just ty_args_why
510         | not (getUnique clas `elem` derivableClassKeys)                = Just (non_std_why clas)
511         | clas `hasKey` enumClassKey    && not is_enumeration           = Just nullary_why
512         | clas `hasKey` boundedClassKey && not is_enumeration_or_single = Just single_nullary_why
513         | clas `hasKey` ixClassKey      && not is_enumeration_or_single = Just single_nullary_why
514         | null data_cons                                                = Just no_cons_why
515         | any isExistentialDataCon data_cons                            = Just existential_why     
516         | otherwise                                                     = Nothing
517         where
518             data_cons = tyConDataCons tycon
519             is_enumeration = isEnumerationTyCon tycon
520             is_single_con  = maybeToBool (maybeTyConSingleCon tycon)
521             is_enumeration_or_single = is_enumeration || is_single_con
522
523             single_nullary_why = ptext SLIT("one constructor data type or type with all nullary constructors expected")
524             nullary_why        = quotes (ppr tycon) <+> ptext SLIT("has non-nullary constructors")
525             no_cons_why        = quotes (ppr tycon) <+> ptext SLIT("has no data constructors")
526             ty_args_why        = quotes (ppr pred) <+> ptext SLIT("is not a class")
527             existential_why    = quotes (ppr tycon) <+> ptext SLIT("has existentially-quantified constructor(s)")
528
529             pred = mkClassPred clas tys
530
531 non_std_why clas = quotes (ppr clas) <+> ptext SLIT("is not a derivable class")
532
533 new_dfun_name clas tycon        -- Just a simple wrapper
534   = newDFunName clas [mkTyConApp tycon []] (getSrcLoc tycon)
535         -- The type passed to newDFunName is only used to generate
536         -- a suitable string; hence the empty type arg list
537 \end{code}
538
539 %************************************************************************
540 %*                                                                      *
541 \subsection[TcDeriv-fixpoint]{Finding the fixed point of \tr{deriving} equations}
542 %*                                                                      *
543 %************************************************************************
544
545 A ``solution'' (to one of the equations) is a list of (k,TyVarTy tv)
546 terms, which is the final correct RHS for the corresponding original
547 equation.
548 \begin{itemize}
549 \item
550 Each (k,TyVarTy tv) in a solution constrains only a type
551 variable, tv.
552
553 \item
554 The (k,TyVarTy tv) pairs in a solution are canonically
555 ordered by sorting on type varible, tv, (major key) and then class, k,
556 (minor key)
557 \end{itemize}
558
559 \begin{code}
560 solveDerivEqns :: [DerivEqn]
561                -> TcM [DFunId]  -- Solns in same order as eqns.
562                                 -- This bunch is Absolutely minimal...
563
564 solveDerivEqns orig_eqns
565   = iterateDeriv 1 initial_solutions
566   where
567         -- The initial solutions for the equations claim that each
568         -- instance has an empty context; this solution is certainly
569         -- in canonical form.
570     initial_solutions :: [DerivSoln]
571     initial_solutions = [ [] | _ <- orig_eqns ]
572
573     ------------------------------------------------------------------
574         -- iterateDeriv calculates the next batch of solutions,
575         -- compares it with the current one; finishes if they are the
576         -- same, otherwise recurses with the new solutions.
577         -- It fails if any iteration fails
578     iterateDeriv :: Int -> [DerivSoln] ->TcM [DFunId]
579     iterateDeriv n current_solns
580       | n > 20  -- Looks as if we are in an infinite loop
581                 -- This can happen if we have -fallow-undecidable-instances
582                 -- (See TcSimplify.tcSimplifyDeriv.)
583       = pprPanic "solveDerivEqns: probable loop" 
584                  (vcat (map pprDerivEqn orig_eqns) $$ ppr current_solns)
585       | otherwise
586       = let 
587             dfuns = zipWithEqual "add_solns" mk_deriv_dfun orig_eqns current_solns
588         in
589         checkNoErrs (
590                   -- Extend the inst info from the explicit instance decls
591                   -- with the current set of solutions, and simplify each RHS
592             tcExtendTempInstEnv dfuns $
593             mappM gen_soln orig_eqns
594         )                               `thenM` \ new_solns ->
595         if (current_solns == new_solns) then
596             returnM dfuns
597         else
598             iterateDeriv (n+1) new_solns
599
600     ------------------------------------------------------------------
601
602     gen_soln (_, clas, tc,tyvars,deriv_rhs)
603       = addSrcLoc (getSrcLoc tc)                $
604         addErrCtxt (derivCtxt (Just clas) tc)   $
605         tcSimplifyDeriv tyvars deriv_rhs        `thenM` \ theta ->
606         returnM (sortLt (<) theta)      -- Canonicalise before returning the soluction
607
608 mk_deriv_dfun (dfun_name, clas, tycon, tyvars, _) theta
609   = mkDictFunId dfun_name tyvars theta
610                 clas [mkTyConApp tycon (mkTyVarTys tyvars)] 
611 \end{code}
612
613 %************************************************************************
614 %*                                                                      *
615 \subsection[TcDeriv-normal-binds]{Bindings for the various classes}
616 %*                                                                      *
617 %************************************************************************
618
619 After all the trouble to figure out the required context for the
620 derived instance declarations, all that's left is to chug along to
621 produce them.  They will then be shoved into @tcInstDecls2@, which
622 will do all its usual business.
623
624 There are lots of possibilities for code to generate.  Here are
625 various general remarks.
626
627 PRINCIPLES:
628 \begin{itemize}
629 \item
630 We want derived instances of @Eq@ and @Ord@ (both v common) to be
631 ``you-couldn't-do-better-by-hand'' efficient.
632
633 \item
634 Deriving @Show@---also pretty common--- should also be reasonable good code.
635
636 \item
637 Deriving for the other classes isn't that common or that big a deal.
638 \end{itemize}
639
640 PRAGMATICS:
641
642 \begin{itemize}
643 \item
644 Deriving @Ord@ is done mostly with the 1.3 @compare@ method.
645
646 \item
647 Deriving @Eq@ also uses @compare@, if we're deriving @Ord@, too.
648
649 \item
650 We {\em normally} generate code only for the non-defaulted methods;
651 there are some exceptions for @Eq@ and (especially) @Ord@...
652
653 \item
654 Sometimes we use a @_con2tag_<tycon>@ function, which returns a data
655 constructor's numeric (@Int#@) tag.  These are generated by
656 @gen_tag_n_con_binds@, and the heuristic for deciding if one of
657 these is around is given by @hasCon2TagFun@.
658
659 The examples under the different sections below will make this
660 clearer.
661
662 \item
663 Much less often (really just for deriving @Ix@), we use a
664 @_tag2con_<tycon>@ function.  See the examples.
665
666 \item
667 We use the renamer!!!  Reason: we're supposed to be
668 producing @RenamedMonoBinds@ for the methods, but that means
669 producing correctly-uniquified code on the fly.  This is entirely
670 possible (the @TcM@ monad has a @UniqueSupply@), but it is painful.
671 So, instead, we produce @RdrNameMonoBinds@ then heave 'em through
672 the renamer.  What a great hack!
673 \end{itemize}
674
675 \begin{code}
676 -- Generate the method bindings for the required instance
677 -- (paired with class name, as we need that when renaming
678 --  the method binds)
679 gen_bind :: DFunId -> TcM (Name, RdrNameMonoBinds)
680 gen_bind dfun
681   = getFixityEnv                `thenM` \ fix_env -> 
682     returnM (cls_nm, gen_binds_fn fix_env cls_nm tycon)
683   where
684     cls_nm        = className clas
685     (clas, tycon) = simpleDFunClassTyCon dfun
686
687 gen_binds_fn fix_env cls_nm
688   = assoc "gen_bind:bad derived class"
689           gen_list (nameUnique cls_nm)
690   where
691     gen_list = [(eqClassKey,      gen_Eq_binds)
692                ,(ordClassKey,     gen_Ord_binds)
693                ,(enumClassKey,    gen_Enum_binds)
694                ,(boundedClassKey, gen_Bounded_binds)
695                ,(ixClassKey,      gen_Ix_binds)
696                ,(showClassKey,    gen_Show_binds fix_env)
697                ,(readClassKey,    gen_Read_binds fix_env)
698                ]
699 \end{code}
700
701
702 %************************************************************************
703 %*                                                                      *
704 \subsection[TcDeriv-taggery-Names]{What con2tag/tag2con functions are available?}
705 %*                                                                      *
706 %************************************************************************
707
708
709 data Foo ... = ...
710
711 con2tag_Foo :: Foo ... -> Int#
712 tag2con_Foo :: Int -> Foo ...   -- easier if Int, not Int#
713 maxtag_Foo  :: Int              -- ditto (NB: not unlifted)
714
715
716 We have a @con2tag@ function for a tycon if:
717 \begin{itemize}
718 \item
719 We're deriving @Eq@ and the tycon has nullary data constructors.
720
721 \item
722 Or: we're deriving @Ord@ (unless single-constructor), @Enum@, @Ix@
723 (enum type only????)
724 \end{itemize}
725
726 We have a @tag2con@ function for a tycon if:
727 \begin{itemize}
728 \item
729 We're deriving @Enum@, or @Ix@ (enum type only???)
730 \end{itemize}
731
732 If we have a @tag2con@ function, we also generate a @maxtag@ constant.
733
734 \begin{code}
735 gen_taggery_Names :: [DFunId]
736                   -> TcM [(RdrName,     -- for an assoc list
737                            TyCon,       -- related tycon
738                            TagThingWanted)]
739
740 gen_taggery_Names dfuns
741   = foldlM do_con2tag []           tycons_of_interest `thenM` \ names_so_far ->
742     foldlM do_tag2con names_so_far tycons_of_interest
743   where
744     all_CTs = map simpleDFunClassTyCon dfuns
745     all_tycons              = map snd all_CTs
746     (tycons_of_interest, _) = removeDups compare all_tycons
747     
748     do_con2tag acc_Names tycon
749       | isDataTyCon tycon &&
750         ((we_are_deriving eqClassKey tycon
751             && any isNullaryDataCon (tyConDataCons tycon))
752          || (we_are_deriving ordClassKey  tycon
753             && not (maybeToBool (maybeTyConSingleCon tycon)))
754          || (we_are_deriving enumClassKey tycon)
755          || (we_are_deriving ixClassKey   tycon))
756         
757       = returnM ((con2tag_RDR tycon, tycon, GenCon2Tag)
758                    : acc_Names)
759       | otherwise
760       = returnM acc_Names
761
762     do_tag2con acc_Names tycon
763       | isDataTyCon tycon &&
764          (we_are_deriving enumClassKey tycon ||
765           we_are_deriving ixClassKey   tycon
766           && isEnumerationTyCon tycon)
767       = returnM ( (tag2con_RDR tycon, tycon, GenTag2Con)
768                  : (maxtag_RDR  tycon, tycon, GenMaxTag)
769                  : acc_Names)
770       | otherwise
771       = returnM acc_Names
772
773     we_are_deriving clas_key tycon
774       = is_in_eqns clas_key tycon all_CTs
775       where
776         is_in_eqns clas_key tycon [] = False
777         is_in_eqns clas_key tycon ((c,t):cts)
778           =  (clas_key == classKey c && tycon == t)
779           || is_in_eqns clas_key tycon cts
780 \end{code}
781
782 \begin{code}
783 derivingThingErr clas tys tycon tyvars why
784   = sep [hsep [ptext SLIT("Can't make a derived instance of"), quotes (ppr pred)],
785          parens why]
786   where
787     pred = mkClassPred clas (tys ++ [mkTyConApp tycon (mkTyVarTys tyvars)])
788
789 malformedPredErr tycon pred = ptext SLIT("Illegal deriving item") <+> ppr pred
790
791 derivCtxt :: Maybe Class -> TyCon -> SDoc
792 derivCtxt maybe_cls tycon
793   = ptext SLIT("When deriving") <+> cls <+> ptext SLIT("for type") <+> quotes (ppr tycon)
794   where
795     cls = case maybe_cls of
796             Nothing -> ptext SLIT("instances")
797             Just c  -> ptext SLIT("the") <+> quotes (ppr c) <+> ptext SLIT("instance")
798 \end{code}
799