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