35995fd0b7372039db5baf04fddbc09adb92a62e
[ghc-hetmet.git] / ghc / compiler / typecheck / TcDeriv.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
3 %
4 \section[TcDeriv]{Deriving}
5
6 Handles @deriving@ clauses on @data@ declarations.
7
8 \begin{code}
9 #include "HsVersions.h"
10
11 module TcDeriv ( tcDeriving ) where
12
13 IMP_Ubiq()
14
15 import HsSyn            ( FixityDecl, Sig, HsBinds(..), Bind(..), MonoBinds(..),
16                           GRHSsAndBinds, Match, HsExpr, HsLit, InPat,
17                           ArithSeqInfo, Fake, MonoType )
18 import HsPragmas        ( InstancePragmas(..) )
19 import RnHsSyn          ( mkRnName, RnName(..), SYN_IE(RenamedHsBinds), RenamedFixityDecl(..) )
20 import TcHsSyn          ( TcIdOcc )
21
22 import TcMonad
23 import Inst             ( SYN_IE(InstanceMapper) )
24 import TcEnv            ( getEnv_TyCons, tcLookupClassByKey )
25 import SpecEnv          ( SpecEnv )
26 import TcKind           ( TcKind )
27 import TcGenDeriv       -- Deriv stuff
28 import TcInstUtil       ( InstInfo(..), mkInstanceRelatedIds, buildInstanceEnvs )
29 import TcSimplify       ( tcSimplifyThetas )
30
31 import RnMonad
32 import RnUtils          ( SYN_IE(RnEnv), extendGlobalRnEnv )
33 import RnBinds          ( rnMethodBinds, rnTopBinds )
34
35 import Bag              ( emptyBag{-ToDo:rm-}, Bag, isEmptyBag, unionBags, listToBag )
36 import Class            ( classKey, needsDataDeclCtxtClassKeys, GenClass )
37 import ErrUtils         ( pprBagOfErrors, addErrLoc, SYN_IE(Error) )
38 import Id               ( dataConArgTys, isNullaryDataCon, mkDictFunId )
39 import Maybes           ( maybeToBool )
40 import Name             ( isLocallyDefined, getSrcLoc,
41                           mkTopLevName, origName, mkImplicitName, ExportFlag(..),
42                           RdrName(..), Name{--O only-}
43                         )
44 import Outputable       ( Outputable(..){-instances e.g., (,)-} )
45 import PprType          ( GenType, GenTyVar, GenClass, TyCon )
46 import PprStyle         ( PprStyle(..) )
47 import Pretty           ( ppAbove, ppAboves, ppCat, ppBesides, ppStr, ppHang, SYN_IE(Pretty) )
48 import Pretty--ToDo:rm
49 import FiniteMap--ToDo:rm
50 import SrcLoc           ( mkGeneratedSrcLoc, SrcLoc )
51 import TyCon            ( tyConTyVars, tyConDataCons, tyConDerivings,
52                           tyConTheta, maybeTyConSingleCon,
53                           isEnumerationTyCon, isDataTyCon, TyCon
54                         )
55 import Type             ( GenType(..), SYN_IE(TauType), mkTyVarTys, applyTyCon,
56                           mkSigmaTy, mkDictTy, isPrimType, instantiateTy,
57                           getAppDataTyCon, getAppTyCon
58                         )
59 import TysPrim          ( voidTy )
60 import TyVar            ( GenTyVar )
61 import UniqFM           ( emptyUFM )
62 import Unique           -- Keys stuff
63 import Util             ( zipWithEqual, zipEqual, sortLt, removeDups,  assoc,
64                           thenCmp, cmpList, panic, pprPanic, pprPanic#,
65                           assertPanic, pprTrace{-ToDo:rm-}
66                         )
67 \end{code}
68
69 %************************************************************************
70 %*                                                                      *
71 \subsection[TcDeriv-intro]{Introduction to how we do deriving}
72 %*                                                                      *
73 %************************************************************************
74
75 Consider
76
77         data T a b = C1 (Foo a) (Bar b)
78                    | C2 Int (T b a)
79                    | C3 (T a a)
80                    deriving (Eq)
81
82 [NOTE: See end of these comments for what to do with 
83         data (C a, D b) => T a b = ...
84 ]
85
86 We want to come up with an instance declaration of the form
87
88         instance (Ping a, Pong b, ...) => Eq (T a b) where
89                 x == y = ...
90
91 It is pretty easy, albeit tedious, to fill in the code "...".  The
92 trick is to figure out what the context for the instance decl is,
93 namely @Ping@, @Pong@ and friends.
94
95 Let's call the context reqd for the T instance of class C at types
96 (a,b, ...)  C (T a b).  Thus:
97
98         Eq (T a b) = (Ping a, Pong b, ...)
99
100 Now we can get a (recursive) equation from the @data@ decl:
101
102         Eq (T a b) = Eq (Foo a) u Eq (Bar b)    -- From C1
103                    u Eq (T b a) u Eq Int        -- From C2
104                    u Eq (T a a)                 -- From C3
105
106 Foo and Bar may have explicit instances for @Eq@, in which case we can
107 just substitute for them.  Alternatively, either or both may have
108 their @Eq@ instances given by @deriving@ clauses, in which case they
109 form part of the system of equations.
110
111 Now all we need do is simplify and solve the equations, iterating to
112 find the least fixpoint.  Notice that the order of the arguments can
113 switch around, as here in the recursive calls to T.
114
115 Let's suppose Eq (Foo a) = Eq a, and Eq (Bar b) = Ping b.
116
117 We start with:
118
119         Eq (T a b) = {}         -- The empty set
120
121 Next iteration:
122         Eq (T a b) = Eq (Foo a) u Eq (Bar b)    -- From C1
123                    u Eq (T b a) u Eq Int        -- From C2
124                    u Eq (T a a)                 -- From C3
125
126         After simplification:
127                    = Eq a u Ping b u {} u {} u {}
128                    = Eq a u Ping b
129
130 Next iteration:
131
132         Eq (T a b) = Eq (Foo a) u Eq (Bar b)    -- From C1
133                    u Eq (T b a) u Eq Int        -- From C2
134                    u Eq (T a a)                 -- From C3
135
136         After simplification:
137                    = Eq a u Ping b
138                    u (Eq b u Ping a)
139                    u (Eq a u Ping a)
140
141                    = Eq a u Ping b u Eq b u Ping a
142
143 The next iteration gives the same result, so this is the fixpoint.  We
144 need to make a canonical form of the RHS to ensure convergence.  We do
145 this by simplifying the RHS to a form in which
146
147         - the classes constrain only tyvars
148         - the list is sorted by tyvar (major key) and then class (minor key)
149         - no duplicates, of course
150
151 So, here are the synonyms for the ``equation'' structures:
152
153 \begin{code}
154 type DerivEqn = (Class, TyCon, [TyVar], DerivRhs)
155                          -- The tyvars bind all the variables in the RHS
156                          -- NEW: it's convenient to re-use InstInfo
157                          -- We'll "panic" out some fields...
158
159 type DerivRhs = [(Class, TauType)]      -- Same as a ThetaType!
160
161 type DerivSoln = DerivRhs
162 \end{code}
163
164
165 A note about contexts on data decls
166 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
167 Consider
168
169         data (RealFloat a) => Complex a = !a :+ !a deriving( Read )
170
171 We will need an instance decl like:
172
173         instance (Read a, RealFloat a) => Read (Complex a) where
174           ...
175
176 The RealFloat in the context is because the read method for Complex is bound
177 to construct a Complex, and doing that requires that the argument type is
178 in RealFloat. 
179
180 But this ain't true for Show, Eq, Ord, etc, since they don't construct
181 a Complex; they only take them apart.
182
183 Our approach: identify the offending classes, and add the data type
184 context to the instance decl.  The "offending classes" are
185
186         Read, Enum?
187
188
189 %************************************************************************
190 %*                                                                      *
191 \subsection[TcDeriv-driver]{Top-level function for \tr{derivings}}
192 %*                                                                      *
193 %************************************************************************
194
195 \begin{code}
196 tcDeriving  :: Module                   -- name of module under scrutiny
197             -> RnEnv                    -- for "renaming" bits of generated code
198             -> Bag InstInfo             -- What we already know about instances
199             -> [RenamedFixityDecl]      -- Fixity info; used by Read and Show
200             -> TcM s (Bag InstInfo,     -- The generated "instance decls".
201                       RenamedHsBinds,   -- Extra generated bindings
202                       PprStyle -> Pretty)  -- Printable derived instance decls;
203                                            -- for debugging via -ddump-derivings.
204
205 tcDeriving modname rn_env inst_decl_infos_in fixities
206   =     -- Fish the "deriving"-related information out of the TcEnv
207         -- and make the necessary "equations".
208     makeDerivEqns               `thenTc` \ eqns ->
209
210         -- Take the equation list and solve it, to deliver a list of
211         -- solutions, a.k.a. the contexts for the instance decls
212         -- required for the corresponding equations.
213     solveDerivEqns inst_decl_infos_in eqns
214                                 `thenTc` \ new_inst_infos ->
215
216         -- Now augment the InstInfos, adding in the rather boring
217         -- actual-code-to-do-the-methods binds.  We may also need to
218         -- generate extra not-one-inst-decl-specific binds, notably
219         -- "con2tag" and/or "tag2con" functions.  We do these
220         -- separately.
221
222     gen_taggery_Names new_inst_infos    `thenTc` \ nm_alist_etc ->
223     gen_tag_n_con_binds rn_env nm_alist_etc
224                                 `thenTc` \ (extra_binds, deriver_rn_env) ->
225
226     mapTc (gen_inst_info modname fixities deriver_rn_env) new_inst_infos
227                                 `thenTc` \ really_new_inst_infos ->
228     let
229         ddump_deriv = ddump_deriving really_new_inst_infos extra_binds
230     in
231     --pprTrace "derived:\n" (ddump_deriv PprDebug) $
232
233     returnTc (listToBag really_new_inst_infos,
234               extra_binds,
235               ddump_deriv)
236   where
237     ddump_deriving :: [InstInfo] -> RenamedHsBinds -> (PprStyle -> Pretty)
238
239     ddump_deriving inst_infos extra_binds sty
240       = ppAboves ((map pp_info inst_infos) ++ [ppr sty extra_binds])
241       where
242         pp_info (InstInfo clas tvs ty inst_decl_theta _ _ _ mbinds _ _ _ _)
243           = ppAbove (ppr sty (mkSigmaTy tvs inst_decl_theta (mkDictTy clas ty)))
244                     (ppr sty mbinds)
245 \end{code}
246
247
248 %************************************************************************
249 %*                                                                      *
250 \subsection[TcDeriv-eqns]{Forming the equations}
251 %*                                                                      *
252 %************************************************************************
253
254 @makeDerivEqns@ fishes around to find the info about needed derived
255 instances.  Complicating factors:
256 \begin{itemize}
257 \item
258 We can only derive @Enum@ if the data type is an enumeration
259 type (all nullary data constructors).
260
261 \item
262 We can only derive @Ix@ if the data type is an enumeration {\em
263 or} has just one data constructor (e.g., tuples).
264 \end{itemize}
265
266 [See Appendix~E in the Haskell~1.2 report.] This code here deals w/
267 all those.
268
269 \begin{code}
270 makeDerivEqns :: TcM s [DerivEqn]
271
272 makeDerivEqns
273   = tcGetEnv                        `thenNF_Tc` \ env ->
274     tcLookupClassByKey evalClassKey `thenNF_Tc` \ eval_clas ->
275     let
276         tycons = filter isDataTyCon (getEnv_TyCons env)
277         -- ToDo: what about newtypes???
278         think_about_deriving = need_deriving eval_clas tycons
279     in
280     mapTc chk_out think_about_deriving `thenTc_`
281     let
282         (derive_these, _) = removeDups cmp_deriv think_about_deriving
283         eqns = map mk_eqn derive_these
284     in
285     returnTc eqns
286   where
287     ------------------------------------------------------------------
288     need_deriving :: Class -> [TyCon] -> [(Class, TyCon)]
289         -- find the tycons that have `deriving' clauses;
290         -- we handle the "every datatype in Eval" by
291         -- doing a dummy "deriving" for it.
292
293     need_deriving eval_clas tycons_to_consider
294       = foldr ( \ tycon acc ->
295                    let
296                         acc_plus = if isLocallyDefined tycon
297                                    then (eval_clas, tycon) : acc
298                                    else acc
299                    in
300                    case (tyConDerivings tycon) of
301                      [] -> acc_plus
302                      cs -> [ (clas,tycon) | clas <- cs ] ++ acc_plus
303               )
304               []
305               tycons_to_consider
306
307     ------------------------------------------------------------------
308     chk_out :: (Class, TyCon) -> TcM s ()
309     chk_out this_one@(clas, tycon)
310       = let
311             clas_key = classKey clas
312
313             is_enumeration = isEnumerationTyCon tycon
314             is_single_con  = maybeToBool (maybeTyConSingleCon tycon)
315
316             chk_clas clas_uniq clas_str cond
317               = if (clas_uniq == clas_key)
318                 then checkTc cond (derivingThingErr clas_str tycon)
319                 else returnTc ()
320         in
321             -- Are things OK for deriving Enum (if appropriate)?
322         chk_clas enumClassKey "Enum" is_enumeration `thenTc_`
323
324             -- Are things OK for deriving Bounded (if appropriate)?
325         chk_clas boundedClassKey "Bounded"
326                 (is_enumeration || is_single_con) `thenTc_`
327
328             -- Are things OK for deriving Ix (if appropriate)?
329         chk_clas ixClassKey "Ix.Ix" (is_enumeration || is_single_con)
330
331     ------------------------------------------------------------------
332     cmp_deriv :: (Class, TyCon) -> (Class, TyCon) -> TAG_
333     cmp_deriv (c1, t1) (c2, t2)
334       = (c1 `cmp` c2) `thenCmp` (t1 `cmp` t2)
335
336     ------------------------------------------------------------------
337     mk_eqn :: (Class, TyCon) -> DerivEqn
338         -- we swizzle the tyvars and datacons out of the tycon
339         -- to make the rest of the equation
340
341     mk_eqn (clas, tycon)
342       = (clas, tycon, tyvars, if_not_Eval constraints)
343       where
344         clas_key  = classKey clas
345         tyvars    = tyConTyVars tycon   -- ToDo: Do we need new tyvars ???
346         tyvar_tys = mkTyVarTys tyvars
347         data_cons = tyConDataCons tycon
348
349         if_not_Eval cs = if clas_key == evalClassKey then [] else cs
350
351         constraints = extra_constraints ++ concat (map mk_constraints data_cons)
352
353         -- "extra_constraints": see notes above about contexts on data decls
354         extra_constraints
355           | offensive_class = tyConTheta tycon
356           | otherwise       = []
357            where
358             offensive_class = clas_key `elem` needsDataDeclCtxtClassKeys
359
360         mk_constraints data_con
361            = [ (clas, arg_ty)
362              | arg_ty <- instd_arg_tys,
363                not (isPrimType arg_ty)  -- No constraints for primitive types
364              ]
365            where
366              instd_arg_tys  = dataConArgTys data_con tyvar_tys
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         -- iterateDeriv calculates the next batch of solutions,
405         -- compares it with the current one; finishes if they are the
406         -- same, otherwise recurses with the new solutions.
407
408     iterateDeriv :: [DerivSoln] ->TcM s [InstInfo]
409
410     iterateDeriv current_solns
411       =     -- Extend the inst info from the explicit instance decls
412             -- with the current set of solutions, giving a
413
414         add_solns inst_decl_infos_in orig_eqns current_solns
415                                 `thenTc` \ (new_inst_infos, inst_mapper) ->
416         let
417            class_to_inst_env cls = fst (inst_mapper cls)
418         in
419             -- Simplify each RHS
420
421         listTc [ tcSimplifyThetas class_to_inst_env [{-Nothing "given"-}] deriv_rhs
422                | (_,_,_,deriv_rhs) <- orig_eqns ]  `thenTc` \ next_solns ->
423
424             -- Canonicalise the solutions, so they compare nicely
425         let canonicalised_next_solns
426               = [ sortLt lt_rhs next_soln | next_soln <- next_solns ] in
427
428         if (current_solns `eq_solns` canonicalised_next_solns) then
429             returnTc new_inst_infos
430         else
431             iterateDeriv canonicalised_next_solns
432
433       where
434         ------------------------------------------------------------------
435         lt_rhs    r1 r2 = case cmp_rhs   r1 r2 of { LT_ -> True; _ -> False }
436         eq_solns  s1 s2 = case cmp_solns s1 s2 of { EQ_ -> True; _ -> False }
437         cmp_solns s1 s2 = cmpList (cmpList cmp_rhs) s1 s2
438         cmp_rhs (c1, TyVarTy tv1) (c2, TyVarTy tv2)
439           = (tv1 `cmp` tv2) `thenCmp` (c1 `cmp` c2)
440 #ifdef DEBUG
441         cmp_rhs other_1 other_2
442           = pprPanic# "tcDeriv:cmp_rhs:" (ppCat [ppr PprDebug other_1, ppr PprDebug other_2])
443 #endif
444
445 \end{code}
446
447 \begin{code}
448 add_solns :: Bag InstInfo                       -- The global, non-derived ones
449           -> [DerivEqn] -> [DerivSoln]
450           -> TcM s ([InstInfo],                 -- The new, derived ones
451                     InstanceMapper)
452     -- the eqns and solns move "in lockstep"; we have the eqns
453     -- because we need the LHS info for addClassInstance.
454
455 add_solns inst_infos_in eqns solns
456   = buildInstanceEnvs all_inst_infos `thenTc` \ inst_mapper ->
457     returnTc (new_inst_infos, inst_mapper)
458   where
459     new_inst_infos = zipWithEqual "add_solns" mk_deriv_inst_info eqns solns
460
461     all_inst_infos = inst_infos_in `unionBags` listToBag new_inst_infos
462
463     mk_deriv_inst_info (clas, tycon, tyvars, _) theta
464       = InstInfo clas tyvars (applyTyCon tycon (mkTyVarTys tyvars))
465                  theta
466                  (my_panic "dfun_theta")
467
468                  dummy_dfun_id
469
470                  (my_panic "const_meth_ids")
471                  (my_panic "binds")   (my_panic "from_here")
472                  (my_panic "modname") mkGeneratedSrcLoc
473                  (my_panic "upragmas")
474       where
475         dummy_dfun_id
476           = mkDictFunId bottom bottom bottom dummy_dfun_ty
477                         bottom bottom bottom bottom
478           where
479             bottom = panic "dummy_dfun_id"
480
481         dummy_dfun_ty = mkSigmaTy tyvars theta voidTy
482                 -- All we need from the dfun is its "theta" part, used during
483                 -- equation simplification (tcSimplifyThetas).  The final
484                 -- dfun_id will have the superclass dictionaries as arguments too,
485                 -- but that'll be added after the equations are solved.  For now,
486                 -- it's enough just to make a dummy dfun with the simple theta part.
487                 -- 
488                 -- The part after the theta is dummied here as voidTy; actually it's
489                 --      (C (T a b)), but it doesn't seem worth constructing it.
490                 -- We can't leave it as a panic because to get the theta part we
491                 -- have to run down the type!
492
493         my_panic str = pprPanic ("add_soln:"++str) (ppCat [ppChar ':', ppr PprDebug clas, ppr PprDebug tycon])
494 \end{code}
495
496 %************************************************************************
497 %*                                                                      *
498 \subsection[TcDeriv-normal-binds]{Bindings for the various classes}
499 %*                                                                      *
500 %************************************************************************
501
502 After all the trouble to figure out the required context for the
503 derived instance declarations, all that's left is to chug along to
504 produce them.  They will then be shoved into @tcInstDecls2@, which
505 will do all its usual business.
506
507 There are lots of possibilities for code to generate.  Here are
508 various general remarks.
509
510 PRINCIPLES:
511 \begin{itemize}
512 \item
513 We want derived instances of @Eq@ and @Ord@ (both v common) to be
514 ``you-couldn't-do-better-by-hand'' efficient.
515
516 \item
517 Deriving @Show@---also pretty common--- should also be reasonable good code.
518
519 \item
520 Deriving for the other classes isn't that common or that big a deal.
521 \end{itemize}
522
523 PRAGMATICS:
524
525 \begin{itemize}
526 \item
527 Deriving @Ord@ is done mostly with the 1.3 @compare@ method.
528
529 \item
530 Deriving @Eq@ also uses @compare@, if we're deriving @Ord@, too.
531
532 \item
533 We {\em normally} generate code only for the non-defaulted methods;
534 there are some exceptions for @Eq@ and (especially) @Ord@...
535
536 \item
537 Sometimes we use a @_con2tag_<tycon>@ function, which returns a data
538 constructor's numeric (@Int#@) tag.  These are generated by
539 @gen_tag_n_con_binds@, and the heuristic for deciding if one of
540 these is around is given by @hasCon2TagFun@.
541
542 The examples under the different sections below will make this
543 clearer.
544
545 \item
546 Much less often (really just for deriving @Ix@), we use a
547 @_tag2con_<tycon>@ function.  See the examples.
548
549 \item
550 We use the renamer!!!  Reason: we're supposed to be
551 producing @RenamedMonoBinds@ for the methods, but that means
552 producing correctly-uniquified code on the fly.  This is entirely
553 possible (the @TcM@ monad has a @UniqueSupply@), but it is painful.
554 So, instead, we produce @RdrNameMonoBinds@ then heave 'em through
555 the renamer.  What a great hack!
556 \end{itemize}
557
558 \begin{code}
559 gen_inst_info :: Module                 -- Module name
560               -> [RenamedFixityDecl]    -- all known fixities;
561                                         -- may be needed for Text
562               -> RnEnv                  -- lookup stuff for names we may use
563               -> InstInfo               -- the main stuff to work on
564               -> TcM s InstInfo         -- the gen'd (filled-in) "instance decl"
565
566 gen_inst_info modname fixities deriver_rn_env
567     (InstInfo clas tyvars ty inst_decl_theta _ _ _ _ _ _ locn _)
568   =
569         -- Generate the various instance-related Ids
570     mkInstanceRelatedIds
571                 True {-from_here-} locn modname
572                 NoInstancePragmas
573                 clas tyvars ty
574                 inst_decl_theta
575                 [{-no user pragmas-}]
576                         `thenTc` \ (dfun_id, dfun_theta, const_meth_ids) ->
577
578         -- Generate the bindings for the new instance declaration,
579         -- rename it, and check for errors
580     let
581         (tycon,_,_)  = --pprTrace "gen_inst_info:ty" (ppCat[ppr PprDebug clas, ppr PprDebug ty]) $
582                        getAppDataTyCon ty
583
584         proto_mbinds
585           = assoc "gen_inst_info:bad derived class"
586                 [(eqClassKey,      gen_Eq_binds)
587                 ,(ordClassKey,     gen_Ord_binds)
588                 ,(enumClassKey,    gen_Enum_binds)
589                 ,(evalClassKey,    gen_Eval_binds)
590                 ,(boundedClassKey, gen_Bounded_binds)
591                 ,(showClassKey,    gen_Show_binds fixities)
592                 ,(readClassKey,    gen_Read_binds fixities)
593                 ,(ixClassKey,      gen_Ix_binds)
594                 ]
595                 clas_key $ tycon
596     in
597 {-
598     let
599         ((qual, unqual, tc_qual, tc_unqual), stack) = deriver_rn_env
600     in
601     pprTrace "gen_inst:qual:"      (ppCat [ppBesides[ppPStr m,ppChar '.',ppPStr n] | (n,m) <- keysFM qual]) $
602     pprTrace "gen_inst:unqual:"    (ppCat (map ppPStr (keysFM unqual))) $
603     pprTrace "gen_inst:tc_qual:"   (ppCat [ppBesides[ppPStr m,ppChar '.',ppPStr n] | (n,m) <- keysFM tc_qual]) $
604     pprTrace "gen_inst:tc_unqual:" (ppCat (map ppPStr (keysFM tc_unqual))) $
605 -}
606     -- pprTrace "derived binds:" (ppr PprDebug proto_mbinds) $
607
608     rnMtoTcM deriver_rn_env (
609         setExtraRn emptyUFM{-no fixities-} $
610         rnMethodBinds clas_Name proto_mbinds
611     )                   `thenNF_Tc` \ (mbinds, errs) ->
612
613     if not (isEmptyBag errs) then
614         pprPanic "gen_inst_info:renamer errs!\n"
615                  (ppAbove (pprBagOfErrors PprDebug errs) (ppr PprDebug proto_mbinds))
616     else
617         -- All done
618     let
619         from_here = isLocallyDefined tycon      -- If so, then from here
620     in
621     returnTc (InstInfo clas tyvars ty inst_decl_theta
622                        dfun_theta dfun_id const_meth_ids
623                        (if from_here then mbinds else EmptyMonoBinds)
624                        from_here modname locn [])
625   where
626     clas_key  = classKey clas
627     clas_Name = RnImplicitClass (mkImplicitName clas_key (origName "gen_inst_info" clas))
628 \end{code}
629
630 %************************************************************************
631 %*                                                                      *
632 \subsection[TcGenDeriv-con2tag-tag2con]{Generating extra binds (@con2tag@ and @tag2con@)}
633 %*                                                                      *
634 %************************************************************************
635
636 data Foo ... = ...
637
638 con2tag_Foo :: Foo ... -> Int#
639 tag2con_Foo :: Int -> Foo ...   -- easier if Int, not Int#
640 maxtag_Foo  :: Int              -- ditto (NB: not unboxed)
641
642 \begin{code}
643 gen_tag_n_con_binds :: RnEnv
644                     -> [(RdrName, TyCon, TagThingWanted)]
645                     -> TcM s (RenamedHsBinds,
646                               RnEnv) -- input one with any new names added
647
648 gen_tag_n_con_binds rn_env nm_alist_etc
649   = 
650     let
651         -- We have the renamer's final "name funs" in our hands
652         -- (they were passed in).  So we can handle ProtoNames
653         -- that refer to anything "out there".  But our generated
654         -- code may also mention "con2tag" (etc.).  So we need
655         -- to augment to "name funs" to include those.
656
657         names_to_add = [ pn | (pn,_,_) <- nm_alist_etc ]
658     in
659     tcGetUniques (length names_to_add)  `thenNF_Tc` \ uniqs ->
660     let
661         pairs_to_add = [ case pn of { Qual pnm pnn ->
662                          (pn, mkRnName (mkTopLevName u (OrigName pnm pnn) mkGeneratedSrcLoc ExportAll [])) }
663                        | (pn,u) <- zipEqual "gen_tag..." names_to_add uniqs ]
664
665         deriver_rn_env
666           = if null names_to_add
667             then rn_env else added_rn_env
668
669         (added_rn_env, errs_bag)
670           = extendGlobalRnEnv rn_env pairs_to_add [{-no tycons-}]
671
672         ----------------
673         proto_mbind_list = map gen_tag_n_con_monobind nm_alist_etc
674         proto_mbinds     = foldr AndMonoBinds EmptyMonoBinds proto_mbind_list
675     in
676     ASSERT(isEmptyBag errs_bag)
677
678     rnMtoTcM deriver_rn_env (
679         setExtraRn emptyUFM{-no fixities-} $
680         rnTopBinds (SingleBind (RecBind proto_mbinds))
681     )                   `thenNF_Tc` \ (binds, errs) ->
682
683     if not (isEmptyBag errs) then
684         pprPanic "gen_tag_n_con_binds:renamer errs!\n"
685                  (ppAbove (pprBagOfErrors PprDebug errs) (ppr PprDebug binds))
686     else
687         returnTc (binds, deriver_rn_env)
688 \end{code}
689
690 %************************************************************************
691 %*                                                                      *
692 \subsection[TcDeriv-taggery-Names]{What con2tag/tag2con functions are available?}
693 %*                                                                      *
694 %************************************************************************
695
696 We have a @con2tag@ function for a tycon if:
697 \begin{itemize}
698 \item
699 We're deriving @Eq@ and the tycon has nullary data constructors.
700
701 \item
702 Or: we're deriving @Ord@ (unless single-constructor), @Enum@, @Ix@
703 (enum type only????)
704 \end{itemize}
705
706 We have a @tag2con@ function for a tycon if:
707 \begin{itemize}
708 \item
709 We're deriving @Enum@, or @Ix@ (enum type only???)
710 \end{itemize}
711
712 If we have a @tag2con@ function, we also generate a @maxtag@ constant.
713
714 \begin{code}
715 gen_taggery_Names :: [InstInfo]
716                   -> TcM s [(RdrName,   -- for an assoc list
717                              TyCon,     -- related tycon
718                              TagThingWanted)]
719
720 gen_taggery_Names inst_infos
721   = --pprTrace "gen_taggery:\n" (ppAboves [ppCat [ppr PprDebug c, ppr PprDebug t] | (c,t) <- all_CTs]) $
722     foldlTc do_con2tag []           tycons_of_interest `thenTc` \ names_so_far ->
723     foldlTc do_tag2con names_so_far tycons_of_interest
724   where
725     all_CTs = [ mk_CT c ty | (InstInfo c _ ty _ _ _ _ _ _ _ _ _) <- inst_infos ]
726                     
727     mk_CT c ty = (c, fst (getAppTyCon ty))
728
729     all_tycons = map snd all_CTs
730     (tycons_of_interest, _) = removeDups cmp all_tycons
731     
732     do_con2tag acc_Names tycon
733       = if (we_are_deriving eqClassKey tycon
734             && any isNullaryDataCon (tyConDataCons tycon))
735         || (we_are_deriving ordClassKey  tycon
736             && not (maybeToBool (maybeTyConSingleCon tycon)))
737         || (we_are_deriving enumClassKey tycon)
738         || (we_are_deriving ixClassKey   tycon)
739         then
740           returnTc ((con2tag_PN tycon, tycon, GenCon2Tag)
741                    : acc_Names)
742         else
743           returnTc acc_Names
744
745     do_tag2con acc_Names tycon
746       = if (we_are_deriving enumClassKey tycon)
747         || (we_are_deriving ixClassKey   tycon)
748         then
749           returnTc ( (tag2con_PN tycon, tycon, GenTag2Con)
750                    : (maxtag_PN  tycon, tycon, GenMaxTag)
751                    : acc_Names)
752         else
753           returnTc acc_Names
754
755     we_are_deriving clas_key tycon
756       = is_in_eqns clas_key tycon all_CTs
757       where
758         is_in_eqns clas_key tycon [] = False
759         is_in_eqns clas_key tycon ((c,t):cts)
760           =  (clas_key == classKey c && tycon == t)
761           || is_in_eqns clas_key tycon cts
762
763 \end{code}
764
765 \begin{code}
766 derivingThingErr :: String -> TyCon -> Error
767
768 derivingThingErr thing tycon sty
769   = ppHang (ppCat [ppStr "Can't make a derived instance of", ppStr thing])
770          4 (ppBesides [ppStr "for the type `", ppr sty tycon, ppStr "'"])
771 \end{code}