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