[project @ 2003-10-29 18:10:25 by simonpj]
[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(..), TyClDecl(..), MonoBinds(..),
14                           andMonoBindList )
15 import RdrHsSyn         ( RdrNameMonoBinds )
16 import RnHsSyn          ( RenamedHsBinds, RenamedTyClDecl, RenamedHsPred )
17 import CmdLineOpts      ( DynFlag(..) )
18
19 import Generics         ( mkGenericBinds )
20 import TcRnMonad
21 import TcEnv            ( newDFunName, 
22                           InstInfo(..), pprInstInfo, InstBindings(..),
23                           pprInstInfoDetails, tcLookupTyCon, tcExtendTyVarEnv
24                         )
25 import TcGenDeriv       -- Deriv stuff
26 import InstEnv          ( simpleDFunClassTyCon, extendInstEnv )
27 import TcHsType         ( tcHsPred )
28 import TcSimplify       ( tcSimplifyDeriv )
29
30 import RnBinds          ( rnMethodBinds, rnTopMonoBinds )
31 import RnEnv            ( bindLocalNames )
32 import TcRnMonad        ( thenM, returnM, mapAndUnzipM )
33 import HscTypes         ( DFunId, FixityEnv, typeEnvTyCons )
34
35 import BasicTypes       ( NewOrData(..) )
36 import Class            ( className, classArity, classKey, classTyVars, classSCTheta, Class )
37 import Subst            ( mkTyVarSubst, substTheta )
38 import ErrUtils         ( dumpIfSet_dyn )
39 import MkId             ( mkDictFunId )
40 import DataCon          ( dataConOrigArgTys, isNullaryDataCon, isExistentialDataCon )
41 import Maybes           ( catMaybes )
42 import Name             ( Name, getSrcLoc )
43 import Unique           ( Unique, getUnique )
44
45 import TyCon            ( tyConTyVars, tyConDataCons, tyConArity, 
46                           tyConTheta, isProductTyCon, isDataTyCon,
47                           isEnumerationTyCon, isRecursiveTyCon, TyCon
48                         )
49 import TcType           ( TcType, ThetaType, mkTyVarTy, mkTyVarTys, mkTyConApp, 
50                           getClassPredTys_maybe, tcTyConAppTyCon,
51                           isUnLiftedType, mkClassPred, tyVarsOfTypes, tcSplitFunTys, isTypeKind,
52                           tcEqTypes, tcSplitAppTys, mkAppTys, tcSplitDFunTy )
53 import Var              ( TyVar, tyVarKind, idType, varName )
54 import VarSet           ( mkVarSet, subVarSet )
55 import PrelNames
56 import Util             ( zipWithEqual, sortLt, notNull )
57 import ListSetOps       ( removeDups,  assoc )
58 import Outputable
59 \end{code}
60
61 %************************************************************************
62 %*                                                                      *
63 \subsection[TcDeriv-intro]{Introduction to how we do deriving}
64 %*                                                                      *
65 %************************************************************************
66
67 Consider
68
69         data T a b = C1 (Foo a) (Bar b)
70                    | C2 Int (T b a)
71                    | C3 (T a a)
72                    deriving (Eq)
73
74 [NOTE: See end of these comments for what to do with 
75         data (C a, D b) => T a b = ...
76 ]
77
78 We want to come up with an instance declaration of the form
79
80         instance (Ping a, Pong b, ...) => Eq (T a b) where
81                 x == y = ...
82
83 It is pretty easy, albeit tedious, to fill in the code "...".  The
84 trick is to figure out what the context for the instance decl is,
85 namely @Ping@, @Pong@ and friends.
86
87 Let's call the context reqd for the T instance of class C at types
88 (a,b, ...)  C (T a b).  Thus:
89
90         Eq (T a b) = (Ping a, Pong b, ...)
91
92 Now we can get a (recursive) equation from the @data@ decl:
93
94         Eq (T a b) = Eq (Foo a) u Eq (Bar b)    -- From C1
95                    u Eq (T b a) u Eq Int        -- From C2
96                    u Eq (T a a)                 -- From C3
97
98 Foo and Bar may have explicit instances for @Eq@, in which case we can
99 just substitute for them.  Alternatively, either or both may have
100 their @Eq@ instances given by @deriving@ clauses, in which case they
101 form part of the system of equations.
102
103 Now all we need do is simplify and solve the equations, iterating to
104 find the least fixpoint.  Notice that the order of the arguments can
105 switch around, as here in the recursive calls to T.
106
107 Let's suppose Eq (Foo a) = Eq a, and Eq (Bar b) = Ping b.
108
109 We start with:
110
111         Eq (T a b) = {}         -- The empty set
112
113 Next iteration:
114         Eq (T a b) = Eq (Foo a) u Eq (Bar b)    -- From C1
115                    u Eq (T b a) u Eq Int        -- From C2
116                    u Eq (T a a)                 -- From C3
117
118         After simplification:
119                    = Eq a u Ping b u {} u {} u {}
120                    = Eq a u Ping b
121
122 Next iteration:
123
124         Eq (T a b) = Eq (Foo a) u Eq (Bar b)    -- From C1
125                    u Eq (T b a) u Eq Int        -- From C2
126                    u Eq (T a a)                 -- From C3
127
128         After simplification:
129                    = Eq a u Ping b
130                    u (Eq b u Ping a)
131                    u (Eq a u Ping a)
132
133                    = Eq a u Ping b u Eq b u Ping a
134
135 The next iteration gives the same result, so this is the fixpoint.  We
136 need to make a canonical form of the RHS to ensure convergence.  We do
137 this by simplifying the RHS to a form in which
138
139         - the classes constrain only tyvars
140         - the list is sorted by tyvar (major key) and then class (minor key)
141         - no duplicates, of course
142
143 So, here are the synonyms for the ``equation'' structures:
144
145 \begin{code}
146 type DerivEqn = (Name, Class, TyCon, [TyVar], DerivRhs)
147                 -- The Name is the name for the DFun we'll build
148                 -- The tyvars bind all the variables in the RHS
149
150 pprDerivEqn (n,c,tc,tvs,rhs)
151   = parens (hsep [ppr n, ppr c, ppr tc, ppr tvs] <+> equals <+> ppr rhs)
152
153 type DerivRhs  = ThetaType
154 type DerivSoln = DerivRhs
155 \end{code}
156
157
158 [Data decl contexts] A note about contexts on data decls
159 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
160 Consider
161
162         data (RealFloat a) => Complex a = !a :+ !a deriving( Read )
163
164 We will need an instance decl like:
165
166         instance (Read a, RealFloat a) => Read (Complex a) where
167           ...
168
169 The RealFloat in the context is because the read method for Complex is bound
170 to construct a Complex, and doing that requires that the argument type is
171 in RealFloat. 
172
173 But this ain't true for Show, Eq, Ord, etc, since they don't construct
174 a Complex; they only take them apart.
175
176 Our approach: identify the offending classes, and add the data type
177 context to the instance decl.  The "offending classes" are
178
179         Read, Enum?
180
181 FURTHER NOTE ADDED March 2002.  In fact, Haskell98 now requires that
182 pattern matching against a constructor from a data type with a context
183 gives rise to the constraints for that context -- or at least the thinned
184 version.  So now all classes are "offending".
185
186
187
188 %************************************************************************
189 %*                                                                      *
190 \subsection[TcDeriv-driver]{Top-level function for \tr{derivings}}
191 %*                                                                      *
192 %************************************************************************
193
194 \begin{code}
195 tcDeriving  :: [RenamedTyClDecl]        -- All type constructors
196             -> TcM ([InstInfo],         -- The generated "instance decls"
197                     RenamedHsBinds)     -- Extra generated top-level bindings
198
199 tcDeriving tycl_decls
200   = recoverM (returnM ([], EmptyBinds)) $
201     getDOpts                    `thenM` \ dflags ->
202
203         -- Fish the "deriving"-related information out of the TcEnv
204         -- and make the necessary "equations".
205     makeDerivEqns tycl_decls                            `thenM` \ (ordinary_eqns, newtype_inst_info) ->
206     extendLocalInstEnv (map iDFunId newtype_inst_info)  $
207         -- Add the newtype-derived instances to the inst env
208         -- before tacking the "ordinary" ones
209
210     deriveOrdinaryStuff ordinary_eqns                   `thenM` \ (ordinary_inst_info, binds) ->
211     let
212         inst_info  = newtype_inst_info ++ ordinary_inst_info
213     in
214
215     ioToTcRn (dumpIfSet_dyn dflags Opt_D_dump_deriv "Derived instances" 
216              (ddump_deriving inst_info binds))          `thenM_`
217
218     returnM (inst_info, binds)
219
220   where
221     ddump_deriving :: [InstInfo] -> RenamedHsBinds -> SDoc
222     ddump_deriving inst_infos extra_binds
223       = vcat (map ppr_info inst_infos) $$ ppr extra_binds
224
225     ppr_info inst_info = pprInstInfo inst_info $$ 
226                          nest 4 (pprInstInfoDetails inst_info)
227         -- pprInstInfo doesn't print much: only the type
228
229 -----------------------------------------
230 deriveOrdinaryStuff []  -- Short cut
231   = returnM ([], EmptyBinds)
232
233 deriveOrdinaryStuff eqns
234   = do  {       -- Take the equation list and solve it, to deliver a list of
235                 -- solutions, a.k.a. the contexts for the instance decls
236                 -- required for the corresponding equations.
237         ; new_dfuns <- solveDerivEqns eqns
238
239         -- Generate the InstInfo for each dfun, 
240         -- plus any auxiliary bindings it needs
241         ; (inst_infos, aux_binds_s) <- mapAndUnzipM genInst new_dfuns
242
243         -- Generate any extra not-one-inst-decl-specific binds, 
244         -- notably "con2tag" and/or "tag2con" functions.  
245         ; extra_binds <- genTaggeryBinds new_dfuns
246
247         -- Generate the generic to/from functions from each type declaration
248         ; tcg_env <- getGblEnv
249         ; let gen_binds = mkGenericBinds (typeEnvTyCons (tcg_type_env tcg_env))
250
251         -- Rename these extra bindings, discarding warnings about unused bindings etc
252         ; (rn_binds, _fvs1) <- discardWarnings $
253                                rnTopMonoBinds (extra_binds `AndMonoBinds` gen_binds) []
254
255         ; let all_binds = rn_binds `ThenBinds` 
256                           foldr ThenBinds EmptyBinds aux_binds_s
257
258         -- Done
259         ; traceTc (text "tcDeriv" <+> vcat (map pprInstInfo inst_infos))
260         ; returnM (inst_infos, all_binds) }
261 \end{code}
262
263
264 %************************************************************************
265 %*                                                                      *
266 \subsection[TcDeriv-eqns]{Forming the equations}
267 %*                                                                      *
268 %************************************************************************
269
270 @makeDerivEqns@ fishes around to find the info about needed derived
271 instances.  Complicating factors:
272 \begin{itemize}
273 \item
274 We can only derive @Enum@ if the data type is an enumeration
275 type (all nullary data constructors).
276
277 \item
278 We can only derive @Ix@ if the data type is an enumeration {\em
279 or} has just one data constructor (e.g., tuples).
280 \end{itemize}
281
282 [See Appendix~E in the Haskell~1.2 report.] This code here deals w/
283 all those.
284
285 \begin{code}
286 makeDerivEqns :: [RenamedTyClDecl] 
287               -> TcM ([DerivEqn],       -- Ordinary derivings
288                       [InstInfo])       -- Special newtype derivings
289
290 makeDerivEqns tycl_decls
291   = mapAndUnzipM mk_eqn derive_these            `thenM` \ (maybe_ordinaries, maybe_newtypes) ->
292     returnM (catMaybes maybe_ordinaries, catMaybes maybe_newtypes)
293   where
294     ------------------------------------------------------------------
295     derive_these :: [(NewOrData, Name, RenamedHsPred)]
296         -- Find the (nd, TyCon, Pred) pairs that must be `derived'
297         -- NB: only source-language decls have deriving, no imported ones do
298     derive_these = [ (nd, tycon, pred) 
299                    | TyData {tcdND = nd, tcdName = tycon, tcdDerivs = Just preds} <- tycl_decls,
300                      pred <- preds ]
301
302     ------------------------------------------------------------------
303     mk_eqn :: (NewOrData, Name, RenamedHsPred) -> TcM (Maybe DerivEqn, Maybe InstInfo)
304         -- We swizzle the tyvars and datacons out of the tycon
305         -- to make the rest of the equation
306
307     mk_eqn (new_or_data, tycon_name, pred)
308       = tcLookupTyCon tycon_name                `thenM` \ tycon ->
309         addSrcLoc (getSrcLoc tycon)             $
310         addErrCtxt (derivCtxt Nothing tycon)    $
311         tcExtendTyVarEnv (tyConTyVars tycon)    $       -- Deriving preds may (now) mention
312                                                         -- the type variables for the type constructor
313         tcHsPred pred                           `thenM` \ pred' ->
314         case getClassPredTys_maybe pred' of
315            Nothing          -> bale_out (malformedPredErr tycon pred)
316            Just (clas, tys) -> doptM Opt_GlasgowExts                    `thenM` \ gla_exts ->
317                                mk_eqn_help gla_exts new_or_data tycon clas tys
318
319     ------------------------------------------------------------------
320     mk_eqn_help gla_exts DataType tycon clas tys
321       | Just err <- checkSideConditions gla_exts clas tycon tys
322       = bale_out (derivingThingErr clas tys tycon tyvars err)
323       | otherwise 
324       = new_dfun_name clas tycon         `thenM` \ dfun_name ->
325         returnM (Just (dfun_name, clas, tycon, tyvars, constraints), Nothing)
326       where
327         tyvars      = tyConTyVars tycon
328         constraints = extra_constraints ++ ordinary_constraints
329                  -- "extra_constraints": see note [Data decl contexts] above
330         extra_constraints = tyConTheta tycon
331
332         ordinary_constraints
333           | clas `hasKey` typeableClassKey      -- For the Typeable class, the constraints
334                                                 -- don't involve the constructor ags, only 
335                                                 -- the tycon tyvars
336                                                 -- e.g.   data T a b = ...
337                                                 -- we want
338                                                 --      instance (Typeable a, Typable b)
339                                                 --               => Typeable (T a b) where
340           = [mkClassPred clas [mkTyVarTy tv] | tv <- tyvars]
341           | otherwise
342           = [ mkClassPred clas [arg_ty] 
343             | data_con <- tyConDataCons tycon,
344               arg_ty   <- dataConOrigArgTys data_con,
345                         -- Use the same type variables
346                         -- as the type constructor,
347                         -- hence no need to instantiate
348               not (isUnLiftedType arg_ty)       -- No constraints for unlifted types?
349             ]
350
351     mk_eqn_help gla_exts NewType tycon clas tys
352       | can_derive_via_isomorphism && (gla_exts || standard_class gla_exts clas)
353       =         -- Go ahead and use the isomorphism
354            traceTc (text "newtype deriving:" <+> ppr tycon <+> ppr rep_tys)     `thenM_`
355            new_dfun_name clas tycon             `thenM` \ dfun_name ->
356            returnM (Nothing, Just (InstInfo { iDFunId = mk_dfun dfun_name,
357                                               iBinds = NewTypeDerived rep_tys }))
358       | standard_class gla_exts clas
359       = mk_eqn_help gla_exts DataType tycon clas tys    -- Go via bale-out route
360
361       | otherwise                               -- Non-standard instance
362       = bale_out (if gla_exts then      
363                         cant_derive_err -- Too hard
364                   else
365                         non_std_err)    -- Just complain about being a non-std instance
366       where
367         -- Here is the plan for newtype derivings.  We see
368         --        newtype T a1...an = T (t ak...an) deriving (.., C s1 .. sm, ...)
369         -- where aj...an do not occur free in t, and the (C s1 ... sm) is a 
370         -- *partial applications* of class C with the last parameter missing
371         --
372         -- We generate the instances
373         --       instance C s1 .. sm (t ak...aj) => C s1 .. sm (T a1...aj)
374         -- where T a1...aj is the partial application of the LHS of the correct kind
375         --
376         -- Running example: newtype T s a = MkT (ST s a) deriving( Monad )
377         --      instance Monad (ST s) => Monad (T s) where 
378         --        fail = coerce ... (fail @ ST s)
379
380         clas_tyvars = classTyVars clas
381         kind = tyVarKind (last clas_tyvars)
382                 -- Kind of the thing we want to instance
383                 --   e.g. argument kind of Monad, *->*
384
385         (arg_kinds, _) = tcSplitFunTys kind
386         n_args_to_drop = length arg_kinds       
387                 -- Want to drop 1 arg from (T s a) and (ST s a)
388                 -- to get       instance Monad (ST s) => Monad (T s)
389
390         -- Note [newtype representation]
391         -- We must not use newTyConRep to get the representation 
392         -- type, because that looks through all intermediate newtypes
393         -- To get the RHS of *this* newtype, just look at the data
394         -- constructor.  For example
395         --      newtype B = MkB Int
396         --      newtype A = MkA B deriving( Num )
397         -- We want the Num instance of B, *not* the Num instance of Int,
398         -- when making the Num instance of A!
399         tyvars                = tyConTyVars tycon
400         rep_ty                = head (dataConOrigArgTys (head (tyConDataCons tycon)))
401         (rep_fn, rep_ty_args) = tcSplitAppTys rep_ty
402
403         n_tyvars_to_keep = tyConArity tycon  - n_args_to_drop
404         tyvars_to_drop   = drop n_tyvars_to_keep tyvars
405         tyvars_to_keep   = take n_tyvars_to_keep tyvars
406
407         n_args_to_keep = length rep_ty_args - n_args_to_drop
408         args_to_drop   = drop n_args_to_keep rep_ty_args
409         args_to_keep   = take n_args_to_keep rep_ty_args
410
411         rep_tys  = tys ++ [mkAppTys rep_fn args_to_keep]
412         rep_pred = mkClassPred clas rep_tys
413                 -- rep_pred is the representation dictionary, from where
414                 -- we are gong to get all the methods for the newtype dictionary
415
416         inst_tys = (tys ++ [mkTyConApp tycon (mkTyVarTys tyvars_to_keep)])
417                 -- The 'tys' here come from the partial application
418                 -- in the deriving clause. The last arg is the new
419                 -- instance type.
420
421                 -- We must pass the superclasses; the newtype might be an instance
422                 -- of them in a different way than the representation type
423                 -- E.g.         newtype Foo a = Foo a deriving( Show, Num, Eq )
424                 -- Then the Show instance is not done via isomprphism; it shows
425                 --      Foo 3 as "Foo 3"
426                 -- The Num instance is derived via isomorphism, but the Show superclass
427                 -- dictionary must the Show instance for Foo, *not* the Show dictionary
428                 -- gotten from the Num dictionary. So we must build a whole new dictionary
429                 -- not just use the Num one.  The instance we want is something like:
430                 --      instance (Num a, Show (Foo a), Eq (Foo a)) => Num (Foo a) where
431                 --              (+) = ((+)@a)
432                 --              ...etc...
433                 -- There's no 'corece' needed because after the type checker newtypes
434                 -- are transparent.
435
436         sc_theta = substTheta (mkTyVarSubst clas_tyvars inst_tys)
437                               (classSCTheta clas)
438
439                 -- If there are no tyvars, there's no need
440                 -- to abstract over the dictionaries we need
441         dict_args | null tyvars = []
442                   | otherwise   = rep_pred : sc_theta
443
444                 -- Finally! Here's where we build the dictionary Id
445         mk_dfun dfun_name = mkDictFunId dfun_name tyvars dict_args clas inst_tys
446
447         -------------------------------------------------------------------
448         --  Figuring out whether we can only do this newtype-deriving thing
449
450         right_arity = length tys + 1 == classArity clas
451
452                 -- Never derive Read,Show,Typeable,Data this way 
453         non_iso_classes = [readClassKey, showClassKey, typeableClassKey, dataClassKey]
454         can_derive_via_isomorphism
455            =  not (getUnique clas `elem` non_iso_classes)
456            && right_arity                       -- Well kinded;
457                                                 -- eg not: newtype T ... deriving( ST )
458                                                 --      because ST needs *2* type params
459            && n_tyvars_to_keep >= 0             -- Type constructor has right kind:
460                                                 -- eg not: newtype T = T Int deriving( Monad )
461            && n_args_to_keep   >= 0             -- Rep type has right kind: 
462                                                 -- eg not: newtype T a = T Int deriving( Monad )
463            && eta_ok                            -- Eta reduction works
464            && not (isRecursiveTyCon tycon)      -- Does not work for recursive tycons:
465                                                 --      newtype A = MkA [A]
466                                                 -- Don't want
467                                                 --      instance Eq [A] => Eq A !!
468
469                         -- Here's a recursive newtype that's actually OK
470                         --      newtype S1 = S1 [T1 ()]
471                         --      newtype T1 a = T1 (StateT S1 IO a ) deriving( Monad )
472                         -- It's currently rejected.  Oh well.
473
474         -- Check that eta reduction is OK
475         --      (a) the dropped-off args are identical
476         --      (b) the remaining type args mention 
477         --          only the remaining type variables
478         eta_ok = (args_to_drop `tcEqTypes` mkTyVarTys tyvars_to_drop)
479               && (tyVarsOfTypes args_to_keep `subVarSet` mkVarSet tyvars_to_keep) 
480
481         cant_derive_err = derivingThingErr clas tys tycon tyvars_to_keep
482                                 (vcat [ptext SLIT("even with cunning newtype deriving:"),
483                                         if isRecursiveTyCon tycon then
484                                           ptext SLIT("the newtype is recursive")
485                                         else empty,
486                                         if not right_arity then 
487                                           quotes (ppr (mkClassPred clas tys)) <+> ptext SLIT("does not have arity 1")
488                                         else empty,
489                                         if not (n_tyvars_to_keep >= 0) then 
490                                           ptext SLIT("the type constructor has wrong kind")
491                                         else if not (n_args_to_keep >= 0) then
492                                           ptext SLIT("the representation type has wrong kind")
493                                         else if not eta_ok then 
494                                           ptext SLIT("the eta-reduction property does not hold")
495                                         else empty
496                                       ])
497
498         non_std_err = derivingThingErr clas tys tycon tyvars_to_keep
499                                 (vcat [non_std_why clas,
500                                        ptext SLIT("Try -fglasgow-exts for GHC's newtype-deriving extension")])
501
502     bale_out err = addErrTc err `thenM_` returnM (Nothing, Nothing) 
503     standard_class gla_exts clas =  key `elem` derivableClassKeys
504                                  || (gla_exts && (key == typeableClassKey || key == dataClassKey))
505         where
506           key = classKey clas
507
508
509
510
511 new_dfun_name clas tycon        -- Just a simple wrapper
512   = newDFunName clas [mkTyConApp tycon []] (getSrcLoc tycon)
513         -- The type passed to newDFunName is only used to generate
514         -- a suitable string; hence the empty type arg list
515
516 ------------------------------------------------------------------
517 -- Check side conditions that dis-allow derivability for particular classes
518 -- This is *apart* from the newtype-deriving mechanism
519
520 checkSideConditions :: Bool -> Class -> TyCon -> [TcType] -> Maybe SDoc
521 checkSideConditions gla_exts clas tycon tys
522   | notNull tys 
523   = Just ty_args_why    -- e.g. deriving( Foo s )
524   | otherwise
525   = case [cond | (key,cond) <- sideConditions, key == getUnique clas] of
526         []     -> Just (non_std_why clas)
527         [cond] -> cond (gla_exts, tycon)
528         other  -> pprPanic "checkSideConditions" (ppr clas)
529   where
530     ty_args_why      = quotes (ppr (mkClassPred clas tys)) <+> ptext SLIT("is not a class")
531
532 non_std_why clas = quotes (ppr clas) <+> ptext SLIT("is not a derivable class")
533
534 sideConditions :: [(Unique, Condition)]
535 sideConditions
536   = [   (eqClassKey,       cond_std),
537         (ordClassKey,      cond_std),
538         (readClassKey,     cond_std),
539         (showClassKey,     cond_std),
540         (enumClassKey,     cond_std `andCond` cond_isEnumeration),
541         (ixClassKey,       cond_std `andCond` (cond_isEnumeration `orCond` cond_isProduct)),
542         (boundedClassKey,  cond_std `andCond` (cond_isEnumeration `orCond` cond_isProduct)),
543         (typeableClassKey, cond_glaExts `andCond` cond_allTypeKind),
544         (dataClassKey,     cond_glaExts `andCond` cond_std)
545     ]
546
547 type Condition = (Bool, TyCon) -> Maybe SDoc    -- Nothing => OK
548
549 orCond :: Condition -> Condition -> Condition
550 orCond c1 c2 tc 
551   = case c1 tc of
552         Nothing -> Nothing              -- c1 succeeds
553         Just x  -> case c2 tc of        -- c1 fails
554                      Nothing -> Nothing
555                      Just y  -> Just (x $$ ptext SLIT("  and") $$ y)
556                                         -- Both fail
557
558 andCond c1 c2 tc = case c1 tc of
559                      Nothing -> c2 tc   -- c1 succeeds
560                      Just x  -> Just x  -- c1 fails
561
562 cond_std :: Condition
563 cond_std (gla_exts, tycon)
564   | any isExistentialDataCon data_cons  = Just existential_why     
565   | null data_cons                      = Just no_cons_why
566   | otherwise                           = Nothing
567   where
568     data_cons       = tyConDataCons tycon
569     no_cons_why     = quotes (ppr tycon) <+> ptext SLIT("has no data constructors")
570     existential_why = quotes (ppr tycon) <+> ptext SLIT("has existentially-quantified constructor(s)")
571   
572 cond_isEnumeration :: Condition
573 cond_isEnumeration (gla_exts, tycon)
574   | isEnumerationTyCon tycon = Nothing
575   | otherwise                = Just why
576   where
577     why = quotes (ppr tycon) <+> ptext SLIT("has non-nullary constructors")
578
579 cond_isProduct :: Condition
580 cond_isProduct (gla_exts, tycon)
581   | isProductTyCon tycon = Nothing
582   | otherwise            = Just why
583   where
584     why = quotes (ppr tycon) <+> ptext SLIT("has more than one constructor")
585
586 cond_allTypeKind :: Condition
587 cond_allTypeKind (gla_exts, tycon)
588   | all (isTypeKind . tyVarKind) (tyConTyVars tycon) = Nothing
589   | otherwise                                        = Just why
590   where
591     why  = quotes (ppr tycon) <+> ptext SLIT("is parameterised over arguments of kind other than `*'")
592
593 cond_glaExts :: Condition
594 cond_glaExts (gla_exts, tycon) | gla_exts  = Nothing
595                                | otherwise = Just why
596   where
597     why  = ptext SLIT("You need -fglasgow-exts to derive an instance for this class")
598 \end{code}
599
600 %************************************************************************
601 %*                                                                      *
602 \subsection[TcDeriv-fixpoint]{Finding the fixed point of \tr{deriving} equations}
603 %*                                                                      *
604 %************************************************************************
605
606 A ``solution'' (to one of the equations) is a list of (k,TyVarTy tv)
607 terms, which is the final correct RHS for the corresponding original
608 equation.
609 \begin{itemize}
610 \item
611 Each (k,TyVarTy tv) in a solution constrains only a type
612 variable, tv.
613
614 \item
615 The (k,TyVarTy tv) pairs in a solution are canonically
616 ordered by sorting on type varible, tv, (major key) and then class, k,
617 (minor key)
618 \end{itemize}
619
620 \begin{code}
621 solveDerivEqns :: [DerivEqn]
622                -> TcM [DFunId]  -- Solns in same order as eqns.
623                                 -- This bunch is Absolutely minimal...
624
625 solveDerivEqns orig_eqns
626   = iterateDeriv 1 initial_solutions
627   where
628         -- The initial solutions for the equations claim that each
629         -- instance has an empty context; this solution is certainly
630         -- in canonical form.
631     initial_solutions :: [DerivSoln]
632     initial_solutions = [ [] | _ <- orig_eqns ]
633
634     ------------------------------------------------------------------
635         -- iterateDeriv calculates the next batch of solutions,
636         -- compares it with the current one; finishes if they are the
637         -- same, otherwise recurses with the new solutions.
638         -- It fails if any iteration fails
639     iterateDeriv :: Int -> [DerivSoln] ->TcM [DFunId]
640     iterateDeriv n current_solns
641       | n > 20  -- Looks as if we are in an infinite loop
642                 -- This can happen if we have -fallow-undecidable-instances
643                 -- (See TcSimplify.tcSimplifyDeriv.)
644       = pprPanic "solveDerivEqns: probable loop" 
645                  (vcat (map pprDerivEqn orig_eqns) $$ ppr current_solns)
646       | otherwise
647       = let 
648             dfuns = zipWithEqual "add_solns" mk_deriv_dfun orig_eqns current_solns
649         in
650         checkNoErrs (
651                   -- Extend the inst info from the explicit instance decls
652                   -- with the current set of solutions, and simplify each RHS
653             extendLocalInstEnv dfuns $
654             mappM gen_soln orig_eqns
655         )                               `thenM` \ new_solns ->
656         if (current_solns == new_solns) then
657             returnM dfuns
658         else
659             iterateDeriv (n+1) new_solns
660
661     ------------------------------------------------------------------
662
663     gen_soln (_, clas, tc,tyvars,deriv_rhs)
664       = addSrcLoc (getSrcLoc tc)                $
665         addErrCtxt (derivCtxt (Just clas) tc)   $
666         tcSimplifyDeriv tyvars deriv_rhs        `thenM` \ theta ->
667         returnM (sortLt (<) theta)      -- Canonicalise before returning the soluction
668
669 mk_deriv_dfun (dfun_name, clas, tycon, tyvars, _) theta
670   = mkDictFunId dfun_name tyvars theta
671                 clas [mkTyConApp tycon (mkTyVarTys tyvars)] 
672
673 extendLocalInstEnv :: [DFunId] -> TcM a -> TcM a
674 -- Add new locall-defined instances; don't bother to check
675 -- for functional dependency errors -- that'll happen in TcInstDcls
676 extendLocalInstEnv dfuns thing_inside
677  = do { env <- getGblEnv
678       ; let  inst_env' = foldl extendInstEnv (tcg_inst_env env) dfuns 
679              env'      = env { tcg_inst_env = inst_env' }
680       ; setGblEnv env' thing_inside }
681 \end{code}
682
683 %************************************************************************
684 %*                                                                      *
685 \subsection[TcDeriv-normal-binds]{Bindings for the various classes}
686 %*                                                                      *
687 %************************************************************************
688
689 After all the trouble to figure out the required context for the
690 derived instance declarations, all that's left is to chug along to
691 produce them.  They will then be shoved into @tcInstDecls2@, which
692 will do all its usual business.
693
694 There are lots of possibilities for code to generate.  Here are
695 various general remarks.
696
697 PRINCIPLES:
698 \begin{itemize}
699 \item
700 We want derived instances of @Eq@ and @Ord@ (both v common) to be
701 ``you-couldn't-do-better-by-hand'' efficient.
702
703 \item
704 Deriving @Show@---also pretty common--- should also be reasonable good code.
705
706 \item
707 Deriving for the other classes isn't that common or that big a deal.
708 \end{itemize}
709
710 PRAGMATICS:
711
712 \begin{itemize}
713 \item
714 Deriving @Ord@ is done mostly with the 1.3 @compare@ method.
715
716 \item
717 Deriving @Eq@ also uses @compare@, if we're deriving @Ord@, too.
718
719 \item
720 We {\em normally} generate code only for the non-defaulted methods;
721 there are some exceptions for @Eq@ and (especially) @Ord@...
722
723 \item
724 Sometimes we use a @_con2tag_<tycon>@ function, which returns a data
725 constructor's numeric (@Int#@) tag.  These are generated by
726 @gen_tag_n_con_binds@, and the heuristic for deciding if one of
727 these is around is given by @hasCon2TagFun@.
728
729 The examples under the different sections below will make this
730 clearer.
731
732 \item
733 Much less often (really just for deriving @Ix@), we use a
734 @_tag2con_<tycon>@ function.  See the examples.
735
736 \item
737 We use the renamer!!!  Reason: we're supposed to be
738 producing @RenamedMonoBinds@ for the methods, but that means
739 producing correctly-uniquified code on the fly.  This is entirely
740 possible (the @TcM@ monad has a @UniqueSupply@), but it is painful.
741 So, instead, we produce @RdrNameMonoBinds@ then heave 'em through
742 the renamer.  What a great hack!
743 \end{itemize}
744
745 \begin{code}
746 -- Generate the InstInfo for the required instance,
747 -- plus any auxiliary bindings required
748 genInst :: DFunId -> TcM (InstInfo, RenamedHsBinds)
749 genInst dfun
750   = getFixityEnv                `thenM` \ fix_env -> 
751     let
752         (tyvars,_,clas,[ty])    = tcSplitDFunTy (idType dfun)
753         clas_nm                 = className clas
754         tycon                   = tcTyConAppTyCon ty 
755         (meth_binds, aux_binds) = assoc "gen_bind:bad derived class"
756                                   gen_list (getUnique clas) fix_env tycon
757     in
758         -- Rename the auxiliary bindings (if any)
759     rnTopMonoBinds aux_binds []                 `thenM` \ (rn_aux_binds, _dus) ->
760     
761         -- Bring the right type variables into 
762         -- scope, and rename the method binds
763     bindLocalNames (map varName tyvars)         $
764     rnMethodBinds clas_nm [] meth_binds         `thenM` \ (rn_meth_binds, _fvs) ->
765
766         -- Build the InstInfo
767     returnM (InstInfo { iDFunId = dfun, iBinds = VanillaInst rn_meth_binds [] }, 
768              rn_aux_binds)
769
770 gen_list :: [(Unique, FixityEnv -> TyCon -> (RdrNameMonoBinds, RdrNameMonoBinds))]
771 gen_list = [(eqClassKey,      no_aux_binds (ignore_fix_env gen_Eq_binds))
772            ,(ordClassKey,     no_aux_binds (ignore_fix_env gen_Ord_binds))
773            ,(enumClassKey,    no_aux_binds (ignore_fix_env gen_Enum_binds))
774            ,(boundedClassKey, no_aux_binds (ignore_fix_env gen_Bounded_binds))
775            ,(ixClassKey,      no_aux_binds (ignore_fix_env gen_Ix_binds))
776            ,(typeableClassKey,no_aux_binds (ignore_fix_env gen_Typeable_binds))
777            ,(showClassKey,    no_aux_binds gen_Show_binds)
778            ,(readClassKey,    no_aux_binds gen_Read_binds)
779            ,(dataClassKey,    gen_Data_binds)
780            ]
781
782   -- no_aux_binds is used for generators that don't 
783   -- need to produce any auxiliary bindings
784 no_aux_binds f fix_env tc = (f fix_env tc, EmptyMonoBinds)
785 ignore_fix_env f fix_env tc = f tc
786 \end{code}
787
788
789 %************************************************************************
790 %*                                                                      *
791 \subsection[TcDeriv-taggery-Names]{What con2tag/tag2con functions are available?}
792 %*                                                                      *
793 %************************************************************************
794
795
796 data Foo ... = ...
797
798 con2tag_Foo :: Foo ... -> Int#
799 tag2con_Foo :: Int -> Foo ...   -- easier if Int, not Int#
800 maxtag_Foo  :: Int              -- ditto (NB: not unlifted)
801
802
803 We have a @con2tag@ function for a tycon if:
804 \begin{itemize}
805 \item
806 We're deriving @Eq@ and the tycon has nullary data constructors.
807
808 \item
809 Or: we're deriving @Ord@ (unless single-constructor), @Enum@, @Ix@
810 (enum type only????)
811 \end{itemize}
812
813 We have a @tag2con@ function for a tycon if:
814 \begin{itemize}
815 \item
816 We're deriving @Enum@, or @Ix@ (enum type only???)
817 \end{itemize}
818
819 If we have a @tag2con@ function, we also generate a @maxtag@ constant.
820
821 \begin{code}
822 genTaggeryBinds :: [DFunId] -> TcM RdrNameMonoBinds
823 genTaggeryBinds dfuns
824   = do  { names_so_far <- foldlM do_con2tag []           tycons_of_interest
825         ; nm_alist_etc <- foldlM do_tag2con names_so_far tycons_of_interest
826         ; return (andMonoBindList (map gen_tag_n_con_monobind nm_alist_etc)) }
827   where
828     all_CTs = map simpleDFunClassTyCon dfuns
829     all_tycons              = map snd all_CTs
830     (tycons_of_interest, _) = removeDups compare all_tycons
831     
832     do_con2tag acc_Names tycon
833       | isDataTyCon tycon &&
834         ((we_are_deriving eqClassKey tycon
835             && any isNullaryDataCon (tyConDataCons tycon))
836          || (we_are_deriving ordClassKey  tycon
837             && not (isProductTyCon tycon))
838          || (we_are_deriving enumClassKey tycon)
839          || (we_are_deriving ixClassKey   tycon))
840         
841       = returnM ((con2tag_RDR tycon, tycon, GenCon2Tag)
842                    : acc_Names)
843       | otherwise
844       = returnM acc_Names
845
846     do_tag2con acc_Names tycon
847       | isDataTyCon tycon &&
848          (we_are_deriving enumClassKey tycon ||
849           we_are_deriving ixClassKey   tycon
850           && isEnumerationTyCon tycon)
851       = returnM ( (tag2con_RDR tycon, tycon, GenTag2Con)
852                  : (maxtag_RDR  tycon, tycon, GenMaxTag)
853                  : acc_Names)
854       | otherwise
855       = returnM acc_Names
856
857     we_are_deriving clas_key tycon
858       = is_in_eqns clas_key tycon all_CTs
859       where
860         is_in_eqns clas_key tycon [] = False
861         is_in_eqns clas_key tycon ((c,t):cts)
862           =  (clas_key == classKey c && tycon == t)
863           || is_in_eqns clas_key tycon cts
864 \end{code}
865
866 \begin{code}
867 derivingThingErr clas tys tycon tyvars why
868   = sep [hsep [ptext SLIT("Can't make a derived instance of"), quotes (ppr pred)],
869          parens why]
870   where
871     pred = mkClassPred clas (tys ++ [mkTyConApp tycon (mkTyVarTys tyvars)])
872
873 malformedPredErr tycon pred = ptext SLIT("Illegal deriving item") <+> ppr pred
874
875 derivCtxt :: Maybe Class -> TyCon -> SDoc
876 derivCtxt maybe_cls tycon
877   = ptext SLIT("When deriving") <+> cls <+> ptext SLIT("for type") <+> quotes (ppr tycon)
878   where
879     cls = case maybe_cls of
880             Nothing -> ptext SLIT("instances")
881             Just c  -> ptext SLIT("the") <+> quotes (ppr c) <+> ptext SLIT("instance")
882 \end{code}
883