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