[project @ 2004-04-02 16:46:57 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
14 import CmdLineOpts      ( DynFlag(..) )
15
16 import Generics         ( mkTyConGenericBinds )
17 import TcRnMonad
18 import TcEnv            ( newDFunName, pprInstInfoDetails, 
19                           InstInfo(..), InstBindings(..),
20                           tcLookupClass, tcLookupTyCon, tcExtendTyVarEnv
21                         )
22 import TcGenDeriv       -- Deriv stuff
23 import InstEnv          ( simpleDFunClassTyCon, extendInstEnv )
24 import TcHsType         ( tcHsDeriv )
25 import TcSimplify       ( tcSimplifyDeriv )
26
27 import RnBinds          ( rnMethodBinds, rnTopBinds )
28 import RnEnv            ( bindLocalNames )
29 import TcRnMonad        ( thenM, returnM, mapAndUnzipM )
30 import HscTypes         ( DFunId, FixityEnv )
31
32 import Class            ( className, classArity, classKey, classTyVars, classSCTheta, Class )
33 import Subst            ( mkTyVarSubst, substTheta )
34 import ErrUtils         ( dumpIfSet_dyn )
35 import MkId             ( mkDictFunId )
36 import DataCon          ( isNullaryDataCon, isExistentialDataCon, dataConOrigArgTys )
37 import Maybes           ( catMaybes )
38 import RdrName          ( RdrName )
39 import Name             ( Name, getSrcLoc )
40 import NameSet          ( NameSet, emptyNameSet, duDefs )
41 import Unique           ( Unique, getUnique )
42 import Kind             ( splitKindFunTys )
43 import TyCon            ( tyConTyVars, tyConDataCons, tyConArity, tyConHasGenerics,
44                           tyConTheta, isProductTyCon, isDataTyCon, newTyConRhs,
45                           isEnumerationTyCon, isRecursiveTyCon, TyCon
46                         )
47 import TcType           ( TcType, ThetaType, mkTyVarTys, mkTyConApp, 
48                           tcSplitForAllTys, tcSplitPredTy_maybe, getClassPredTys_maybe, tcTyConAppTyCon,
49                           isUnLiftedType, mkClassPred, tyVarsOfTypes, isArgTypeKind,
50                           tcEqTypes, tcSplitAppTys, mkAppTys, tcSplitDFunTy )
51 import Var              ( TyVar, tyVarKind, idType, varName )
52 import VarSet           ( mkVarSet, subVarSet )
53 import PrelNames
54 import SrcLoc           ( srcLocSpan, Located(..) )
55 import Util             ( zipWithEqual, sortLt, notNull )
56 import ListSetOps       ( removeDups,  assocMaybe )
57 import Outputable
58 import Bag
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 [Newtype deriving]
187 ~~~~~~~~~~~~~~~~~~
188 Consider this:
189     class C a b
190     instance C [a] Char
191     newtype T = T Char deriving( C [a] )
192
193 Notice the free 'a' in the deriving.  We have to fill this out to 
194     newtype T = T Char deriving( forall a. C [a] )
195
196 And then translate it to:
197     instance C [a] Char => C [a] T where ...
198     
199         
200
201
202 %************************************************************************
203 %*                                                                      *
204 \subsection[TcDeriv-driver]{Top-level function for \tr{derivings}}
205 %*                                                                      *
206 %************************************************************************
207
208 \begin{code}
209 tcDeriving  :: [LTyClDecl Name] -- All type constructors
210             -> TcM ([InstInfo],         -- The generated "instance decls"
211                     [HsBindGroup Name], -- Extra generated top-level bindings
212                     NameSet)            -- Binders to keep alive
213
214 tcDeriving tycl_decls
215   = recoverM (returnM ([], [], emptyNameSet)) $
216     do  {       -- Fish the "deriving"-related information out of the TcEnv
217                 -- and make the necessary "equations".
218         ; (ordinary_eqns, newtype_inst_info) <- makeDerivEqns tycl_decls
219
220         ; (ordinary_inst_info, deriv_binds) 
221                 <- extendLocalInstEnv (map iDFunId newtype_inst_info)  $
222                    deriveOrdinaryStuff ordinary_eqns
223                 -- Add the newtype-derived instances to the inst env
224                 -- before tacking the "ordinary" ones
225
226         -- Generate the generic to/from functions from each type declaration
227         ; gen_binds <- mkGenericBinds tycl_decls
228         ; let inst_info  = newtype_inst_info ++ ordinary_inst_info
229
230         -- Rename these extra bindings, discarding warnings about unused bindings etc
231         -- Set -fglasgow exts so that we can have type signatures in patterns,
232         -- which is used in the generic binds
233         ; (rn_binds, gen_bndrs) 
234                 <- discardWarnings $ setOptM Opt_GlasgowExts $ do
235                         { (rn_deriv, _dus1) <- rnTopBinds deriv_binds []
236                         ; (rn_gen, dus_gen) <- rnTopBinds gen_binds   []
237                         ; return (rn_deriv ++ rn_gen, duDefs dus_gen) }
238
239
240         ; dflags <- getDOpts
241         ; ioToTcRn (dumpIfSet_dyn dflags Opt_D_dump_deriv "Derived instances" 
242                    (ddump_deriving inst_info rn_binds))
243
244         ; returnM (inst_info, rn_binds, gen_bndrs)
245         }
246   where
247     ddump_deriving :: [InstInfo] -> [HsBindGroup Name] -> SDoc
248     ddump_deriving inst_infos extra_binds
249       = vcat (map pprInstInfoDetails inst_infos) $$ vcat (map ppr extra_binds)
250
251 -----------------------------------------
252 deriveOrdinaryStuff []  -- Short cut
253   = returnM ([], emptyBag)
254
255 deriveOrdinaryStuff eqns
256   = do  {       -- Take the equation list and solve it, to deliver a list of
257                 -- solutions, a.k.a. the contexts for the instance decls
258                 -- required for the corresponding equations.
259         ; new_dfuns <- solveDerivEqns eqns
260
261         -- Generate the InstInfo for each dfun, 
262         -- plus any auxiliary bindings it needs
263         ; (inst_infos, aux_binds_s) <- mapAndUnzipM genInst new_dfuns
264
265         -- Generate any extra not-one-inst-decl-specific binds, 
266         -- notably "con2tag" and/or "tag2con" functions.  
267         ; extra_binds <- genTaggeryBinds new_dfuns
268
269         -- Done
270         ; returnM (inst_infos, unionManyBags (extra_binds : aux_binds_s))
271    }
272
273 -----------------------------------------
274 mkGenericBinds tycl_decls
275   = do  { tcs <- mapM tcLookupTyCon 
276                         [ tc_name | 
277                           L _ (TyData { tcdLName = L _ tc_name }) <- tycl_decls]
278                 -- We are only interested in the data type declarations
279         ; return (unionManyBags [ mkTyConGenericBinds tc | 
280                                   tc <- tcs, tyConHasGenerics tc ]) }
281                 -- And then only in the ones whose 'has-generics' flag is on
282 \end{code}
283
284
285 %************************************************************************
286 %*                                                                      *
287 \subsection[TcDeriv-eqns]{Forming the equations}
288 %*                                                                      *
289 %************************************************************************
290
291 @makeDerivEqns@ fishes around to find the info about needed derived
292 instances.  Complicating factors:
293 \begin{itemize}
294 \item
295 We can only derive @Enum@ if the data type is an enumeration
296 type (all nullary data constructors).
297
298 \item
299 We can only derive @Ix@ if the data type is an enumeration {\em
300 or} has just one data constructor (e.g., tuples).
301 \end{itemize}
302
303 [See Appendix~E in the Haskell~1.2 report.] This code here deals w/
304 all those.
305
306 \begin{code}
307 makeDerivEqns :: [LTyClDecl Name] 
308               -> TcM ([DerivEqn],       -- Ordinary derivings
309                       [InstInfo])       -- Special newtype derivings
310
311 makeDerivEqns tycl_decls
312   = mapAndUnzipM mk_eqn derive_these            `thenM` \ (maybe_ordinaries, maybe_newtypes) ->
313     returnM (catMaybes maybe_ordinaries, catMaybes maybe_newtypes)
314   where
315     ------------------------------------------------------------------
316     derive_these :: [(NewOrData, Name, LHsType Name)]
317         -- Find the (nd, TyCon, Pred) pairs that must be `derived'
318     derive_these = [ (nd, tycon, pred) 
319                    | L _ (TyData { tcdND = nd, tcdLName = L _ tycon, 
320                                   tcdDerivs = Just preds }) <- tycl_decls,
321                      pred <- preds ]
322
323     ------------------------------------------------------------------
324     mk_eqn :: (NewOrData, Name, LHsType Name) -> TcM (Maybe DerivEqn, Maybe InstInfo)
325         -- We swizzle the tyvars and datacons out of the tycon
326         -- to make the rest of the equation
327         --
328         -- The "deriv_ty" is a LHsType to take account of the fact that for newtype derivign
329         -- we allow deriving (forall a. C [a]).
330
331     mk_eqn (new_or_data, tycon_name, hs_deriv_ty)
332       = tcLookupTyCon tycon_name                `thenM` \ tycon ->
333         addSrcSpan (srcLocSpan (getSrcLoc tycon))               $
334         addErrCtxt (derivCtxt Nothing tycon)    $
335         tcExtendTyVarEnv (tyConTyVars tycon)    $       -- Deriving preds may (now) mention
336                                                         -- the type variables for the type constructor
337         tcHsDeriv hs_deriv_ty                   `thenM` \ (deriv_tvs, clas, tys) ->
338         doptM Opt_GlasgowExts                   `thenM` \ gla_exts ->
339         mk_eqn_help gla_exts new_or_data tycon deriv_tvs clas tys
340
341     ------------------------------------------------------------------
342     mk_eqn_help gla_exts DataType tycon deriv_tvs clas tys
343       | Just err <- checkSideConditions gla_exts tycon deriv_tvs clas tys
344       = bale_out (derivingThingErr clas tys tycon (tyConTyVars tycon) err)
345       | otherwise 
346       = do { eqn <- mkDataTypeEqn tycon clas
347            ; returnM (Just eqn, Nothing) }
348
349     mk_eqn_help gla_exts NewType tycon deriv_tvs clas tys
350       | can_derive_via_isomorphism && (gla_exts || std_class_via_iso clas)
351       =         -- Go ahead and use the isomorphism
352            traceTc (text "newtype deriving:" <+> ppr tycon <+> ppr rep_tys)     `thenM_`
353            new_dfun_name clas tycon             `thenM` \ dfun_name ->
354            returnM (Nothing, Just (InstInfo { iDFunId = mk_dfun dfun_name,
355                                               iBinds = NewTypeDerived rep_tys }))
356       | std_class gla_exts clas
357       = mk_eqn_help gla_exts DataType tycon deriv_tvs clas tys  -- Go via bale-out route
358
359       | otherwise                               -- Non-standard instance
360       = bale_out (if gla_exts then      
361                         cant_derive_err -- Too hard
362                   else
363                         non_std_err)    -- Just complain about being a non-std instance
364       where
365         -- Here is the plan for newtype derivings.  We see
366         --        newtype T a1...an = T (t ak...an) deriving (.., C s1 .. sm, ...)
367         -- where t is a type,
368         --       ak...an is a suffix of a1..an
369         --       ak...an do not occur free in t, 
370         --       (C s1 ... sm) is a  *partial applications* of class C 
371         --                      with the last parameter missing
372         --
373         -- We generate the instances
374         --       instance C s1 .. sm (t ak...ap) => C s1 .. sm (T a1...ap)
375         -- where T a1...ap is the partial application of the LHS of the correct kind
376         -- and p >= k
377         --
378         -- Running example: newtype T s a = MkT (ST s a) deriving( Monad )
379         --      instance Monad (ST s) => Monad (T s) where 
380         --        fail = coerce ... (fail @ ST s)
381         -- (Actually we don't need the coerce, because non-rec newtypes are transparent
382
383         clas_tyvars = classTyVars clas
384         kind = tyVarKind (last clas_tyvars)
385                 -- Kind of the thing we want to instance
386                 --   e.g. argument kind of Monad, *->*
387
388         (arg_kinds, _) = splitKindFunTys kind
389         n_args_to_drop = length arg_kinds       
390                 -- Want to drop 1 arg from (T s a) and (ST s a)
391                 -- to get       instance Monad (ST s) => Monad (T s)
392
393         -- Note [newtype representation]
394         -- Need newTyConRhs *not* newTyConRep to get the representation 
395         -- type, because the latter looks through all intermediate newtypes
396         -- For example
397         --      newtype B = MkB Int
398         --      newtype A = MkA B deriving( Num )
399         -- We want the Num instance of B, *not* the Num instance of Int,
400         -- when making the Num instance of A!
401         (tc_tvs, rep_ty)      = newTyConRhs tycon
402         (rep_fn, rep_ty_args) = tcSplitAppTys rep_ty
403
404         n_tyvars_to_keep = tyConArity tycon  - n_args_to_drop
405         tyvars_to_drop   = drop n_tyvars_to_keep tc_tvs
406         tyvars_to_keep   = take n_tyvars_to_keep tc_tvs
407
408         n_args_to_keep = length rep_ty_args - n_args_to_drop
409         args_to_drop   = drop n_args_to_keep rep_ty_args
410         args_to_keep   = take n_args_to_keep rep_ty_args
411
412         rep_tys  = tys ++ [mkAppTys rep_fn args_to_keep]
413         rep_pred = mkClassPred clas rep_tys
414                 -- rep_pred is the representation dictionary, from where
415                 -- we are gong to get all the methods for the newtype dictionary
416
417         inst_tys = (tys ++ [mkTyConApp tycon (mkTyVarTys tyvars_to_keep)])
418                 -- The 'tys' here come from the partial application
419                 -- in the deriving clause. The last arg is the new
420                 -- instance type.
421
422                 -- We must pass the superclasses; the newtype might be an instance
423                 -- of them in a different way than the representation type
424                 -- E.g.         newtype Foo a = Foo a deriving( Show, Num, Eq )
425                 -- Then the Show instance is not done via isomprphism; it shows
426                 --      Foo 3 as "Foo 3"
427                 -- The Num instance is derived via isomorphism, but the Show superclass
428                 -- dictionary must the Show instance for Foo, *not* the Show dictionary
429                 -- gotten from the Num dictionary. So we must build a whole new dictionary
430                 -- not just use the Num one.  The instance we want is something like:
431                 --      instance (Num a, Show (Foo a), Eq (Foo a)) => Num (Foo a) where
432                 --              (+) = ((+)@a)
433                 --              ...etc...
434                 -- There's no 'corece' needed because after the type checker newtypes
435                 -- are transparent.
436
437         sc_theta = substTheta (mkTyVarSubst clas_tyvars inst_tys)
438                               (classSCTheta clas)
439
440                 -- If there are no tyvars, there's no need
441                 -- to abstract over the dictionaries we need
442         dict_tvs = deriv_tvs ++ tc_tvs
443         dict_args | null dict_tvs = []
444                   | otherwise     = rep_pred : sc_theta
445
446                 -- Finally! Here's where we build the dictionary Id
447         mk_dfun dfun_name = mkDictFunId dfun_name dict_tvs dict_args clas inst_tys
448
449         -------------------------------------------------------------------
450         --  Figuring out whether we can only do this newtype-deriving thing
451
452         right_arity = length tys + 1 == classArity clas
453
454                 -- Never derive Read,Show,Typeable,Data this way 
455         non_iso_classes = [readClassKey, showClassKey, typeableClassKey, dataClassKey]
456         can_derive_via_isomorphism
457            =  not (getUnique clas `elem` non_iso_classes)
458            && right_arity                       -- Well kinded;
459                                                 -- eg not: newtype T ... deriving( ST )
460                                                 --      because ST needs *2* type params
461            && n_tyvars_to_keep >= 0             -- Type constructor has right kind:
462                                                 -- eg not: newtype T = T Int deriving( Monad )
463            && n_args_to_keep   >= 0             -- Rep type has right kind: 
464                                                 -- eg not: newtype T a = T Int deriving( Monad )
465            && eta_ok                            -- Eta reduction works
466            && not (isRecursiveTyCon tycon)      -- Does not work for recursive tycons:
467                                                 --      newtype A = MkA [A]
468                                                 -- Don't want
469                                                 --      instance Eq [A] => Eq A !!
470                         -- Here's a recursive newtype that's actually OK
471                         --      newtype S1 = S1 [T1 ()]
472                         --      newtype T1 a = T1 (StateT S1 IO a ) deriving( Monad )
473                         -- It's currently rejected.  Oh well.
474                         -- In fact we generate an instance decl that has method of form
475                         --      meth @ instTy = meth @ repTy
476                         -- (no coerce's).  We'd need a coerce if we wanted to handle
477                         -- recursive newtypes too
478
479         -- Check that eta reduction is OK
480         --      (a) the dropped-off args are identical
481         --      (b) the remaining type args mention 
482         --          only the remaining type variables
483         eta_ok = (args_to_drop `tcEqTypes` mkTyVarTys tyvars_to_drop)
484               && (tyVarsOfTypes args_to_keep `subVarSet` mkVarSet tyvars_to_keep) 
485
486         cant_derive_err = derivingThingErr clas tys tycon tyvars_to_keep
487                                 (vcat [ptext SLIT("even with cunning newtype deriving:"),
488                                         if isRecursiveTyCon tycon then
489                                           ptext SLIT("the newtype is recursive")
490                                         else empty,
491                                         if not right_arity then 
492                                           quotes (ppr (mkClassPred clas tys)) <+> ptext SLIT("does not have arity 1")
493                                         else empty,
494                                         if not (n_tyvars_to_keep >= 0) then 
495                                           ptext SLIT("the type constructor has wrong kind")
496                                         else if not (n_args_to_keep >= 0) then
497                                           ptext SLIT("the representation type has wrong kind")
498                                         else if not eta_ok then 
499                                           ptext SLIT("the eta-reduction property does not hold")
500                                         else empty
501                                       ])
502
503         non_std_err = derivingThingErr clas tys tycon tyvars_to_keep
504                                 (vcat [non_std_why clas,
505                                        ptext SLIT("Try -fglasgow-exts for GHC's newtype-deriving extension")])
506
507     bale_out err = addErrTc err `thenM_` returnM (Nothing, Nothing) 
508
509 std_class gla_exts clas 
510   =  key `elem` derivableClassKeys
511   || (gla_exts && (key == typeableClassKey || key == dataClassKey))
512   where
513      key = classKey clas
514     
515 std_class_via_iso clas  -- These standard classes can be derived for a newtype
516                         -- using the isomorphism trick *even if no -fglasgow-exts*
517   = classKey clas `elem`  [eqClassKey, ordClassKey, ixClassKey, boundedClassKey]
518         -- Not Read/Show because they respect the type
519         -- Not Enum, becuase newtypes are never in Enum
520
521
522 new_dfun_name clas tycon        -- Just a simple wrapper
523   = newDFunName clas [mkTyConApp tycon []] (getSrcLoc tycon)
524         -- The type passed to newDFunName is only used to generate
525         -- a suitable string; hence the empty type arg list
526
527 ------------------------------------------------------------------
528 mkDataTypeEqn :: TyCon -> Class -> TcM DerivEqn
529 mkDataTypeEqn tycon clas
530   | clas `hasKey` typeableClassKey
531   =     -- The Typeable class is special in several ways
532         --        data T a b = ... deriving( Typeable )
533         -- gives
534         --        instance Typeable2 T where ...
535         -- 1. There are no constraints in the instance
536         -- 2. There are no type variables either
537         -- 2. The actual class we want to generate isn't necessarily
538         --      Typeable; it depends on the arity of the type
539     do  { real_clas <- tcLookupClass (typeableClassNames !! tyConArity tycon)
540         ; dfun_name <- new_dfun_name real_clas tycon
541         ; return (dfun_name, real_clas, tycon, [], []) }
542
543   | otherwise
544   = do  { dfun_name <- new_dfun_name clas tycon
545         ; return (dfun_name, clas, tycon, tyvars, constraints) }
546   where
547     tyvars            = tyConTyVars tycon
548     constraints       = extra_constraints ++ ordinary_constraints
549     extra_constraints = tyConTheta tycon
550          -- "extra_constraints": see note [Data decl contexts] above
551
552     ordinary_constraints
553       = [ mkClassPred clas [arg_ty] 
554         | data_con <- tyConDataCons tycon,
555           arg_ty   <- dataConOrigArgTys data_con,
556                 -- Use the same type variables
557                 -- as the type constructor,
558                 -- hence no need to instantiate
559           not (isUnLiftedType arg_ty)   -- No constraints for unlifted types?
560         ]
561
562
563 ------------------------------------------------------------------
564 -- Check side conditions that dis-allow derivability for particular classes
565 -- This is *apart* from the newtype-deriving mechanism
566
567 checkSideConditions :: Bool -> TyCon -> [TyVar] -> Class -> [TcType] -> Maybe SDoc
568 checkSideConditions gla_exts tycon deriv_tvs clas tys
569   | notNull deriv_tvs || notNull tys    
570   = Just ty_args_why    -- e.g. deriving( Foo s )
571   | otherwise
572   = case [cond | (key,cond) <- sideConditions, key == getUnique clas] of
573         []     -> Just (non_std_why clas)
574         [cond] -> cond (gla_exts, tycon)
575         other  -> pprPanic "checkSideConditions" (ppr clas)
576   where
577     ty_args_why = quotes (ppr (mkClassPred clas tys)) <+> ptext SLIT("is not a class")
578
579 non_std_why clas = quotes (ppr clas) <+> ptext SLIT("is not a derivable class")
580
581 sideConditions :: [(Unique, Condition)]
582 sideConditions
583   = [   (eqClassKey,       cond_std),
584         (ordClassKey,      cond_std),
585         (readClassKey,     cond_std),
586         (showClassKey,     cond_std),
587         (enumClassKey,     cond_std `andCond` cond_isEnumeration),
588         (ixClassKey,       cond_std `andCond` (cond_isEnumeration `orCond` cond_isProduct)),
589         (boundedClassKey,  cond_std `andCond` (cond_isEnumeration `orCond` cond_isProduct)),
590         (typeableClassKey, cond_glaExts `andCond` cond_allTypeKind),
591         (dataClassKey,     cond_glaExts `andCond` cond_std)
592     ]
593
594 type Condition = (Bool, TyCon) -> Maybe SDoc    -- Nothing => OK
595
596 orCond :: Condition -> Condition -> Condition
597 orCond c1 c2 tc 
598   = case c1 tc of
599         Nothing -> Nothing              -- c1 succeeds
600         Just x  -> case c2 tc of        -- c1 fails
601                      Nothing -> Nothing
602                      Just y  -> Just (x $$ ptext SLIT("  and") $$ y)
603                                         -- Both fail
604
605 andCond c1 c2 tc = case c1 tc of
606                      Nothing -> c2 tc   -- c1 succeeds
607                      Just x  -> Just x  -- c1 fails
608
609 cond_std :: Condition
610 cond_std (gla_exts, tycon)
611   | any isExistentialDataCon data_cons  = Just existential_why     
612   | null data_cons                      = Just no_cons_why
613   | otherwise                           = Nothing
614   where
615     data_cons       = tyConDataCons tycon
616     no_cons_why     = quotes (ppr tycon) <+> ptext SLIT("has no data constructors")
617     existential_why = quotes (ppr tycon) <+> ptext SLIT("has existentially-quantified constructor(s)")
618   
619 cond_isEnumeration :: Condition
620 cond_isEnumeration (gla_exts, tycon)
621   | isEnumerationTyCon tycon = Nothing
622   | otherwise                = Just why
623   where
624     why = quotes (ppr tycon) <+> ptext SLIT("has non-nullary constructors")
625
626 cond_isProduct :: Condition
627 cond_isProduct (gla_exts, tycon)
628   | isProductTyCon tycon = Nothing
629   | otherwise            = Just why
630   where
631     why = quotes (ppr tycon) <+> ptext SLIT("has more than one constructor")
632
633 cond_allTypeKind :: Condition
634 cond_allTypeKind (gla_exts, tycon)
635   | all (isArgTypeKind . tyVarKind) (tyConTyVars tycon) = Nothing
636   | otherwise                                        = Just why
637   where
638     why  = quotes (ppr tycon) <+> ptext SLIT("is parameterised over arguments of kind other than `*'")
639
640 cond_glaExts :: Condition
641 cond_glaExts (gla_exts, tycon) | gla_exts  = Nothing
642                                | otherwise = Just why
643   where
644     why  = ptext SLIT("You need -fglasgow-exts to derive an instance for this class")
645 \end{code}
646
647 %************************************************************************
648 %*                                                                      *
649 \subsection[TcDeriv-fixpoint]{Finding the fixed point of \tr{deriving} equations}
650 %*                                                                      *
651 %************************************************************************
652
653 A ``solution'' (to one of the equations) is a list of (k,TyVarTy tv)
654 terms, which is the final correct RHS for the corresponding original
655 equation.
656 \begin{itemize}
657 \item
658 Each (k,TyVarTy tv) in a solution constrains only a type
659 variable, tv.
660
661 \item
662 The (k,TyVarTy tv) pairs in a solution are canonically
663 ordered by sorting on type varible, tv, (major key) and then class, k,
664 (minor key)
665 \end{itemize}
666
667 \begin{code}
668 solveDerivEqns :: [DerivEqn]
669                -> TcM [DFunId]  -- Solns in same order as eqns.
670                                 -- This bunch is Absolutely minimal...
671
672 solveDerivEqns orig_eqns
673   = iterateDeriv 1 initial_solutions
674   where
675         -- The initial solutions for the equations claim that each
676         -- instance has an empty context; this solution is certainly
677         -- in canonical form.
678     initial_solutions :: [DerivSoln]
679     initial_solutions = [ [] | _ <- orig_eqns ]
680
681     ------------------------------------------------------------------
682         -- iterateDeriv calculates the next batch of solutions,
683         -- compares it with the current one; finishes if they are the
684         -- same, otherwise recurses with the new solutions.
685         -- It fails if any iteration fails
686     iterateDeriv :: Int -> [DerivSoln] ->TcM [DFunId]
687     iterateDeriv n current_solns
688       | n > 20  -- Looks as if we are in an infinite loop
689                 -- This can happen if we have -fallow-undecidable-instances
690                 -- (See TcSimplify.tcSimplifyDeriv.)
691       = pprPanic "solveDerivEqns: probable loop" 
692                  (vcat (map pprDerivEqn orig_eqns) $$ ppr current_solns)
693       | otherwise
694       = let 
695             dfuns = zipWithEqual "add_solns" mk_deriv_dfun orig_eqns current_solns
696         in
697         checkNoErrs (
698                   -- Extend the inst info from the explicit instance decls
699                   -- with the current set of solutions, and simplify each RHS
700             extendLocalInstEnv dfuns $
701             mappM gen_soln orig_eqns
702         )                               `thenM` \ new_solns ->
703         if (current_solns == new_solns) then
704             returnM dfuns
705         else
706             iterateDeriv (n+1) new_solns
707
708     ------------------------------------------------------------------
709
710     gen_soln (_, clas, tc,tyvars,deriv_rhs)
711       = addSrcSpan (srcLocSpan (getSrcLoc tc))          $
712         addErrCtxt (derivCtxt (Just clas) tc)   $
713         tcSimplifyDeriv tyvars deriv_rhs        `thenM` \ theta ->
714         returnM (sortLt (<) theta)      -- Canonicalise before returning the soluction
715
716 mk_deriv_dfun (dfun_name, clas, tycon, tyvars, _) theta
717   = mkDictFunId dfun_name tyvars theta
718                 clas [mkTyConApp tycon (mkTyVarTys tyvars)] 
719
720 extendLocalInstEnv :: [DFunId] -> TcM a -> TcM a
721 -- Add new locall-defined instances; don't bother to check
722 -- for functional dependency errors -- that'll happen in TcInstDcls
723 extendLocalInstEnv dfuns thing_inside
724  = do { env <- getGblEnv
725       ; let  inst_env' = foldl extendInstEnv (tcg_inst_env env) dfuns 
726              env'      = env { tcg_inst_env = inst_env' }
727       ; setGblEnv env' thing_inside }
728 \end{code}
729
730 %************************************************************************
731 %*                                                                      *
732 \subsection[TcDeriv-normal-binds]{Bindings for the various classes}
733 %*                                                                      *
734 %************************************************************************
735
736 After all the trouble to figure out the required context for the
737 derived instance declarations, all that's left is to chug along to
738 produce them.  They will then be shoved into @tcInstDecls2@, which
739 will do all its usual business.
740
741 There are lots of possibilities for code to generate.  Here are
742 various general remarks.
743
744 PRINCIPLES:
745 \begin{itemize}
746 \item
747 We want derived instances of @Eq@ and @Ord@ (both v common) to be
748 ``you-couldn't-do-better-by-hand'' efficient.
749
750 \item
751 Deriving @Show@---also pretty common--- should also be reasonable good code.
752
753 \item
754 Deriving for the other classes isn't that common or that big a deal.
755 \end{itemize}
756
757 PRAGMATICS:
758
759 \begin{itemize}
760 \item
761 Deriving @Ord@ is done mostly with the 1.3 @compare@ method.
762
763 \item
764 Deriving @Eq@ also uses @compare@, if we're deriving @Ord@, too.
765
766 \item
767 We {\em normally} generate code only for the non-defaulted methods;
768 there are some exceptions for @Eq@ and (especially) @Ord@...
769
770 \item
771 Sometimes we use a @_con2tag_<tycon>@ function, which returns a data
772 constructor's numeric (@Int#@) tag.  These are generated by
773 @gen_tag_n_con_binds@, and the heuristic for deciding if one of
774 these is around is given by @hasCon2TagFun@.
775
776 The examples under the different sections below will make this
777 clearer.
778
779 \item
780 Much less often (really just for deriving @Ix@), we use a
781 @_tag2con_<tycon>@ function.  See the examples.
782
783 \item
784 We use the renamer!!!  Reason: we're supposed to be
785 producing @LHsBinds Name@ for the methods, but that means
786 producing correctly-uniquified code on the fly.  This is entirely
787 possible (the @TcM@ monad has a @UniqueSupply@), but it is painful.
788 So, instead, we produce @MonoBinds RdrName@ then heave 'em through
789 the renamer.  What a great hack!
790 \end{itemize}
791
792 \begin{code}
793 -- Generate the InstInfo for the required instance,
794 -- plus any auxiliary bindings required
795 genInst :: DFunId -> TcM (InstInfo, LHsBinds RdrName)
796 genInst dfun
797   = getFixityEnv                `thenM` \ fix_env -> 
798     let
799         (tyvars,_,clas,[ty])    = tcSplitDFunTy (idType dfun)
800         clas_nm                 = className clas
801         tycon                   = tcTyConAppTyCon ty 
802         (meth_binds, aux_binds) = genDerivBinds clas fix_env tycon
803     in
804         -- Bring the right type variables into 
805         -- scope, and rename the method binds
806     bindLocalNames (map varName tyvars)         $
807     rnMethodBinds clas_nm [] meth_binds         `thenM` \ (rn_meth_binds, _fvs) ->
808
809         -- Build the InstInfo
810     returnM (InstInfo { iDFunId = dfun, iBinds = VanillaInst rn_meth_binds [] }, 
811              aux_binds)
812
813 genDerivBinds clas fix_env tycon
814   | className clas `elem` typeableClassNames
815   = (gen_Typeable_binds tycon, emptyBag)
816
817   | otherwise
818   = case assocMaybe gen_list (getUnique clas) of
819         Just gen_fn -> gen_fn fix_env tycon
820         Nothing     -> pprPanic "genDerivBinds: bad derived class" (ppr clas)
821   where
822     gen_list :: [(Unique, FixityEnv -> TyCon -> (LHsBinds RdrName, LHsBinds RdrName))]
823     gen_list = [(eqClassKey,      no_aux_binds (ignore_fix_env gen_Eq_binds))
824                ,(ordClassKey,     no_aux_binds (ignore_fix_env gen_Ord_binds))
825                ,(enumClassKey,    no_aux_binds (ignore_fix_env gen_Enum_binds))
826                ,(boundedClassKey, no_aux_binds (ignore_fix_env gen_Bounded_binds))
827                ,(ixClassKey,      no_aux_binds (ignore_fix_env gen_Ix_binds))
828                ,(typeableClassKey,no_aux_binds (ignore_fix_env gen_Typeable_binds))
829                ,(showClassKey,    no_aux_binds gen_Show_binds)
830                ,(readClassKey,    no_aux_binds gen_Read_binds)
831                ,(dataClassKey,    gen_Data_binds)
832                ]
833
834       -- no_aux_binds is used for generators that don't 
835       -- need to produce any auxiliary bindings
836     no_aux_binds f fix_env tc = (f fix_env tc, emptyBag)
837     ignore_fix_env f fix_env tc = f tc
838 \end{code}
839
840
841 %************************************************************************
842 %*                                                                      *
843 \subsection[TcDeriv-taggery-Names]{What con2tag/tag2con functions are available?}
844 %*                                                                      *
845 %************************************************************************
846
847
848 data Foo ... = ...
849
850 con2tag_Foo :: Foo ... -> Int#
851 tag2con_Foo :: Int -> Foo ...   -- easier if Int, not Int#
852 maxtag_Foo  :: Int              -- ditto (NB: not unlifted)
853
854
855 We have a @con2tag@ function for a tycon if:
856 \begin{itemize}
857 \item
858 We're deriving @Eq@ and the tycon has nullary data constructors.
859
860 \item
861 Or: we're deriving @Ord@ (unless single-constructor), @Enum@, @Ix@
862 (enum type only????)
863 \end{itemize}
864
865 We have a @tag2con@ function for a tycon if:
866 \begin{itemize}
867 \item
868 We're deriving @Enum@, or @Ix@ (enum type only???)
869 \end{itemize}
870
871 If we have a @tag2con@ function, we also generate a @maxtag@ constant.
872
873 \begin{code}
874 genTaggeryBinds :: [DFunId] -> TcM (LHsBinds RdrName)
875 genTaggeryBinds dfuns
876   = do  { names_so_far <- foldlM do_con2tag []           tycons_of_interest
877         ; nm_alist_etc <- foldlM do_tag2con names_so_far tycons_of_interest
878         ; return (listToBag (map gen_tag_n_con_monobind nm_alist_etc)) }
879   where
880     all_CTs = map simpleDFunClassTyCon dfuns
881     all_tycons              = map snd all_CTs
882     (tycons_of_interest, _) = removeDups compare all_tycons
883     
884     do_con2tag acc_Names tycon
885       | isDataTyCon tycon &&
886         ((we_are_deriving eqClassKey tycon
887             && any isNullaryDataCon (tyConDataCons tycon))
888          || (we_are_deriving ordClassKey  tycon
889             && not (isProductTyCon tycon))
890          || (we_are_deriving enumClassKey tycon)
891          || (we_are_deriving ixClassKey   tycon))
892         
893       = returnM ((con2tag_RDR tycon, tycon, GenCon2Tag)
894                    : acc_Names)
895       | otherwise
896       = returnM acc_Names
897
898     do_tag2con acc_Names tycon
899       | isDataTyCon tycon &&
900          (we_are_deriving enumClassKey tycon ||
901           we_are_deriving ixClassKey   tycon
902           && isEnumerationTyCon tycon)
903       = returnM ( (tag2con_RDR tycon, tycon, GenTag2Con)
904                  : (maxtag_RDR  tycon, tycon, GenMaxTag)
905                  : acc_Names)
906       | otherwise
907       = returnM acc_Names
908
909     we_are_deriving clas_key tycon
910       = is_in_eqns clas_key tycon all_CTs
911       where
912         is_in_eqns clas_key tycon [] = False
913         is_in_eqns clas_key tycon ((c,t):cts)
914           =  (clas_key == classKey c && tycon == t)
915           || is_in_eqns clas_key tycon cts
916 \end{code}
917
918 \begin{code}
919 derivingThingErr clas tys tycon tyvars why
920   = sep [hsep [ptext SLIT("Can't make a derived instance of"), quotes (ppr pred)],
921          parens why]
922   where
923     pred = mkClassPred clas (tys ++ [mkTyConApp tycon (mkTyVarTys tyvars)])
924
925 derivCtxt :: Maybe Class -> TyCon -> SDoc
926 derivCtxt maybe_cls tycon
927   = ptext SLIT("When deriving") <+> cls <+> ptext SLIT("for type") <+> quotes (ppr tycon)
928   where
929     cls = case maybe_cls of
930             Nothing -> ptext SLIT("instances")
931             Just c  -> ptext SLIT("the") <+> quotes (ppr c) <+> ptext SLIT("instance")
932 \end{code}
933