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