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