079bd72d3e2637575a5c3d924a6f7268ae53b111
[ghc-hetmet.git] / ghc / compiler / typecheck / TcDeriv.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
3 %
4 \section[TcDeriv]{Deriving}
5
6 Handles @deriving@ clauses on @data@ declarations.
7
8 \begin{code}
9 #include "HsVersions.h"
10
11 module TcDeriv ( tcDeriving ) where
12
13 IMP_Ubiq()
14
15 import HsSyn            ( HsDecl, FixityDecl, Fixity, InstDecl, 
16                           Sig, HsBinds(..), Bind(..), MonoBinds(..),
17                           GRHSsAndBinds, Match, HsExpr, HsLit, InPat,
18                           ArithSeqInfo, Fake, HsType,
19                           collectMonoBinders
20                         )
21 import HsPragmas        ( InstancePragmas(..) )
22 import RdrHsSyn         ( RdrName, SYN_IE(RdrNameMonoBinds) )
23 import RnHsSyn          ( SYN_IE(RenamedHsBinds), SYN_IE(RenamedMonoBinds), SYN_IE(RenamedFixityDecl) )
24 import TcHsSyn          ( TcIdOcc )
25
26 import TcMonad
27 import Inst             ( SYN_IE(InstanceMapper) )
28 import TcEnv            ( getEnv_TyCons, tcLookupClassByKey )
29 import SpecEnv          ( SpecEnv )
30 import TcKind           ( TcKind )
31 import TcGenDeriv       -- Deriv stuff
32 import TcInstUtil       ( InstInfo(..), mkInstanceRelatedIds, buildInstanceEnvs )
33 import TcSimplify       ( tcSimplifyThetas )
34
35 import RnBinds          ( rnMethodBinds, rnTopMonoBinds )
36 import RnEnv            ( newDfunName, bindLocatedLocalsRn )
37 import RnMonad          ( SYN_IE(RnM), RnDown, GDown, SDown, RnNameSupply(..), 
38                           setNameSupplyRn, renameSourceCode, thenRn, mapRn, returnRn )
39
40 import Bag              ( Bag, isEmptyBag, unionBags, listToBag )
41 import Class            ( classKey, GenClass )
42 import ErrUtils         ( pprBagOfErrors, addErrLoc, SYN_IE(Error) )
43 import Id               ( dataConArgTys, isNullaryDataCon, mkDictFunId )
44 import PrelInfo         ( needsDataDeclCtxtClassKeys )
45 import Maybes           ( maybeToBool )
46 import Name             ( isLocallyDefined, getSrcLoc, ExportFlag(..), Provenance, 
47                           Name{--O only-}
48                         )
49 import Outputable       ( Outputable(..){-instances e.g., (,)-} )
50 import PprType          ( GenType, GenTyVar, GenClass, TyCon )
51 import PprStyle         ( PprStyle(..) )
52 import Pretty           ( ppAbove, ppAboves, ppCat, ppBesides, ppStr, ppHang, SYN_IE(Pretty) )
53 --import Pretty--ToDo:rm
54 --import FiniteMap--ToDo:rm
55 import SrcLoc           ( mkGeneratedSrcLoc, SrcLoc )
56 import TyCon            ( tyConTyVars, tyConDataCons, tyConDerivings,
57                           tyConTheta, maybeTyConSingleCon,
58                           isEnumerationTyCon, isDataTyCon, TyCon
59                         )
60 import Type             ( GenType(..), SYN_IE(TauType), mkTyVarTys, applyTyCon,
61                           mkSigmaTy, mkDictTy, isPrimType, instantiateTy,
62                           getAppDataTyCon, getAppTyCon
63                         )
64 import TysPrim          ( voidTy )
65 import TyVar            ( GenTyVar )
66 import UniqFM           ( emptyUFM )
67 import Unique           -- Keys stuff
68 import Bag              ( bagToList )
69 import Util             ( zipWithEqual, zipEqual, sortLt, removeDups,  assoc,
70                           thenCmp, cmpList, panic, panic#, pprPanic, pprPanic#,
71                           assertPanic-- , pprTrace{-ToDo:rm-}
72                         )
73 \end{code}
74
75 %************************************************************************
76 %*                                                                      *
77 \subsection[TcDeriv-intro]{Introduction to how we do deriving}
78 %*                                                                      *
79 %************************************************************************
80
81 Consider
82
83         data T a b = C1 (Foo a) (Bar b)
84                    | C2 Int (T b a)
85                    | C3 (T a a)
86                    deriving (Eq)
87
88 [NOTE: See end of these comments for what to do with 
89         data (C a, D b) => T a b = ...
90 ]
91
92 We want to come up with an instance declaration of the form
93
94         instance (Ping a, Pong b, ...) => Eq (T a b) where
95                 x == y = ...
96
97 It is pretty easy, albeit tedious, to fill in the code "...".  The
98 trick is to figure out what the context for the instance decl is,
99 namely @Ping@, @Pong@ and friends.
100
101 Let's call the context reqd for the T instance of class C at types
102 (a,b, ...)  C (T a b).  Thus:
103
104         Eq (T a b) = (Ping a, Pong b, ...)
105
106 Now we can get a (recursive) equation from the @data@ decl:
107
108         Eq (T a b) = Eq (Foo a) u Eq (Bar b)    -- From C1
109                    u Eq (T b a) u Eq Int        -- From C2
110                    u Eq (T a a)                 -- From C3
111
112 Foo and Bar may have explicit instances for @Eq@, in which case we can
113 just substitute for them.  Alternatively, either or both may have
114 their @Eq@ instances given by @deriving@ clauses, in which case they
115 form part of the system of equations.
116
117 Now all we need do is simplify and solve the equations, iterating to
118 find the least fixpoint.  Notice that the order of the arguments can
119 switch around, as here in the recursive calls to T.
120
121 Let's suppose Eq (Foo a) = Eq a, and Eq (Bar b) = Ping b.
122
123 We start with:
124
125         Eq (T a b) = {}         -- The empty set
126
127 Next iteration:
128         Eq (T a b) = Eq (Foo a) u Eq (Bar b)    -- From C1
129                    u Eq (T b a) u Eq Int        -- From C2
130                    u Eq (T a a)                 -- From C3
131
132         After simplification:
133                    = Eq a u Ping b u {} u {} u {}
134                    = Eq a u Ping b
135
136 Next iteration:
137
138         Eq (T a b) = Eq (Foo a) u Eq (Bar b)    -- From C1
139                    u Eq (T b a) u Eq Int        -- From C2
140                    u Eq (T a a)                 -- From C3
141
142         After simplification:
143                    = Eq a u Ping b
144                    u (Eq b u Ping a)
145                    u (Eq a u Ping a)
146
147                    = Eq a u Ping b u Eq b u Ping a
148
149 The next iteration gives the same result, so this is the fixpoint.  We
150 need to make a canonical form of the RHS to ensure convergence.  We do
151 this by simplifying the RHS to a form in which
152
153         - the classes constrain only tyvars
154         - the list is sorted by tyvar (major key) and then class (minor key)
155         - no duplicates, of course
156
157 So, here are the synonyms for the ``equation'' structures:
158
159 \begin{code}
160 type DerivEqn = (Class, TyCon, [TyVar], DerivRhs)
161                          -- The tyvars bind all the variables in the RHS
162                          -- NEW: it's convenient to re-use InstInfo
163                          -- We'll "panic" out some fields...
164
165 type DerivRhs = [(Class, TauType)]      -- Same as a ThetaType!
166
167 type DerivSoln = DerivRhs
168 \end{code}
169
170
171 A note about contexts on data decls
172 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
173 Consider
174
175         data (RealFloat a) => Complex a = !a :+ !a deriving( Read )
176
177 We will need an instance decl like:
178
179         instance (Read a, RealFloat a) => Read (Complex a) where
180           ...
181
182 The RealFloat in the context is because the read method for Complex is bound
183 to construct a Complex, and doing that requires that the argument type is
184 in RealFloat. 
185
186 But this ain't true for Show, Eq, Ord, etc, since they don't construct
187 a Complex; they only take them apart.
188
189 Our approach: identify the offending classes, and add the data type
190 context to the instance decl.  The "offending classes" are
191
192         Read, Enum?
193
194
195 %************************************************************************
196 %*                                                                      *
197 \subsection[TcDeriv-driver]{Top-level function for \tr{derivings}}
198 %*                                                                      *
199 %************************************************************************
200
201 \begin{code}
202 tcDeriving  :: Module                   -- name of module under scrutiny
203             -> RnNameSupply             -- for "renaming" bits of generated code
204             -> Bag InstInfo             -- What we already know about instances
205             -> TcM s (Bag InstInfo,     -- The generated "instance decls".
206                       RenamedHsBinds,   -- Extra generated bindings
207                       PprStyle -> Pretty)  -- Printable derived instance decls;
208                                            -- for debugging via -ddump-derivings.
209
210 tcDeriving modname rn_name_supply inst_decl_infos_in
211   =     -- Fish the "deriving"-related information out of the TcEnv
212         -- and make the necessary "equations".
213     makeDerivEqns                               `thenTc` \ eqns ->
214
215         -- Take the equation list and solve it, to deliver a list of
216         -- solutions, a.k.a. the contexts for the instance decls
217         -- required for the corresponding equations.
218     solveDerivEqns inst_decl_infos_in eqns      `thenTc` \ new_inst_infos ->
219
220         -- Now augment the InstInfos, adding in the rather boring
221         -- actual-code-to-do-the-methods binds.  We may also need to
222         -- generate extra not-one-inst-decl-specific binds, notably
223         -- "con2tag" and/or "tag2con" functions.  We do these
224         -- separately.
225
226     gen_taggery_Names new_inst_infos            `thenTc` \ nm_alist_etc ->
227
228
229     let
230         extra_mbind_list = map gen_tag_n_con_monobind nm_alist_etc
231         extra_mbinds     = foldr AndMonoBinds EmptyMonoBinds extra_mbind_list
232         method_binds_s   = map gen_bind new_inst_infos
233         mbinders         = bagToList (collectMonoBinders extra_mbinds)
234         
235         -- Rename to get RenamedBinds.
236         -- The only tricky bit is that the extra_binds must scope over the
237         -- method bindings for the instances.
238         (dfun_names_w_method_binds, rn_extra_binds)
239                 = renameSourceCode modname rn_name_supply (
240                         bindLocatedLocalsRn "deriving" mbinders $ \ _ ->
241                         rnTopMonoBinds extra_mbinds []          `thenRn` \ rn_extra_binds ->
242                         mapRn rn_one method_binds_s             `thenRn` \ dfun_names_w_method_binds ->
243                         returnRn (dfun_names_w_method_binds, rn_extra_binds)
244                   )
245         rn_one meth_binds = newDfunName mkGeneratedSrcLoc       `thenRn` \ dfun_name ->
246                             rnMethodBinds meth_binds    `thenRn` \ rn_meth_binds ->
247                             returnRn (dfun_name, rn_meth_binds)
248     in
249
250     mapTc (gen_inst_info modname)
251           (new_inst_infos `zip` dfun_names_w_method_binds)      `thenTc` \ really_new_inst_infos ->
252     let
253         ddump_deriv = ddump_deriving really_new_inst_infos rn_extra_binds
254     in
255     --pprTrace "derived:\n" (ddump_deriv PprDebug) $
256
257     returnTc (listToBag really_new_inst_infos,
258               rn_extra_binds,
259               ddump_deriv)
260   where
261     ddump_deriving :: [InstInfo] -> RenamedHsBinds -> (PprStyle -> Pretty)
262
263     ddump_deriving inst_infos extra_binds sty
264       = ppAboves ((map pp_info inst_infos) ++ [ppr sty extra_binds])
265       where
266         pp_info (InstInfo clas tvs ty inst_decl_theta _ _ mbinds _ _)
267           = ppAbove (ppr sty (mkSigmaTy tvs inst_decl_theta (mkDictTy clas ty)))
268                     (ppr sty mbinds)
269 \end{code}
270
271
272 %************************************************************************
273 %*                                                                      *
274 \subsection[TcDeriv-eqns]{Forming the equations}
275 %*                                                                      *
276 %************************************************************************
277
278 @makeDerivEqns@ fishes around to find the info about needed derived
279 instances.  Complicating factors:
280 \begin{itemize}
281 \item
282 We can only derive @Enum@ if the data type is an enumeration
283 type (all nullary data constructors).
284
285 \item
286 We can only derive @Ix@ if the data type is an enumeration {\em
287 or} has just one data constructor (e.g., tuples).
288 \end{itemize}
289
290 [See Appendix~E in the Haskell~1.2 report.] This code here deals w/
291 all those.
292
293 \begin{code}
294 makeDerivEqns :: TcM s [DerivEqn]
295
296 makeDerivEqns
297   = tcGetEnv                        `thenNF_Tc` \ env ->
298     let
299         local_data_tycons = filter (\tc -> isLocallyDefined tc && isDataTyCon tc)
300                                    (getEnv_TyCons env)
301         -- ToDo: what about newtypes???
302     in
303     if null local_data_tycons then
304         -- Bale out now; evalClass may not be loaded if there aren't any
305         returnTc []
306     else
307     tcLookupClassByKey evalClassKey `thenNF_Tc` \ eval_clas ->
308     let
309         think_about_deriving = need_deriving eval_clas local_data_tycons
310         (derive_these, _)    = removeDups cmp_deriv think_about_deriving
311         eqns                 = map mk_eqn derive_these
312     in
313     mapTc chk_out think_about_deriving `thenTc_`
314     returnTc eqns
315   where
316     ------------------------------------------------------------------
317     need_deriving :: Class -> [TyCon] -> [(Class, TyCon)]
318         -- find the tycons that have `deriving' clauses;
319         -- we handle the "every datatype in Eval" by
320         -- doing a dummy "deriving" for it.
321
322     need_deriving eval_clas tycons_to_consider
323       = foldr ( \ tycon acc ->
324                    let
325                         acc_plus = if isLocallyDefined tycon
326                                    then (eval_clas, tycon) : acc
327                                    else acc
328                    in
329                    case (tyConDerivings tycon) of
330                      [] -> acc_plus
331                      cs -> [ (clas,tycon) | clas <- cs ] ++ acc_plus
332               )
333               []
334               tycons_to_consider
335
336     ------------------------------------------------------------------
337     chk_out :: (Class, TyCon) -> TcM s ()
338     chk_out this_one@(clas, tycon)
339       = let
340             clas_key = classKey clas
341
342             is_enumeration = isEnumerationTyCon tycon
343             is_single_con  = maybeToBool (maybeTyConSingleCon tycon)
344
345             chk_clas clas_uniq clas_str cond
346               = if (clas_uniq == clas_key)
347                 then checkTc cond (derivingThingErr clas_str tycon)
348                 else returnTc ()
349         in
350             -- Are things OK for deriving Enum (if appropriate)?
351         chk_clas enumClassKey "Enum" is_enumeration `thenTc_`
352
353             -- Are things OK for deriving Bounded (if appropriate)?
354         chk_clas boundedClassKey "Bounded"
355                 (is_enumeration || is_single_con) `thenTc_`
356
357             -- Are things OK for deriving Ix (if appropriate)?
358         chk_clas ixClassKey "Ix.Ix" (is_enumeration || is_single_con)
359
360     ------------------------------------------------------------------
361     cmp_deriv :: (Class, TyCon) -> (Class, TyCon) -> TAG_
362     cmp_deriv (c1, t1) (c2, t2)
363       = (c1 `cmp` c2) `thenCmp` (t1 `cmp` t2)
364
365     ------------------------------------------------------------------
366     mk_eqn :: (Class, TyCon) -> DerivEqn
367         -- we swizzle the tyvars and datacons out of the tycon
368         -- to make the rest of the equation
369
370     mk_eqn (clas, tycon)
371       = (clas, tycon, tyvars, if_not_Eval constraints)
372       where
373         clas_key  = classKey clas
374         tyvars    = tyConTyVars tycon   -- ToDo: Do we need new tyvars ???
375         tyvar_tys = mkTyVarTys tyvars
376         data_cons = tyConDataCons tycon
377
378         if_not_Eval cs = if clas_key == evalClassKey then [] else cs
379
380         constraints = extra_constraints ++ concat (map mk_constraints data_cons)
381
382         -- "extra_constraints": see notes above about contexts on data decls
383         extra_constraints
384           | offensive_class = tyConTheta tycon
385           | otherwise       = []
386            where
387             offensive_class = clas_key `elem` needsDataDeclCtxtClassKeys
388
389         mk_constraints data_con
390            = [ (clas, arg_ty)
391              | arg_ty <- instd_arg_tys,
392                not (isPrimType arg_ty)  -- No constraints for primitive types
393              ]
394            where
395              instd_arg_tys  = dataConArgTys data_con tyvar_tys
396 \end{code}
397
398 %************************************************************************
399 %*                                                                      *
400 \subsection[TcDeriv-fixpoint]{Finding the fixed point of \tr{deriving} equations}
401 %*                                                                      *
402 %************************************************************************
403
404 A ``solution'' (to one of the equations) is a list of (k,TyVarTy tv)
405 terms, which is the final correct RHS for the corresponding original
406 equation.
407 \begin{itemize}
408 \item
409 Each (k,TyVarTy tv) in a solution constrains only a type
410 variable, tv.
411
412 \item
413 The (k,TyVarTy tv) pairs in a solution are canonically
414 ordered by sorting on type varible, tv, (major key) and then class, k,
415 (minor key)
416 \end{itemize}
417
418 \begin{code}
419 solveDerivEqns :: Bag InstInfo
420                -> [DerivEqn]
421                -> TcM s [InstInfo]      -- Solns in same order as eqns.
422                                         -- This bunch is Absolutely minimal...
423
424 solveDerivEqns inst_decl_infos_in orig_eqns
425   = iterateDeriv initial_solutions
426   where
427         -- The initial solutions for the equations claim that each
428         -- instance has an empty context; this solution is certainly
429         -- in canonical form.
430     initial_solutions :: [DerivSoln]
431     initial_solutions = [ [] | _ <- orig_eqns ]
432
433         -- iterateDeriv calculates the next batch of solutions,
434         -- compares it with the current one; finishes if they are the
435         -- same, otherwise recurses with the new solutions.
436
437     iterateDeriv :: [DerivSoln] ->TcM s [InstInfo]
438
439     iterateDeriv current_solns
440       =     -- Extend the inst info from the explicit instance decls
441             -- with the current set of solutions, giving a
442
443         add_solns inst_decl_infos_in orig_eqns current_solns
444                                 `thenTc` \ (new_inst_infos, inst_mapper) ->
445         let
446            class_to_inst_env cls = fst (inst_mapper cls)
447         in
448             -- Simplify each RHS
449
450         listTc [ tcSimplifyThetas class_to_inst_env [{-Nothing "given"-}] deriv_rhs
451                | (_,_,_,deriv_rhs) <- orig_eqns ]  `thenTc` \ next_solns ->
452
453             -- Canonicalise the solutions, so they compare nicely
454         let canonicalised_next_solns
455               = [ sortLt lt_rhs next_soln | next_soln <- next_solns ] in
456
457         if (current_solns `eq_solns` canonicalised_next_solns) then
458             returnTc new_inst_infos
459         else
460             iterateDeriv canonicalised_next_solns
461
462       where
463         ------------------------------------------------------------------
464         lt_rhs    r1 r2 = case cmp_rhs   r1 r2 of { LT_ -> True; _ -> False }
465         eq_solns  s1 s2 = case cmp_solns s1 s2 of { EQ_ -> True; _ -> False }
466         cmp_solns s1 s2 = cmpList (cmpList cmp_rhs) s1 s2
467         cmp_rhs (c1, TyVarTy tv1) (c2, TyVarTy tv2)
468           = (tv1 `cmp` tv2) `thenCmp` (c1 `cmp` c2)
469 #ifdef DEBUG
470         cmp_rhs other_1 other_2
471           = panic# "tcDeriv:cmp_rhs:" --(ppCat [ppr PprDebug other_1, ppr PprDebug other_2])
472 #endif
473
474 \end{code}
475
476 \begin{code}
477 add_solns :: Bag InstInfo                       -- The global, non-derived ones
478           -> [DerivEqn] -> [DerivSoln]
479           -> TcM s ([InstInfo],                 -- The new, derived ones
480                     InstanceMapper)
481     -- the eqns and solns move "in lockstep"; we have the eqns
482     -- because we need the LHS info for addClassInstance.
483
484 add_solns inst_infos_in eqns solns
485   = buildInstanceEnvs all_inst_infos `thenTc` \ inst_mapper ->
486     returnTc (new_inst_infos, inst_mapper)
487   where
488     new_inst_infos = zipWithEqual "add_solns" mk_deriv_inst_info eqns solns
489
490     all_inst_infos = inst_infos_in `unionBags` listToBag new_inst_infos
491
492     mk_deriv_inst_info (clas, tycon, tyvars, _) theta
493       = InstInfo clas tyvars (applyTyCon tycon (mkTyVarTys tyvars))
494                  theta
495                  (my_panic "dfun_theta")
496
497                  dummy_dfun_id
498
499                  (my_panic "binds") (getSrcLoc tycon)
500                  (my_panic "upragmas")
501       where
502         dummy_dfun_id
503           = mkDictFunId bottom dummy_dfun_ty bottom bottom
504           where
505             bottom = panic "dummy_dfun_id"
506
507         dummy_dfun_ty = mkSigmaTy tyvars theta voidTy
508                 -- All we need from the dfun is its "theta" part, used during
509                 -- equation simplification (tcSimplifyThetas).  The final
510                 -- dfun_id will have the superclass dictionaries as arguments too,
511                 -- but that'll be added after the equations are solved.  For now,
512                 -- it's enough just to make a dummy dfun with the simple theta part.
513                 -- 
514                 -- The part after the theta is dummied here as voidTy; actually it's
515                 --      (C (T a b)), but it doesn't seem worth constructing it.
516                 -- We can't leave it as a panic because to get the theta part we
517                 -- have to run down the type!
518
519         my_panic str = panic "add_soln" -- pprPanic ("add_soln:"++str) (ppCat [ppChar ':', ppr PprDebug clas, ppr PprDebug tycon])
520 \end{code}
521
522 %************************************************************************
523 %*                                                                      *
524 \subsection[TcDeriv-normal-binds]{Bindings for the various classes}
525 %*                                                                      *
526 %************************************************************************
527
528 After all the trouble to figure out the required context for the
529 derived instance declarations, all that's left is to chug along to
530 produce them.  They will then be shoved into @tcInstDecls2@, which
531 will do all its usual business.
532
533 There are lots of possibilities for code to generate.  Here are
534 various general remarks.
535
536 PRINCIPLES:
537 \begin{itemize}
538 \item
539 We want derived instances of @Eq@ and @Ord@ (both v common) to be
540 ``you-couldn't-do-better-by-hand'' efficient.
541
542 \item
543 Deriving @Show@---also pretty common--- should also be reasonable good code.
544
545 \item
546 Deriving for the other classes isn't that common or that big a deal.
547 \end{itemize}
548
549 PRAGMATICS:
550
551 \begin{itemize}
552 \item
553 Deriving @Ord@ is done mostly with the 1.3 @compare@ method.
554
555 \item
556 Deriving @Eq@ also uses @compare@, if we're deriving @Ord@, too.
557
558 \item
559 We {\em normally} generate code only for the non-defaulted methods;
560 there are some exceptions for @Eq@ and (especially) @Ord@...
561
562 \item
563 Sometimes we use a @_con2tag_<tycon>@ function, which returns a data
564 constructor's numeric (@Int#@) tag.  These are generated by
565 @gen_tag_n_con_binds@, and the heuristic for deciding if one of
566 these is around is given by @hasCon2TagFun@.
567
568 The examples under the different sections below will make this
569 clearer.
570
571 \item
572 Much less often (really just for deriving @Ix@), we use a
573 @_tag2con_<tycon>@ function.  See the examples.
574
575 \item
576 We use the renamer!!!  Reason: we're supposed to be
577 producing @RenamedMonoBinds@ for the methods, but that means
578 producing correctly-uniquified code on the fly.  This is entirely
579 possible (the @TcM@ monad has a @UniqueSupply@), but it is painful.
580 So, instead, we produce @RdrNameMonoBinds@ then heave 'em through
581 the renamer.  What a great hack!
582 \end{itemize}
583
584 \begin{code}
585 -- Generate the method bindings for the required instance
586 gen_bind :: InstInfo -> RdrNameMonoBinds
587 gen_bind (InstInfo clas _ ty _ _ _ _ _ _)
588   | not from_here 
589   = EmptyMonoBinds
590   | otherwise
591   = assoc "gen_inst_info:bad derived class"
592           [(eqClassKey,      gen_Eq_binds)
593           ,(ordClassKey,     gen_Ord_binds)
594           ,(enumClassKey,    gen_Enum_binds)
595           ,(evalClassKey,    gen_Eval_binds)
596           ,(boundedClassKey, gen_Bounded_binds)
597           ,(showClassKey,    gen_Show_binds)
598           ,(readClassKey,    gen_Read_binds)
599           ,(ixClassKey,      gen_Ix_binds)
600           ]
601           (classKey clas) 
602           tycon
603   where
604       from_here   = isLocallyDefined tycon
605       (tycon,_,_) = getAppDataTyCon ty  
606             
607
608 gen_inst_info :: Module                                 -- Module name
609               -> (InstInfo, (Name, RenamedMonoBinds))           -- the main stuff to work on
610               -> TcM s InstInfo                         -- the gen'd (filled-in) "instance decl"
611
612 gen_inst_info modname
613     (InstInfo clas tyvars ty inst_decl_theta _ _ _ locn _, (dfun_name, meth_binds))
614   =
615         -- Generate the various instance-related Ids
616     mkInstanceRelatedIds
617                 dfun_name
618                 clas tyvars ty
619                 inst_decl_theta
620                                         `thenNF_Tc` \ (dfun_id, dfun_theta) ->
621
622     returnTc (InstInfo clas tyvars ty inst_decl_theta
623                        dfun_theta dfun_id
624                        meth_binds
625                        locn [])
626   where
627     from_here = isLocallyDefined tycon
628     (tycon,_,_) = getAppDataTyCon ty
629 \end{code}
630
631
632 %************************************************************************
633 %*                                                                      *
634 \subsection[TcDeriv-taggery-Names]{What con2tag/tag2con functions are available?}
635 %*                                                                      *
636 %************************************************************************
637
638
639 data Foo ... = ...
640
641 con2tag_Foo :: Foo ... -> Int#
642 tag2con_Foo :: Int -> Foo ...   -- easier if Int, not Int#
643 maxtag_Foo  :: Int              -- ditto (NB: not unboxed)
644
645
646 We have a @con2tag@ function for a tycon if:
647 \begin{itemize}
648 \item
649 We're deriving @Eq@ and the tycon has nullary data constructors.
650
651 \item
652 Or: we're deriving @Ord@ (unless single-constructor), @Enum@, @Ix@
653 (enum type only????)
654 \end{itemize}
655
656 We have a @tag2con@ function for a tycon if:
657 \begin{itemize}
658 \item
659 We're deriving @Enum@, or @Ix@ (enum type only???)
660 \end{itemize}
661
662 If we have a @tag2con@ function, we also generate a @maxtag@ constant.
663
664 \begin{code}
665 gen_taggery_Names :: [InstInfo]
666                   -> TcM s [(RdrName,   -- for an assoc list
667                              TyCon,     -- related tycon
668                              TagThingWanted)]
669
670 gen_taggery_Names inst_infos
671   = --pprTrace "gen_taggery:\n" (ppAboves [ppCat [ppr PprDebug c, ppr PprDebug t] | (c,t) <- all_CTs]) $
672     foldlTc do_con2tag []           tycons_of_interest `thenTc` \ names_so_far ->
673     foldlTc do_tag2con names_so_far tycons_of_interest
674   where
675     all_CTs = [ mk_CT c ty | (InstInfo c _ ty _ _ _ _ _ _) <- inst_infos ]
676                     
677     mk_CT c ty = (c, fst (getAppTyCon ty))
678
679     all_tycons = map snd all_CTs
680     (tycons_of_interest, _) = removeDups cmp all_tycons
681     
682     do_con2tag acc_Names tycon
683       = if (we_are_deriving eqClassKey tycon
684             && any isNullaryDataCon (tyConDataCons tycon))
685         || (we_are_deriving ordClassKey  tycon
686             && not (maybeToBool (maybeTyConSingleCon tycon)))
687         || (we_are_deriving enumClassKey tycon)
688         || (we_are_deriving ixClassKey   tycon)
689         then
690           returnTc ((con2tag_RDR tycon, tycon, GenCon2Tag)
691                    : acc_Names)
692         else
693           returnTc acc_Names
694
695     do_tag2con acc_Names tycon
696       = if (we_are_deriving enumClassKey tycon)
697         || (we_are_deriving ixClassKey   tycon)
698         then
699           returnTc ( (tag2con_RDR tycon, tycon, GenTag2Con)
700                    : (maxtag_RDR  tycon, tycon, GenMaxTag)
701                    : acc_Names)
702         else
703           returnTc acc_Names
704
705     we_are_deriving clas_key tycon
706       = is_in_eqns clas_key tycon all_CTs
707       where
708         is_in_eqns clas_key tycon [] = False
709         is_in_eqns clas_key tycon ((c,t):cts)
710           =  (clas_key == classKey c && tycon == t)
711           || is_in_eqns clas_key tycon cts
712
713 \end{code}
714
715 \begin{code}
716 derivingThingErr :: String -> TyCon -> Error
717
718 derivingThingErr thing tycon sty
719   = ppHang (ppCat [ppStr "Can't make a derived instance of", ppStr thing])
720          4 (ppBesides [ppStr "for the type `", ppr sty tycon, ppStr "'"])
721 \end{code}