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