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