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