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