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