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