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