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