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