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