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