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