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