c31e6aaf0fba2e205d24fc8319814395a0d2fa74
[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, tyVarsOfType,
48                           isArgTypeKind, 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_fn'  = mkAppTys rep_fn args_to_keep
423         rep_tys  = tys ++ [rep_fn']
424         rep_pred = mkClassPred clas rep_tys
425                 -- rep_pred is the representation dictionary, from where
426                 -- we are gong to get all the methods for the newtype dictionary
427
428         inst_tys = (tys ++ [mkTyConApp tycon (mkTyVarTys tyvars_to_keep)])
429                 -- The 'tys' here come from the partial application
430                 -- in the deriving clause. The last arg is the new
431                 -- instance type.
432
433                 -- We must pass the superclasses; the newtype might be an instance
434                 -- of them in a different way than the representation type
435                 -- E.g.         newtype Foo a = Foo a deriving( Show, Num, Eq )
436                 -- Then the Show instance is not done via isomprphism; it shows
437                 --      Foo 3 as "Foo 3"
438                 -- The Num instance is derived via isomorphism, but the Show superclass
439                 -- dictionary must the Show instance for Foo, *not* the Show dictionary
440                 -- gotten from the Num dictionary. So we must build a whole new dictionary
441                 -- not just use the Num one.  The instance we want is something like:
442                 --      instance (Num a, Show (Foo a), Eq (Foo a)) => Num (Foo a) where
443                 --              (+) = ((+)@a)
444                 --              ...etc...
445                 -- There's no 'corece' needed because after the type checker newtypes
446                 -- are transparent.
447
448         sc_theta = substTheta (zipOpenTvSubst clas_tyvars inst_tys)
449                               (classSCTheta clas)
450
451                 -- If there are no tyvars, there's no need
452                 -- to abstract over the dictionaries we need
453         dict_tvs = deriv_tvs ++ tc_tvs
454         dict_args | null dict_tvs = []
455                   | otherwise     = rep_pred : sc_theta
456
457                 -- Finally! Here's where we build the dictionary Id
458         mk_inst_spec dfun_name 
459           = mkLocalInstance dfun overlap_flag
460           where
461             dfun = mkDictFunId dfun_name dict_tvs dict_args clas inst_tys
462
463         -------------------------------------------------------------------
464         --  Figuring out whether we can only do this newtype-deriving thing
465
466         right_arity = length tys + 1 == classArity clas
467
468                 -- Never derive Read,Show,Typeable,Data this way 
469         non_iso_classes = [readClassKey, showClassKey, typeableClassKey, dataClassKey]
470         can_derive_via_isomorphism
471            =  not (getUnique clas `elem` non_iso_classes)
472            && right_arity                       -- Well kinded;
473                                                 -- eg not: newtype T ... deriving( ST )
474                                                 --      because ST needs *2* type params
475            && n_tyvars_to_keep >= 0             -- Type constructor has right kind:
476                                                 -- eg not: newtype T = T Int deriving( Monad )
477            && n_args_to_keep   >= 0             -- Rep type has right kind: 
478                                                 -- eg not: newtype T a = T Int deriving( Monad )
479            && eta_ok                            -- Eta reduction works
480            && not (isRecursiveTyCon tycon)      -- Does not work for recursive tycons:
481                                                 --      newtype A = MkA [A]
482                                                 -- Don't want
483                                                 --      instance Eq [A] => Eq A !!
484                         -- Here's a recursive newtype that's actually OK
485                         --      newtype S1 = S1 [T1 ()]
486                         --      newtype T1 a = T1 (StateT S1 IO a ) deriving( Monad )
487                         -- It's currently rejected.  Oh well.
488                         -- In fact we generate an instance decl that has method of form
489                         --      meth @ instTy = meth @ repTy
490                         -- (no coerce's).  We'd need a coerce if we wanted to handle
491                         -- recursive newtypes too
492
493         -- Check that eta reduction is OK
494         --      (a) the dropped-off args are identical
495         --      (b) the remaining type args mention 
496         --          only the remaining type variables
497         eta_ok = (args_to_drop `tcEqTypes` mkTyVarTys tyvars_to_drop)
498               && (tyVarsOfType rep_fn' `subVarSet` mkVarSet tyvars_to_keep) 
499
500         cant_derive_err = derivingThingErr clas tys tycon tyvars_to_keep
501                                 (vcat [ptext SLIT("even with cunning newtype deriving:"),
502                                         if isRecursiveTyCon tycon then
503                                           ptext SLIT("the newtype is recursive")
504                                         else empty,
505                                         if not right_arity then 
506                                           quotes (ppr (mkClassPred clas tys)) <+> ptext SLIT("does not have arity 1")
507                                         else empty,
508                                         if not (n_tyvars_to_keep >= 0) then 
509                                           ptext SLIT("the type constructor has wrong kind")
510                                         else if not (n_args_to_keep >= 0) then
511                                           ptext SLIT("the representation type has wrong kind")
512                                         else if not eta_ok then 
513                                           ptext SLIT("the eta-reduction property does not hold")
514                                         else empty
515                                       ])
516
517         non_std_err = derivingThingErr clas tys tycon tyvars_to_keep
518                                 (vcat [non_std_why clas,
519                                        ptext SLIT("Try -fglasgow-exts for GHC's newtype-deriving extension")])
520
521     bale_out err = addErrTc err `thenM_` returnM (Nothing, Nothing) 
522
523 std_class gla_exts clas 
524   =  key `elem` derivableClassKeys
525   || (gla_exts && (key == typeableClassKey || key == dataClassKey))
526   where
527      key = classKey clas
528     
529 std_class_via_iso clas  -- These standard classes can be derived for a newtype
530                         -- using the isomorphism trick *even if no -fglasgow-exts*
531   = classKey clas `elem`  [eqClassKey, ordClassKey, ixClassKey, boundedClassKey]
532         -- Not Read/Show because they respect the type
533         -- Not Enum, becuase newtypes are never in Enum
534
535
536 new_dfun_name clas tycon        -- Just a simple wrapper
537   = newDFunName clas [mkTyConApp tycon []] (getSrcLoc tycon)
538         -- The type passed to newDFunName is only used to generate
539         -- a suitable string; hence the empty type arg list
540
541 ------------------------------------------------------------------
542 mkDataTypeEqn :: TyCon -> Class -> TcM DerivEqn
543 mkDataTypeEqn tycon clas
544   | clas `hasKey` typeableClassKey
545   =     -- The Typeable class is special in several ways
546         --        data T a b = ... deriving( Typeable )
547         -- gives
548         --        instance Typeable2 T where ...
549         -- Notice that:
550         -- 1. There are no constraints in the instance
551         -- 2. There are no type variables either
552         -- 3. The actual class we want to generate isn't necessarily
553         --      Typeable; it depends on the arity of the type
554     do  { real_clas <- tcLookupClass (typeableClassNames !! tyConArity tycon)
555         ; dfun_name <- new_dfun_name real_clas tycon
556         ; return (dfun_name, real_clas, tycon, [], []) }
557
558   | otherwise
559   = do  { dfun_name <- new_dfun_name clas tycon
560         ; return (dfun_name, clas, tycon, tyvars, constraints) }
561   where
562     tyvars            = tyConTyVars tycon
563     constraints       = extra_constraints ++ ordinary_constraints
564     extra_constraints = tyConStupidTheta tycon
565          -- "extra_constraints": see note [Data decl contexts] above
566
567     ordinary_constraints
568       = [ mkClassPred clas [arg_ty] 
569         | data_con <- tyConDataCons tycon,
570           arg_ty   <- dataConOrigArgTys data_con,
571           not (isUnLiftedType arg_ty)   -- No constraints for unlifted types?
572         ]
573
574
575 ------------------------------------------------------------------
576 -- Check side conditions that dis-allow derivability for particular classes
577 -- This is *apart* from the newtype-deriving mechanism
578
579 checkSideConditions :: Bool -> TyCon -> [TyVar] -> Class -> [TcType] -> Maybe SDoc
580 checkSideConditions gla_exts tycon deriv_tvs clas tys
581   | notNull deriv_tvs || notNull tys    
582   = Just ty_args_why    -- e.g. deriving( Foo s )
583   | otherwise
584   = case [cond | (key,cond) <- sideConditions, key == getUnique clas] of
585         []     -> Just (non_std_why clas)
586         [cond] -> cond (gla_exts, tycon)
587         other  -> pprPanic "checkSideConditions" (ppr clas)
588   where
589     ty_args_why = quotes (ppr (mkClassPred clas tys)) <+> ptext SLIT("is not a class")
590
591 non_std_why clas = quotes (ppr clas) <+> ptext SLIT("is not a derivable class")
592
593 sideConditions :: [(Unique, Condition)]
594 sideConditions
595   = [   (eqClassKey,       cond_std),
596         (ordClassKey,      cond_std),
597         (readClassKey,     cond_std),
598         (showClassKey,     cond_std),
599         (enumClassKey,     cond_std `andCond` cond_isEnumeration),
600         (ixClassKey,       cond_std `andCond` (cond_isEnumeration `orCond` cond_isProduct)),
601         (boundedClassKey,  cond_std `andCond` (cond_isEnumeration `orCond` cond_isProduct)),
602         (typeableClassKey, cond_glaExts `andCond` cond_typeableOK),
603         (dataClassKey,     cond_glaExts `andCond` cond_std)
604     ]
605
606 type Condition = (Bool, TyCon) -> Maybe SDoc    -- Nothing => OK
607
608 orCond :: Condition -> Condition -> Condition
609 orCond c1 c2 tc 
610   = case c1 tc of
611         Nothing -> Nothing              -- c1 succeeds
612         Just x  -> case c2 tc of        -- c1 fails
613                      Nothing -> Nothing
614                      Just y  -> Just (x $$ ptext SLIT("  and") $$ y)
615                                         -- Both fail
616
617 andCond c1 c2 tc = case c1 tc of
618                      Nothing -> c2 tc   -- c1 succeeds
619                      Just x  -> Just x  -- c1 fails
620
621 cond_std :: Condition
622 cond_std (gla_exts, tycon)
623   | any (not . isVanillaDataCon) data_cons = Just existential_why     
624   | null data_cons                         = Just no_cons_why
625   | otherwise                              = Nothing
626   where
627     data_cons       = tyConDataCons tycon
628     no_cons_why     = quotes (ppr tycon) <+> ptext SLIT("has no data constructors")
629     existential_why = quotes (ppr tycon) <+> ptext SLIT("has non-Haskell-98 constructor(s)")
630   
631 cond_isEnumeration :: Condition
632 cond_isEnumeration (gla_exts, tycon)
633   | isEnumerationTyCon tycon = Nothing
634   | otherwise                = Just why
635   where
636     why = quotes (ppr tycon) <+> ptext SLIT("has non-nullary constructors")
637
638 cond_isProduct :: Condition
639 cond_isProduct (gla_exts, tycon)
640   | isProductTyCon tycon = Nothing
641   | otherwise            = Just why
642   where
643     why = quotes (ppr tycon) <+> ptext SLIT("has more than one constructor")
644
645 cond_typeableOK :: Condition
646 -- OK for Typeable class
647 -- Currently: (a) args all of kind *
648 --            (b) 7 or fewer args
649 cond_typeableOK (gla_exts, tycon)
650   | tyConArity tycon > 7                                      = Just too_many
651   | not (all (isArgTypeKind . tyVarKind) (tyConTyVars tycon)) = Just bad_kind
652   | otherwise                                                 = Nothing
653   where
654     too_many = quotes (ppr tycon) <+> ptext SLIT("has too many arguments")
655     bad_kind = quotes (ppr tycon) <+> ptext SLIT("has arguments of kind other than `*'")
656
657 cond_glaExts :: Condition
658 cond_glaExts (gla_exts, tycon) | gla_exts  = Nothing
659                                | otherwise = Just why
660   where
661     why  = ptext SLIT("You need -fglasgow-exts to derive an instance for this class")
662 \end{code}
663
664 %************************************************************************
665 %*                                                                      *
666 \subsection[TcDeriv-fixpoint]{Finding the fixed point of \tr{deriving} equations}
667 %*                                                                      *
668 %************************************************************************
669
670 A ``solution'' (to one of the equations) is a list of (k,TyVarTy tv)
671 terms, which is the final correct RHS for the corresponding original
672 equation.
673 \begin{itemize}
674 \item
675 Each (k,TyVarTy tv) in a solution constrains only a type
676 variable, tv.
677
678 \item
679 The (k,TyVarTy tv) pairs in a solution are canonically
680 ordered by sorting on type varible, tv, (major key) and then class, k,
681 (minor key)
682 \end{itemize}
683
684 \begin{code}
685 solveDerivEqns :: OverlapFlag
686                -> [DerivEqn]
687                -> TcM [Instance]-- Solns in same order as eqns.
688                                 -- This bunch is Absolutely minimal...
689
690 solveDerivEqns overlap_flag orig_eqns
691   = iterateDeriv 1 initial_solutions
692   where
693         -- The initial solutions for the equations claim that each
694         -- instance has an empty context; this solution is certainly
695         -- in canonical form.
696     initial_solutions :: [DerivSoln]
697     initial_solutions = [ [] | _ <- orig_eqns ]
698
699     ------------------------------------------------------------------
700         -- iterateDeriv calculates the next batch of solutions,
701         -- compares it with the current one; finishes if they are the
702         -- same, otherwise recurses with the new solutions.
703         -- It fails if any iteration fails
704     iterateDeriv :: Int -> [DerivSoln] -> TcM [Instance]
705     iterateDeriv n current_solns
706       | n > 20  -- Looks as if we are in an infinite loop
707                 -- This can happen if we have -fallow-undecidable-instances
708                 -- (See TcSimplify.tcSimplifyDeriv.)
709       = pprPanic "solveDerivEqns: probable loop" 
710                  (vcat (map pprDerivEqn orig_eqns) $$ ppr current_solns)
711       | otherwise
712       = let 
713             inst_specs = zipWithEqual "add_solns" mk_inst_spec 
714                                       orig_eqns current_solns
715         in
716         checkNoErrs (
717                   -- Extend the inst info from the explicit instance decls
718                   -- with the current set of solutions, and simplify each RHS
719             extendLocalInstEnv inst_specs $
720             mappM gen_soln orig_eqns
721         )                               `thenM` \ new_solns ->
722         if (current_solns == new_solns) then
723             returnM inst_specs
724         else
725             iterateDeriv (n+1) new_solns
726
727     ------------------------------------------------------------------
728     gen_soln (_, clas, tc,tyvars,deriv_rhs)
729       = setSrcSpan (srcLocSpan (getSrcLoc tc))          $
730         addErrCtxt (derivCtxt (Just clas) tc)   $
731         tcSimplifyDeriv tc tyvars deriv_rhs     `thenM` \ theta ->
732         returnM (sortLe (<=) theta)     -- Canonicalise before returning the soluction
733
734     ------------------------------------------------------------------
735     mk_inst_spec (dfun_name, clas, tycon, tyvars, _) theta
736         = mkLocalInstance dfun overlap_flag
737         where
738           dfun = mkDictFunId dfun_name tyvars theta clas
739                              [mkTyConApp tycon (mkTyVarTys tyvars)]
740
741 extendLocalInstEnv :: [Instance] -> TcM a -> TcM a
742 -- Add new locally-defined instances; don't bother to check
743 -- for functional dependency errors -- that'll happen in TcInstDcls
744 extendLocalInstEnv dfuns thing_inside
745  = do { env <- getGblEnv
746       ; let  inst_env' = extendInstEnvList (tcg_inst_env env) dfuns 
747              env'      = env { tcg_inst_env = inst_env' }
748       ; setGblEnv env' thing_inside }
749 \end{code}
750
751 %************************************************************************
752 %*                                                                      *
753 \subsection[TcDeriv-normal-binds]{Bindings for the various classes}
754 %*                                                                      *
755 %************************************************************************
756
757 After all the trouble to figure out the required context for the
758 derived instance declarations, all that's left is to chug along to
759 produce them.  They will then be shoved into @tcInstDecls2@, which
760 will do all its usual business.
761
762 There are lots of possibilities for code to generate.  Here are
763 various general remarks.
764
765 PRINCIPLES:
766 \begin{itemize}
767 \item
768 We want derived instances of @Eq@ and @Ord@ (both v common) to be
769 ``you-couldn't-do-better-by-hand'' efficient.
770
771 \item
772 Deriving @Show@---also pretty common--- should also be reasonable good code.
773
774 \item
775 Deriving for the other classes isn't that common or that big a deal.
776 \end{itemize}
777
778 PRAGMATICS:
779
780 \begin{itemize}
781 \item
782 Deriving @Ord@ is done mostly with the 1.3 @compare@ method.
783
784 \item
785 Deriving @Eq@ also uses @compare@, if we're deriving @Ord@, too.
786
787 \item
788 We {\em normally} generate code only for the non-defaulted methods;
789 there are some exceptions for @Eq@ and (especially) @Ord@...
790
791 \item
792 Sometimes we use a @_con2tag_<tycon>@ function, which returns a data
793 constructor's numeric (@Int#@) tag.  These are generated by
794 @gen_tag_n_con_binds@, and the heuristic for deciding if one of
795 these is around is given by @hasCon2TagFun@.
796
797 The examples under the different sections below will make this
798 clearer.
799
800 \item
801 Much less often (really just for deriving @Ix@), we use a
802 @_tag2con_<tycon>@ function.  See the examples.
803
804 \item
805 We use the renamer!!!  Reason: we're supposed to be
806 producing @LHsBinds Name@ for the methods, but that means
807 producing correctly-uniquified code on the fly.  This is entirely
808 possible (the @TcM@ monad has a @UniqueSupply@), but it is painful.
809 So, instead, we produce @MonoBinds RdrName@ then heave 'em through
810 the renamer.  What a great hack!
811 \end{itemize}
812
813 \begin{code}
814 -- Generate the InstInfo for the required instance,
815 -- plus any auxiliary bindings required
816 genInst :: Instance -> TcM (InstInfo, LHsBinds RdrName)
817 genInst spec
818   = do  { fix_env <- getFixityEnv
819         ; let
820             (tyvars,_,clas,[ty])    = instanceHead spec
821             clas_nm                 = className clas
822             tycon                   = tcTyConAppTyCon ty 
823             (meth_binds, aux_binds) = genDerivBinds clas fix_env tycon
824
825         -- Bring the right type variables into 
826         -- scope, and rename the method binds
827         -- It's a bit yukky that we return *renamed* InstInfo, but
828         -- *non-renamed* auxiliary bindings
829         ; (rn_meth_binds, _fvs) <- discardWarnings $ 
830                                    bindLocalNames (map varName tyvars)  $
831                                    rnMethodBinds clas_nm [] meth_binds
832
833         -- Build the InstInfo
834         ; return (InstInfo { iSpec = spec, 
835                              iBinds = VanillaInst rn_meth_binds [] }, 
836                   aux_binds)
837         }
838
839 genDerivBinds clas fix_env tycon
840   | className clas `elem` typeableClassNames
841   = (gen_Typeable_binds tycon, emptyLHsBinds)
842
843   | otherwise
844   = case assocMaybe gen_list (getUnique clas) of
845         Just gen_fn -> gen_fn fix_env tycon
846         Nothing     -> pprPanic "genDerivBinds: bad derived class" (ppr clas)
847   where
848     gen_list :: [(Unique, FixityEnv -> TyCon -> (LHsBinds RdrName, LHsBinds RdrName))]
849     gen_list = [(eqClassKey,      no_aux_binds (ignore_fix_env gen_Eq_binds))
850                ,(ordClassKey,     no_aux_binds (ignore_fix_env gen_Ord_binds))
851                ,(enumClassKey,    no_aux_binds (ignore_fix_env gen_Enum_binds))
852                ,(boundedClassKey, no_aux_binds (ignore_fix_env gen_Bounded_binds))
853                ,(ixClassKey,      no_aux_binds (ignore_fix_env gen_Ix_binds))
854                ,(typeableClassKey,no_aux_binds (ignore_fix_env gen_Typeable_binds))
855                ,(showClassKey,    no_aux_binds gen_Show_binds)
856                ,(readClassKey,    no_aux_binds gen_Read_binds)
857                ,(dataClassKey,    gen_Data_binds)
858                ]
859
860       -- no_aux_binds is used for generators that don't 
861       -- need to produce any auxiliary bindings
862     no_aux_binds f fix_env tc = (f fix_env tc, emptyLHsBinds)
863     ignore_fix_env f fix_env tc = f tc
864 \end{code}
865
866
867 %************************************************************************
868 %*                                                                      *
869 \subsection[TcDeriv-taggery-Names]{What con2tag/tag2con functions are available?}
870 %*                                                                      *
871 %************************************************************************
872
873
874 data Foo ... = ...
875
876 con2tag_Foo :: Foo ... -> Int#
877 tag2con_Foo :: Int -> Foo ...   -- easier if Int, not Int#
878 maxtag_Foo  :: Int              -- ditto (NB: not unlifted)
879
880
881 We have a @con2tag@ function for a tycon if:
882 \begin{itemize}
883 \item
884 We're deriving @Eq@ and the tycon has nullary data constructors.
885
886 \item
887 Or: we're deriving @Ord@ (unless single-constructor), @Enum@, @Ix@
888 (enum type only????)
889 \end{itemize}
890
891 We have a @tag2con@ function for a tycon if:
892 \begin{itemize}
893 \item
894 We're deriving @Enum@, or @Ix@ (enum type only???)
895 \end{itemize}
896
897 If we have a @tag2con@ function, we also generate a @maxtag@ constant.
898
899 \begin{code}
900 genTaggeryBinds :: [InstInfo] -> TcM (LHsBinds RdrName)
901 genTaggeryBinds infos
902   = do  { names_so_far <- foldlM do_con2tag []           tycons_of_interest
903         ; nm_alist_etc <- foldlM do_tag2con names_so_far tycons_of_interest
904         ; return (listToBag (map gen_tag_n_con_monobind nm_alist_etc)) }
905   where
906     all_CTs = [ (cls, tcTyConAppTyCon ty)
907               | info <- infos, 
908                 let (cls,ty) = simpleInstInfoClsTy info ]
909     all_tycons              = map snd all_CTs
910     (tycons_of_interest, _) = removeDups compare all_tycons
911     
912     do_con2tag acc_Names tycon
913       | isDataTyCon tycon &&
914         ((we_are_deriving eqClassKey tycon
915             && any isNullarySrcDataCon (tyConDataCons tycon))
916          || (we_are_deriving ordClassKey  tycon
917             && not (isProductTyCon tycon))
918          || (we_are_deriving enumClassKey tycon)
919          || (we_are_deriving ixClassKey   tycon))
920         
921       = returnM ((con2tag_RDR tycon, tycon, GenCon2Tag)
922                    : acc_Names)
923       | otherwise
924       = returnM acc_Names
925
926     do_tag2con acc_Names tycon
927       | isDataTyCon tycon &&
928          (we_are_deriving enumClassKey tycon ||
929           we_are_deriving ixClassKey   tycon
930           && isEnumerationTyCon tycon)
931       = returnM ( (tag2con_RDR tycon, tycon, GenTag2Con)
932                  : (maxtag_RDR  tycon, tycon, GenMaxTag)
933                  : acc_Names)
934       | otherwise
935       = returnM acc_Names
936
937     we_are_deriving clas_key tycon
938       = is_in_eqns clas_key tycon all_CTs
939       where
940         is_in_eqns clas_key tycon [] = False
941         is_in_eqns clas_key tycon ((c,t):cts)
942           =  (clas_key == classKey c && tycon == t)
943           || is_in_eqns clas_key tycon cts
944 \end{code}
945
946 \begin{code}
947 derivingThingErr clas tys tycon tyvars why
948   = sep [hsep [ptext SLIT("Can't make a derived instance of"), quotes (ppr pred)],
949          parens why]
950   where
951     pred = mkClassPred clas (tys ++ [mkTyConApp tycon (mkTyVarTys tyvars)])
952
953 derivCtxt :: Maybe Class -> TyCon -> SDoc
954 derivCtxt maybe_cls tycon
955   = ptext SLIT("When deriving") <+> cls <+> ptext SLIT("for type") <+> quotes (ppr tycon)
956   where
957     cls = case maybe_cls of
958             Nothing -> ptext SLIT("instances")
959             Just c  -> ptext SLIT("the") <+> quotes (ppr c) <+> ptext SLIT("instance")
960 \end{code}
961