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