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