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