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