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