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