2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
6 Handles @deriving@ clauses on @data@ declarations.
9 module TcDeriv ( tcDeriving ) where
11 #include "HsVersions.h"
19 import TcClassDcl( tcAddDeclCtxt ) -- Small helper
20 import TcGenDeriv -- Deriv stuff
59 %************************************************************************
63 %************************************************************************
67 1. Convert the decls (i.e. data/newtype deriving clauses,
68 plus standalone deriving) to [EarlyDerivSpec]
70 2. Infer the missing contexts for the Left DerivSpecs
72 3. Add the derived bindings, generating InstInfos
76 -- DerivSpec is purely local to this module
77 data DerivSpec = DS { ds_loc :: SrcSpan
81 , ds_theta :: ThetaType
85 , ds_tc_args :: [Type]
86 , ds_newtype :: Bool }
87 -- This spec implies a dfun declaration of the form
88 -- df :: forall tvs. theta => C tys
89 -- The Name is the name for the DFun we'll build
90 -- The tyvars bind all the variables in the theta
91 -- For type families, the tycon in
92 -- in ds_tys is the *family* tycon
93 -- in ds_tc, ds_tc_args is the *representation* tycon
94 -- For non-family tycons, both are the same
96 -- ds_newtype = True <=> Newtype deriving
97 -- False <=> Vanilla deriving
102 newtype instance T [a] = MkT (Tree a) deriving( C s )
104 axiom T [a] = :RTList a
105 axiom :RTList a = Tree a
107 DS { ds_tvs = [a,s], ds_cls = C, ds_tys = [s, T [a]]
108 , ds_tc = :RTList, ds_tc_args = [a]
109 , ds_newtype = True }
112 type DerivContext = Maybe ThetaType
113 -- Nothing <=> Vanilla deriving; infer the context of the instance decl
114 -- Just theta <=> Standalone deriving: context supplied by programmer
116 type EarlyDerivSpec = Either DerivSpec DerivSpec
117 -- Left ds => the context for the instance should be inferred
118 -- In this case ds_theta is the list of all the
119 -- constraints needed, such as (Eq [a], Eq a)
120 -- The inference process is to reduce this to a
121 -- simpler form (e.g. Eq a)
123 -- Right ds => the exact context for the instance is supplied
124 -- by the programmer; it is ds_theta
126 pprDerivSpec :: DerivSpec -> SDoc
127 pprDerivSpec (DS { ds_loc = l, ds_name = n, ds_tvs = tvs,
128 ds_cls = c, ds_tys = tys, ds_theta = rhs })
129 = parens (hsep [ppr l, ppr n, ppr tvs, ppr c, ppr tys]
130 <+> equals <+> ppr rhs)
132 instance Outputable DerivSpec where
137 Inferring missing contexts
138 ~~~~~~~~~~~~~~~~~~~~~~~~~~
141 data T a b = C1 (Foo a) (Bar b)
146 [NOTE: See end of these comments for what to do with
147 data (C a, D b) => T a b = ...
150 We want to come up with an instance declaration of the form
152 instance (Ping a, Pong b, ...) => Eq (T a b) where
155 It is pretty easy, albeit tedious, to fill in the code "...". The
156 trick is to figure out what the context for the instance decl is,
157 namely @Ping@, @Pong@ and friends.
159 Let's call the context reqd for the T instance of class C at types
160 (a,b, ...) C (T a b). Thus:
162 Eq (T a b) = (Ping a, Pong b, ...)
164 Now we can get a (recursive) equation from the @data@ decl:
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
170 Foo and Bar may have explicit instances for @Eq@, in which case we can
171 just substitute for them. Alternatively, either or both may have
172 their @Eq@ instances given by @deriving@ clauses, in which case they
173 form part of the system of equations.
175 Now all we need do is simplify and solve the equations, iterating to
176 find the least fixpoint. Notice that the order of the arguments can
177 switch around, as here in the recursive calls to T.
179 Let's suppose Eq (Foo a) = Eq a, and Eq (Bar b) = Ping b.
183 Eq (T a b) = {} -- The empty set
186 Eq (T a b) = Eq (Foo a) u Eq (Bar b) -- From C1
187 u Eq (T b a) u Eq Int -- From C2
188 u Eq (T a a) -- From C3
190 After simplification:
191 = Eq a u Ping b u {} u {} u {}
196 Eq (T a b) = Eq (Foo a) u Eq (Bar b) -- From C1
197 u Eq (T b a) u Eq Int -- From C2
198 u Eq (T a a) -- From C3
200 After simplification:
205 = Eq a u Ping b u Eq b u Ping a
207 The next iteration gives the same result, so this is the fixpoint. We
208 need to make a canonical form of the RHS to ensure convergence. We do
209 this by simplifying the RHS to a form in which
211 - the classes constrain only tyvars
212 - the list is sorted by tyvar (major key) and then class (minor key)
213 - no duplicates, of course
215 So, here are the synonyms for the ``equation'' structures:
218 Note [Data decl contexts]
219 ~~~~~~~~~~~~~~~~~~~~~~~~~
222 data (RealFloat a) => Complex a = !a :+ !a deriving( Read )
224 We will need an instance decl like:
226 instance (Read a, RealFloat a) => Read (Complex a) where
229 The RealFloat in the context is because the read method for Complex is bound
230 to construct a Complex, and doing that requires that the argument type is
233 But this ain't true for Show, Eq, Ord, etc, since they don't construct
234 a Complex; they only take them apart.
236 Our approach: identify the offending classes, and add the data type
237 context to the instance decl. The "offending classes" are
241 FURTHER NOTE ADDED March 2002. In fact, Haskell98 now requires that
242 pattern matching against a constructor from a data type with a context
243 gives rise to the constraints for that context -- or at least the thinned
244 version. So now all classes are "offending".
246 Note [Newtype deriving]
247 ~~~~~~~~~~~~~~~~~~~~~~~
251 newtype T = T Char deriving( C [a] )
253 Notice the free 'a' in the deriving. We have to fill this out to
254 newtype T = T Char deriving( forall a. C [a] )
256 And then translate it to:
257 instance C [a] Char => C [a] T where ...
260 Note [Newtype deriving superclasses]
261 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
262 (See also Trac #1220 for an interesting exchange on newtype
263 deriving and superclasses.)
265 The 'tys' here come from the partial application in the deriving
266 clause. The last arg is the new instance type.
268 We must pass the superclasses; the newtype might be an instance
269 of them in a different way than the representation type
270 E.g. newtype Foo a = Foo a deriving( Show, Num, Eq )
271 Then the Show instance is not done via isomorphism; it shows
273 The Num instance is derived via isomorphism, but the Show superclass
274 dictionary must the Show instance for Foo, *not* the Show dictionary
275 gotten from the Num dictionary. So we must build a whole new dictionary
276 not just use the Num one. The instance we want is something like:
277 instance (Num a, Show (Foo a), Eq (Foo a)) => Num (Foo a) where
280 There may be a coercion needed which we get from the tycon for the newtype
281 when the dict is constructed in TcInstDcls.tcInstDecl2
284 Note [Unused constructors and deriving clauses]
285 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
286 See Trac #3221. Consider
287 data T = T1 | T2 deriving( Show )
288 Are T1 and T2 unused? Well, no: the deriving clause expands to mention
289 both of them. So we gather defs/uses from deriving just like anything else.
291 %************************************************************************
293 \subsection[TcDeriv-driver]{Top-level function for \tr{derivings}}
295 %************************************************************************
298 tcDeriving :: [LTyClDecl Name] -- All type constructors
299 -> [LInstDecl Name] -- All instance declarations
300 -> [LDerivDecl Name] -- All stand-alone deriving declarations
301 -> TcM ([InstInfo Name] -- The generated "instance decls"
302 ,HsValBinds Name -- Extra generated top-level bindings
304 ,[TyCon] -- Extra generated top-level types
305 ,[TyCon]) -- Extra generated type family instances
307 tcDeriving tycl_decls inst_decls deriv_decls
308 = recoverM (return ([], emptyValBindsOut, emptyDUs, [], [])) $
309 do { -- Fish the "deriving"-related information out of the TcEnv
310 -- And make the necessary "equations".
311 is_boot <- tcIsHsBoot
312 ; traceTc "tcDeriving" (ppr is_boot)
313 ; (early_specs, genericsExtras)
314 <- makeDerivSpecs is_boot tycl_decls inst_decls deriv_decls
315 ; let (repMetaTys, repTyCons, metaInsts) = unzip3 genericsExtras
317 ; overlap_flag <- getOverlapFlag
318 ; let (infer_specs, given_specs) = splitEithers early_specs
319 ; insts1 <- mapM (genInst True overlap_flag) given_specs
321 ; final_specs <- extendLocalInstEnv (map (iSpec . fst) insts1) $
322 inferInstanceContexts overlap_flag infer_specs
324 ; insts2 <- mapM (genInst False overlap_flag) final_specs
326 -- We no longer generate the old generic to/from functions
327 -- from each type declaration, so this is emptyBag
328 ; gen_binds <- return emptyBag -- mkGenericBinds is_boot tycl_decls
330 ; (inst_info, rn_binds, rn_dus)
331 <- renameDeriv is_boot gen_binds (insts1 ++ insts2 ++ concat metaInsts)
334 ; liftIO (dumpIfSet_dyn dflags Opt_D_dump_deriv "Derived instances"
335 (ddump_deriving inst_info rn_binds))
337 ; when (not (null inst_info)) $
338 dumpDerivingInfo (ddump_deriving inst_info rn_binds)
340 ; return ( inst_info, rn_binds, rn_dus
341 , concat (map metaTyCons2TyCons repMetaTys), repTyCons) }
343 ddump_deriving :: [InstInfo Name] -> HsValBinds Name -> SDoc
344 ddump_deriving inst_infos extra_binds
345 = hang (ptext (sLit "Derived instances"))
346 2 (vcat (map (\i -> pprInstInfoDetails i $$ text "") inst_infos)
350 renameDeriv :: Bool -> LHsBinds RdrName
351 -> [(InstInfo RdrName, DerivAuxBinds)]
352 -> TcM ([InstInfo Name], HsValBinds Name, DefUses)
353 renameDeriv is_boot gen_binds insts
354 | is_boot -- If we are compiling a hs-boot file, don't generate any derived bindings
355 -- The inst-info bindings will all be empty, but it's easier to
356 -- just use rn_inst_info to change the type appropriately
357 = do { (rn_inst_infos, fvs) <- mapAndUnzipM rn_inst_info inst_infos
358 ; return (rn_inst_infos, emptyValBindsOut, usesOnly (plusFVs fvs)) }
361 = discardWarnings $ -- Discard warnings about unused bindings etc
362 do { (rn_gen, dus_gen) <- setOptM Opt_ScopedTypeVariables $ -- Type signatures in patterns
363 -- are used in the generic binds
364 rnTopBinds (ValBindsIn gen_binds [])
365 ; keepAliveSetTc (duDefs dus_gen) -- Mark these guys to be kept alive
367 -- Generate and rename any extra not-one-inst-decl-specific binds,
368 -- notably "con2tag" and/or "tag2con" functions.
369 -- Bring those names into scope before renaming the instances themselves
370 ; loc <- getSrcSpanM -- Generic loc for shared bindings
371 ; let (aux_binds, aux_sigs) = unzip $ map (genAuxBind loc) $
372 rm_dups [] $ concat deriv_aux_binds
373 aux_val_binds = ValBindsIn (listToBag aux_binds) aux_sigs
374 ; rn_aux_lhs <- rnTopBindsLHS emptyFsEnv aux_val_binds
375 ; bindLocalNames (collectHsValBinders rn_aux_lhs) $
376 do { (rn_aux, dus_aux) <- rnTopBindsRHS rn_aux_lhs
377 ; (rn_inst_infos, fvs_insts) <- mapAndUnzipM rn_inst_info inst_infos
378 ; return (rn_inst_infos, rn_aux `plusHsValBinds` rn_gen,
379 dus_gen `plusDU` dus_aux `plusDU` usesOnly (plusFVs fvs_insts)) } }
382 (inst_infos, deriv_aux_binds) = unzip insts
384 -- Remove duplicate requests for auxilliary bindings
386 rm_dups acc (b:bs) | any (isDupAux b) acc = rm_dups acc bs
387 | otherwise = rm_dups (b:acc) bs
390 rn_inst_info :: InstInfo RdrName -> TcM (InstInfo Name, FreeVars)
391 rn_inst_info info@(InstInfo { iBinds = NewTypeDerived coi tc })
392 = return ( info { iBinds = NewTypeDerived coi tc }
393 , mkFVs (map dataConName (tyConDataCons tc)))
394 -- See Note [Newtype deriving and unused constructors]
396 rn_inst_info inst_info@(InstInfo { iSpec = inst, iBinds = VanillaInst binds sigs standalone_deriv })
397 = -- Bring the right type variables into
398 -- scope (yuk), and rename the method binds
400 bindLocalNames (map Var.varName tyvars) $
401 do { (rn_binds, fvs) <- rnMethodBinds clas_nm (\_ -> []) binds
402 ; let binds' = VanillaInst rn_binds [] standalone_deriv
403 ; return (inst_info { iBinds = binds' }, fvs) }
405 (tyvars,_, clas,_) = instanceHead inst
406 clas_nm = className clas
409 Note [Newtype deriving and unused constructors]
410 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
411 Consider this (see Trac #1954):
414 newtype P a = MkP (IO a) deriving Monad
416 If you compile with -fwarn-unused-binds you do not expect the warning
417 "Defined but not used: data consructor MkP". Yet the newtype deriving
418 code does not explicitly mention MkP, but it should behave as if you
420 instance Monad P where
421 return x = MkP (return x)
424 So we want to signal a user of the data constructor 'MkP'. That's
425 what we do in rn_inst_info, and it's the only reason we have the TyCon
426 stored in NewTypeDerived.
429 %************************************************************************
431 From HsSyn to DerivSpec
433 %************************************************************************
435 @makeDerivSpecs@ fishes around to find the info about needed derived instances.
438 -- Make the "extras" for the generic representation
439 mkGenDerivExtras :: TyCon
440 -> TcRn (MetaTyCons, TyCon, [(InstInfo RdrName, DerivAuxBinds)])
441 mkGenDerivExtras tc = do
442 { (metaTyCons, rep0TyInst) <- genGenericRepExtras tc
443 ; metaInsts <- genDtMeta (tc, metaTyCons)
444 ; return (metaTyCons, rep0TyInst, metaInsts) }
446 makeDerivSpecs :: Bool
450 -> TcM ( [EarlyDerivSpec]
451 , [(MetaTyCons, TyCon, [(InstInfo RdrName, DerivAuxBinds)])])
452 makeDerivSpecs is_boot tycl_decls inst_decls deriv_decls
453 | is_boot -- No 'deriving' at all in hs-boot files
454 = do { mapM_ add_deriv_err deriv_locs
457 = do { eqns1 <- mapAndRecoverM deriveTyData all_tydata
458 ; eqns2 <- mapAndRecoverM deriveStandalone deriv_decls
460 -- Generic representation stuff: we might need to add some "extras"
462 ; xDerRep <- getDOpts >>= return . xopt Opt_DeriveGeneric
463 ; generic_extras_deriv <- if not xDerRep
464 -- No extras if the flag is off
467 let allTyNames = [ tcdName d | L _ d <- tycl_decls, isDataDecl d ]
468 -- Select only those types that derive Generic
469 ; let sel_tydata = [ tcdName t | (L _ c, L _ t) <- all_tydata
470 , getClassName c == Just genClassName ]
471 ; let sel_deriv_decls = catMaybes [ getTypeName t
472 | L _ (DerivDecl (L _ t)) <- deriv_decls
473 , getClassName t == Just genClassName ]
474 ; derTyDecls <- mapM tcLookupTyCon $
475 filter (needsExtras xDerRep
476 (sel_tydata ++ sel_deriv_decls)) allTyNames
477 -- We need to generate the extras to add to what has
478 -- already been derived
479 ; {- pprTrace "sel_tydata" (ppr sel_tydata) $
480 pprTrace "sel_deriv_decls" (ppr sel_deriv_decls) $
481 pprTrace "derTyDecls" (ppr derTyDecls) $
482 pprTrace "deriv_decls" (ppr deriv_decls) $ -}
483 mapM mkGenDerivExtras derTyDecls }
486 ; return ( eqns1 ++ eqns2, generic_extras_deriv) }
488 -- We need extras if the flag DeriveGeneric is on and this type is
490 needsExtras xDerRep tydata tc_name = xDerRep && tc_name `elem` tydata
492 -- Extracts the name of the class in the deriving
493 getClassName :: HsType Name -> Maybe Name
494 getClassName (HsForAllTy _ _ _ (L _ n)) = getClassName n
495 getClassName (HsPredTy (HsClassP n _)) = Just n
496 getClassName _ = Nothing
498 -- Extracts the name of the type in the deriving
499 -- This function (and also getClassName above) is not really nice, and I
500 -- might not have covered all possible cases. I wonder if there is no easier
501 -- way to extract class and type name from a LDerivDecl...
502 getTypeName :: HsType Name -> Maybe Name
503 getTypeName (HsForAllTy _ _ _ (L _ n)) = getTypeName n
504 getTypeName (HsTyVar n) = Just n
505 getTypeName (HsOpTy _ (L _ n) _) = Just n
506 getTypeName (HsPredTy (HsClassP _ [L _ n])) = getTypeName n
507 getTypeName (HsAppTy (L _ n) _) = getTypeName n
508 getTypeName (HsParTy (L _ n)) = getTypeName n
509 getTypeName (HsKindSig (L _ n) _) = getTypeName n
510 getTypeName _ = Nothing
512 extractTyDataPreds decls
513 = [(p, d) | d@(L _ (TyData {tcdDerivs = Just preds})) <- decls, p <- preds]
515 all_tydata :: [(LHsType Name, LTyClDecl Name)]
516 -- Derived predicate paired with its data type declaration
517 all_tydata = extractTyDataPreds (instDeclATs inst_decls ++ tycl_decls)
519 deriv_locs = map (getLoc . snd) all_tydata
520 ++ map getLoc deriv_decls
522 add_deriv_err loc = setSrcSpan loc $
523 addErr (hang (ptext (sLit "Deriving not permitted in hs-boot file"))
524 2 (ptext (sLit "Use an instance declaration instead")))
526 ------------------------------------------------------------------
527 deriveStandalone :: LDerivDecl Name -> TcM EarlyDerivSpec
528 -- Standalone deriving declarations
529 -- e.g. deriving instance Show a => Show (T a)
530 -- Rather like tcLocalInstDecl
531 deriveStandalone (L loc (DerivDecl deriv_ty))
533 addErrCtxt (standaloneCtxt deriv_ty) $
534 do { traceTc "Standalone deriving decl for" (ppr deriv_ty)
535 ; (tvs, theta, cls, inst_tys) <- tcHsInstHead deriv_ty
536 ; traceTc "Standalone deriving;" $ vcat
537 [ text "tvs:" <+> ppr tvs
538 , text "theta:" <+> ppr theta
539 , text "cls:" <+> ppr cls
540 , text "tys:" <+> ppr inst_tys ]
541 ; checkValidInstance deriv_ty tvs theta cls inst_tys
542 -- C.f. TcInstDcls.tcLocalInstDecl1
544 ; let cls_tys = take (length inst_tys - 1) inst_tys
545 inst_ty = last inst_tys
546 ; traceTc "Standalone deriving:" $ vcat
547 [ text "class:" <+> ppr cls
548 , text "class types:" <+> ppr cls_tys
549 , text "type:" <+> ppr inst_ty ]
550 ; mkEqnHelp StandAloneDerivOrigin tvs cls cls_tys inst_ty
553 ------------------------------------------------------------------
554 deriveTyData :: (LHsType Name, LTyClDecl Name) -> TcM EarlyDerivSpec
555 deriveTyData (L loc deriv_pred, L _ decl@(TyData { tcdLName = L _ tycon_name,
556 tcdTyVars = tv_names,
557 tcdTyPats = ty_pats }))
558 = setSrcSpan loc $ -- Use the location of the 'deriving' item
560 do { (tvs, tc, tc_args) <- get_lhs ty_pats
561 ; tcExtendTyVarEnv tvs $ -- Deriving preds may (now) mention
562 -- the type variables for the type constructor
564 do { (deriv_tvs, cls, cls_tys) <- tcHsDeriv deriv_pred
565 -- The "deriv_pred" is a LHsType to take account of the fact that for
566 -- newtype deriving we allow deriving (forall a. C [a]).
568 -- Given data T a b c = ... deriving( C d ),
569 -- we want to drop type variables from T so that (C d (T a)) is well-kinded
570 ; let cls_tyvars = classTyVars cls
571 kind = tyVarKind (last cls_tyvars)
572 (arg_kinds, _) = splitKindFunTys kind
573 n_args_to_drop = length arg_kinds
574 n_args_to_keep = tyConArity tc - n_args_to_drop
575 args_to_drop = drop n_args_to_keep tc_args
576 inst_ty = mkTyConApp tc (take n_args_to_keep tc_args)
577 inst_ty_kind = typeKind inst_ty
578 dropped_tvs = mkVarSet (mapCatMaybes getTyVar_maybe args_to_drop)
579 univ_tvs = (mkVarSet tvs `extendVarSetList` deriv_tvs)
580 `minusVarSet` dropped_tvs
582 -- Check that the result really is well-kinded
583 ; checkTc (n_args_to_keep >= 0 && (inst_ty_kind `eqKind` kind))
584 (derivingKindErr tc cls cls_tys kind)
586 ; checkTc (sizeVarSet dropped_tvs == n_args_to_drop && -- (a)
587 tyVarsOfTypes (inst_ty:cls_tys) `subVarSet` univ_tvs) -- (b)
588 (derivingEtaErr cls cls_tys inst_ty)
590 -- (a) The data type can be eta-reduced; eg reject:
591 -- data instance T a a = ... deriving( Monad )
592 -- (b) The type class args do not mention any of the dropped type
594 -- newtype T a s = ... deriving( ST s )
596 -- Type families can't be partially applied
597 -- e.g. newtype instance T Int a = MkT [a] deriving( Monad )
598 -- Note [Deriving, type families, and partial applications]
599 ; checkTc (not (isFamilyTyCon tc) || n_args_to_drop == 0)
600 (typeFamilyPapErr tc cls cls_tys inst_ty)
602 ; mkEqnHelp DerivOrigin (varSetElems univ_tvs) cls cls_tys inst_ty Nothing } }
604 -- Tiresomely we must figure out the "lhs", which is awkward for type families
605 -- E.g. data T a b = .. deriving( Eq )
606 -- Here, the lhs is (T a b)
607 -- data instance TF Int b = ... deriving( Eq )
608 -- Here, the lhs is (TF Int b)
609 -- But if we just look up the tycon_name, we get is the *family*
610 -- tycon, but not pattern types -- they are in the *rep* tycon.
611 get_lhs Nothing = do { tc <- tcLookupTyCon tycon_name
612 ; let tvs = tyConTyVars tc
613 ; return (tvs, tc, mkTyVarTys tvs) }
614 get_lhs (Just pats) = do { let hs_app = nlHsTyConApp tycon_name pats
615 ; (tvs, tc_app) <- tcHsQuantifiedType tv_names hs_app
616 ; let (tc, tc_args) = tcSplitTyConApp tc_app
617 ; return (tvs, tc, tc_args) }
620 = panic "derivTyData" -- Caller ensures that only TyData can happen
623 Note [Deriving, type families, and partial applications]
624 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
625 When there are no type families, it's quite easy:
627 newtype S a = MkS [a]
628 -- :CoS :: S ~ [] -- Eta-reduced
630 instance Eq [a] => Eq (S a) -- by coercion sym (Eq (:CoS a)) : Eq [a] ~ Eq (S a)
631 instance Monad [] => Monad S -- by coercion sym (Monad :CoS) : Monad [] ~ Monad S
633 When type familes are involved it's trickier:
636 newtype instance T Int a = MkT [a] deriving( Eq, Monad )
637 -- :RT is the representation type for (T Int a)
638 -- :CoF:R1T a :: T Int a ~ :RT a -- Not eta reduced
639 -- :Co:R1T :: :RT ~ [] -- Eta-reduced
641 instance Eq [a] => Eq (T Int a) -- easy by coercion
642 instance Monad [] => Monad (T Int) -- only if we can eta reduce???
644 The "???" bit is that we don't build the :CoF thing in eta-reduced form
645 Henc the current typeFamilyPapErr, even though the instance makes sense.
646 After all, we can write it out
647 instance Monad [] => Monad (T Int) -- only if we can eta reduce???
652 mkEqnHelp :: CtOrigin -> [TyVar] -> Class -> [Type] -> Type
653 -> DerivContext -- Just => context supplied (standalone deriving)
654 -- Nothing => context inferred (deriving on data decl)
655 -> TcRn EarlyDerivSpec
656 -- Make the EarlyDerivSpec for an instance
657 -- forall tvs. theta => cls (tys ++ [ty])
658 -- where the 'theta' is optional (that's the Maybe part)
659 -- Assumes that this declaration is well-kinded
661 mkEqnHelp orig tvs cls cls_tys tc_app mtheta
662 | Just (tycon, tc_args) <- tcSplitTyConApp_maybe tc_app
663 , isAlgTyCon tycon -- Check for functions, primitive types etc
664 = mk_alg_eqn tycon tc_args
666 = failWithTc (derivingThingErr False cls cls_tys tc_app
667 (ptext (sLit "The last argument of the instance must be a data or newtype application")))
670 bale_out msg = failWithTc (derivingThingErr False cls cls_tys tc_app msg)
672 mk_alg_eqn tycon tc_args
673 | className cls `elem` typeableClassNames
674 = do { dflags <- getDOpts
675 ; case checkTypeableConditions (dflags, tycon) of
676 Just err -> bale_out err
677 Nothing -> mk_typeable_eqn orig tvs cls tycon tc_args mtheta }
679 | isDataFamilyTyCon tycon
680 , length tc_args /= tyConArity tycon
681 = bale_out (ptext (sLit "Unsaturated data family application"))
684 = do { (rep_tc, rep_tc_args) <- tcLookupDataFamInst tycon tc_args
685 -- Be careful to test rep_tc here: in the case of families,
686 -- we want to check the instance tycon, not the family tycon
688 -- For standalone deriving (mtheta /= Nothing),
689 -- check that all the data constructors are in scope.
690 ; rdr_env <- getGlobalRdrEnv
691 ; let hidden_data_cons = isAbstractTyCon rep_tc ||
692 any not_in_scope (tyConDataCons rep_tc)
693 not_in_scope dc = null (lookupGRE_Name rdr_env (dataConName dc))
694 ; unless (isNothing mtheta || not hidden_data_cons)
695 (bale_out (derivingHiddenErr tycon))
698 ; if isDataTyCon rep_tc then
699 mkDataTypeEqn orig dflags tvs cls cls_tys
700 tycon tc_args rep_tc rep_tc_args mtheta
702 mkNewTypeEqn orig dflags tvs cls cls_tys
703 tycon tc_args rep_tc rep_tc_args mtheta }
707 %************************************************************************
711 %************************************************************************
714 mkDataTypeEqn :: CtOrigin
716 -> [Var] -- Universally quantified type variables in the instance
717 -> Class -- Class for which we need to derive an instance
718 -> [Type] -- Other parameters to the class except the last
719 -> TyCon -- Type constructor for which the instance is requested
720 -- (last parameter to the type class)
721 -> [Type] -- Parameters to the type constructor
722 -> TyCon -- rep of the above (for type families)
723 -> [Type] -- rep of the above
724 -> DerivContext -- Context of the instance, for standalone deriving
725 -> TcRn EarlyDerivSpec -- Return 'Nothing' if error
727 mkDataTypeEqn orig dflags tvs cls cls_tys
728 tycon tc_args rep_tc rep_tc_args mtheta
729 = case checkSideConditions dflags mtheta cls cls_tys rep_tc of
730 -- NB: pass the *representation* tycon to checkSideConditions
731 CanDerive -> go_for_it
732 NonDerivableClass -> bale_out (nonStdErr cls)
733 DerivableClassError msg -> bale_out msg
735 go_for_it = mk_data_eqn orig tvs cls tycon tc_args rep_tc rep_tc_args mtheta
736 bale_out msg = failWithTc (derivingThingErr False cls cls_tys (mkTyConApp tycon tc_args) msg)
738 mk_data_eqn :: CtOrigin -> [TyVar] -> Class
739 -> TyCon -> [TcType] -> TyCon -> [TcType] -> DerivContext
740 -> TcM EarlyDerivSpec
741 mk_data_eqn orig tvs cls tycon tc_args rep_tc rep_tc_args mtheta
742 = do { dfun_name <- new_dfun_name cls tycon
744 ; let inst_tys = [mkTyConApp tycon tc_args]
745 inferred_constraints = inferConstraints tvs cls inst_tys rep_tc rep_tc_args
746 spec = DS { ds_loc = loc, ds_orig = orig
747 , ds_name = dfun_name, ds_tvs = tvs
748 , ds_cls = cls, ds_tys = inst_tys
749 , ds_tc = rep_tc, ds_tc_args = rep_tc_args
750 , ds_theta = mtheta `orElse` inferred_constraints
751 , ds_newtype = False }
753 ; return (if isJust mtheta then Right spec -- Specified context
754 else Left spec) } -- Infer context
756 ----------------------
757 mk_typeable_eqn :: CtOrigin -> [TyVar] -> Class
758 -> TyCon -> [TcType] -> DerivContext
759 -> TcM EarlyDerivSpec
760 mk_typeable_eqn orig tvs cls tycon tc_args mtheta
761 -- The Typeable class is special in several ways
762 -- data T a b = ... deriving( Typeable )
764 -- instance Typeable2 T where ...
766 -- 1. There are no constraints in the instance
767 -- 2. There are no type variables either
768 -- 3. The actual class we want to generate isn't necessarily
769 -- Typeable; it depends on the arity of the type
770 | isNothing mtheta -- deriving on a data type decl
771 = do { checkTc (cls `hasKey` typeableClassKey)
772 (ptext (sLit "Use deriving( Typeable ) on a data type declaration"))
773 ; real_cls <- tcLookupClass (typeableClassNames !! tyConArity tycon)
774 ; mk_typeable_eqn orig tvs real_cls tycon [] (Just []) }
776 | otherwise -- standaone deriving
777 = do { checkTc (null tc_args)
778 (ptext (sLit "Derived typeable instance must be of form (Typeable")
779 <> int (tyConArity tycon) <+> ppr tycon <> rparen)
780 ; dfun_name <- new_dfun_name cls tycon
783 DS { ds_loc = loc, ds_orig = orig, ds_name = dfun_name, ds_tvs = []
784 , ds_cls = cls, ds_tys = [mkTyConApp tycon []]
785 , ds_tc = tycon, ds_tc_args = []
786 , ds_theta = mtheta `orElse` [], ds_newtype = False }) }
788 ----------------------
789 inferConstraints :: [TyVar] -> Class -> [TcType] -> TyCon -> [TcType] -> ThetaType
790 -- Generate a sufficiently large set of constraints that typechecking the
791 -- generated method definitions should succeed. This set will be simplified
792 -- before being used in the instance declaration
793 inferConstraints _ cls inst_tys rep_tc rep_tc_args
794 -- Generic constraints are easy
795 | cls `hasKey` genClassKey
797 -- The others are a bit more complicated
799 = ASSERT2( equalLength rep_tc_tvs all_rep_tc_args, ppr cls <+> ppr rep_tc )
800 stupid_constraints ++ extra_constraints
801 ++ sc_constraints ++ con_arg_constraints
803 -- Constraints arising from the arguments of each constructor
805 = [ mkClassPred cls [arg_ty]
806 | data_con <- tyConDataCons rep_tc,
807 arg_ty <- ASSERT( isVanillaDataCon data_con )
808 get_constrained_tys $
809 dataConInstOrigArgTys data_con all_rep_tc_args,
810 not (isUnLiftedType arg_ty) ]
811 -- No constraints for unlifted types
812 -- Where they are legal we generate specilised function calls
814 -- For functor-like classes, two things are different
815 -- (a) We recurse over argument types to generate constraints
816 -- See Functor examples in TcGenDeriv
817 -- (b) The rep_tc_args will be one short
818 is_functor_like = getUnique cls `elem` functorLikeClassKeys
820 get_constrained_tys :: [Type] -> [Type]
821 get_constrained_tys tys
822 | is_functor_like = concatMap (deepSubtypesContaining last_tv) tys
825 rep_tc_tvs = tyConTyVars rep_tc
826 last_tv = last rep_tc_tvs
827 all_rep_tc_args | is_functor_like = rep_tc_args ++ [mkTyVarTy last_tv]
828 | otherwise = rep_tc_args
830 -- Constraints arising from superclasses
831 -- See Note [Superclasses of derived instance]
832 sc_constraints = substTheta (zipOpenTvSubst (classTyVars cls) inst_tys)
835 -- Stupid constraints
836 stupid_constraints = substTheta subst (tyConStupidTheta rep_tc)
837 subst = zipTopTvSubst rep_tc_tvs all_rep_tc_args
839 -- Extra Data constraints
840 -- The Data class (only) requires that for
841 -- instance (...) => Data (T t1 t2)
843 -- THEN (Data t1, Data t2) are among the (...) constraints
844 -- Reason: when the IF holds, we generate a method
845 -- dataCast2 f = gcast2 f
846 -- and we need the Data constraints to typecheck the method
848 | cls `hasKey` dataClassKey
849 , all (isLiftedTypeKind . typeKind) rep_tc_args
850 = [mkClassPred cls [ty] | ty <- rep_tc_args]
854 ------------------------------------------------------------------
855 -- Check side conditions that dis-allow derivability for particular classes
856 -- This is *apart* from the newtype-deriving mechanism
858 -- Here we get the representation tycon in case of family instances as it has
859 -- the data constructors - but we need to be careful to fall back to the
860 -- family tycon (with indexes) in error messages.
862 data DerivStatus = CanDerive
863 | DerivableClassError SDoc -- Standard class, but can't do it
864 | NonDerivableClass -- Non-standard class
866 checkSideConditions :: DynFlags -> DerivContext -> Class -> [TcType] -> TyCon -> DerivStatus
867 checkSideConditions dflags mtheta cls cls_tys rep_tc
868 | Just cond <- sideConditions mtheta cls
869 = case (cond (dflags, rep_tc)) of
870 Just err -> DerivableClassError err -- Class-specific error
871 Nothing | null cls_tys -> CanDerive -- All derivable classes are unary, so
872 -- cls_tys (the type args other than last)
874 | otherwise -> DerivableClassError ty_args_why -- e.g. deriving( Eq s )
875 | otherwise = NonDerivableClass -- Not a standard class
877 ty_args_why = quotes (ppr (mkClassPred cls cls_tys)) <+> ptext (sLit "is not a class")
879 checkTypeableConditions :: Condition
880 checkTypeableConditions = checkFlag Opt_DeriveDataTypeable `andCond` cond_typeableOK
882 nonStdErr :: Class -> SDoc
883 nonStdErr cls = quotes (ppr cls) <+> ptext (sLit "is not a derivable class")
885 sideConditions :: DerivContext -> Class -> Maybe Condition
886 sideConditions mtheta cls
887 | cls_key == eqClassKey = Just cond_std
888 | cls_key == ordClassKey = Just cond_std
889 | cls_key == showClassKey = Just cond_std
890 | cls_key == readClassKey = Just (cond_std `andCond` cond_noUnliftedArgs)
891 | cls_key == enumClassKey = Just (cond_std `andCond` cond_isEnumeration)
892 | cls_key == ixClassKey = Just (cond_std `andCond` cond_enumOrProduct)
893 | cls_key == boundedClassKey = Just (cond_std `andCond` cond_enumOrProduct)
894 | cls_key == dataClassKey = Just (checkFlag Opt_DeriveDataTypeable `andCond`
895 cond_std `andCond` cond_noUnliftedArgs)
896 | cls_key == functorClassKey = Just (checkFlag Opt_DeriveFunctor `andCond`
897 cond_functorOK True) -- NB: no cond_std!
898 | cls_key == foldableClassKey = Just (checkFlag Opt_DeriveFoldable `andCond`
899 cond_functorOK False) -- Functor/Fold/Trav works ok for rank-n types
900 | cls_key == traversableClassKey = Just (checkFlag Opt_DeriveTraversable `andCond`
901 cond_functorOK False)
902 | cls_key == genClassKey = Just (cond_RepresentableOk `andCond`
903 checkFlag Opt_DeriveGeneric)
904 | otherwise = Nothing
906 cls_key = getUnique cls
907 cond_std = cond_stdOK mtheta
909 type Condition = (DynFlags, TyCon) -> Maybe SDoc
910 -- first Bool is whether or not we are allowed to derive Data and Typeable
911 -- second Bool is whether or not we are allowed to derive Functor
912 -- TyCon is the *representation* tycon if the
913 -- data type is an indexed one
916 orCond :: Condition -> Condition -> Condition
919 Nothing -> Nothing -- c1 succeeds
920 Just x -> case c2 tc of -- c1 fails
922 Just y -> Just (x $$ ptext (sLit " or") $$ y)
925 andCond :: Condition -> Condition -> Condition
926 andCond c1 c2 tc = case c1 tc of
927 Nothing -> c2 tc -- c1 succeeds
928 Just x -> Just x -- c1 fails
930 cond_stdOK :: DerivContext -> Condition
931 cond_stdOK (Just _) _
932 = Nothing -- Don't check these conservative conditions for
933 -- standalone deriving; just generate the code
934 -- and let the typechecker handle the result
935 cond_stdOK Nothing (_, rep_tc)
936 | null data_cons = Just (no_cons_why rep_tc $$ suggestion)
937 | not (null con_whys) = Just (vcat con_whys $$ suggestion)
938 | otherwise = Nothing
940 suggestion = ptext (sLit "Possible fix: use a standalone deriving declaration instead")
941 data_cons = tyConDataCons rep_tc
942 con_whys = mapCatMaybes check_con data_cons
944 check_con :: DataCon -> Maybe SDoc
946 | isVanillaDataCon con
947 , all isTauTy (dataConOrigArgTys con) = Nothing
948 | otherwise = Just (badCon con (ptext (sLit "must have a Haskell-98 type")))
950 no_cons_why :: TyCon -> SDoc
951 no_cons_why rep_tc = quotes (pprSourceTyCon rep_tc) <+>
952 ptext (sLit "must have at least one data constructor")
954 cond_RepresentableOk :: Condition
955 cond_RepresentableOk (_,t) = canDoGenerics t
957 cond_enumOrProduct :: Condition
958 cond_enumOrProduct = cond_isEnumeration `orCond`
959 (cond_isProduct `andCond` cond_noUnliftedArgs)
961 cond_noUnliftedArgs :: Condition
962 -- For some classes (eg Eq, Ord) we allow unlifted arg types
963 -- by generating specilaised code. For others (eg Data) we don't.
964 cond_noUnliftedArgs (_, tc)
965 | null bad_cons = Nothing
966 | otherwise = Just why
968 bad_cons = [ con | con <- tyConDataCons tc
969 , any isUnLiftedType (dataConOrigArgTys con) ]
970 why = badCon (head bad_cons) (ptext (sLit "must have only arguments of lifted type"))
972 cond_isEnumeration :: Condition
973 cond_isEnumeration (_, rep_tc)
974 | isEnumerationTyCon rep_tc = Nothing
975 | otherwise = Just why
977 why = sep [ quotes (pprSourceTyCon rep_tc) <+>
978 ptext (sLit "must be an enumeration type")
979 , ptext (sLit "(an enumeration consists of one or more nullary, non-GADT constructors)") ]
980 -- See Note [Enumeration types] in TyCon
982 cond_isProduct :: Condition
983 cond_isProduct (_, rep_tc)
984 | isProductTyCon rep_tc = Nothing
985 | otherwise = Just why
987 why = quotes (pprSourceTyCon rep_tc) <+>
988 ptext (sLit "must have precisely one constructor")
990 cond_typeableOK :: Condition
991 -- OK for Typeable class
992 -- Currently: (a) args all of kind *
993 -- (b) 7 or fewer args
994 cond_typeableOK (_, tc)
995 | tyConArity tc > 7 = Just too_many
996 | not (all (isSubArgTypeKind . tyVarKind) (tyConTyVars tc))
998 | otherwise = Nothing
1000 too_many = quotes (pprSourceTyCon tc) <+>
1001 ptext (sLit "must have 7 or fewer arguments")
1002 bad_kind = quotes (pprSourceTyCon tc) <+>
1003 ptext (sLit "must only have arguments of kind `*'")
1005 functorLikeClassKeys :: [Unique]
1006 functorLikeClassKeys = [functorClassKey, foldableClassKey, traversableClassKey]
1008 cond_functorOK :: Bool -> Condition
1009 -- OK for Functor/Foldable/Traversable class
1010 -- Currently: (a) at least one argument
1011 -- (b) don't use argument contravariantly
1012 -- (c) don't use argument in the wrong place, e.g. data T a = T (X a a)
1013 -- (d) optionally: don't use function types
1014 -- (e) no "stupid context" on data type
1015 cond_functorOK allowFunctions (_, rep_tc)
1017 = Just (ptext (sLit "Data type") <+> quotes (ppr rep_tc)
1018 <+> ptext (sLit "must have some type parameters"))
1020 | not (null bad_stupid_theta)
1021 = Just (ptext (sLit "Data type") <+> quotes (ppr rep_tc)
1022 <+> ptext (sLit "must not have a class context") <+> pprTheta bad_stupid_theta)
1025 = msum (map check_con data_cons) -- msum picks the first 'Just', if any
1027 tc_tvs = tyConTyVars rep_tc
1028 Just (_, last_tv) = snocView tc_tvs
1029 bad_stupid_theta = filter is_bad (tyConStupidTheta rep_tc)
1030 is_bad pred = last_tv `elemVarSet` tyVarsOfPred pred
1032 data_cons = tyConDataCons rep_tc
1033 check_con con = msum (check_vanilla con : foldDataConArgs (ft_check con) con)
1035 check_vanilla :: DataCon -> Maybe SDoc
1036 check_vanilla con | isVanillaDataCon con = Nothing
1037 | otherwise = Just (badCon con existential)
1039 ft_check :: DataCon -> FFoldType (Maybe SDoc)
1040 ft_check con = FT { ft_triv = Nothing, ft_var = Nothing
1041 , ft_co_var = Just (badCon con covariant)
1042 , ft_fun = \x y -> if allowFunctions then x `mplus` y
1043 else Just (badCon con functions)
1044 , ft_tup = \_ xs -> msum xs
1045 , ft_ty_app = \_ x -> x
1046 , ft_bad_app = Just (badCon con wrong_arg)
1047 , ft_forall = \_ x -> x }
1049 existential = ptext (sLit "must not have existential arguments")
1050 covariant = ptext (sLit "must not use the type variable in a function argument")
1051 functions = ptext (sLit "must not contain function types")
1052 wrong_arg = ptext (sLit "must not use the type variable in an argument other than the last")
1054 checkFlag :: ExtensionFlag -> Condition
1055 checkFlag flag (dflags, _)
1056 | xopt flag dflags = Nothing
1057 | otherwise = Just why
1059 why = ptext (sLit "You need -X") <> text flag_str
1060 <+> ptext (sLit "to derive an instance for this class")
1061 flag_str = case [ s | (s, f, _) <- xFlags, f==flag ] of
1063 other -> pprPanic "checkFlag" (ppr other)
1065 std_class_via_iso :: Class -> Bool
1066 -- These standard classes can be derived for a newtype
1067 -- using the isomorphism trick *even if no -XGeneralizedNewtypeDeriving
1068 -- because giving so gives the same results as generating the boilerplate
1069 std_class_via_iso clas
1070 = classKey clas `elem` [eqClassKey, ordClassKey, ixClassKey, boundedClassKey]
1071 -- Not Read/Show because they respect the type
1072 -- Not Enum, because newtypes are never in Enum
1075 non_iso_class :: Class -> Bool
1076 -- *Never* derive Read, Show, Typeable, Data, Generic by isomorphism,
1077 -- even with -XGeneralizedNewtypeDeriving
1079 = classKey cls `elem` ([ readClassKey, showClassKey, dataClassKey
1080 , genClassKey] ++ typeableClassKeys)
1082 typeableClassKeys :: [Unique]
1083 typeableClassKeys = map getUnique typeableClassNames
1085 new_dfun_name :: Class -> TyCon -> TcM Name
1086 new_dfun_name clas tycon -- Just a simple wrapper
1087 = do { loc <- getSrcSpanM -- The location of the instance decl, not of the tycon
1088 ; newDFunName clas [mkTyConApp tycon []] loc }
1089 -- The type passed to newDFunName is only used to generate
1090 -- a suitable string; hence the empty type arg list
1092 badCon :: DataCon -> SDoc -> SDoc
1093 badCon con msg = ptext (sLit "Constructor") <+> quotes (ppr con) <+> msg
1096 Note [Superclasses of derived instance]
1097 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1098 In general, a derived instance decl needs the superclasses of the derived
1099 class too. So if we have
1100 data T a = ...deriving( Ord )
1101 then the initial context for Ord (T a) should include Eq (T a). Often this is
1102 redundant; we'll also generate an Ord constraint for each constructor argument,
1103 and that will probably generate enough constraints to make the Eq (T a) constraint
1104 be satisfied too. But not always; consider:
1110 data T a = MkT (S a) deriving( Ord )
1111 instance Num a => Eq (T a)
1113 The derived instance for (Ord (T a)) must have a (Num a) constraint!
1115 data T a = MkT deriving( Data, Typeable )
1116 Here there *is* no argument field, but we must nevertheless generate
1117 a context for the Data instances:
1118 instance Typable a => Data (T a) where ...
1121 %************************************************************************
1125 %************************************************************************
1128 mkNewTypeEqn :: CtOrigin -> DynFlags -> [Var] -> Class
1129 -> [Type] -> TyCon -> [Type] -> TyCon -> [Type]
1131 -> TcRn EarlyDerivSpec
1132 mkNewTypeEqn orig dflags tvs
1133 cls cls_tys tycon tc_args rep_tycon rep_tc_args mtheta
1134 -- Want: instance (...) => cls (cls_tys ++ [tycon tc_args]) where ...
1135 | can_derive_via_isomorphism && (newtype_deriving || std_class_via_iso cls)
1136 = do { traceTc "newtype deriving:" (ppr tycon <+> ppr rep_tys <+> ppr all_preds)
1137 ; dfun_name <- new_dfun_name cls tycon
1138 ; loc <- getSrcSpanM
1139 ; let spec = DS { ds_loc = loc, ds_orig = orig
1140 , ds_name = dfun_name, ds_tvs = varSetElems dfun_tvs
1141 , ds_cls = cls, ds_tys = inst_tys
1142 , ds_tc = rep_tycon, ds_tc_args = rep_tc_args
1143 , ds_theta = mtheta `orElse` all_preds
1144 , ds_newtype = True }
1145 ; return (if isJust mtheta then Right spec
1149 = case checkSideConditions dflags mtheta cls cls_tys rep_tycon of
1150 CanDerive -> go_for_it -- Use the standard H98 method
1151 DerivableClassError msg -- Error with standard class
1152 | can_derive_via_isomorphism -> bale_out (msg $$ suggest_nd)
1153 | otherwise -> bale_out msg
1154 NonDerivableClass -- Must use newtype deriving
1155 | newtype_deriving -> bale_out cant_derive_err -- Too hard, even with newtype deriving
1156 | can_derive_via_isomorphism -> bale_out (non_std $$ suggest_nd) -- Try newtype deriving!
1157 | otherwise -> bale_out non_std
1159 newtype_deriving = xopt Opt_GeneralizedNewtypeDeriving dflags
1160 go_for_it = mk_data_eqn orig tvs cls tycon tc_args rep_tycon rep_tc_args mtheta
1161 bale_out msg = failWithTc (derivingThingErr newtype_deriving cls cls_tys inst_ty msg)
1163 non_std = nonStdErr cls
1164 suggest_nd = ptext (sLit "Try -XGeneralizedNewtypeDeriving for GHC's newtype-deriving extension")
1166 -- Here is the plan for newtype derivings. We see
1167 -- newtype T a1...an = MkT (t ak+1...an) deriving (.., C s1 .. sm, ...)
1168 -- where t is a type,
1169 -- ak+1...an is a suffix of a1..an, and are all tyars
1170 -- ak+1...an do not occur free in t, nor in the s1..sm
1171 -- (C s1 ... sm) is a *partial applications* of class C
1172 -- with the last parameter missing
1173 -- (T a1 .. ak) matches the kind of C's last argument
1174 -- (and hence so does t)
1175 -- The latter kind-check has been done by deriveTyData already,
1176 -- and tc_args are already trimmed
1178 -- We generate the instance
1179 -- instance forall ({a1..ak} u fvs(s1..sm)).
1180 -- C s1 .. sm t => C s1 .. sm (T a1...ak)
1181 -- where T a1...ap is the partial application of
1182 -- the LHS of the correct kind and p >= k
1184 -- NB: the variables below are:
1185 -- tc_tvs = [a1, ..., an]
1186 -- tyvars_to_keep = [a1, ..., ak]
1187 -- rep_ty = t ak .. an
1188 -- deriv_tvs = fvs(s1..sm) \ tc_tvs
1189 -- tys = [s1, ..., sm]
1192 -- Running example: newtype T s a = MkT (ST s a) deriving( Monad )
1193 -- We generate the instance
1194 -- instance Monad (ST s) => Monad (T s) where
1196 nt_eta_arity = length (fst (newTyConEtadRhs rep_tycon))
1197 -- For newtype T a b = MkT (S a a b), the TyCon machinery already
1198 -- eta-reduces the representation type, so we know that
1200 -- That's convenient here, because we may have to apply
1201 -- it to fewer than its original complement of arguments
1203 -- Note [Newtype representation]
1204 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1205 -- Need newTyConRhs (*not* a recursive representation finder)
1206 -- to get the representation type. For example
1207 -- newtype B = MkB Int
1208 -- newtype A = MkA B deriving( Num )
1209 -- We want the Num instance of B, *not* the Num instance of Int,
1210 -- when making the Num instance of A!
1211 rep_inst_ty = newTyConInstRhs rep_tycon rep_tc_args
1212 rep_tys = cls_tys ++ [rep_inst_ty]
1213 rep_pred = mkClassPred cls rep_tys
1214 -- rep_pred is the representation dictionary, from where
1215 -- we are gong to get all the methods for the newtype
1219 -- Next we figure out what superclass dictionaries to use
1220 -- See Note [Newtype deriving superclasses] above
1222 cls_tyvars = classTyVars cls
1223 dfun_tvs = tyVarsOfTypes inst_tys
1224 inst_ty = mkTyConApp tycon tc_args
1225 inst_tys = cls_tys ++ [inst_ty]
1226 sc_theta = substTheta (zipOpenTvSubst cls_tyvars inst_tys)
1229 -- If there are no tyvars, there's no need
1230 -- to abstract over the dictionaries we need
1231 -- Example: newtype T = MkT Int deriving( C )
1232 -- We get the derived instance
1235 -- instance C Int => C T
1236 all_preds = rep_pred : sc_theta -- NB: rep_pred comes first
1238 -------------------------------------------------------------------
1239 -- Figuring out whether we can only do this newtype-deriving thing
1241 can_derive_via_isomorphism
1242 = not (non_iso_class cls)
1246 -- && not (isRecursiveTyCon tycon) -- Note [Recursive newtypes]
1248 arity_ok = length cls_tys + 1 == classArity cls
1249 -- Well kinded; eg not: newtype T ... deriving( ST )
1250 -- because ST needs *2* type params
1252 -- Check that eta reduction is OK
1253 eta_ok = nt_eta_arity <= length rep_tc_args
1254 -- The newtype can be eta-reduced to match the number
1255 -- of type argument actually supplied
1256 -- newtype T a b = MkT (S [a] b) deriving( Monad )
1257 -- Here the 'b' must be the same in the rep type (S [a] b)
1258 -- And the [a] must not mention 'b'. That's all handled
1261 ats_ok = null (classATs cls)
1262 -- No associated types for the class, because we don't
1263 -- currently generate type 'instance' decls; and cannot do
1264 -- so for 'data' instance decls
1267 = vcat [ ppUnless arity_ok arity_msg
1268 , ppUnless eta_ok eta_msg
1269 , ppUnless ats_ok ats_msg ]
1270 arity_msg = quotes (ppr (mkClassPred cls cls_tys)) <+> ptext (sLit "does not have arity 1")
1271 eta_msg = ptext (sLit "cannot eta-reduce the representation type enough")
1272 ats_msg = ptext (sLit "the class has associated types")
1275 Note [Recursive newtypes]
1276 ~~~~~~~~~~~~~~~~~~~~~~~~~
1277 Newtype deriving works fine, even if the newtype is recursive.
1278 e.g. newtype S1 = S1 [T1 ()]
1279 newtype T1 a = T1 (StateT S1 IO a ) deriving( Monad )
1280 Remember, too, that type families are curretly (conservatively) given
1281 a recursive flag, so this also allows newtype deriving to work
1284 We used to exclude recursive types, because we had a rather simple
1285 minded way of generating the instance decl:
1287 instance Eq [A] => Eq A -- Makes typechecker loop!
1288 But now we require a simple context, so it's ok.
1291 %************************************************************************
1293 \subsection[TcDeriv-fixpoint]{Finding the fixed point of \tr{deriving} equations}
1295 %************************************************************************
1297 A ``solution'' (to one of the equations) is a list of (k,TyVarTy tv)
1298 terms, which is the final correct RHS for the corresponding original
1302 Each (k,TyVarTy tv) in a solution constrains only a type
1306 The (k,TyVarTy tv) pairs in a solution are canonically
1307 ordered by sorting on type varible, tv, (major key) and then class, k,
1312 inferInstanceContexts :: OverlapFlag -> [DerivSpec] -> TcM [DerivSpec]
1314 inferInstanceContexts _ [] = return []
1316 inferInstanceContexts oflag infer_specs
1317 = do { traceTc "inferInstanceContexts" $ vcat (map pprDerivSpec infer_specs)
1318 ; iterate_deriv 1 initial_solutions }
1320 ------------------------------------------------------------------
1321 -- The initial solutions for the equations claim that each
1322 -- instance has an empty context; this solution is certainly
1323 -- in canonical form.
1324 initial_solutions :: [ThetaType]
1325 initial_solutions = [ [] | _ <- infer_specs ]
1327 ------------------------------------------------------------------
1328 -- iterate_deriv calculates the next batch of solutions,
1329 -- compares it with the current one; finishes if they are the
1330 -- same, otherwise recurses with the new solutions.
1331 -- It fails if any iteration fails
1332 iterate_deriv :: Int -> [ThetaType] -> TcM [DerivSpec]
1333 iterate_deriv n current_solns
1334 | n > 20 -- Looks as if we are in an infinite loop
1335 -- This can happen if we have -XUndecidableInstances
1336 -- (See TcSimplify.tcSimplifyDeriv.)
1337 = pprPanic "solveDerivEqns: probable loop"
1338 (vcat (map pprDerivSpec infer_specs) $$ ppr current_solns)
1340 = do { -- Extend the inst info from the explicit instance decls
1341 -- with the current set of solutions, and simplify each RHS
1342 let inst_specs = zipWithEqual "add_solns" (mkInstance oflag)
1343 current_solns infer_specs
1344 ; new_solns <- checkNoErrs $
1345 extendLocalInstEnv inst_specs $
1346 mapM gen_soln infer_specs
1348 ; if (current_solns == new_solns) then
1349 return [ spec { ds_theta = soln }
1350 | (spec, soln) <- zip infer_specs current_solns ]
1352 iterate_deriv (n+1) new_solns }
1354 ------------------------------------------------------------------
1355 gen_soln :: DerivSpec -> TcM [PredType]
1356 gen_soln (DS { ds_loc = loc, ds_orig = orig, ds_tvs = tyvars
1357 , ds_cls = clas, ds_tys = inst_tys, ds_theta = deriv_rhs })
1359 addErrCtxt (derivInstCtxt the_pred) $
1360 do { -- Check for a bizarre corner case, when the derived instance decl should
1361 -- have form instance C a b => D (T a) where ...
1362 -- Note that 'b' isn't a parameter of T. This gives rise to all sorts
1363 -- of problems; in particular, it's hard to compare solutions for
1364 -- equality when finding the fixpoint. Moreover, simplifyDeriv
1365 -- has an assert failure because it finds a TyVar when it expects
1366 -- only TcTyVars. So I just rule it out for now. I'm not
1367 -- even sure how it can arise.
1369 ; let tv_set = mkVarSet tyvars
1370 weird_preds = [pred | pred <- deriv_rhs
1371 , not (tyVarsOfPred pred `subVarSet` tv_set)]
1372 ; mapM_ (addErrTc . badDerivedPred) weird_preds
1374 ; theta <- simplifyDeriv orig the_pred tyvars deriv_rhs
1375 -- checkValidInstance tyvars theta clas inst_tys
1376 -- Not necessary; see Note [Exotic derived instance contexts]
1379 ; traceTc "TcDeriv" (ppr deriv_rhs $$ ppr theta)
1380 -- Claim: the result instance declaration is guaranteed valid
1381 -- Hence no need to call:
1382 -- checkValidInstance tyvars theta clas inst_tys
1383 ; return (sortLe (<=) theta) } -- Canonicalise before returning the solution
1385 the_pred = mkClassPred clas inst_tys
1387 ------------------------------------------------------------------
1388 mkInstance :: OverlapFlag -> ThetaType -> DerivSpec -> Instance
1389 mkInstance overlap_flag theta
1390 (DS { ds_name = dfun_name
1391 , ds_tvs = tyvars, ds_cls = clas, ds_tys = tys })
1392 = mkLocalInstance dfun overlap_flag
1394 dfun = mkDictFunId dfun_name tyvars theta clas tys
1397 extendLocalInstEnv :: [Instance] -> TcM a -> TcM a
1398 -- Add new locally-defined instances; don't bother to check
1399 -- for functional dependency errors -- that'll happen in TcInstDcls
1400 extendLocalInstEnv dfuns thing_inside
1401 = do { env <- getGblEnv
1402 ; let inst_env' = extendInstEnvList (tcg_inst_env env) dfuns
1403 env' = env { tcg_inst_env = inst_env' }
1404 ; setGblEnv env' thing_inside }
1408 %************************************************************************
1410 \subsection[TcDeriv-normal-binds]{Bindings for the various classes}
1412 %************************************************************************
1414 After all the trouble to figure out the required context for the
1415 derived instance declarations, all that's left is to chug along to
1416 produce them. They will then be shoved into @tcInstDecls2@, which
1417 will do all its usual business.
1419 There are lots of possibilities for code to generate. Here are
1420 various general remarks.
1425 We want derived instances of @Eq@ and @Ord@ (both v common) to be
1426 ``you-couldn't-do-better-by-hand'' efficient.
1429 Deriving @Show@---also pretty common--- should also be reasonable good code.
1432 Deriving for the other classes isn't that common or that big a deal.
1439 Deriving @Ord@ is done mostly with the 1.3 @compare@ method.
1442 Deriving @Eq@ also uses @compare@, if we're deriving @Ord@, too.
1445 We {\em normally} generate code only for the non-defaulted methods;
1446 there are some exceptions for @Eq@ and (especially) @Ord@...
1449 Sometimes we use a @_con2tag_<tycon>@ function, which returns a data
1450 constructor's numeric (@Int#@) tag. These are generated by
1451 @gen_tag_n_con_binds@, and the heuristic for deciding if one of
1452 these is around is given by @hasCon2TagFun@.
1454 The examples under the different sections below will make this
1458 Much less often (really just for deriving @Ix@), we use a
1459 @_tag2con_<tycon>@ function. See the examples.
1462 We use the renamer!!! Reason: we're supposed to be
1463 producing @LHsBinds Name@ for the methods, but that means
1464 producing correctly-uniquified code on the fly. This is entirely
1465 possible (the @TcM@ monad has a @UniqueSupply@), but it is painful.
1466 So, instead, we produce @MonoBinds RdrName@ then heave 'em through
1467 the renamer. What a great hack!
1471 -- Generate the InstInfo for the required instance paired with the
1472 -- *representation* tycon for that instance,
1473 -- plus any auxiliary bindings required
1475 -- Representation tycons differ from the tycon in the instance signature in
1476 -- case of instances for indexed families.
1478 genInst :: Bool -- True <=> standalone deriving
1480 -> DerivSpec -> TcM (InstInfo RdrName, DerivAuxBinds)
1481 genInst standalone_deriv oflag
1482 spec@(DS { ds_tc = rep_tycon, ds_tc_args = rep_tc_args
1483 , ds_theta = theta, ds_newtype = is_newtype
1484 , ds_name = name, ds_cls = clas })
1486 = return (InstInfo { iSpec = inst_spec
1487 , iBinds = NewTypeDerived co rep_tycon }, [])
1490 = do { fix_env <- getFixityEnv
1491 ; let loc = getSrcSpan name
1492 (meth_binds, aux_binds) = genDerivBinds loc fix_env clas rep_tycon
1493 -- In case of a family instance, we need to use the representation
1494 -- tycon (after all, it has the data constructors)
1496 ; return (InstInfo { iSpec = inst_spec
1497 , iBinds = VanillaInst meth_binds [] standalone_deriv }
1500 inst_spec = mkInstance oflag theta spec
1501 co1 = case tyConFamilyCoercion_maybe rep_tycon of
1502 Just co_con -> mkAxInstCo co_con rep_tc_args
1504 -- Not a family => rep_tycon = main tycon
1505 co2 = mkAxInstCo (newTyConCo rep_tycon) rep_tc_args
1506 co = co1 `mkTransCo` co2
1507 id_co = mkReflCo (mkTyConApp rep_tycon rep_tc_args)
1509 -- Example: newtype instance N [a] = N1 (Tree a)
1510 -- deriving instance Eq b => Eq (N [(b,b)])
1511 -- From the instance, we get an implicit newtype R1:N a = N1 (Tree a)
1512 -- When dealing with the deriving clause
1513 -- co1 : N [(b,b)] ~ R1:N (b,b)
1514 -- co2 : R1:N (b,b) ~ Tree (b,b)
1515 -- co : N [(b,b)] ~ Tree (b,b)
1517 genDerivBinds :: SrcSpan -> FixityEnv -> Class -> TyCon -> (LHsBinds RdrName, DerivAuxBinds)
1518 genDerivBinds loc fix_env clas tycon
1519 | className clas `elem` typeableClassNames
1520 = (gen_Typeable_binds loc tycon, [])
1523 = case assocMaybe gen_list (getUnique clas) of
1524 Just gen_fn -> gen_fn loc tycon
1525 Nothing -> pprPanic "genDerivBinds: bad derived class" (ppr clas)
1527 gen_list :: [(Unique, SrcSpan -> TyCon -> (LHsBinds RdrName, DerivAuxBinds))]
1528 gen_list = [(eqClassKey, gen_Eq_binds)
1529 ,(ordClassKey, gen_Ord_binds)
1530 ,(enumClassKey, gen_Enum_binds)
1531 ,(boundedClassKey, gen_Bounded_binds)
1532 ,(ixClassKey, gen_Ix_binds)
1533 ,(showClassKey, gen_Show_binds fix_env)
1534 ,(readClassKey, gen_Read_binds fix_env)
1535 ,(dataClassKey, gen_Data_binds)
1536 ,(functorClassKey, gen_Functor_binds)
1537 ,(foldableClassKey, gen_Foldable_binds)
1538 ,(traversableClassKey, gen_Traversable_binds)
1539 ,(genClassKey, genGenericBinds)
1543 %************************************************************************
1545 \subsection[TcDeriv-generic-binds]{Bindings for the new generic deriving mechanism}
1547 %************************************************************************
1549 For the generic representation we need to generate:
1551 \item A Generic instance
1552 \item A Rep type instance
1553 \item Many auxiliary datatypes and instances for them (for the meta-information)
1556 @genGenericBinds@ does (1)
1557 @genGenericRepExtras@ does (2) and (3)
1558 @genGenericAll@ does all of them
1561 genGenericBinds :: SrcSpan -> TyCon -> (LHsBinds RdrName, DerivAuxBinds)
1562 genGenericBinds _ tc = (mkBindsRep tc, [ {- No DerivAuxBinds -} ])
1564 genGenericRepExtras :: TyCon -> TcM (MetaTyCons, TyCon)
1565 genGenericRepExtras tc =
1566 do uniqS <- newUniqueSupply
1568 -- Uniques for everyone
1569 (uniqD:uniqs) = uniqsFromSupply uniqS
1570 (uniqsC,us) = splitAt (length tc_cons) uniqs
1571 uniqsS :: [[Unique]] -- Unique supply for the S datatypes
1572 uniqsS = mkUniqsS tc_arits us
1574 mkUniqsS (n:t) us = case splitAt n us of
1575 (us1,us2) -> us1 : mkUniqsS t us2
1577 tc_name = tyConName tc
1578 tc_cons = tyConDataCons tc
1579 tc_arits = map dataConSourceArity tc_cons
1581 tc_occ = nameOccName tc_name
1582 d_occ = mkGenD tc_occ
1583 c_occ m = mkGenC tc_occ m
1584 s_occ m n = mkGenS tc_occ m n
1585 mod_name = nameModule (tyConName tc)
1586 d_name = mkExternalName uniqD mod_name d_occ wiredInSrcSpan
1587 c_names = [ mkExternalName u mod_name (c_occ m) wiredInSrcSpan
1588 | (u,m) <- zip uniqsC [0..] ]
1589 s_names = [ [ mkExternalName u mod_name (s_occ m n) wiredInSrcSpan
1590 | (u,n) <- zip us [0..] ] | (us,m) <- zip uniqsS [0..] ]
1592 mkTyCon name = ASSERT( isExternalName name )
1593 buildAlgTyCon name [] [] mkAbstractTyConRhs
1594 NonRecursive False NoParentTyCon Nothing
1596 metaDTyCon <- mkTyCon d_name
1597 metaCTyCons <- sequence [ mkTyCon c_name | c_name <- c_names ]
1598 metaSTyCons <- mapM sequence
1600 | s_name <- s_namesC ] | s_namesC <- s_names ]
1602 let metaDts = MetaTyCons metaDTyCon metaCTyCons metaSTyCons
1604 rep0_tycon <- tc_mkRepTyCon tc metaDts
1606 -- pprTrace "rep0" (ppr rep0_tycon) $
1607 return (metaDts, rep0_tycon)
1609 genGenericAll :: TyCon
1610 -> TcM ((InstInfo RdrName, DerivAuxBinds), MetaTyCons, TyCon)
1612 do (metaDts, rep0_tycon) <- genGenericRepExtras tc
1613 clas <- tcLookupClass genClassName
1614 dfun_name <- new_dfun_name clas tc
1616 mkInstRep = (InstInfo { iSpec = inst, iBinds = binds }
1617 , [ {- No DerivAuxBinds -} ])
1618 inst = mkLocalInstance dfun NoOverlap
1619 binds = VanillaInst (mkBindsRep tc) [] False
1621 tvs = tyConTyVars tc
1622 tc_ty = mkTyConApp tc (mkTyVarTys tvs)
1624 dfun = mkDictFunId dfun_name (tyConTyVars tc) [] clas [tc_ty]
1625 return (mkInstRep, metaDts, rep0_tycon)
1627 genDtMeta :: (TyCon, MetaTyCons) -> TcM [(InstInfo RdrName, DerivAuxBinds)]
1628 genDtMeta (tc,metaDts) =
1629 do dClas <- tcLookupClass datatypeClassName
1630 d_dfun_name <- new_dfun_name dClas tc
1631 cClas <- tcLookupClass constructorClassName
1632 c_dfun_names <- sequence [ new_dfun_name cClas tc | _ <- metaC metaDts ]
1633 sClas <- tcLookupClass selectorClassName
1634 s_dfun_names <- sequence (map sequence [ [ new_dfun_name sClas tc
1636 | x <- metaS metaDts ])
1637 fix_env <- getFixityEnv
1640 (dBinds,cBinds,sBinds) = mkBindsMetaD fix_env tc
1643 d_metaTycon = metaD metaDts
1644 d_inst = mkLocalInstance d_dfun NoOverlap
1645 d_binds = VanillaInst dBinds [] False
1646 d_dfun = mkDictFunId d_dfun_name (tyConTyVars tc) [] dClas
1647 [ mkTyConTy d_metaTycon ]
1648 d_mkInst = (InstInfo { iSpec = d_inst, iBinds = d_binds }, [])
1651 c_metaTycons = metaC metaDts
1652 c_insts = [ mkLocalInstance (c_dfun c ds) NoOverlap
1653 | (c, ds) <- myZip1 c_metaTycons c_dfun_names ]
1654 c_binds = [ VanillaInst c [] False | c <- cBinds ]
1655 c_dfun c dfun_name = mkDictFunId dfun_name (tyConTyVars tc) [] cClas
1657 c_mkInst = [ (InstInfo { iSpec = is, iBinds = bs }, [])
1658 | (is,bs) <- myZip1 c_insts c_binds ]
1661 s_metaTycons = metaS metaDts
1662 s_insts = map (map (\(s,ds) -> mkLocalInstance (s_dfun s ds) NoOverlap))
1663 (myZip2 s_metaTycons s_dfun_names)
1664 s_binds = [ [ VanillaInst s [] False | s <- ss ] | ss <- sBinds ]
1665 s_dfun s dfun_name = mkDictFunId dfun_name (tyConTyVars tc) [] sClas
1667 s_mkInst = map (map (\(is,bs) -> (InstInfo {iSpec=is, iBinds=bs}, [])))
1668 (myZip2 s_insts s_binds)
1670 myZip1 :: [a] -> [b] -> [(a,b)]
1671 myZip1 l1 l2 = ASSERT (length l1 == length l2) zip l1 l2
1673 myZip2 :: [[a]] -> [[b]] -> [[(a,b)]]
1675 ASSERT (and (zipWith (>=) (map length l1) (map length l2)))
1676 [ zip x1 x2 | (x1,x2) <- zip l1 l2 ]
1678 return (d_mkInst : c_mkInst ++ concat s_mkInst)
1682 %************************************************************************
1684 \subsection[TcDeriv-taggery-Names]{What con2tag/tag2con functions are available?}
1686 %************************************************************************
1689 derivingKindErr :: TyCon -> Class -> [Type] -> Kind -> Message
1690 derivingKindErr tc cls cls_tys cls_kind
1691 = hang (ptext (sLit "Cannot derive well-kinded instance of form")
1692 <+> quotes (pprClassPred cls cls_tys <+> parens (ppr tc <+> ptext (sLit "..."))))
1693 2 (ptext (sLit "Class") <+> quotes (ppr cls)
1694 <+> ptext (sLit "expects an argument of kind") <+> quotes (pprKind cls_kind))
1696 derivingEtaErr :: Class -> [Type] -> Type -> Message
1697 derivingEtaErr cls cls_tys inst_ty
1698 = sep [ptext (sLit "Cannot eta-reduce to an instance of form"),
1699 nest 2 (ptext (sLit "instance (...) =>")
1700 <+> pprClassPred cls (cls_tys ++ [inst_ty]))]
1702 typeFamilyPapErr :: TyCon -> Class -> [Type] -> Type -> Message
1703 typeFamilyPapErr tc cls cls_tys inst_ty
1704 = hang (ptext (sLit "Derived instance") <+> quotes (pprClassPred cls (cls_tys ++ [inst_ty])))
1705 2 (ptext (sLit "requires illegal partial application of data type family") <+> ppr tc)
1707 derivingThingErr :: Bool -> Class -> [Type] -> Type -> Message -> Message
1708 derivingThingErr newtype_deriving clas tys ty why
1709 = sep [(hang (ptext (sLit "Can't make a derived instance of"))
1710 2 (quotes (ppr pred))
1711 $$ nest 2 extra) <> colon,
1714 extra | newtype_deriving = ptext (sLit "(even with cunning newtype deriving)")
1716 pred = mkClassPred clas (tys ++ [ty])
1718 derivingHiddenErr :: TyCon -> SDoc
1719 derivingHiddenErr tc
1720 = hang (ptext (sLit "The data constructors of") <+> quotes (ppr tc) <+> ptext (sLit "are not all in scope"))
1721 2 (ptext (sLit "so you cannot derive an instance for it"))
1723 standaloneCtxt :: LHsType Name -> SDoc
1724 standaloneCtxt ty = hang (ptext (sLit "In the stand-alone deriving instance for"))
1727 derivInstCtxt :: PredType -> Message
1729 = ptext (sLit "When deriving the instance for") <+> parens (ppr pred)
1731 badDerivedPred :: PredType -> Message
1733 = vcat [ptext (sLit "Can't derive instances where the instance context mentions"),
1734 ptext (sLit "type variables that are not data type parameters"),
1735 nest 2 (ptext (sLit "Offending constraint:") <+> ppr pred)]