Add type signatures in "deriving" bindings
[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 TcClassDcl( tcAddDeclCtxt )      -- Small helper
20 import TcGenDeriv                       -- Deriv stuff
21 import InstEnv
22 import Inst
23 import TcHsType
24 import TcMType
25 import TcSimplify
26
27 import RnBinds
28 import RnEnv
29 import HscTypes
30
31 import Class
32 import Type
33 import Coercion
34 import ErrUtils
35 import MkId
36 import DataCon
37 import Maybes
38 import RdrName
39 import Name
40 import NameSet
41 import TyCon
42 import TcType
43 import Var
44 import VarSet
45 import PrelNames
46 import SrcLoc
47 import Util
48 import ListSetOps
49 import Outputable
50 import FastString
51 import Bag
52
53 import Control.Monad
54 \end{code}
55
56 %************************************************************************
57 %*                                                                      *
58                 Overview
59 %*                                                                      *
60 %************************************************************************
61
62 Overall plan
63 ~~~~~~~~~~~~
64 1.  Convert the decls (i.e. data/newtype deriving clauses, 
65     plus standalone deriving) to [EarlyDerivSpec]
66
67 2.  Infer the missing contexts for the Left DerivSpecs
68
69 3.  Add the derived bindings, generating InstInfos
70
71 \begin{code}
72 -- DerivSpec is purely  local to this module
73 data DerivSpec  = DS { ds_loc     :: SrcSpan 
74                      , ds_orig    :: InstOrigin 
75                      , ds_name    :: Name
76                      , ds_tvs     :: [TyVar] 
77                      , ds_theta   :: ThetaType
78                      , ds_cls     :: Class
79                      , ds_tys     :: [Type]
80                      , ds_tc      :: TyCon
81                      , ds_tc_args :: [Type]
82                      , ds_newtype :: Bool }
83         -- This spec implies a dfun declaration of the form
84         --       df :: forall tvs. theta => C tys
85         -- The Name is the name for the DFun we'll build
86         -- The tyvars bind all the variables in the theta
87         -- For family indexes, the tycon in 
88         --       in ds_tys is the *family* tycon
89         --       in ds_tc, ds_tc_args is the *representation* tycon
90         -- For non-family tycons, both are the same
91
92         -- ds_newtype = True  <=> Newtype deriving
93         --              False <=> Vanilla deriving
94
95 type DerivContext = Maybe ThetaType
96    -- Nothing    <=> Vanilla deriving; infer the context of the instance decl
97    -- Just theta <=> Standalone deriving: context supplied by programmer
98
99 type EarlyDerivSpec = Either DerivSpec DerivSpec
100         -- Left  ds => the context for the instance should be inferred
101         --             In this case ds_theta is the list of all the 
102         --                constraints needed, such as (Eq [a], Eq a)
103         --                The inference process is to reduce this to a 
104         --                simpler form (e.g. Eq a)
105         -- 
106         -- Right ds => the exact context for the instance is supplied 
107         --             by the programmer; it is ds_theta
108
109 pprDerivSpec :: DerivSpec -> SDoc
110 pprDerivSpec (DS { ds_loc = l, ds_name = n, ds_tvs = tvs, 
111                    ds_cls = c, ds_tys = tys, ds_theta = rhs })
112   = parens (hsep [ppr l, ppr n, ppr tvs, ppr c, ppr tys]
113             <+> equals <+> ppr rhs)
114 \end{code}
115
116
117 Inferring missing contexts 
118 ~~~~~~~~~~~~~~~~~~~~~~~~~~
119 Consider
120
121         data T a b = C1 (Foo a) (Bar b)
122                    | C2 Int (T b a)
123                    | C3 (T a a)
124                    deriving (Eq)
125
126 [NOTE: See end of these comments for what to do with 
127         data (C a, D b) => T a b = ...
128 ]
129
130 We want to come up with an instance declaration of the form
131
132         instance (Ping a, Pong b, ...) => Eq (T a b) where
133                 x == y = ...
134
135 It is pretty easy, albeit tedious, to fill in the code "...".  The
136 trick is to figure out what the context for the instance decl is,
137 namely @Ping@, @Pong@ and friends.
138
139 Let's call the context reqd for the T instance of class C at types
140 (a,b, ...)  C (T a b).  Thus:
141
142         Eq (T a b) = (Ping a, Pong b, ...)
143
144 Now we can get a (recursive) equation from the @data@ decl:
145
146         Eq (T a b) = Eq (Foo a) u Eq (Bar b)    -- From C1
147                    u Eq (T b a) u Eq Int        -- From C2
148                    u Eq (T a a)                 -- From C3
149
150 Foo and Bar may have explicit instances for @Eq@, in which case we can
151 just substitute for them.  Alternatively, either or both may have
152 their @Eq@ instances given by @deriving@ clauses, in which case they
153 form part of the system of equations.
154
155 Now all we need do is simplify and solve the equations, iterating to
156 find the least fixpoint.  Notice that the order of the arguments can
157 switch around, as here in the recursive calls to T.
158
159 Let's suppose Eq (Foo a) = Eq a, and Eq (Bar b) = Ping b.
160
161 We start with:
162
163         Eq (T a b) = {}         -- The empty set
164
165 Next iteration:
166         Eq (T a b) = Eq (Foo a) u Eq (Bar b)    -- From C1
167                    u Eq (T b a) u Eq Int        -- From C2
168                    u Eq (T a a)                 -- From C3
169
170         After simplification:
171                    = Eq a u Ping b u {} u {} u {}
172                    = Eq a u Ping b
173
174 Next iteration:
175
176         Eq (T a b) = Eq (Foo a) u Eq (Bar b)    -- From C1
177                    u Eq (T b a) u Eq Int        -- From C2
178                    u Eq (T a a)                 -- From C3
179
180         After simplification:
181                    = Eq a u Ping b
182                    u (Eq b u Ping a)
183                    u (Eq a u Ping a)
184
185                    = Eq a u Ping b u Eq b u Ping a
186
187 The next iteration gives the same result, so this is the fixpoint.  We
188 need to make a canonical form of the RHS to ensure convergence.  We do
189 this by simplifying the RHS to a form in which
190
191         - the classes constrain only tyvars
192         - the list is sorted by tyvar (major key) and then class (minor key)
193         - no duplicates, of course
194
195 So, here are the synonyms for the ``equation'' structures:
196
197
198 Note [Data decl contexts]
199 ~~~~~~~~~~~~~~~~~~~~~~~~~
200 Consider
201
202         data (RealFloat a) => Complex a = !a :+ !a deriving( Read )
203
204 We will need an instance decl like:
205
206         instance (Read a, RealFloat a) => Read (Complex a) where
207           ...
208
209 The RealFloat in the context is because the read method for Complex is bound
210 to construct a Complex, and doing that requires that the argument type is
211 in RealFloat. 
212
213 But this ain't true for Show, Eq, Ord, etc, since they don't construct
214 a Complex; they only take them apart.
215
216 Our approach: identify the offending classes, and add the data type
217 context to the instance decl.  The "offending classes" are
218
219         Read, Enum?
220
221 FURTHER NOTE ADDED March 2002.  In fact, Haskell98 now requires that
222 pattern matching against a constructor from a data type with a context
223 gives rise to the constraints for that context -- or at least the thinned
224 version.  So now all classes are "offending".
225
226 Note [Newtype deriving]
227 ~~~~~~~~~~~~~~~~~~~~~~~
228 Consider this:
229     class C a b
230     instance C [a] Char
231     newtype T = T Char deriving( C [a] )
232
233 Notice the free 'a' in the deriving.  We have to fill this out to 
234     newtype T = T Char deriving( forall a. C [a] )
235
236 And then translate it to:
237     instance C [a] Char => C [a] T where ...
238     
239         
240 Note [Newtype deriving superclasses]
241 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
242 (See also Trac #1220 for an interesting exchange on newtype
243 deriving and superclasses.)
244
245 The 'tys' here come from the partial application in the deriving
246 clause. The last arg is the new instance type.
247
248 We must pass the superclasses; the newtype might be an instance
249 of them in a different way than the representation type
250 E.g.            newtype Foo a = Foo a deriving( Show, Num, Eq )
251 Then the Show instance is not done via isomorphism; it shows
252         Foo 3 as "Foo 3"
253 The Num instance is derived via isomorphism, but the Show superclass
254 dictionary must the Show instance for Foo, *not* the Show dictionary
255 gotten from the Num dictionary. So we must build a whole new dictionary
256 not just use the Num one.  The instance we want is something like:
257      instance (Num a, Show (Foo a), Eq (Foo a)) => Num (Foo a) where
258         (+) = ((+)@a)
259         ...etc...
260 There may be a coercion needed which we get from the tycon for the newtype
261 when the dict is constructed in TcInstDcls.tcInstDecl2
262
263
264 Note [Unused constructors and deriving clauses]
265 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
266 See Trac #3221.  Consider
267    data T = T1 | T2 deriving( Show )
268 Are T1 and T2 unused?  Well, no: the deriving clause expands to mention
269 both of them.  So we gather defs/uses from deriving just like anything else.
270
271 %************************************************************************
272 %*                                                                      *
273 \subsection[TcDeriv-driver]{Top-level function for \tr{derivings}}
274 %*                                                                      *
275 %************************************************************************
276
277 \begin{code}
278 tcDeriving  :: [LTyClDecl Name]  -- All type constructors
279             -> [LInstDecl Name]  -- All instance declarations
280             -> [LDerivDecl Name] -- All stand-alone deriving declarations
281             -> TcM ([InstInfo Name],    -- The generated "instance decls"
282                     HsValBinds Name,    -- Extra generated top-level bindings
283                     DefUses)
284
285 tcDeriving tycl_decls inst_decls deriv_decls
286   = recoverM (return ([], emptyValBindsOut, emptyDUs)) $
287     do  {       -- Fish the "deriving"-related information out of the TcEnv
288                 -- And make the necessary "equations".
289           is_boot <- tcIsHsBoot
290         ; traceTc (text "tcDeriving" <+> ppr is_boot)
291         ; early_specs <- makeDerivSpecs is_boot tycl_decls inst_decls deriv_decls
292
293         ; overlap_flag <- getOverlapFlag
294         ; let (infer_specs, given_specs) = splitEithers early_specs
295         ; insts1 <- mapM (genInst True overlap_flag) given_specs
296
297         ; final_specs <- extendLocalInstEnv (map (iSpec . fst) insts1) $
298                          inferInstanceContexts overlap_flag infer_specs
299
300         ; insts2 <- mapM (genInst False overlap_flag) final_specs
301
302                  -- Generate the generic to/from functions from each type declaration
303         ; gen_binds <- mkGenericBinds is_boot tycl_decls
304         ; (inst_info, rn_binds, rn_dus) <- renameDeriv is_boot gen_binds (insts1 ++ insts2)
305
306         ; dflags <- getDOpts
307         ; liftIO (dumpIfSet_dyn dflags Opt_D_dump_deriv "Derived instances"
308                  (ddump_deriving inst_info rn_binds))
309
310         ; return (inst_info, rn_binds, rn_dus) }
311   where
312     ddump_deriving :: [InstInfo Name] -> HsValBinds Name -> SDoc
313     ddump_deriving inst_infos extra_binds
314       = vcat (map pprInstInfoDetails inst_infos) $$ ppr extra_binds
315
316 renameDeriv :: Bool -> LHsBinds RdrName
317             -> [(InstInfo RdrName, DerivAuxBinds)]
318             -> TcM ([InstInfo Name], HsValBinds Name, DefUses)
319 renameDeriv is_boot gen_binds insts
320   | is_boot     -- If we are compiling a hs-boot file, don't generate any derived bindings
321                 -- The inst-info bindings will all be empty, but it's easier to
322                 -- just use rn_inst_info to change the type appropriately
323   = do  { (rn_inst_infos, fvs) <- mapAndUnzipM rn_inst_info inst_infos  
324         ; return (rn_inst_infos, emptyValBindsOut, usesOnly (plusFVs fvs)) }
325
326   | otherwise
327   = discardWarnings $    -- Discard warnings about unused bindings etc
328     do  { (rn_gen, dus_gen) <- setOptM Opt_ScopedTypeVariables $  -- Type signatures in patterns 
329                                                                   -- are used in the generic binds
330                                rnTopBinds (ValBindsIn gen_binds [])
331         ; keepAliveSetTc (duDefs dus_gen)       -- Mark these guys to be kept alive
332
333                 -- Generate and rename any extra not-one-inst-decl-specific binds, 
334                 -- notably "con2tag" and/or "tag2con" functions.  
335                 -- Bring those names into scope before renaming the instances themselves
336         ; loc <- getSrcSpanM    -- Generic loc for shared bindings
337         ; let (aux_binds, aux_sigs) = unzip $ map (genAuxBind loc) $ 
338                                       rm_dups [] $ concat deriv_aux_binds
339               aux_val_binds = ValBindsIn (listToBag aux_binds) aux_sigs
340         ; rn_aux_lhs <- rnTopBindsLHS emptyFsEnv aux_val_binds
341         ; let aux_names = collectHsValBinders rn_aux_lhs
342
343         ; bindLocalNames aux_names $ 
344     do  { (rn_aux, dus_aux) <- rnTopBindsRHS (mkNameSet aux_names) rn_aux_lhs
345         ; (rn_inst_infos, fvs_insts) <- mapAndUnzipM rn_inst_info inst_infos
346         ; return (rn_inst_infos, rn_aux `plusHsValBinds` rn_gen,
347                   dus_gen `plusDU` dus_aux `plusDU` usesOnly (plusFVs fvs_insts)) } }
348
349   where
350     (inst_infos, deriv_aux_binds) = unzip insts
351     
352         -- Remove duplicate requests for auxilliary bindings
353     rm_dups acc [] = acc
354     rm_dups acc (b:bs) | any (isDupAux b) acc = rm_dups acc bs
355                        | otherwise            = rm_dups (b:acc) bs
356
357
358     rn_inst_info :: InstInfo RdrName -> TcM (InstInfo Name, FreeVars)
359     rn_inst_info info@(InstInfo { iBinds = NewTypeDerived coi tc })
360         = return ( info { iBinds = NewTypeDerived coi tc }
361                  , mkFVs (map dataConName (tyConDataCons tc)))
362           -- See Note [Newtype deriving and unused constructors]
363
364     rn_inst_info (InstInfo { iSpec = inst, iBinds = VanillaInst binds sigs standalone_deriv })
365         =       -- Bring the right type variables into 
366                 -- scope (yuk), and rename the method binds
367            ASSERT( null sigs )
368            bindLocalNames (map Var.varName tyvars) $
369            do { (rn_binds, fvs) <- rnMethodBinds clas_nm (\_ -> []) [] binds
370               ; let binds' = VanillaInst rn_binds [] standalone_deriv
371               ; return (InstInfo { iSpec = inst, iBinds = binds' }, fvs) }
372         where
373           (tyvars,_, clas,_) = instanceHead inst
374           clas_nm            = className clas
375
376 -----------------------------------------
377 mkGenericBinds :: Bool -> [LTyClDecl Name] -> TcM (LHsBinds RdrName)
378 mkGenericBinds is_boot tycl_decls
379   | is_boot 
380   = return emptyBag
381   | otherwise
382   = do  { tcs <- mapM tcLookupTyCon [ tcdName d 
383                                     | L _ d <- tycl_decls, isDataDecl d ]
384         ; return (unionManyBags [ mkTyConGenericBinds tc
385                                 | tc <- tcs, tyConHasGenerics tc ]) }
386                 -- We are only interested in the data type declarations,
387                 -- and then only in the ones whose 'has-generics' flag is on
388                 -- The predicate tyConHasGenerics finds both of these
389 \end{code}
390
391 Note [Newtype deriving and unused constructors]
392 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
393 Consider this (see Trac #1954):
394
395   module Bug(P) where
396   newtype P a = MkP (IO a) deriving Monad
397
398 If you compile with -fwarn-unused-binds you do not expect the warning
399 "Defined but not used: data consructor MkP". Yet the newtype deriving
400 code does not explicitly mention MkP, but it should behave as if you
401 had written
402   instance Monad P where
403      return x = MkP (return x)
404      ...etc...
405
406 So we want to signal a user of the data constructor 'MkP'.  That's
407 what we do in rn_inst_info, and it's the only reason we have the TyCon
408 stored in NewTypeDerived.
409
410
411 %************************************************************************
412 %*                                                                      *
413                 From HsSyn to DerivSpec
414 %*                                                                      *
415 %************************************************************************
416
417 @makeDerivSpecs@ fishes around to find the info about needed derived instances.
418
419 \begin{code}
420 makeDerivSpecs :: Bool 
421                -> [LTyClDecl Name] 
422                -> [LInstDecl Name]
423                -> [LDerivDecl Name] 
424                -> TcM [EarlyDerivSpec]
425
426 makeDerivSpecs is_boot tycl_decls inst_decls deriv_decls
427   | is_boot     -- No 'deriving' at all in hs-boot files
428   = do  { mapM_ add_deriv_err deriv_locs 
429         ; return [] }
430   | otherwise
431   = do  { eqns1 <- mapAndRecoverM deriveTyData all_tydata
432         ; eqns2 <- mapAndRecoverM deriveStandalone deriv_decls
433         ; return (eqns1 ++ eqns2) }
434   where
435     extractTyDataPreds decls
436       = [(p, d) | d@(L _ (TyData {tcdDerivs = Just preds})) <- decls, p <- preds]
437
438     all_tydata :: [(LHsType Name, LTyClDecl Name)]
439         -- Derived predicate paired with its data type declaration
440     all_tydata = extractTyDataPreds (instDeclATs inst_decls ++ tycl_decls)
441
442     deriv_locs = map (getLoc . snd) all_tydata
443                  ++ map getLoc deriv_decls
444
445     add_deriv_err loc = setSrcSpan loc $
446                         addErr (hang (ptext (sLit "Deriving not permitted in hs-boot file"))
447                                    2 (ptext (sLit "Use an instance declaration instead")))
448
449 ------------------------------------------------------------------
450 deriveStandalone :: LDerivDecl Name -> TcM EarlyDerivSpec
451 -- Standalone deriving declarations
452 --  e.g.   deriving instance Show a => Show (T a)
453 -- Rather like tcLocalInstDecl
454 deriveStandalone (L loc (DerivDecl deriv_ty))
455   = setSrcSpan loc                   $
456     addErrCtxt (standaloneCtxt deriv_ty)  $
457     do { traceTc (text "standalone deriving decl for" <+> ppr deriv_ty)
458        ; (tvs, theta, tau) <- tcHsInstHead deriv_ty
459        ; traceTc (text "standalone deriving;"
460               <+> text "tvs:" <+> ppr tvs
461               <+> text "theta:" <+> ppr theta
462               <+> text "tau:" <+> ppr tau)
463        ; (cls, inst_tys) <- checkValidInstance deriv_ty tvs theta tau
464                 -- C.f. TcInstDcls.tcLocalInstDecl1
465
466        ; let cls_tys = take (length inst_tys - 1) inst_tys
467              inst_ty = last inst_tys
468        ; traceTc (text "standalone deriving;"
469               <+> text "class:" <+> ppr cls
470               <+> text "class types:" <+> ppr cls_tys
471               <+> text "type:" <+> ppr inst_ty)
472        ; mkEqnHelp StandAloneDerivOrigin tvs cls cls_tys inst_ty
473                    (Just theta) }
474
475 ------------------------------------------------------------------
476 deriveTyData :: (LHsType Name, LTyClDecl Name) -> TcM EarlyDerivSpec
477 deriveTyData (L loc deriv_pred, L _ decl@(TyData { tcdLName = L _ tycon_name, 
478                                                    tcdTyVars = tv_names, 
479                                                    tcdTyPats = ty_pats }))
480   = setSrcSpan loc     $        -- Use the location of the 'deriving' item
481     tcAddDeclCtxt decl $
482     do  { (tvs, tc, tc_args) <- get_lhs ty_pats
483         ; tcExtendTyVarEnv tvs $        -- Deriving preds may (now) mention
484                                         -- the type variables for the type constructor
485
486     do  { (deriv_tvs, cls, cls_tys) <- tcHsDeriv deriv_pred
487                 -- The "deriv_pred" is a LHsType to take account of the fact that for
488                 -- newtype deriving we allow deriving (forall a. C [a]).
489
490         -- Given data T a b c = ... deriving( C d ),
491         -- we want to drop type variables from T so that (C d (T a)) is well-kinded
492         ; let cls_tyvars = classTyVars cls
493               kind = tyVarKind (last cls_tyvars)
494               (arg_kinds, _) = splitKindFunTys kind
495               n_args_to_drop = length arg_kinds 
496               n_args_to_keep = tyConArity tc - n_args_to_drop
497               args_to_drop   = drop n_args_to_keep tc_args
498               inst_ty        = mkTyConApp tc (take n_args_to_keep tc_args)
499               inst_ty_kind   = typeKind inst_ty
500               dropped_tvs    = mkVarSet (mapCatMaybes getTyVar_maybe args_to_drop)
501               univ_tvs       = (mkVarSet tvs `extendVarSetList` deriv_tvs)
502                                         `minusVarSet` dropped_tvs
503  
504         -- Check that the result really is well-kinded
505         ; checkTc (n_args_to_keep >= 0 && (inst_ty_kind `eqKind` kind))
506                   (derivingKindErr tc cls cls_tys kind)
507
508         ; checkTc (sizeVarSet dropped_tvs == n_args_to_drop &&           -- (a)
509                    tyVarsOfTypes (inst_ty:cls_tys) `subVarSet` univ_tvs) -- (b)
510                   (derivingEtaErr cls cls_tys inst_ty)
511                 -- Check that 
512                 --  (a) The data type can be eta-reduced; eg reject:
513                 --              data instance T a a = ... deriving( Monad )
514                 --  (b) The type class args do not mention any of the dropped type
515                 --      variables 
516                 --              newtype T a s = ... deriving( ST s )
517
518         -- Type families can't be partially applied
519         -- e.g.   newtype instance T Int a = MkT [a] deriving( Monad )
520         -- Note [Deriving, type families, and partial applications]
521         ; checkTc (not (isOpenTyCon tc) || n_args_to_drop == 0)
522                   (typeFamilyPapErr tc cls cls_tys inst_ty)
523
524         ; mkEqnHelp DerivOrigin (varSetElems univ_tvs) cls cls_tys inst_ty Nothing } }
525   where
526         -- Tiresomely we must figure out the "lhs", which is awkward for type families
527         -- E.g.   data T a b = .. deriving( Eq )
528         --          Here, the lhs is (T a b)
529         --        data instance TF Int b = ... deriving( Eq )
530         --          Here, the lhs is (TF Int b)
531         -- But if we just look up the tycon_name, we get is the *family*
532         -- tycon, but not pattern types -- they are in the *rep* tycon.
533     get_lhs Nothing     = do { tc <- tcLookupTyCon tycon_name
534                              ; let tvs = tyConTyVars tc
535                              ; return (tvs, tc, mkTyVarTys tvs) }
536     get_lhs (Just pats) = do { let hs_app = nlHsTyConApp tycon_name pats
537                              ; (tvs, tc_app) <- tcHsQuantifiedType tv_names hs_app
538                              ; let (tc, tc_args) = tcSplitTyConApp tc_app
539                              ; return (tvs, tc, tc_args) }
540
541 deriveTyData _other
542   = panic "derivTyData" -- Caller ensures that only TyData can happen
543 \end{code}
544
545 Note [Deriving, type families, and partial applications]
546 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
547 When there are no type families, it's quite easy:
548
549     newtype S a = MkS [a]
550     -- :CoS :: S  ~ []  -- Eta-reduced
551
552     instance Eq [a] => Eq (S a)         -- by coercion sym (Eq (:CoS a)) : Eq [a] ~ Eq (S a)
553     instance Monad [] => Monad S        -- by coercion sym (Monad :CoS)  : Monad [] ~ Monad S 
554
555 When type familes are involved it's trickier:
556
557     data family T a b
558     newtype instance T Int a = MkT [a] deriving( Eq, Monad )
559     -- :RT is the representation type for (T Int a)
560     --  :CoF:R1T a :: T Int a ~ :RT a   -- Not eta reduced
561     --  :Co:R1T    :: :RT ~ []          -- Eta-reduced
562
563     instance Eq [a] => Eq (T Int a)     -- easy by coercion
564     instance Monad [] => Monad (T Int)  -- only if we can eta reduce???
565
566 The "???" bit is that we don't build the :CoF thing in eta-reduced form
567 Henc the current typeFamilyPapErr, even though the instance makes sense.
568 After all, we can write it out
569     instance Monad [] => Monad (T Int)  -- only if we can eta reduce???
570       return x = MkT [x]
571       ... etc ...       
572
573 \begin{code}
574 mkEqnHelp :: InstOrigin -> [TyVar] -> Class -> [Type] -> Type
575           -> DerivContext       -- Just    => context supplied (standalone deriving)
576                                 -- Nothing => context inferred (deriving on data decl)
577           -> TcRn EarlyDerivSpec
578 -- Make the EarlyDerivSpec for an instance
579 --      forall tvs. theta => cls (tys ++ [ty])
580 -- where the 'theta' is optional (that's the Maybe part)
581 -- Assumes that this declaration is well-kinded
582
583 mkEqnHelp orig tvs cls cls_tys tc_app mtheta
584   | Just (tycon, tc_args) <- tcSplitTyConApp_maybe tc_app
585   , isAlgTyCon tycon    -- Check for functions, primitive types etc
586   = do  { (rep_tc, rep_tc_args) <- tcLookupFamInstExact tycon tc_args
587                   -- Be careful to test rep_tc here: in the case of families, 
588                   -- we want to check the instance tycon, not the family tycon
589
590         -- For standalone deriving (mtheta /= Nothing), 
591         -- check that all the data constructors are in scope.
592         -- No need for this when deriving Typeable, becuase we don't need
593         -- the constructors for that.
594         ; rdr_env <- getGlobalRdrEnv
595         ; let hidden_data_cons = isAbstractTyCon rep_tc || any not_in_scope (tyConDataCons rep_tc)
596               not_in_scope dc  = null (lookupGRE_Name rdr_env (dataConName dc))
597         ; checkTc (isNothing mtheta || 
598                    not hidden_data_cons ||
599                    className cls `elem` typeableClassNames) 
600                   (derivingHiddenErr tycon)
601
602         ; dflags <- getDOpts
603         ; if isDataTyCon rep_tc then
604                 mkDataTypeEqn orig dflags tvs cls cls_tys
605                               tycon tc_args rep_tc rep_tc_args mtheta
606           else
607                 mkNewTypeEqn orig dflags tvs cls cls_tys 
608                              tycon tc_args rep_tc rep_tc_args mtheta }
609   | otherwise
610   = failWithTc (derivingThingErr False cls cls_tys tc_app
611                (ptext (sLit "The last argument of the instance must be a data or newtype application")))
612 \end{code}
613
614 Note [Looking up family instances for deriving]
615 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
616 tcLookupFamInstExact is an auxiliary lookup wrapper which requires
617 that looked-up family instances exist.  If called with a vanilla
618 tycon, the old type application is simply returned.
619
620 If we have
621   data instance F () = ... deriving Eq
622   data instance F () = ... deriving Eq
623 then tcLookupFamInstExact will be confused by the two matches;
624 but that can't happen because tcInstDecls1 doesn't call tcDeriving
625 if there are any overlaps.
626
627 There are two other things that might go wrong with the lookup.
628 First, we might see a standalone deriving clause
629         deriving Eq (F ())
630 when there is no data instance F () in scope. 
631
632 Note that it's OK to have
633   data instance F [a] = ...
634   deriving Eq (F [(a,b)])
635 where the match is not exact; the same holds for ordinary data types
636 with standalone deriving declrations.
637
638 \begin{code}
639 tcLookupFamInstExact :: TyCon -> [Type] -> TcM (TyCon, [Type])
640 tcLookupFamInstExact tycon tys
641   | not (isOpenTyCon tycon)
642   = return (tycon, tys)
643   | otherwise
644   = do { maybeFamInst <- tcLookupFamInst tycon tys
645        ; case maybeFamInst of
646            Nothing      -> famInstNotFound tycon tys
647            Just famInst -> return famInst
648        }
649
650 famInstNotFound :: TyCon -> [Type] -> TcM a
651 famInstNotFound tycon tys 
652   = failWithTc (ptext (sLit "No family instance for")
653                         <+> quotes (pprTypeApp tycon tys))
654 \end{code}
655
656
657 %************************************************************************
658 %*                                                                      *
659                 Deriving data types
660 %*                                                                      *
661 %************************************************************************
662
663 \begin{code}
664 mkDataTypeEqn :: InstOrigin
665               -> DynFlags
666               -> [Var]                  -- Universally quantified type variables in the instance
667               -> Class                  -- Class for which we need to derive an instance
668               -> [Type]                 -- Other parameters to the class except the last
669               -> TyCon                  -- Type constructor for which the instance is requested 
670                                         --    (last parameter to the type class)
671               -> [Type]                 -- Parameters to the type constructor
672               -> TyCon                  -- rep of the above (for type families)
673               -> [Type]                 -- rep of the above
674               -> DerivContext        -- Context of the instance, for standalone deriving
675               -> TcRn EarlyDerivSpec    -- Return 'Nothing' if error
676
677 mkDataTypeEqn orig dflags tvs cls cls_tys
678               tycon tc_args rep_tc rep_tc_args mtheta
679   = case checkSideConditions dflags mtheta cls cls_tys rep_tc of
680         -- NB: pass the *representation* tycon to checkSideConditions
681         CanDerive               -> go_for_it
682         NonDerivableClass       -> bale_out (nonStdErr cls)
683         DerivableClassError msg -> bale_out msg
684   where
685     go_for_it    = mk_data_eqn orig tvs cls tycon tc_args rep_tc rep_tc_args mtheta
686     bale_out msg = failWithTc (derivingThingErr False cls cls_tys (mkTyConApp tycon tc_args) msg)
687
688 mk_data_eqn, mk_typeable_eqn
689    :: InstOrigin -> [TyVar] -> Class 
690    -> TyCon -> [TcType] -> TyCon -> [TcType] -> DerivContext
691    -> TcM EarlyDerivSpec
692 mk_data_eqn orig tvs cls tycon tc_args rep_tc rep_tc_args mtheta
693   | getName cls `elem` typeableClassNames
694   = mk_typeable_eqn orig tvs cls tycon tc_args rep_tc rep_tc_args mtheta
695
696   | otherwise
697   = do  { dfun_name <- new_dfun_name cls tycon
698         ; loc <- getSrcSpanM
699         ; let inst_tys = [mkTyConApp tycon tc_args]
700               inferred_constraints = inferConstraints tvs cls inst_tys rep_tc rep_tc_args
701               spec = DS { ds_loc = loc, ds_orig = orig
702                         , ds_name = dfun_name, ds_tvs = tvs 
703                         , ds_cls = cls, ds_tys = inst_tys
704                         , ds_tc = rep_tc, ds_tc_args = rep_tc_args
705                         , ds_theta =  mtheta `orElse` inferred_constraints
706                         , ds_newtype = False }
707
708         ; return (if isJust mtheta then Right spec      -- Specified context
709                                    else Left spec) }    -- Infer context
710
711 mk_typeable_eqn orig tvs cls tycon tc_args rep_tc rep_tc_args mtheta
712         -- The Typeable class is special in several ways
713         --        data T a b = ... deriving( Typeable )
714         -- gives
715         --        instance Typeable2 T where ...
716         -- Notice that:
717         -- 1. There are no constraints in the instance
718         -- 2. There are no type variables either
719         -- 3. The actual class we want to generate isn't necessarily
720         --      Typeable; it depends on the arity of the type
721   | isNothing mtheta    -- deriving on a data type decl
722   = do  { checkTc (cls `hasKey` typeableClassKey)
723                   (ptext (sLit "Use deriving( Typeable ) on a data type declaration"))
724         ; real_cls <- tcLookupClass (typeableClassNames !! tyConArity tycon)
725         ; mk_typeable_eqn orig tvs real_cls tycon [] rep_tc [] (Just []) }
726
727   | otherwise           -- standaone deriving
728   = do  { checkTc (null tc_args)
729                   (ptext (sLit "Derived typeable instance must be of form (Typeable") 
730                         <> int (tyConArity tycon) <+> ppr tycon <> rparen)
731         ; dfun_name <- new_dfun_name cls tycon
732         ; loc <- getSrcSpanM
733         ; return (Right $
734                   DS { ds_loc = loc, ds_orig = orig, ds_name = dfun_name, ds_tvs = []
735                      , ds_cls = cls, ds_tys = [mkTyConApp tycon []]
736                      , ds_tc = rep_tc, ds_tc_args = rep_tc_args
737                      , ds_theta = mtheta `orElse` [], ds_newtype = False })  }
738
739
740 inferConstraints :: [TyVar] -> Class -> [TcType] -> TyCon -> [TcType] -> ThetaType
741 -- Generate a sufficiently large set of constraints that typechecking the
742 -- generated method definitions should succeed.   This set will be simplified
743 -- before being used in the instance declaration
744 inferConstraints _ cls inst_tys rep_tc rep_tc_args
745   = ASSERT2( equalLength rep_tc_tvs all_rep_tc_args, ppr cls <+> ppr rep_tc )
746     stupid_constraints ++ extra_constraints
747     ++ sc_constraints ++ con_arg_constraints
748   where
749        -- Constraints arising from the arguments of each constructor
750     con_arg_constraints
751       = [ mkClassPred cls [arg_ty] 
752         | data_con <- tyConDataCons rep_tc,
753           arg_ty   <- ASSERT( isVanillaDataCon data_con )
754                         get_constrained_tys $
755                         dataConInstOrigArgTys data_con all_rep_tc_args,
756           not (isUnLiftedType arg_ty) ]
757                 -- No constraints for unlifted types
758                 -- Where they are legal we generate specilised function calls
759
760                 -- For functor-like classes, two things are different
761                 -- (a) We recurse over argument types to generate constraints
762                 --     See Functor examples in TcGenDeriv
763                 -- (b) The rep_tc_args will be one short
764     is_functor_like = getUnique cls `elem` functorLikeClassKeys
765
766     get_constrained_tys :: [Type] -> [Type]
767     get_constrained_tys tys 
768         | is_functor_like = concatMap (deepSubtypesContaining last_tv) tys
769         | otherwise       = tys
770
771     rep_tc_tvs = tyConTyVars rep_tc
772     last_tv = last rep_tc_tvs
773     all_rep_tc_args | is_functor_like = rep_tc_args ++ [mkTyVarTy last_tv]
774                     | otherwise       = rep_tc_args
775
776         -- Constraints arising from superclasses
777         -- See Note [Superclasses of derived instance]
778     sc_constraints = substTheta (zipOpenTvSubst (classTyVars cls) inst_tys)
779                                 (classSCTheta cls)
780
781         -- Stupid constraints
782     stupid_constraints = substTheta subst (tyConStupidTheta rep_tc)
783     subst = zipTopTvSubst rep_tc_tvs all_rep_tc_args
784               
785         -- Extra Data constraints
786         -- The Data class (only) requires that for 
787         --    instance (...) => Data (T t1 t2) 
788         -- IF   t1:*, t2:*
789         -- THEN (Data t1, Data t2) are among the (...) constraints
790         -- Reason: when the IF holds, we generate a method
791         --             dataCast2 f = gcast2 f
792         --         and we need the Data constraints to typecheck the method
793     extra_constraints 
794       | cls `hasKey` dataClassKey
795       , all (isLiftedTypeKind . typeKind) rep_tc_args 
796       = [mkClassPred cls [ty] | ty <- rep_tc_args]
797       | otherwise 
798       = []
799
800 ------------------------------------------------------------------
801 -- Check side conditions that dis-allow derivability for particular classes
802 -- This is *apart* from the newtype-deriving mechanism
803 --
804 -- Here we get the representation tycon in case of family instances as it has
805 -- the data constructors - but we need to be careful to fall back to the
806 -- family tycon (with indexes) in error messages.
807
808 data DerivStatus = CanDerive
809                  | DerivableClassError SDoc     -- Standard class, but can't do it
810                  | NonDerivableClass            -- Non-standard class
811
812 checkSideConditions :: DynFlags -> DerivContext -> Class -> [TcType] -> TyCon -> DerivStatus
813 checkSideConditions dflags mtheta cls cls_tys rep_tc
814   | Just cond <- sideConditions mtheta cls
815   = case (cond (dflags, rep_tc)) of
816         Just err -> DerivableClassError err     -- Class-specific error
817         Nothing  | null cls_tys -> CanDerive    -- All derivable classes are unary, so
818                                                 -- cls_tys (the type args other than last) 
819                                                 -- should be null
820                  | otherwise    -> DerivableClassError ty_args_why      -- e.g. deriving( Eq s )
821   | otherwise = NonDerivableClass       -- Not a standard class
822   where
823     ty_args_why = quotes (ppr (mkClassPred cls cls_tys)) <+> ptext (sLit "is not a class")
824
825 nonStdErr :: Class -> SDoc
826 nonStdErr cls = quotes (ppr cls) <+> ptext (sLit "is not a derivable class")
827
828 sideConditions :: DerivContext -> Class -> Maybe Condition
829 sideConditions mtheta cls
830   | cls_key == eqClassKey          = Just cond_std
831   | cls_key == ordClassKey         = Just cond_std
832   | cls_key == showClassKey        = Just cond_std
833   | cls_key == readClassKey        = Just (cond_std `andCond` cond_noUnliftedArgs)
834   | cls_key == enumClassKey        = Just (cond_std `andCond` cond_isEnumeration)
835   | cls_key == ixClassKey          = Just (cond_std `andCond` cond_enumOrProduct)
836   | cls_key == boundedClassKey     = Just (cond_std `andCond` cond_enumOrProduct)
837   | cls_key == dataClassKey        = Just (checkFlag Opt_DeriveDataTypeable `andCond` 
838                                            cond_std `andCond` cond_noUnliftedArgs)
839   | cls_key == functorClassKey     = Just (checkFlag Opt_DeriveFunctor `andCond`
840                                            cond_functorOK True)  -- NB: no cond_std!
841   | cls_key == foldableClassKey    = Just (checkFlag Opt_DeriveFoldable `andCond`
842                                            cond_functorOK False) -- Functor/Fold/Trav works ok for rank-n types
843   | cls_key == traversableClassKey = Just (checkFlag Opt_DeriveTraversable `andCond`
844                                            cond_functorOK False)
845   | getName cls `elem` typeableClassNames = Just (checkFlag Opt_DeriveDataTypeable `andCond` cond_typeableOK)
846   | otherwise = Nothing
847   where
848     cls_key = getUnique cls
849     cond_std = cond_stdOK mtheta
850
851 type Condition = (DynFlags, TyCon) -> Maybe SDoc
852         -- first Bool is whether or not we are allowed to derive Data and Typeable
853         -- second Bool is whether or not we are allowed to derive Functor
854         -- TyCon is the *representation* tycon if the 
855         --      data type is an indexed one
856         -- Nothing => OK
857
858 orCond :: Condition -> Condition -> Condition
859 orCond c1 c2 tc 
860   = case c1 tc of
861         Nothing -> Nothing              -- c1 succeeds
862         Just x  -> case c2 tc of        -- c1 fails
863                      Nothing -> Nothing
864                      Just y  -> Just (x $$ ptext (sLit "  and") $$ y)
865                                         -- Both fail
866
867 andCond :: Condition -> Condition -> Condition
868 andCond c1 c2 tc = case c1 tc of
869                      Nothing -> c2 tc   -- c1 succeeds
870                      Just x  -> Just x  -- c1 fails
871
872 cond_stdOK :: DerivContext -> Condition
873 cond_stdOK (Just _) _
874   = Nothing     -- Don't check these conservative conditions for
875                 -- standalone deriving; just generate the code
876 cond_stdOK Nothing (_, rep_tc)
877   | null data_cons      = Just (no_cons_why $$ suggestion)
878   | not (null con_whys) = Just (vcat con_whys $$ suggestion)
879   | otherwise           = Nothing
880   where
881     suggestion  = ptext (sLit "Possible fix: use a standalone deriving declaration instead")
882     data_cons   = tyConDataCons rep_tc
883     no_cons_why = quotes (pprSourceTyCon rep_tc) <+> 
884                   ptext (sLit "has no data constructors")
885
886     con_whys = mapCatMaybes check_con data_cons
887
888     check_con :: DataCon -> Maybe SDoc
889     check_con con 
890       | isVanillaDataCon con
891       , all isTauTy (dataConOrigArgTys con) = Nothing
892       | otherwise = Just (badCon con (ptext (sLit "does not have a Haskell-98 type")))
893   
894 cond_enumOrProduct :: Condition
895 cond_enumOrProduct = cond_isEnumeration `orCond` 
896                        (cond_isProduct `andCond` cond_noUnliftedArgs)
897
898 cond_noUnliftedArgs :: Condition
899 -- For some classes (eg Eq, Ord) we allow unlifted arg types
900 -- by generating specilaised code.  For others (eg Data) we don't.
901 cond_noUnliftedArgs (_, tc)
902   | null bad_cons = Nothing
903   | otherwise     = Just why
904   where
905     bad_cons = [ con | con <- tyConDataCons tc
906                      , any isUnLiftedType (dataConOrigArgTys con) ]
907     why = badCon (head bad_cons) (ptext (sLit "has arguments of unlifted type"))
908
909 cond_isEnumeration :: Condition
910 cond_isEnumeration (_, rep_tc)
911   | isEnumerationTyCon rep_tc = Nothing
912   | otherwise                 = Just why
913   where
914     why = quotes (pprSourceTyCon rep_tc) <+> 
915           ptext (sLit "has non-nullary constructors")
916
917 cond_isProduct :: Condition
918 cond_isProduct (_, rep_tc)
919   | isProductTyCon rep_tc = Nothing
920   | otherwise             = Just why
921   where
922     why = quotes (pprSourceTyCon rep_tc) <+> 
923           ptext (sLit "has more than one constructor")
924
925 cond_typeableOK :: Condition
926 -- OK for Typeable class
927 -- Currently: (a) args all of kind *
928 --            (b) 7 or fewer args
929 cond_typeableOK (_, rep_tc)
930   | tyConArity rep_tc > 7       = Just too_many
931   | not (all (isSubArgTypeKind . tyVarKind) (tyConTyVars rep_tc)) 
932                                 = Just bad_kind
933   | isFamInstTyCon rep_tc       = Just fam_inst  -- no Typable for family insts
934   | otherwise                   = Nothing
935   where
936     too_many = quotes (pprSourceTyCon rep_tc) <+> 
937                ptext (sLit "has too many arguments")
938     bad_kind = quotes (pprSourceTyCon rep_tc) <+> 
939                ptext (sLit "has arguments of kind other than `*'")
940     fam_inst = quotes (pprSourceTyCon rep_tc) <+> 
941                ptext (sLit "is a type family")
942
943
944 functorLikeClassKeys :: [Unique]
945 functorLikeClassKeys = [functorClassKey, foldableClassKey, traversableClassKey]
946
947 cond_functorOK :: Bool -> Condition
948 -- OK for Functor class
949 -- Currently: (a) at least one argument
950 --            (b) don't use argument contravariantly
951 --            (c) don't use argument in the wrong place, e.g. data T a = T (X a a)
952 --            (d) optionally: don't use function types
953 cond_functorOK allowFunctions (dflags, rep_tc) 
954   | not (dopt Opt_DeriveFunctor dflags)
955   = Just (ptext (sLit "You need -XDeriveFunctor to derive an instance for this class"))
956   | otherwise
957   = msum (map check_con data_cons)      -- msum picks the first 'Just', if any
958   where
959     data_cons = tyConDataCons rep_tc
960     check_con con = msum (check_vanilla con : foldDataConArgs (ft_check con) con)
961
962     check_vanilla :: DataCon -> Maybe SDoc
963     check_vanilla con | isVanillaDataCon con = Nothing
964                       | otherwise            = Just (badCon con existential)
965
966     ft_check :: DataCon -> FFoldType (Maybe SDoc)
967     ft_check con = FT { ft_triv = Nothing, ft_var = Nothing
968                       , ft_co_var = Just (badCon con covariant)
969                       , ft_fun = \x y -> if allowFunctions then x `mplus` y 
970                                                            else Just (badCon con functions)
971                       , ft_tup = \_ xs  -> msum xs
972                       , ft_ty_app = \_ x   -> x
973                       , ft_bad_app = Just (badCon con wrong_arg)
974                       , ft_forall = \_ x   -> x }
975                     
976     existential = ptext (sLit "has existential arguments")
977     covariant   = ptext (sLit "uses the type variable in a function argument")
978     functions   = ptext (sLit "contains function types")
979     wrong_arg   = ptext (sLit "uses the type variable in an argument other than the last")
980
981 checkFlag :: ExtensionFlag -> Condition
982 checkFlag flag (dflags, _)
983   | dopt flag dflags = Nothing
984   | otherwise        = Just why
985   where
986     why = ptext (sLit "You need -X") <> text flag_str 
987           <+> ptext (sLit "to derive an instance for this class")
988     flag_str = case [ s | (s, f, _) <- xFlags, f==flag ] of
989                  [s]   -> s
990                  other -> pprPanic "checkFlag" (ppr other)
991
992 std_class_via_iso :: Class -> Bool
993 -- These standard classes can be derived for a newtype
994 -- using the isomorphism trick *even if no -XGeneralizedNewtypeDeriving
995 -- because giving so gives the same results as generating the boilerplate
996 std_class_via_iso clas  
997   = classKey clas `elem` [eqClassKey, ordClassKey, ixClassKey, boundedClassKey]
998         -- Not Read/Show because they respect the type
999         -- Not Enum, because newtypes are never in Enum
1000
1001
1002 non_iso_class :: Class -> Bool
1003 -- *Never* derive Read,Show,Typeable,Data by isomorphism,
1004 -- even with -XGeneralizedNewtypeDeriving
1005 non_iso_class cls 
1006   = classKey cls `elem` ([readClassKey, showClassKey, dataClassKey] ++
1007                          typeableClassKeys)
1008
1009 typeableClassKeys :: [Unique]
1010 typeableClassKeys = map getUnique typeableClassNames
1011
1012 new_dfun_name :: Class -> TyCon -> TcM Name
1013 new_dfun_name clas tycon        -- Just a simple wrapper
1014   = do { loc <- getSrcSpanM     -- The location of the instance decl, not of the tycon
1015         ; newDFunName clas [mkTyConApp tycon []] loc }
1016         -- The type passed to newDFunName is only used to generate
1017         -- a suitable string; hence the empty type arg list
1018
1019 badCon :: DataCon -> SDoc -> SDoc
1020 badCon con msg = ptext (sLit "Constructor") <+> quotes (ppr con) <+> msg
1021 \end{code}
1022
1023 Note [Superclasses of derived instance] 
1024 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1025 In general, a derived instance decl needs the superclasses of the derived
1026 class too.  So if we have
1027         data T a = ...deriving( Ord )
1028 then the initial context for Ord (T a) should include Eq (T a).  Often this is 
1029 redundant; we'll also generate an Ord constraint for each constructor argument,
1030 and that will probably generate enough constraints to make the Eq (T a) constraint 
1031 be satisfied too.  But not always; consider:
1032
1033  data S a = S
1034  instance Eq (S a)
1035  instance Ord (S a)
1036
1037  data T a = MkT (S a) deriving( Ord )
1038  instance Num a => Eq (T a)
1039
1040 The derived instance for (Ord (T a)) must have a (Num a) constraint!
1041 Similarly consider:
1042         data T a = MkT deriving( Data, Typeable )
1043 Here there *is* no argument field, but we must nevertheless generate
1044 a context for the Data instances:
1045         instance Typable a => Data (T a) where ...
1046
1047
1048 %************************************************************************
1049 %*                                                                      *
1050                 Deriving newtypes
1051 %*                                                                      *
1052 %************************************************************************
1053
1054 \begin{code}
1055 mkNewTypeEqn :: InstOrigin -> DynFlags -> [Var] -> Class
1056              -> [Type] -> TyCon -> [Type] -> TyCon -> [Type]
1057              -> DerivContext
1058              -> TcRn EarlyDerivSpec
1059 mkNewTypeEqn orig dflags tvs
1060              cls cls_tys tycon tc_args rep_tycon rep_tc_args mtheta
1061 -- Want: instance (...) => cls (cls_tys ++ [tycon tc_args]) where ...
1062   | can_derive_via_isomorphism && (newtype_deriving || std_class_via_iso cls)
1063   = do  { traceTc (text "newtype deriving:" <+> ppr tycon <+> ppr rep_tys)
1064         ; dfun_name <- new_dfun_name cls tycon
1065         ; loc <- getSrcSpanM
1066         ; let spec = DS { ds_loc = loc, ds_orig = orig
1067                         , ds_name = dfun_name, ds_tvs = varSetElems dfun_tvs 
1068                         , ds_cls = cls, ds_tys = inst_tys
1069                         , ds_tc = rep_tycon, ds_tc_args = rep_tc_args
1070                         , ds_theta =  mtheta `orElse` all_preds
1071                         , ds_newtype = True }
1072         ; return (if isJust mtheta then Right spec
1073                                    else Left spec) }
1074
1075   | otherwise
1076   = case checkSideConditions dflags mtheta cls cls_tys rep_tycon of
1077       CanDerive -> go_for_it    -- Use the standard H98 method
1078       DerivableClassError msg   -- Error with standard class
1079         | can_derive_via_isomorphism -> bale_out (msg $$ suggest_nd)
1080         | otherwise                  -> bale_out msg
1081       NonDerivableClass         -- Must use newtype deriving
1082         | newtype_deriving           -> bale_out cant_derive_err  -- Too hard, even with newtype deriving
1083         | can_derive_via_isomorphism -> bale_out (non_std $$ suggest_nd) -- Try newtype deriving!
1084         | otherwise                  -> bale_out non_std
1085   where
1086         newtype_deriving = dopt Opt_GeneralizedNewtypeDeriving dflags
1087         go_for_it        = mk_data_eqn orig tvs cls tycon tc_args rep_tycon rep_tc_args mtheta
1088         bale_out msg     = failWithTc (derivingThingErr newtype_deriving cls cls_tys inst_ty msg)
1089
1090         non_std    = nonStdErr cls
1091         suggest_nd = ptext (sLit "Try -XGeneralizedNewtypeDeriving for GHC's newtype-deriving extension")
1092
1093         -- Here is the plan for newtype derivings.  We see
1094         --        newtype T a1...an = MkT (t ak+1...an) deriving (.., C s1 .. sm, ...)
1095         -- where t is a type,
1096         --       ak+1...an is a suffix of a1..an, and are all tyars
1097         --       ak+1...an do not occur free in t, nor in the s1..sm
1098         --       (C s1 ... sm) is a  *partial applications* of class C 
1099         --                      with the last parameter missing
1100         --       (T a1 .. ak) matches the kind of C's last argument
1101         --              (and hence so does t)
1102         -- The latter kind-check has been done by deriveTyData already,
1103         -- and tc_args are already trimmed
1104         --
1105         -- We generate the instance
1106         --       instance forall ({a1..ak} u fvs(s1..sm)).
1107         --                C s1 .. sm t => C s1 .. sm (T a1...ak)
1108         -- where T a1...ap is the partial application of 
1109         --       the LHS of the correct kind and p >= k
1110         --
1111         --      NB: the variables below are:
1112         --              tc_tvs = [a1, ..., an]
1113         --              tyvars_to_keep = [a1, ..., ak]
1114         --              rep_ty = t ak .. an
1115         --              deriv_tvs = fvs(s1..sm) \ tc_tvs
1116         --              tys = [s1, ..., sm]
1117         --              rep_fn' = t
1118         --
1119         -- Running example: newtype T s a = MkT (ST s a) deriving( Monad )
1120         -- We generate the instance
1121         --      instance Monad (ST s) => Monad (T s) where 
1122
1123         nt_eta_arity = length (fst (newTyConEtadRhs rep_tycon))
1124                 -- For newtype T a b = MkT (S a a b), the TyCon machinery already
1125                 -- eta-reduces the representation type, so we know that
1126                 --      T a ~ S a a
1127                 -- That's convenient here, because we may have to apply
1128                 -- it to fewer than its original complement of arguments
1129
1130         -- Note [Newtype representation]
1131         -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1132         -- Need newTyConRhs (*not* a recursive representation finder) 
1133         -- to get the representation type. For example
1134         --      newtype B = MkB Int
1135         --      newtype A = MkA B deriving( Num )
1136         -- We want the Num instance of B, *not* the Num instance of Int,
1137         -- when making the Num instance of A!
1138         rep_inst_ty = newTyConInstRhs rep_tycon rep_tc_args
1139         rep_tys     = cls_tys ++ [rep_inst_ty]
1140         rep_pred    = mkClassPred cls rep_tys
1141                 -- rep_pred is the representation dictionary, from where
1142                 -- we are gong to get all the methods for the newtype
1143                 -- dictionary 
1144
1145
1146     -- Next we figure out what superclass dictionaries to use
1147     -- See Note [Newtype deriving superclasses] above
1148
1149         cls_tyvars = classTyVars cls
1150         dfun_tvs = tyVarsOfTypes inst_tys
1151         inst_ty = mkTyConApp tycon tc_args
1152         inst_tys = cls_tys ++ [inst_ty]
1153         sc_theta = substTheta (zipOpenTvSubst cls_tyvars inst_tys)
1154                               (classSCTheta cls)
1155
1156                 -- If there are no tyvars, there's no need
1157                 -- to abstract over the dictionaries we need
1158                 -- Example:     newtype T = MkT Int deriving( C )
1159                 -- We get the derived instance
1160                 --              instance C T
1161                 -- rather than
1162                 --              instance C Int => C T
1163         all_preds = rep_pred : sc_theta         -- NB: rep_pred comes first
1164
1165         -------------------------------------------------------------------
1166         --  Figuring out whether we can only do this newtype-deriving thing
1167
1168         can_derive_via_isomorphism
1169            =  not (non_iso_class cls)
1170            && arity_ok
1171            && eta_ok
1172            && ats_ok
1173 --         && not (isRecursiveTyCon tycon)      -- Note [Recursive newtypes]
1174
1175         arity_ok = length cls_tys + 1 == classArity cls
1176                 -- Well kinded; eg not: newtype T ... deriving( ST )
1177                 --                      because ST needs *2* type params
1178
1179         -- Check that eta reduction is OK
1180         eta_ok = nt_eta_arity <= length rep_tc_args
1181                 -- The newtype can be eta-reduced to match the number
1182                 --     of type argument actually supplied
1183                 --        newtype T a b = MkT (S [a] b) deriving( Monad )
1184                 --     Here the 'b' must be the same in the rep type (S [a] b)
1185                 --     And the [a] must not mention 'b'.  That's all handled
1186                 --     by nt_eta_rity.
1187
1188         ats_ok = null (classATs cls)    
1189                -- No associated types for the class, because we don't 
1190                -- currently generate type 'instance' decls; and cannot do
1191                -- so for 'data' instance decls
1192                                          
1193         cant_derive_err
1194            = vcat [ ppUnless arity_ok arity_msg
1195                   , ppUnless eta_ok eta_msg
1196                   , ppUnless ats_ok ats_msg ]
1197         arity_msg = quotes (ppr (mkClassPred cls cls_tys)) <+> ptext (sLit "does not have arity 1")
1198         eta_msg   = ptext (sLit "cannot eta-reduce the representation type enough")
1199         ats_msg   = ptext (sLit "the class has associated types")
1200 \end{code}
1201
1202 Note [Recursive newtypes]
1203 ~~~~~~~~~~~~~~~~~~~~~~~~~
1204 Newtype deriving works fine, even if the newtype is recursive.
1205 e.g.    newtype S1 = S1 [T1 ()]
1206         newtype T1 a = T1 (StateT S1 IO a ) deriving( Monad )
1207 Remember, too, that type families are curretly (conservatively) given
1208 a recursive flag, so this also allows newtype deriving to work
1209 for type famillies.
1210
1211 We used to exclude recursive types, because we had a rather simple
1212 minded way of generating the instance decl:
1213    newtype A = MkA [A]
1214    instance Eq [A] => Eq A      -- Makes typechecker loop!
1215 But now we require a simple context, so it's ok.
1216
1217
1218 %************************************************************************
1219 %*                                                                      *
1220 \subsection[TcDeriv-fixpoint]{Finding the fixed point of \tr{deriving} equations}
1221 %*                                                                      *
1222 %************************************************************************
1223
1224 A ``solution'' (to one of the equations) is a list of (k,TyVarTy tv)
1225 terms, which is the final correct RHS for the corresponding original
1226 equation.
1227 \begin{itemize}
1228 \item
1229 Each (k,TyVarTy tv) in a solution constrains only a type
1230 variable, tv.
1231
1232 \item
1233 The (k,TyVarTy tv) pairs in a solution are canonically
1234 ordered by sorting on type varible, tv, (major key) and then class, k,
1235 (minor key)
1236 \end{itemize}
1237
1238 \begin{code}
1239 inferInstanceContexts :: OverlapFlag -> [DerivSpec] -> TcM [DerivSpec]
1240
1241 inferInstanceContexts _ [] = return []
1242
1243 inferInstanceContexts oflag infer_specs
1244   = do  { traceTc (text "inferInstanceContexts" <+> vcat (map pprDerivSpec infer_specs))
1245         ; iterate_deriv 1 initial_solutions }
1246   where
1247     ------------------------------------------------------------------
1248         -- The initial solutions for the equations claim that each
1249         -- instance has an empty context; this solution is certainly
1250         -- in canonical form.
1251     initial_solutions :: [ThetaType]
1252     initial_solutions = [ [] | _ <- infer_specs ]
1253
1254     ------------------------------------------------------------------
1255         -- iterate_deriv calculates the next batch of solutions,
1256         -- compares it with the current one; finishes if they are the
1257         -- same, otherwise recurses with the new solutions.
1258         -- It fails if any iteration fails
1259     iterate_deriv :: Int -> [ThetaType] -> TcM [DerivSpec]
1260     iterate_deriv n current_solns
1261       | n > 20  -- Looks as if we are in an infinite loop
1262                 -- This can happen if we have -XUndecidableInstances
1263                 -- (See TcSimplify.tcSimplifyDeriv.)
1264       = pprPanic "solveDerivEqns: probable loop" 
1265                  (vcat (map pprDerivSpec infer_specs) $$ ppr current_solns)
1266       | otherwise
1267       = do {      -- Extend the inst info from the explicit instance decls
1268                   -- with the current set of solutions, and simplify each RHS
1269              let inst_specs = zipWithEqual "add_solns" (mkInstance oflag)
1270                                            current_solns infer_specs
1271            ; new_solns <- checkNoErrs $
1272                           extendLocalInstEnv inst_specs $
1273                           mapM gen_soln infer_specs
1274
1275            ; if (current_solns == new_solns) then
1276                 return [ spec { ds_theta = soln } 
1277                        | (spec, soln) <- zip infer_specs current_solns ]
1278              else
1279                 iterate_deriv (n+1) new_solns }
1280
1281     ------------------------------------------------------------------
1282     gen_soln :: DerivSpec  -> TcM [PredType]
1283     gen_soln (DS { ds_loc = loc, ds_orig = orig, ds_tvs = tyvars 
1284                  , ds_cls = clas, ds_tys = inst_tys, ds_theta = deriv_rhs })
1285       = setSrcSpan loc  $
1286         addErrCtxt (derivInstCtxt clas inst_tys) $ 
1287         do { theta <- tcSimplifyDeriv orig tyvars deriv_rhs
1288                 -- checkValidInstance tyvars theta clas inst_tys
1289                 -- Not necessary; see Note [Exotic derived instance contexts]
1290                 --                in TcSimplify
1291
1292                   -- Check for a bizarre corner case, when the derived instance decl should
1293                   -- have form  instance C a b => D (T a) where ...
1294                   -- Note that 'b' isn't a parameter of T.  This gives rise to all sorts
1295                   -- of problems; in particular, it's hard to compare solutions for
1296                   -- equality when finding the fixpoint.  So I just rule it out for now.
1297            ; let tv_set = mkVarSet tyvars
1298                  weird_preds = [pred | pred <- theta, not (tyVarsOfPred pred `subVarSet` tv_set)]  
1299            ; mapM_ (addErrTc . badDerivedPred) weird_preds      
1300
1301            ; traceTc (text "TcDeriv" <+> (ppr deriv_rhs $$ ppr theta))
1302                 -- Claim: the result instance declaration is guaranteed valid
1303                 -- Hence no need to call:
1304                 --   checkValidInstance tyvars theta clas inst_tys
1305            ; return (sortLe (<=) theta) }       -- Canonicalise before returning the solution
1306
1307 ------------------------------------------------------------------
1308 mkInstance :: OverlapFlag -> ThetaType -> DerivSpec -> Instance
1309 mkInstance overlap_flag theta
1310             (DS { ds_name = dfun_name
1311                 , ds_tvs = tyvars, ds_cls = clas, ds_tys = tys })
1312   = mkLocalInstance dfun overlap_flag
1313   where
1314     dfun = mkDictFunId dfun_name tyvars theta clas tys
1315
1316
1317 extendLocalInstEnv :: [Instance] -> TcM a -> TcM a
1318 -- Add new locally-defined instances; don't bother to check
1319 -- for functional dependency errors -- that'll happen in TcInstDcls
1320 extendLocalInstEnv dfuns thing_inside
1321  = do { env <- getGblEnv
1322       ; let  inst_env' = extendInstEnvList (tcg_inst_env env) dfuns 
1323              env'      = env { tcg_inst_env = inst_env' }
1324       ; setGblEnv env' thing_inside }
1325 \end{code}
1326
1327
1328 %************************************************************************
1329 %*                                                                      *
1330 \subsection[TcDeriv-normal-binds]{Bindings for the various classes}
1331 %*                                                                      *
1332 %************************************************************************
1333
1334 After all the trouble to figure out the required context for the
1335 derived instance declarations, all that's left is to chug along to
1336 produce them.  They will then be shoved into @tcInstDecls2@, which
1337 will do all its usual business.
1338
1339 There are lots of possibilities for code to generate.  Here are
1340 various general remarks.
1341
1342 PRINCIPLES:
1343 \begin{itemize}
1344 \item
1345 We want derived instances of @Eq@ and @Ord@ (both v common) to be
1346 ``you-couldn't-do-better-by-hand'' efficient.
1347
1348 \item
1349 Deriving @Show@---also pretty common--- should also be reasonable good code.
1350
1351 \item
1352 Deriving for the other classes isn't that common or that big a deal.
1353 \end{itemize}
1354
1355 PRAGMATICS:
1356
1357 \begin{itemize}
1358 \item
1359 Deriving @Ord@ is done mostly with the 1.3 @compare@ method.
1360
1361 \item
1362 Deriving @Eq@ also uses @compare@, if we're deriving @Ord@, too.
1363
1364 \item
1365 We {\em normally} generate code only for the non-defaulted methods;
1366 there are some exceptions for @Eq@ and (especially) @Ord@...
1367
1368 \item
1369 Sometimes we use a @_con2tag_<tycon>@ function, which returns a data
1370 constructor's numeric (@Int#@) tag.  These are generated by
1371 @gen_tag_n_con_binds@, and the heuristic for deciding if one of
1372 these is around is given by @hasCon2TagFun@.
1373
1374 The examples under the different sections below will make this
1375 clearer.
1376
1377 \item
1378 Much less often (really just for deriving @Ix@), we use a
1379 @_tag2con_<tycon>@ function.  See the examples.
1380
1381 \item
1382 We use the renamer!!!  Reason: we're supposed to be
1383 producing @LHsBinds Name@ for the methods, but that means
1384 producing correctly-uniquified code on the fly.  This is entirely
1385 possible (the @TcM@ monad has a @UniqueSupply@), but it is painful.
1386 So, instead, we produce @MonoBinds RdrName@ then heave 'em through
1387 the renamer.  What a great hack!
1388 \end{itemize}
1389
1390 \begin{code}
1391 -- Generate the InstInfo for the required instance paired with the
1392 --   *representation* tycon for that instance,
1393 -- plus any auxiliary bindings required
1394 --
1395 -- Representation tycons differ from the tycon in the instance signature in
1396 -- case of instances for indexed families.
1397 --
1398 genInst :: Bool         -- True <=> standalone deriving
1399         -> OverlapFlag
1400         -> DerivSpec -> TcM (InstInfo RdrName, DerivAuxBinds)
1401 genInst standalone_deriv oflag spec
1402   | ds_newtype spec
1403   = return (InstInfo { iSpec  = mkInstance oflag (ds_theta spec) spec
1404                      , iBinds = NewTypeDerived co rep_tycon }, [])
1405
1406   | otherwise
1407   = do  { let loc  = getSrcSpan (ds_name spec)
1408               inst = mkInstance oflag (ds_theta spec) spec
1409               clas = ds_cls spec
1410
1411           -- In case of a family instance, we need to use the representation
1412           -- tycon (after all, it has the data constructors)
1413         ; fix_env <- getFixityEnv
1414         ; let (meth_binds, aux_binds) = genDerivBinds loc fix_env clas rep_tycon
1415               binds = VanillaInst meth_binds [] standalone_deriv
1416         ; return (InstInfo { iSpec = inst, iBinds = binds }, aux_binds)
1417         }
1418   where
1419     rep_tycon   = ds_tc spec
1420     rep_tc_args = ds_tc_args spec
1421     co1 = case tyConFamilyCoercion_maybe rep_tycon of
1422               Nothing     -> IdCo
1423               Just co_con -> ACo (mkTyConApp co_con rep_tc_args)
1424     co2 = case newTyConCo_maybe rep_tycon of
1425               Nothing     -> IdCo       -- The newtype is transparent; no need for a cast
1426               Just co_con -> ACo (mkTyConApp co_con rep_tc_args)
1427     co = co1 `mkTransCoI` co2
1428
1429 -- Example: newtype instance N [a] = N1 (Tree a) 
1430 --          deriving instance Eq b => Eq (N [(b,b)])
1431 -- From the instance, we get an implicit newtype R1:N a = N1 (Tree a)
1432 -- When dealing with the deriving clause
1433 --    co1 : N [(b,b)] ~ R1:N (b,b)
1434 --    co2 : R1:N (b,b) ~ Tree (b,b)
1435 --    co  : N [(b,b)] ~ Tree (b,b)
1436
1437 genDerivBinds :: SrcSpan -> FixityEnv -> Class -> TyCon -> (LHsBinds RdrName, DerivAuxBinds)
1438 genDerivBinds loc fix_env clas tycon
1439   | className clas `elem` typeableClassNames
1440   = (gen_Typeable_binds loc tycon, [])
1441
1442   | otherwise
1443   = case assocMaybe gen_list (getUnique clas) of
1444         Just gen_fn -> gen_fn loc tycon
1445         Nothing     -> pprPanic "genDerivBinds: bad derived class" (ppr clas)
1446   where
1447     gen_list :: [(Unique, SrcSpan -> TyCon -> (LHsBinds RdrName, DerivAuxBinds))]
1448     gen_list = [(eqClassKey,       gen_Eq_binds)
1449                ,(ordClassKey,      gen_Ord_binds)
1450                ,(enumClassKey,     gen_Enum_binds)
1451                ,(boundedClassKey,  gen_Bounded_binds)
1452                ,(ixClassKey,       gen_Ix_binds)
1453                ,(showClassKey,     gen_Show_binds fix_env)
1454                ,(readClassKey,     gen_Read_binds fix_env)
1455                ,(dataClassKey,     gen_Data_binds)
1456                ,(functorClassKey,  gen_Functor_binds)
1457                ,(foldableClassKey, gen_Foldable_binds)
1458                ,(traversableClassKey, gen_Traversable_binds)
1459                ]
1460 \end{code}
1461
1462
1463 %************************************************************************
1464 %*                                                                      *
1465 \subsection[TcDeriv-taggery-Names]{What con2tag/tag2con functions are available?}
1466 %*                                                                      *
1467 %************************************************************************
1468
1469 \begin{code}
1470 derivingKindErr :: TyCon -> Class -> [Type] -> Kind -> Message
1471 derivingKindErr tc cls cls_tys cls_kind
1472   = hang (ptext (sLit "Cannot derive well-kinded instance of form")
1473                 <+> quotes (pprClassPred cls cls_tys <+> parens (ppr tc <+> ptext (sLit "..."))))
1474        2 (ptext (sLit "Class") <+> quotes (ppr cls)
1475             <+> ptext (sLit "expects an argument of kind") <+> quotes (pprKind cls_kind))
1476
1477 derivingEtaErr :: Class -> [Type] -> Type -> Message
1478 derivingEtaErr cls cls_tys inst_ty
1479   = sep [ptext (sLit "Cannot eta-reduce to an instance of form"),
1480          nest 2 (ptext (sLit "instance (...) =>")
1481                 <+> pprClassPred cls (cls_tys ++ [inst_ty]))]
1482
1483 typeFamilyPapErr :: TyCon -> Class -> [Type] -> Type -> Message
1484 typeFamilyPapErr tc cls cls_tys inst_ty
1485   = hang (ptext (sLit "Derived instance") <+> quotes (pprClassPred cls (cls_tys ++ [inst_ty])))
1486        2 (ptext (sLit "requires illegal partial application of data type family") <+> ppr tc) 
1487
1488 derivingThingErr :: Bool -> Class -> [Type] -> Type -> Message -> Message
1489 derivingThingErr newtype_deriving clas tys ty why
1490   = sep [(hang (ptext (sLit "Can't make a derived instance of"))
1491              2 (quotes (ppr pred)) 
1492           $$ nest 2 extra) <> colon,
1493          nest 2 why]
1494   where
1495     extra | newtype_deriving = ptext (sLit "(even with cunning newtype deriving)")
1496           | otherwise        = empty
1497     pred = mkClassPred clas (tys ++ [ty])
1498
1499 derivingHiddenErr :: TyCon -> SDoc
1500 derivingHiddenErr tc
1501   = hang (ptext (sLit "The data constructors of") <+> quotes (ppr tc) <+> ptext (sLit "are not all in scope"))
1502        2 (ptext (sLit "so you cannot derive an instance for it"))
1503
1504 standaloneCtxt :: LHsType Name -> SDoc
1505 standaloneCtxt ty = hang (ptext (sLit "In the stand-alone deriving instance for")) 
1506                        2 (quotes (ppr ty))
1507
1508 derivInstCtxt :: Class -> [Type] -> Message
1509 derivInstCtxt clas inst_tys
1510   = ptext (sLit "When deriving the instance for") <+> parens (pprClassPred clas inst_tys)
1511
1512 badDerivedPred :: PredType -> Message
1513 badDerivedPred pred
1514   = vcat [ptext (sLit "Can't derive instances where the instance context mentions"),
1515           ptext (sLit "type variables that are not data type parameters"),
1516           nest 2 (ptext (sLit "Offending constraint:") <+> ppr pred)]
1517 \end{code}