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