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