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)
134 Inferring missing contexts
135 ~~~~~~~~~~~~~~~~~~~~~~~~~~
138 data T a b = C1 (Foo a) (Bar b)
143 [NOTE: See end of these comments for what to do with
144 data (C a, D b) => T a b = ...
147 We want to come up with an instance declaration of the form
149 instance (Ping a, Pong b, ...) => Eq (T a b) where
152 It is pretty easy, albeit tedious, to fill in the code "...". The
153 trick is to figure out what the context for the instance decl is,
154 namely @Ping@, @Pong@ and friends.
156 Let's call the context reqd for the T instance of class C at types
157 (a,b, ...) C (T a b). Thus:
159 Eq (T a b) = (Ping a, Pong b, ...)
161 Now we can get a (recursive) equation from the @data@ decl:
163 Eq (T a b) = Eq (Foo a) u Eq (Bar b) -- From C1
164 u Eq (T b a) u Eq Int -- From C2
165 u Eq (T a a) -- From C3
167 Foo and Bar may have explicit instances for @Eq@, in which case we can
168 just substitute for them. Alternatively, either or both may have
169 their @Eq@ instances given by @deriving@ clauses, in which case they
170 form part of the system of equations.
172 Now all we need do is simplify and solve the equations, iterating to
173 find the least fixpoint. Notice that the order of the arguments can
174 switch around, as here in the recursive calls to T.
176 Let's suppose Eq (Foo a) = Eq a, and Eq (Bar b) = Ping b.
180 Eq (T a b) = {} -- The empty set
183 Eq (T a b) = Eq (Foo a) u Eq (Bar b) -- From C1
184 u Eq (T b a) u Eq Int -- From C2
185 u Eq (T a a) -- From C3
187 After simplification:
188 = Eq a u Ping b u {} u {} u {}
193 Eq (T a b) = Eq (Foo a) u Eq (Bar b) -- From C1
194 u Eq (T b a) u Eq Int -- From C2
195 u Eq (T a a) -- From C3
197 After simplification:
202 = Eq a u Ping b u Eq b u Ping a
204 The next iteration gives the same result, so this is the fixpoint. We
205 need to make a canonical form of the RHS to ensure convergence. We do
206 this by simplifying the RHS to a form in which
208 - the classes constrain only tyvars
209 - the list is sorted by tyvar (major key) and then class (minor key)
210 - no duplicates, of course
212 So, here are the synonyms for the ``equation'' structures:
215 Note [Data decl contexts]
216 ~~~~~~~~~~~~~~~~~~~~~~~~~
219 data (RealFloat a) => Complex a = !a :+ !a deriving( Read )
221 We will need an instance decl like:
223 instance (Read a, RealFloat a) => Read (Complex a) where
226 The RealFloat in the context is because the read method for Complex is bound
227 to construct a Complex, and doing that requires that the argument type is
230 But this ain't true for Show, Eq, Ord, etc, since they don't construct
231 a Complex; they only take them apart.
233 Our approach: identify the offending classes, and add the data type
234 context to the instance decl. The "offending classes" are
238 FURTHER NOTE ADDED March 2002. In fact, Haskell98 now requires that
239 pattern matching against a constructor from a data type with a context
240 gives rise to the constraints for that context -- or at least the thinned
241 version. So now all classes are "offending".
243 Note [Newtype deriving]
244 ~~~~~~~~~~~~~~~~~~~~~~~
248 newtype T = T Char deriving( C [a] )
250 Notice the free 'a' in the deriving. We have to fill this out to
251 newtype T = T Char deriving( forall a. C [a] )
253 And then translate it to:
254 instance C [a] Char => C [a] T where ...
257 Note [Newtype deriving superclasses]
258 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
259 (See also Trac #1220 for an interesting exchange on newtype
260 deriving and superclasses.)
262 The 'tys' here come from the partial application in the deriving
263 clause. The last arg is the new instance type.
265 We must pass the superclasses; the newtype might be an instance
266 of them in a different way than the representation type
267 E.g. newtype Foo a = Foo a deriving( Show, Num, Eq )
268 Then the Show instance is not done via isomorphism; it shows
270 The Num instance is derived via isomorphism, but the Show superclass
271 dictionary must the Show instance for Foo, *not* the Show dictionary
272 gotten from the Num dictionary. So we must build a whole new dictionary
273 not just use the Num one. The instance we want is something like:
274 instance (Num a, Show (Foo a), Eq (Foo a)) => Num (Foo a) where
277 There may be a coercion needed which we get from the tycon for the newtype
278 when the dict is constructed in TcInstDcls.tcInstDecl2
281 Note [Unused constructors and deriving clauses]
282 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
283 See Trac #3221. Consider
284 data T = T1 | T2 deriving( Show )
285 Are T1 and T2 unused? Well, no: the deriving clause expands to mention
286 both of them. So we gather defs/uses from deriving just like anything else.
288 %************************************************************************
290 \subsection[TcDeriv-driver]{Top-level function for \tr{derivings}}
292 %************************************************************************
295 tcDeriving :: [LTyClDecl Name] -- All type constructors
296 -> [LInstDecl Name] -- All instance declarations
297 -> [LDerivDecl Name] -- All stand-alone deriving declarations
298 -> TcM ([InstInfo Name] -- The generated "instance decls"
299 ,HsValBinds Name -- Extra generated top-level bindings
301 ,[TyCon] -- Extra generated top-level types
302 ,[TyCon]) -- Extra generated type family instances
304 tcDeriving tycl_decls inst_decls deriv_decls
305 = recoverM (return ([], emptyValBindsOut, emptyDUs, [], [])) $
306 do { -- Fish the "deriving"-related information out of the TcEnv
307 -- And make the necessary "equations".
308 is_boot <- tcIsHsBoot
309 ; traceTc "tcDeriving" (ppr is_boot)
310 ; early_specs <- makeDerivSpecs is_boot tycl_decls inst_decls deriv_decls
312 ; overlap_flag <- getOverlapFlag
313 ; let (infer_specs, given_specs) = splitEithers early_specs
314 ; insts1 <- mapM (genInst True overlap_flag) given_specs
316 ; final_specs <- extendLocalInstEnv (map (iSpec . fst) insts1) $
317 inferInstanceContexts overlap_flag infer_specs
319 ; insts2 <- mapM (genInst False overlap_flag) final_specs
321 -- We no longer generate the old generic to/from functions
322 -- from each type declaration, so this is emptyBag
323 ; gen_binds <- return emptyBag -- mkGenericBinds is_boot tycl_decls
325 -- Generate the generic Representable0 instances
326 -- from each type declaration
327 ; repInstsMeta <- genGenericRepBinds is_boot tycl_decls
329 ; let repInsts = concat (map (\(a,_,_) -> a) repInstsMeta)
330 repMetaTys = map (\(_,b,_) -> b) repInstsMeta
331 repTyCons = map (\(_,_,c) -> c) repInstsMeta
333 ; (inst_info, rn_binds, rn_dus)
334 <- renameDeriv is_boot gen_binds (insts1 ++ insts2 ++ repInsts)
337 ; liftIO (dumpIfSet_dyn dflags Opt_D_dump_deriv "Derived instances"
338 (ddump_deriving inst_info rn_binds))
340 ; when (not (null inst_info)) $
341 dumpDerivingInfo (ddump_deriving inst_info rn_binds)
342 ; return ( inst_info, rn_binds, rn_dus
343 , concat (map metaTyCons2TyCons repMetaTys), repTyCons) }
345 ddump_deriving :: [InstInfo Name] -> HsValBinds Name -> SDoc
346 ddump_deriving inst_infos extra_binds
347 = hang (ptext (sLit "Derived instances"))
348 2 (vcat (map (\i -> pprInstInfoDetails i $$ text "") inst_infos)
351 renameDeriv :: Bool -> LHsBinds RdrName
352 -> [(InstInfo RdrName, DerivAuxBinds)]
353 -> TcM ([InstInfo Name], HsValBinds Name, DefUses)
354 renameDeriv is_boot gen_binds insts
355 | is_boot -- If we are compiling a hs-boot file, don't generate any derived bindings
356 -- The inst-info bindings will all be empty, but it's easier to
357 -- just use rn_inst_info to change the type appropriately
358 = do { (rn_inst_infos, fvs) <- mapAndUnzipM rn_inst_info inst_infos
359 ; return (rn_inst_infos, emptyValBindsOut, usesOnly (plusFVs fvs)) }
362 = discardWarnings $ -- Discard warnings about unused bindings etc
363 do { (rn_gen, dus_gen) <- setOptM Opt_ScopedTypeVariables $ -- Type signatures in patterns
364 -- are used in the generic binds
365 rnTopBinds (ValBindsIn gen_binds [])
366 ; keepAliveSetTc (duDefs dus_gen) -- Mark these guys to be kept alive
368 -- Generate and rename any extra not-one-inst-decl-specific binds,
369 -- notably "con2tag" and/or "tag2con" functions.
370 -- Bring those names into scope before renaming the instances themselves
371 ; loc <- getSrcSpanM -- Generic loc for shared bindings
372 ; let (aux_binds, aux_sigs) = unzip $ map (genAuxBind loc) $
373 rm_dups [] $ concat deriv_aux_binds
374 aux_val_binds = ValBindsIn (listToBag aux_binds) aux_sigs
375 ; rn_aux_lhs <- rnTopBindsLHS emptyFsEnv aux_val_binds
376 ; bindLocalNames (collectHsValBinders rn_aux_lhs) $
377 do { (rn_aux, dus_aux) <- rnTopBindsRHS rn_aux_lhs
378 ; (rn_inst_infos, fvs_insts) <- mapAndUnzipM rn_inst_info inst_infos
379 ; return (rn_inst_infos, rn_aux `plusHsValBinds` rn_gen,
380 dus_gen `plusDU` dus_aux `plusDU` usesOnly (plusFVs fvs_insts)) } }
383 (inst_infos, deriv_aux_binds) = unzip insts
385 -- Remove duplicate requests for auxilliary bindings
387 rm_dups acc (b:bs) | any (isDupAux b) acc = rm_dups acc bs
388 | otherwise = rm_dups (b:acc) bs
391 rn_inst_info :: InstInfo RdrName -> TcM (InstInfo Name, FreeVars)
392 rn_inst_info info@(InstInfo { iBinds = NewTypeDerived coi tc })
393 = return ( info { iBinds = NewTypeDerived coi tc }
394 , mkFVs (map dataConName (tyConDataCons tc)))
395 -- See Note [Newtype deriving and unused constructors]
397 rn_inst_info inst_info@(InstInfo { iSpec = inst, iBinds = VanillaInst binds sigs standalone_deriv })
398 = -- Bring the right type variables into
399 -- scope (yuk), and rename the method binds
401 bindLocalNames (map Var.varName tyvars) $
402 do { (rn_binds, fvs) <- rnMethodBinds clas_nm (\_ -> []) [] binds
403 ; let binds' = VanillaInst rn_binds [] standalone_deriv
404 ; return (inst_info { iBinds = binds' }, fvs) }
406 (tyvars,_, clas,_) = instanceHead inst
407 clas_nm = className clas
409 -----------------------------------------
411 mkGenericBinds :: Bool -> [LTyClDecl Name] -> TcM (LHsBinds RdrName)
412 mkGenericBinds is_boot tycl_decls
416 = do { tcs <- mapM tcLookupTyCon [ tcdName d
417 | L _ d <- tycl_decls, isDataDecl d ]
418 ; return (unionManyBags [ mkTyConGenericBinds tc
419 | tc <- tcs, tyConHasGenerics tc ]) }
420 -- We are only interested in the data type declarations,
421 -- and then only in the ones whose 'has-generics' flag is on
422 -- The predicate tyConHasGenerics finds both of these
426 Note [Newtype deriving and unused constructors]
427 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
428 Consider this (see Trac #1954):
431 newtype P a = MkP (IO a) deriving Monad
433 If you compile with -fwarn-unused-binds you do not expect the warning
434 "Defined but not used: data consructor MkP". Yet the newtype deriving
435 code does not explicitly mention MkP, but it should behave as if you
437 instance Monad P where
438 return x = MkP (return x)
441 So we want to signal a user of the data constructor 'MkP'. That's
442 what we do in rn_inst_info, and it's the only reason we have the TyCon
443 stored in NewTypeDerived.
446 %************************************************************************
448 From HsSyn to DerivSpec
450 %************************************************************************
452 @makeDerivSpecs@ fishes around to find the info about needed derived instances.
455 makeDerivSpecs :: Bool
459 -> TcM [EarlyDerivSpec]
461 makeDerivSpecs is_boot tycl_decls inst_decls deriv_decls
462 | is_boot -- No 'deriving' at all in hs-boot files
463 = do { mapM_ add_deriv_err deriv_locs
466 = do { eqns1 <- mapAndRecoverM deriveTyData all_tydata
467 ; eqns2 <- mapAndRecoverM deriveStandalone deriv_decls
468 ; return (eqns1 ++ eqns2) }
470 extractTyDataPreds decls
471 = [(p, d) | d@(L _ (TyData {tcdDerivs = Just preds})) <- decls, p <- preds]
473 all_tydata :: [(LHsType Name, LTyClDecl Name)]
474 -- Derived predicate paired with its data type declaration
475 all_tydata = extractTyDataPreds (instDeclATs inst_decls ++ tycl_decls)
477 deriv_locs = map (getLoc . snd) all_tydata
478 ++ map getLoc deriv_decls
480 add_deriv_err loc = setSrcSpan loc $
481 addErr (hang (ptext (sLit "Deriving not permitted in hs-boot file"))
482 2 (ptext (sLit "Use an instance declaration instead")))
484 ------------------------------------------------------------------
485 deriveStandalone :: LDerivDecl Name -> TcM EarlyDerivSpec
486 -- Standalone deriving declarations
487 -- e.g. deriving instance Show a => Show (T a)
488 -- Rather like tcLocalInstDecl
489 deriveStandalone (L loc (DerivDecl deriv_ty))
491 addErrCtxt (standaloneCtxt deriv_ty) $
492 do { traceTc "Standalone deriving decl for" (ppr deriv_ty)
493 ; (tvs, theta, cls, inst_tys) <- tcHsInstHead deriv_ty
494 ; traceTc "Standalone deriving;" $ vcat
495 [ text "tvs:" <+> ppr tvs
496 , text "theta:" <+> ppr theta
497 , text "cls:" <+> ppr cls
498 , text "tys:" <+> ppr inst_tys ]
499 ; checkValidInstance deriv_ty tvs theta cls inst_tys
500 -- C.f. TcInstDcls.tcLocalInstDecl1
502 ; let cls_tys = take (length inst_tys - 1) inst_tys
503 inst_ty = last inst_tys
504 ; traceTc "Standalone deriving:" $ vcat
505 [ text "class:" <+> ppr cls
506 , text "class types:" <+> ppr cls_tys
507 , text "type:" <+> ppr inst_ty ]
508 ; mkEqnHelp StandAloneDerivOrigin tvs cls cls_tys inst_ty
511 ------------------------------------------------------------------
512 deriveTyData :: (LHsType Name, LTyClDecl Name) -> TcM EarlyDerivSpec
513 deriveTyData (L loc deriv_pred, L _ decl@(TyData { tcdLName = L _ tycon_name,
514 tcdTyVars = tv_names,
515 tcdTyPats = ty_pats }))
516 = setSrcSpan loc $ -- Use the location of the 'deriving' item
518 do { (tvs, tc, tc_args) <- get_lhs ty_pats
519 ; tcExtendTyVarEnv tvs $ -- Deriving preds may (now) mention
520 -- the type variables for the type constructor
522 do { (deriv_tvs, cls, cls_tys) <- tcHsDeriv deriv_pred
523 -- The "deriv_pred" is a LHsType to take account of the fact that for
524 -- newtype deriving we allow deriving (forall a. C [a]).
526 -- Given data T a b c = ... deriving( C d ),
527 -- we want to drop type variables from T so that (C d (T a)) is well-kinded
528 ; let cls_tyvars = classTyVars cls
529 kind = tyVarKind (last cls_tyvars)
530 (arg_kinds, _) = splitKindFunTys kind
531 n_args_to_drop = length arg_kinds
532 n_args_to_keep = tyConArity tc - n_args_to_drop
533 args_to_drop = drop n_args_to_keep tc_args
534 inst_ty = mkTyConApp tc (take n_args_to_keep tc_args)
535 inst_ty_kind = typeKind inst_ty
536 dropped_tvs = mkVarSet (mapCatMaybes getTyVar_maybe args_to_drop)
537 univ_tvs = (mkVarSet tvs `extendVarSetList` deriv_tvs)
538 `minusVarSet` dropped_tvs
540 -- Check that the result really is well-kinded
541 ; checkTc (n_args_to_keep >= 0 && (inst_ty_kind `eqKind` kind))
542 (derivingKindErr tc cls cls_tys kind)
544 ; checkTc (sizeVarSet dropped_tvs == n_args_to_drop && -- (a)
545 tyVarsOfTypes (inst_ty:cls_tys) `subVarSet` univ_tvs) -- (b)
546 (derivingEtaErr cls cls_tys inst_ty)
548 -- (a) The data type can be eta-reduced; eg reject:
549 -- data instance T a a = ... deriving( Monad )
550 -- (b) The type class args do not mention any of the dropped type
552 -- newtype T a s = ... deriving( ST s )
554 -- Type families can't be partially applied
555 -- e.g. newtype instance T Int a = MkT [a] deriving( Monad )
556 -- Note [Deriving, type families, and partial applications]
557 ; checkTc (not (isFamilyTyCon tc) || n_args_to_drop == 0)
558 (typeFamilyPapErr tc cls cls_tys inst_ty)
560 ; mkEqnHelp DerivOrigin (varSetElems univ_tvs) cls cls_tys inst_ty Nothing } }
562 -- Tiresomely we must figure out the "lhs", which is awkward for type families
563 -- E.g. data T a b = .. deriving( Eq )
564 -- Here, the lhs is (T a b)
565 -- data instance TF Int b = ... deriving( Eq )
566 -- Here, the lhs is (TF Int b)
567 -- But if we just look up the tycon_name, we get is the *family*
568 -- tycon, but not pattern types -- they are in the *rep* tycon.
569 get_lhs Nothing = do { tc <- tcLookupTyCon tycon_name
570 ; let tvs = tyConTyVars tc
571 ; return (tvs, tc, mkTyVarTys tvs) }
572 get_lhs (Just pats) = do { let hs_app = nlHsTyConApp tycon_name pats
573 ; (tvs, tc_app) <- tcHsQuantifiedType tv_names hs_app
574 ; let (tc, tc_args) = tcSplitTyConApp tc_app
575 ; return (tvs, tc, tc_args) }
578 = panic "derivTyData" -- Caller ensures that only TyData can happen
581 Note [Deriving, type families, and partial applications]
582 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
583 When there are no type families, it's quite easy:
585 newtype S a = MkS [a]
586 -- :CoS :: S ~ [] -- Eta-reduced
588 instance Eq [a] => Eq (S a) -- by coercion sym (Eq (:CoS a)) : Eq [a] ~ Eq (S a)
589 instance Monad [] => Monad S -- by coercion sym (Monad :CoS) : Monad [] ~ Monad S
591 When type familes are involved it's trickier:
594 newtype instance T Int a = MkT [a] deriving( Eq, Monad )
595 -- :RT is the representation type for (T Int a)
596 -- :CoF:R1T a :: T Int a ~ :RT a -- Not eta reduced
597 -- :Co:R1T :: :RT ~ [] -- Eta-reduced
599 instance Eq [a] => Eq (T Int a) -- easy by coercion
600 instance Monad [] => Monad (T Int) -- only if we can eta reduce???
602 The "???" bit is that we don't build the :CoF thing in eta-reduced form
603 Henc the current typeFamilyPapErr, even though the instance makes sense.
604 After all, we can write it out
605 instance Monad [] => Monad (T Int) -- only if we can eta reduce???
610 mkEqnHelp :: CtOrigin -> [TyVar] -> Class -> [Type] -> Type
611 -> DerivContext -- Just => context supplied (standalone deriving)
612 -- Nothing => context inferred (deriving on data decl)
613 -> TcRn EarlyDerivSpec
614 -- Make the EarlyDerivSpec for an instance
615 -- forall tvs. theta => cls (tys ++ [ty])
616 -- where the 'theta' is optional (that's the Maybe part)
617 -- Assumes that this declaration is well-kinded
619 mkEqnHelp orig tvs cls cls_tys tc_app mtheta
620 | Just (tycon, tc_args) <- tcSplitTyConApp_maybe tc_app
621 , isAlgTyCon tycon -- Check for functions, primitive types etc
622 = mk_alg_eqn tycon tc_args
624 = failWithTc (derivingThingErr False cls cls_tys tc_app
625 (ptext (sLit "The last argument of the instance must be a data or newtype application")))
628 bale_out msg = failWithTc (derivingThingErr False cls cls_tys tc_app msg)
630 mk_alg_eqn tycon tc_args
631 | className cls `elem` typeableClassNames
632 = do { dflags <- getDOpts
633 ; case checkTypeableConditions (dflags, tycon) of
634 Just err -> bale_out err
635 Nothing -> mk_typeable_eqn orig tvs cls tycon tc_args mtheta }
637 | isDataFamilyTyCon tycon
638 , length tc_args /= tyConArity tycon
639 = bale_out (ptext (sLit "Unsaturated data family application"))
642 = do { (rep_tc, rep_tc_args) <- tcLookupDataFamInst tycon tc_args
643 -- Be careful to test rep_tc here: in the case of families,
644 -- we want to check the instance tycon, not the family tycon
646 -- For standalone deriving (mtheta /= Nothing),
647 -- check that all the data constructors are in scope.
648 ; rdr_env <- getGlobalRdrEnv
649 ; let hidden_data_cons = isAbstractTyCon rep_tc ||
650 any not_in_scope (tyConDataCons rep_tc)
651 not_in_scope dc = null (lookupGRE_Name rdr_env (dataConName dc))
652 ; unless (isNothing mtheta || not hidden_data_cons)
653 (bale_out (derivingHiddenErr tycon))
656 ; if isDataTyCon rep_tc then
657 mkDataTypeEqn orig dflags tvs cls cls_tys
658 tycon tc_args rep_tc rep_tc_args mtheta
660 mkNewTypeEqn orig dflags tvs cls cls_tys
661 tycon tc_args rep_tc rep_tc_args mtheta }
665 %************************************************************************
669 %************************************************************************
672 mkDataTypeEqn :: CtOrigin
674 -> [Var] -- Universally quantified type variables in the instance
675 -> Class -- Class for which we need to derive an instance
676 -> [Type] -- Other parameters to the class except the last
677 -> TyCon -- Type constructor for which the instance is requested
678 -- (last parameter to the type class)
679 -> [Type] -- Parameters to the type constructor
680 -> TyCon -- rep of the above (for type families)
681 -> [Type] -- rep of the above
682 -> DerivContext -- Context of the instance, for standalone deriving
683 -> TcRn EarlyDerivSpec -- Return 'Nothing' if error
685 mkDataTypeEqn orig dflags tvs cls cls_tys
686 tycon tc_args rep_tc rep_tc_args mtheta
687 = case checkSideConditions dflags mtheta cls cls_tys rep_tc of
688 -- NB: pass the *representation* tycon to checkSideConditions
689 CanDerive -> go_for_it
690 NonDerivableClass -> bale_out (nonStdErr cls)
691 DerivableClassError msg -> bale_out msg
693 go_for_it = mk_data_eqn orig tvs cls tycon tc_args rep_tc rep_tc_args mtheta
694 bale_out msg = failWithTc (derivingThingErr False cls cls_tys (mkTyConApp tycon tc_args) msg)
696 mk_data_eqn :: CtOrigin -> [TyVar] -> Class
697 -> TyCon -> [TcType] -> TyCon -> [TcType] -> DerivContext
698 -> TcM EarlyDerivSpec
699 mk_data_eqn orig tvs cls tycon tc_args rep_tc rep_tc_args mtheta
700 = do { dfun_name <- new_dfun_name cls tycon
702 ; let inst_tys = [mkTyConApp tycon tc_args]
703 inferred_constraints = inferConstraints tvs cls inst_tys rep_tc rep_tc_args
704 spec = DS { ds_loc = loc, ds_orig = orig
705 , ds_name = dfun_name, ds_tvs = tvs
706 , ds_cls = cls, ds_tys = inst_tys
707 , ds_tc = rep_tc, ds_tc_args = rep_tc_args
708 , ds_theta = mtheta `orElse` inferred_constraints
709 , ds_newtype = False }
711 ; return (if isJust mtheta then Right spec -- Specified context
712 else Left spec) } -- Infer context
714 ----------------------
715 mk_typeable_eqn :: CtOrigin -> [TyVar] -> Class
716 -> TyCon -> [TcType] -> DerivContext
717 -> TcM EarlyDerivSpec
718 mk_typeable_eqn orig tvs cls tycon tc_args mtheta
719 -- The Typeable class is special in several ways
720 -- data T a b = ... deriving( Typeable )
722 -- instance Typeable2 T where ...
724 -- 1. There are no constraints in the instance
725 -- 2. There are no type variables either
726 -- 3. The actual class we want to generate isn't necessarily
727 -- Typeable; it depends on the arity of the type
728 | isNothing mtheta -- deriving on a data type decl
729 = do { checkTc (cls `hasKey` typeableClassKey)
730 (ptext (sLit "Use deriving( Typeable ) on a data type declaration"))
731 ; real_cls <- tcLookupClass (typeableClassNames !! tyConArity tycon)
732 ; mk_typeable_eqn orig tvs real_cls tycon [] (Just []) }
734 | otherwise -- standaone deriving
735 = do { checkTc (null tc_args)
736 (ptext (sLit "Derived typeable instance must be of form (Typeable")
737 <> int (tyConArity tycon) <+> ppr tycon <> rparen)
738 ; dfun_name <- new_dfun_name cls tycon
741 DS { ds_loc = loc, ds_orig = orig, ds_name = dfun_name, ds_tvs = []
742 , ds_cls = cls, ds_tys = [mkTyConApp tycon []]
743 , ds_tc = tycon, ds_tc_args = []
744 , ds_theta = mtheta `orElse` [], ds_newtype = False }) }
746 ----------------------
747 inferConstraints :: [TyVar] -> Class -> [TcType] -> TyCon -> [TcType] -> ThetaType
748 -- Generate a sufficiently large set of constraints that typechecking the
749 -- generated method definitions should succeed. This set will be simplified
750 -- before being used in the instance declaration
751 inferConstraints _ cls inst_tys rep_tc rep_tc_args
752 = ASSERT2( equalLength rep_tc_tvs all_rep_tc_args, ppr cls <+> ppr rep_tc )
753 stupid_constraints ++ extra_constraints
754 ++ sc_constraints ++ con_arg_constraints
756 -- Constraints arising from the arguments of each constructor
758 = [ mkClassPred cls [arg_ty]
759 | data_con <- tyConDataCons rep_tc,
760 arg_ty <- ASSERT( isVanillaDataCon data_con )
761 get_constrained_tys $
762 dataConInstOrigArgTys data_con all_rep_tc_args,
763 not (isUnLiftedType arg_ty) ]
764 -- No constraints for unlifted types
765 -- Where they are legal we generate specilised function calls
767 -- For functor-like classes, two things are different
768 -- (a) We recurse over argument types to generate constraints
769 -- See Functor examples in TcGenDeriv
770 -- (b) The rep_tc_args will be one short
771 is_functor_like = getUnique cls `elem` functorLikeClassKeys
773 get_constrained_tys :: [Type] -> [Type]
774 get_constrained_tys tys
775 | is_functor_like = concatMap (deepSubtypesContaining last_tv) tys
778 rep_tc_tvs = tyConTyVars rep_tc
779 last_tv = last rep_tc_tvs
780 all_rep_tc_args | is_functor_like = rep_tc_args ++ [mkTyVarTy last_tv]
781 | otherwise = rep_tc_args
783 -- Constraints arising from superclasses
784 -- See Note [Superclasses of derived instance]
785 sc_constraints = substTheta (zipOpenTvSubst (classTyVars cls) inst_tys)
788 -- Stupid constraints
789 stupid_constraints = substTheta subst (tyConStupidTheta rep_tc)
790 subst = zipTopTvSubst rep_tc_tvs all_rep_tc_args
792 -- Extra Data constraints
793 -- The Data class (only) requires that for
794 -- instance (...) => Data (T t1 t2)
796 -- THEN (Data t1, Data t2) are among the (...) constraints
797 -- Reason: when the IF holds, we generate a method
798 -- dataCast2 f = gcast2 f
799 -- and we need the Data constraints to typecheck the method
801 | cls `hasKey` dataClassKey
802 , all (isLiftedTypeKind . typeKind) rep_tc_args
803 = [mkClassPred cls [ty] | ty <- rep_tc_args]
807 ------------------------------------------------------------------
808 -- Check side conditions that dis-allow derivability for particular classes
809 -- This is *apart* from the newtype-deriving mechanism
811 -- Here we get the representation tycon in case of family instances as it has
812 -- the data constructors - but we need to be careful to fall back to the
813 -- family tycon (with indexes) in error messages.
815 data DerivStatus = CanDerive
816 | DerivableClassError SDoc -- Standard class, but can't do it
817 | NonDerivableClass -- Non-standard class
819 checkSideConditions :: DynFlags -> DerivContext -> Class -> [TcType] -> TyCon -> DerivStatus
820 checkSideConditions dflags mtheta cls cls_tys rep_tc
821 | Just cond <- sideConditions mtheta cls
822 = case (cond (dflags, rep_tc)) of
823 Just err -> DerivableClassError err -- Class-specific error
824 Nothing | null cls_tys -> CanDerive -- All derivable classes are unary, so
825 -- cls_tys (the type args other than last)
827 | otherwise -> DerivableClassError ty_args_why -- e.g. deriving( Eq s )
828 | otherwise = NonDerivableClass -- Not a standard class
830 ty_args_why = quotes (ppr (mkClassPred cls cls_tys)) <+> ptext (sLit "is not a class")
832 checkTypeableConditions :: Condition
833 checkTypeableConditions = checkFlag Opt_DeriveDataTypeable `andCond` cond_typeableOK
835 nonStdErr :: Class -> SDoc
836 nonStdErr cls = quotes (ppr cls) <+> ptext (sLit "is not a derivable class")
838 sideConditions :: DerivContext -> Class -> Maybe Condition
839 sideConditions mtheta cls
840 | cls_key == eqClassKey = Just cond_std
841 | cls_key == ordClassKey = Just cond_std
842 | cls_key == showClassKey = Just cond_std
843 | cls_key == readClassKey = Just (cond_std `andCond` cond_noUnliftedArgs)
844 | cls_key == enumClassKey = Just (cond_std `andCond` cond_isEnumeration)
845 | cls_key == ixClassKey = Just (cond_std `andCond` cond_enumOrProduct)
846 | cls_key == boundedClassKey = Just (cond_std `andCond` cond_enumOrProduct)
847 | cls_key == dataClassKey = Just (checkFlag Opt_DeriveDataTypeable `andCond`
848 cond_std `andCond` cond_noUnliftedArgs)
849 | cls_key == functorClassKey = Just (checkFlag Opt_DeriveFunctor `andCond`
850 cond_functorOK True) -- NB: no cond_std!
851 | cls_key == foldableClassKey = Just (checkFlag Opt_DeriveFoldable `andCond`
852 cond_functorOK False) -- Functor/Fold/Trav works ok for rank-n types
853 | cls_key == traversableClassKey = Just (checkFlag Opt_DeriveTraversable `andCond`
854 cond_functorOK False)
855 | otherwise = Nothing
857 cls_key = getUnique cls
858 cond_std = cond_stdOK mtheta
860 type Condition = (DynFlags, TyCon) -> Maybe SDoc
861 -- first Bool is whether or not we are allowed to derive Data and Typeable
862 -- second Bool is whether or not we are allowed to derive Functor
863 -- TyCon is the *representation* tycon if the
864 -- data type is an indexed one
867 orCond :: Condition -> Condition -> Condition
870 Nothing -> Nothing -- c1 succeeds
871 Just x -> case c2 tc of -- c1 fails
873 Just y -> Just (x $$ ptext (sLit " and") $$ y)
876 andCond :: Condition -> Condition -> Condition
877 andCond c1 c2 tc = case c1 tc of
878 Nothing -> c2 tc -- c1 succeeds
879 Just x -> Just x -- c1 fails
881 cond_stdOK :: DerivContext -> Condition
882 cond_stdOK (Just _) _
883 = Nothing -- Don't check these conservative conditions for
884 -- standalone deriving; just generate the code
885 -- and let the typechecker handle the result
886 cond_stdOK Nothing (_, rep_tc)
887 | null data_cons = Just (no_cons_why rep_tc $$ suggestion)
888 | not (null con_whys) = Just (vcat con_whys $$ suggestion)
889 | otherwise = Nothing
891 suggestion = ptext (sLit "Possible fix: use a standalone deriving declaration instead")
892 data_cons = tyConDataCons rep_tc
893 con_whys = mapCatMaybes check_con data_cons
895 check_con :: DataCon -> Maybe SDoc
897 | isVanillaDataCon con
898 , all isTauTy (dataConOrigArgTys con) = Nothing
899 | otherwise = Just (badCon con (ptext (sLit "does not have a Haskell-98 type")))
901 no_cons_why :: TyCon -> SDoc
902 no_cons_why rep_tc = quotes (pprSourceTyCon rep_tc) <+>
903 ptext (sLit "has no data constructors")
905 cond_enumOrProduct :: Condition
906 cond_enumOrProduct = cond_isEnumeration `orCond`
907 (cond_isProduct `andCond` cond_noUnliftedArgs)
909 cond_noUnliftedArgs :: Condition
910 -- For some classes (eg Eq, Ord) we allow unlifted arg types
911 -- by generating specilaised code. For others (eg Data) we don't.
912 cond_noUnliftedArgs (_, tc)
913 | null bad_cons = Nothing
914 | otherwise = Just why
916 bad_cons = [ con | con <- tyConDataCons tc
917 , any isUnLiftedType (dataConOrigArgTys con) ]
918 why = badCon (head bad_cons) (ptext (sLit "has arguments of unlifted type"))
920 cond_isEnumeration :: Condition
921 cond_isEnumeration (_, rep_tc)
922 | isEnumerationTyCon rep_tc = Nothing
923 | otherwise = Just why
925 why = sep [ quotes (pprSourceTyCon rep_tc) <+>
926 ptext (sLit "is not an enumeration type")
927 , ptext (sLit "(an enumeration consists of one or more nullary, non-GADT constructors)") ]
928 -- See Note [Enumeration types] in TyCon
930 cond_isProduct :: Condition
931 cond_isProduct (_, rep_tc)
932 | isProductTyCon rep_tc = Nothing
933 | otherwise = Just why
935 why = quotes (pprSourceTyCon rep_tc) <+>
936 ptext (sLit "does not have precisely one constructor")
938 cond_typeableOK :: Condition
939 -- OK for Typeable class
940 -- Currently: (a) args all of kind *
941 -- (b) 7 or fewer args
942 cond_typeableOK (_, tc)
943 | tyConArity tc > 7 = Just too_many
944 | not (all (isSubArgTypeKind . tyVarKind) (tyConTyVars tc))
946 | otherwise = Nothing
948 too_many = quotes (pprSourceTyCon tc) <+>
949 ptext (sLit "has too many arguments")
950 bad_kind = quotes (pprSourceTyCon tc) <+>
951 ptext (sLit "has arguments of kind other than `*'")
953 functorLikeClassKeys :: [Unique]
954 functorLikeClassKeys = [functorClassKey, foldableClassKey, traversableClassKey]
956 cond_functorOK :: Bool -> Condition
957 -- OK for Functor/Foldable/Traversable class
958 -- Currently: (a) at least one argument
959 -- (b) don't use argument contravariantly
960 -- (c) don't use argument in the wrong place, e.g. data T a = T (X a a)
961 -- (d) optionally: don't use function types
962 -- (e) no "stupid context" on data type
963 cond_functorOK allowFunctions (_, rep_tc)
965 = Just (ptext (sLit "Data type") <+> quotes (ppr rep_tc)
966 <+> ptext (sLit "has no parameters"))
968 | not (null bad_stupid_theta)
969 = Just (ptext (sLit "Data type") <+> quotes (ppr rep_tc)
970 <+> ptext (sLit "has a class context") <+> pprTheta bad_stupid_theta)
973 = msum (map check_con data_cons) -- msum picks the first 'Just', if any
975 tc_tvs = tyConTyVars rep_tc
976 Just (_, last_tv) = snocView tc_tvs
977 bad_stupid_theta = filter is_bad (tyConStupidTheta rep_tc)
978 is_bad pred = last_tv `elemVarSet` tyVarsOfPred pred
980 data_cons = tyConDataCons rep_tc
981 check_con con = msum (check_vanilla con : foldDataConArgs (ft_check con) con)
983 check_vanilla :: DataCon -> Maybe SDoc
984 check_vanilla con | isVanillaDataCon con = Nothing
985 | otherwise = Just (badCon con existential)
987 ft_check :: DataCon -> FFoldType (Maybe SDoc)
988 ft_check con = FT { ft_triv = Nothing, ft_var = Nothing
989 , ft_co_var = Just (badCon con covariant)
990 , ft_fun = \x y -> if allowFunctions then x `mplus` y
991 else Just (badCon con functions)
992 , ft_tup = \_ xs -> msum xs
993 , ft_ty_app = \_ x -> x
994 , ft_bad_app = Just (badCon con wrong_arg)
995 , ft_forall = \_ x -> x }
997 existential = ptext (sLit "has existential arguments")
998 covariant = ptext (sLit "uses the type variable in a function argument")
999 functions = ptext (sLit "contains function types")
1000 wrong_arg = ptext (sLit "uses the type variable in an argument other than the last")
1002 checkFlag :: ExtensionFlag -> Condition
1003 checkFlag flag (dflags, _)
1004 | xopt flag dflags = Nothing
1005 | otherwise = Just why
1007 why = ptext (sLit "You need -X") <> text flag_str
1008 <+> ptext (sLit "to derive an instance for this class")
1009 flag_str = case [ s | (s, f, _) <- xFlags, f==flag ] of
1011 other -> pprPanic "checkFlag" (ppr other)
1013 std_class_via_iso :: Class -> Bool
1014 -- These standard classes can be derived for a newtype
1015 -- using the isomorphism trick *even if no -XGeneralizedNewtypeDeriving
1016 -- because giving so gives the same results as generating the boilerplate
1017 std_class_via_iso clas
1018 = classKey clas `elem` [eqClassKey, ordClassKey, ixClassKey, boundedClassKey]
1019 -- Not Read/Show because they respect the type
1020 -- Not Enum, because newtypes are never in Enum
1023 non_iso_class :: Class -> Bool
1024 -- *Never* derive Read,Show,Typeable,Data by isomorphism,
1025 -- even with -XGeneralizedNewtypeDeriving
1027 = classKey cls `elem` ([readClassKey, showClassKey, dataClassKey] ++
1030 typeableClassKeys :: [Unique]
1031 typeableClassKeys = map getUnique typeableClassNames
1033 new_dfun_name :: Class -> TyCon -> TcM Name
1034 new_dfun_name clas tycon -- Just a simple wrapper
1035 = do { loc <- getSrcSpanM -- The location of the instance decl, not of the tycon
1036 ; newDFunName clas [mkTyConApp tycon []] loc }
1037 -- The type passed to newDFunName is only used to generate
1038 -- a suitable string; hence the empty type arg list
1040 badCon :: DataCon -> SDoc -> SDoc
1041 badCon con msg = ptext (sLit "Constructor") <+> quotes (ppr con) <+> msg
1044 Note [Superclasses of derived instance]
1045 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1046 In general, a derived instance decl needs the superclasses of the derived
1047 class too. So if we have
1048 data T a = ...deriving( Ord )
1049 then the initial context for Ord (T a) should include Eq (T a). Often this is
1050 redundant; we'll also generate an Ord constraint for each constructor argument,
1051 and that will probably generate enough constraints to make the Eq (T a) constraint
1052 be satisfied too. But not always; consider:
1058 data T a = MkT (S a) deriving( Ord )
1059 instance Num a => Eq (T a)
1061 The derived instance for (Ord (T a)) must have a (Num a) constraint!
1063 data T a = MkT deriving( Data, Typeable )
1064 Here there *is* no argument field, but we must nevertheless generate
1065 a context for the Data instances:
1066 instance Typable a => Data (T a) where ...
1069 %************************************************************************
1073 %************************************************************************
1076 mkNewTypeEqn :: CtOrigin -> DynFlags -> [Var] -> Class
1077 -> [Type] -> TyCon -> [Type] -> TyCon -> [Type]
1079 -> TcRn EarlyDerivSpec
1080 mkNewTypeEqn orig dflags tvs
1081 cls cls_tys tycon tc_args rep_tycon rep_tc_args mtheta
1082 -- Want: instance (...) => cls (cls_tys ++ [tycon tc_args]) where ...
1083 | can_derive_via_isomorphism && (newtype_deriving || std_class_via_iso cls)
1084 = do { traceTc "newtype deriving:" (ppr tycon <+> ppr rep_tys <+> ppr all_preds)
1085 ; dfun_name <- new_dfun_name cls tycon
1086 ; loc <- getSrcSpanM
1087 ; let spec = DS { ds_loc = loc, ds_orig = orig
1088 , ds_name = dfun_name, ds_tvs = varSetElems dfun_tvs
1089 , ds_cls = cls, ds_tys = inst_tys
1090 , ds_tc = rep_tycon, ds_tc_args = rep_tc_args
1091 , ds_theta = mtheta `orElse` all_preds
1092 , ds_newtype = True }
1093 ; return (if isJust mtheta then Right spec
1097 = case checkSideConditions dflags mtheta cls cls_tys rep_tycon of
1098 CanDerive -> go_for_it -- Use the standard H98 method
1099 DerivableClassError msg -- Error with standard class
1100 | can_derive_via_isomorphism -> bale_out (msg $$ suggest_nd)
1101 | otherwise -> bale_out msg
1102 NonDerivableClass -- Must use newtype deriving
1103 | newtype_deriving -> bale_out cant_derive_err -- Too hard, even with newtype deriving
1104 | can_derive_via_isomorphism -> bale_out (non_std $$ suggest_nd) -- Try newtype deriving!
1105 | otherwise -> bale_out non_std
1107 newtype_deriving = xopt Opt_GeneralizedNewtypeDeriving dflags
1108 go_for_it = mk_data_eqn orig tvs cls tycon tc_args rep_tycon rep_tc_args mtheta
1109 bale_out msg = failWithTc (derivingThingErr newtype_deriving cls cls_tys inst_ty msg)
1111 non_std = nonStdErr cls
1112 suggest_nd = ptext (sLit "Try -XGeneralizedNewtypeDeriving for GHC's newtype-deriving extension")
1114 -- Here is the plan for newtype derivings. We see
1115 -- newtype T a1...an = MkT (t ak+1...an) deriving (.., C s1 .. sm, ...)
1116 -- where t is a type,
1117 -- ak+1...an is a suffix of a1..an, and are all tyars
1118 -- ak+1...an do not occur free in t, nor in the s1..sm
1119 -- (C s1 ... sm) is a *partial applications* of class C
1120 -- with the last parameter missing
1121 -- (T a1 .. ak) matches the kind of C's last argument
1122 -- (and hence so does t)
1123 -- The latter kind-check has been done by deriveTyData already,
1124 -- and tc_args are already trimmed
1126 -- We generate the instance
1127 -- instance forall ({a1..ak} u fvs(s1..sm)).
1128 -- C s1 .. sm t => C s1 .. sm (T a1...ak)
1129 -- where T a1...ap is the partial application of
1130 -- the LHS of the correct kind and p >= k
1132 -- NB: the variables below are:
1133 -- tc_tvs = [a1, ..., an]
1134 -- tyvars_to_keep = [a1, ..., ak]
1135 -- rep_ty = t ak .. an
1136 -- deriv_tvs = fvs(s1..sm) \ tc_tvs
1137 -- tys = [s1, ..., sm]
1140 -- Running example: newtype T s a = MkT (ST s a) deriving( Monad )
1141 -- We generate the instance
1142 -- instance Monad (ST s) => Monad (T s) where
1144 nt_eta_arity = length (fst (newTyConEtadRhs rep_tycon))
1145 -- For newtype T a b = MkT (S a a b), the TyCon machinery already
1146 -- eta-reduces the representation type, so we know that
1148 -- That's convenient here, because we may have to apply
1149 -- it to fewer than its original complement of arguments
1151 -- Note [Newtype representation]
1152 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1153 -- Need newTyConRhs (*not* a recursive representation finder)
1154 -- to get the representation type. For example
1155 -- newtype B = MkB Int
1156 -- newtype A = MkA B deriving( Num )
1157 -- We want the Num instance of B, *not* the Num instance of Int,
1158 -- when making the Num instance of A!
1159 rep_inst_ty = newTyConInstRhs rep_tycon rep_tc_args
1160 rep_tys = cls_tys ++ [rep_inst_ty]
1161 rep_pred = mkClassPred cls rep_tys
1162 -- rep_pred is the representation dictionary, from where
1163 -- we are gong to get all the methods for the newtype
1167 -- Next we figure out what superclass dictionaries to use
1168 -- See Note [Newtype deriving superclasses] above
1170 cls_tyvars = classTyVars cls
1171 dfun_tvs = tyVarsOfTypes inst_tys
1172 inst_ty = mkTyConApp tycon tc_args
1173 inst_tys = cls_tys ++ [inst_ty]
1174 sc_theta = substTheta (zipOpenTvSubst cls_tyvars inst_tys)
1177 -- If there are no tyvars, there's no need
1178 -- to abstract over the dictionaries we need
1179 -- Example: newtype T = MkT Int deriving( C )
1180 -- We get the derived instance
1183 -- instance C Int => C T
1184 all_preds = rep_pred : sc_theta -- NB: rep_pred comes first
1186 -------------------------------------------------------------------
1187 -- Figuring out whether we can only do this newtype-deriving thing
1189 can_derive_via_isomorphism
1190 = not (non_iso_class cls)
1194 -- && not (isRecursiveTyCon tycon) -- Note [Recursive newtypes]
1196 arity_ok = length cls_tys + 1 == classArity cls
1197 -- Well kinded; eg not: newtype T ... deriving( ST )
1198 -- because ST needs *2* type params
1200 -- Check that eta reduction is OK
1201 eta_ok = nt_eta_arity <= length rep_tc_args
1202 -- The newtype can be eta-reduced to match the number
1203 -- of type argument actually supplied
1204 -- newtype T a b = MkT (S [a] b) deriving( Monad )
1205 -- Here the 'b' must be the same in the rep type (S [a] b)
1206 -- And the [a] must not mention 'b'. That's all handled
1209 ats_ok = null (classATs cls)
1210 -- No associated types for the class, because we don't
1211 -- currently generate type 'instance' decls; and cannot do
1212 -- so for 'data' instance decls
1215 = vcat [ ppUnless arity_ok arity_msg
1216 , ppUnless eta_ok eta_msg
1217 , ppUnless ats_ok ats_msg ]
1218 arity_msg = quotes (ppr (mkClassPred cls cls_tys)) <+> ptext (sLit "does not have arity 1")
1219 eta_msg = ptext (sLit "cannot eta-reduce the representation type enough")
1220 ats_msg = ptext (sLit "the class has associated types")
1223 Note [Recursive newtypes]
1224 ~~~~~~~~~~~~~~~~~~~~~~~~~
1225 Newtype deriving works fine, even if the newtype is recursive.
1226 e.g. newtype S1 = S1 [T1 ()]
1227 newtype T1 a = T1 (StateT S1 IO a ) deriving( Monad )
1228 Remember, too, that type families are curretly (conservatively) given
1229 a recursive flag, so this also allows newtype deriving to work
1232 We used to exclude recursive types, because we had a rather simple
1233 minded way of generating the instance decl:
1235 instance Eq [A] => Eq A -- Makes typechecker loop!
1236 But now we require a simple context, so it's ok.
1239 %************************************************************************
1241 \subsection[TcDeriv-fixpoint]{Finding the fixed point of \tr{deriving} equations}
1243 %************************************************************************
1245 A ``solution'' (to one of the equations) is a list of (k,TyVarTy tv)
1246 terms, which is the final correct RHS for the corresponding original
1250 Each (k,TyVarTy tv) in a solution constrains only a type
1254 The (k,TyVarTy tv) pairs in a solution are canonically
1255 ordered by sorting on type varible, tv, (major key) and then class, k,
1260 inferInstanceContexts :: OverlapFlag -> [DerivSpec] -> TcM [DerivSpec]
1262 inferInstanceContexts _ [] = return []
1264 inferInstanceContexts oflag infer_specs
1265 = do { traceTc "inferInstanceContexts" $ vcat (map pprDerivSpec infer_specs)
1266 ; iterate_deriv 1 initial_solutions }
1268 ------------------------------------------------------------------
1269 -- The initial solutions for the equations claim that each
1270 -- instance has an empty context; this solution is certainly
1271 -- in canonical form.
1272 initial_solutions :: [ThetaType]
1273 initial_solutions = [ [] | _ <- infer_specs ]
1275 ------------------------------------------------------------------
1276 -- iterate_deriv calculates the next batch of solutions,
1277 -- compares it with the current one; finishes if they are the
1278 -- same, otherwise recurses with the new solutions.
1279 -- It fails if any iteration fails
1280 iterate_deriv :: Int -> [ThetaType] -> TcM [DerivSpec]
1281 iterate_deriv n current_solns
1282 | n > 20 -- Looks as if we are in an infinite loop
1283 -- This can happen if we have -XUndecidableInstances
1284 -- (See TcSimplify.tcSimplifyDeriv.)
1285 = pprPanic "solveDerivEqns: probable loop"
1286 (vcat (map pprDerivSpec infer_specs) $$ ppr current_solns)
1288 = do { -- Extend the inst info from the explicit instance decls
1289 -- with the current set of solutions, and simplify each RHS
1290 let inst_specs = zipWithEqual "add_solns" (mkInstance oflag)
1291 current_solns infer_specs
1292 ; new_solns <- checkNoErrs $
1293 extendLocalInstEnv inst_specs $
1294 mapM gen_soln infer_specs
1296 ; if (current_solns == new_solns) then
1297 return [ spec { ds_theta = soln }
1298 | (spec, soln) <- zip infer_specs current_solns ]
1300 iterate_deriv (n+1) new_solns }
1302 ------------------------------------------------------------------
1303 gen_soln :: DerivSpec -> TcM [PredType]
1304 gen_soln (DS { ds_loc = loc, ds_orig = orig, ds_tvs = tyvars
1305 , ds_cls = clas, ds_tys = inst_tys, ds_theta = deriv_rhs })
1307 addErrCtxt (derivInstCtxt the_pred) $
1308 do { -- Check for a bizarre corner case, when the derived instance decl should
1309 -- have form instance C a b => D (T a) where ...
1310 -- Note that 'b' isn't a parameter of T. This gives rise to all sorts
1311 -- of problems; in particular, it's hard to compare solutions for
1312 -- equality when finding the fixpoint. Moreover, simplifyDeriv
1313 -- has an assert failure because it finds a TyVar when it expects
1314 -- only TcTyVars. So I just rule it out for now. I'm not
1315 -- even sure how it can arise.
1317 ; let tv_set = mkVarSet tyvars
1318 weird_preds = [pred | pred <- deriv_rhs
1319 , not (tyVarsOfPred pred `subVarSet` tv_set)]
1320 ; mapM_ (addErrTc . badDerivedPred) weird_preds
1322 ; theta <- simplifyDeriv orig the_pred tyvars deriv_rhs
1323 -- checkValidInstance tyvars theta clas inst_tys
1324 -- Not necessary; see Note [Exotic derived instance contexts]
1327 ; traceTc "TcDeriv" (ppr deriv_rhs $$ ppr theta)
1328 -- Claim: the result instance declaration is guaranteed valid
1329 -- Hence no need to call:
1330 -- checkValidInstance tyvars theta clas inst_tys
1331 ; return (sortLe (<=) theta) } -- Canonicalise before returning the solution
1333 the_pred = mkClassPred clas inst_tys
1335 ------------------------------------------------------------------
1336 mkInstance :: OverlapFlag -> ThetaType -> DerivSpec -> Instance
1337 mkInstance overlap_flag theta
1338 (DS { ds_name = dfun_name
1339 , ds_tvs = tyvars, ds_cls = clas, ds_tys = tys })
1340 = mkLocalInstance dfun overlap_flag
1342 dfun = mkDictFunId dfun_name tyvars theta clas tys
1345 extendLocalInstEnv :: [Instance] -> TcM a -> TcM a
1346 -- Add new locally-defined instances; don't bother to check
1347 -- for functional dependency errors -- that'll happen in TcInstDcls
1348 extendLocalInstEnv dfuns thing_inside
1349 = do { env <- getGblEnv
1350 ; let inst_env' = extendInstEnvList (tcg_inst_env env) dfuns
1351 env' = env { tcg_inst_env = inst_env' }
1352 ; setGblEnv env' thing_inside }
1356 %************************************************************************
1358 \subsection[TcDeriv-normal-binds]{Bindings for the various classes}
1360 %************************************************************************
1362 After all the trouble to figure out the required context for the
1363 derived instance declarations, all that's left is to chug along to
1364 produce them. They will then be shoved into @tcInstDecls2@, which
1365 will do all its usual business.
1367 There are lots of possibilities for code to generate. Here are
1368 various general remarks.
1373 We want derived instances of @Eq@ and @Ord@ (both v common) to be
1374 ``you-couldn't-do-better-by-hand'' efficient.
1377 Deriving @Show@---also pretty common--- should also be reasonable good code.
1380 Deriving for the other classes isn't that common or that big a deal.
1387 Deriving @Ord@ is done mostly with the 1.3 @compare@ method.
1390 Deriving @Eq@ also uses @compare@, if we're deriving @Ord@, too.
1393 We {\em normally} generate code only for the non-defaulted methods;
1394 there are some exceptions for @Eq@ and (especially) @Ord@...
1397 Sometimes we use a @_con2tag_<tycon>@ function, which returns a data
1398 constructor's numeric (@Int#@) tag. These are generated by
1399 @gen_tag_n_con_binds@, and the heuristic for deciding if one of
1400 these is around is given by @hasCon2TagFun@.
1402 The examples under the different sections below will make this
1406 Much less often (really just for deriving @Ix@), we use a
1407 @_tag2con_<tycon>@ function. See the examples.
1410 We use the renamer!!! Reason: we're supposed to be
1411 producing @LHsBinds Name@ for the methods, but that means
1412 producing correctly-uniquified code on the fly. This is entirely
1413 possible (the @TcM@ monad has a @UniqueSupply@), but it is painful.
1414 So, instead, we produce @MonoBinds RdrName@ then heave 'em through
1415 the renamer. What a great hack!
1419 -- Generate the InstInfo for the required instance paired with the
1420 -- *representation* tycon for that instance,
1421 -- plus any auxiliary bindings required
1423 -- Representation tycons differ from the tycon in the instance signature in
1424 -- case of instances for indexed families.
1426 genInst :: Bool -- True <=> standalone deriving
1428 -> DerivSpec -> TcM (InstInfo RdrName, DerivAuxBinds)
1429 genInst standalone_deriv oflag
1430 spec@(DS { ds_tc = rep_tycon, ds_tc_args = rep_tc_args
1431 , ds_theta = theta, ds_newtype = is_newtype
1432 , ds_name = name, ds_cls = clas })
1434 = return (InstInfo { iSpec = inst_spec
1435 , iBinds = NewTypeDerived co rep_tycon }, [])
1438 = do { fix_env <- getFixityEnv
1439 ; let loc = getSrcSpan name
1440 (meth_binds, aux_binds) = genDerivBinds loc fix_env clas rep_tycon
1441 -- In case of a family instance, we need to use the representation
1442 -- tycon (after all, it has the data constructors)
1444 ; return (InstInfo { iSpec = inst_spec
1445 , iBinds = VanillaInst meth_binds [] standalone_deriv }
1448 inst_spec = mkInstance oflag theta spec
1449 co1 = case tyConFamilyCoercion_maybe rep_tycon of
1450 Just co_con -> ACo (mkTyConApp co_con rep_tc_args)
1452 -- Not a family => rep_tycon = main tycon
1453 co2 = case newTyConCo_maybe rep_tycon of
1454 Just co_con -> ACo (mkTyConApp co_con rep_tc_args)
1455 Nothing -> id_co -- The newtype is transparent; no need for a cast
1456 co = co1 `mkTransCoI` co2
1457 id_co = IdCo (mkTyConApp rep_tycon rep_tc_args)
1459 -- Example: newtype instance N [a] = N1 (Tree a)
1460 -- deriving instance Eq b => Eq (N [(b,b)])
1461 -- From the instance, we get an implicit newtype R1:N a = N1 (Tree a)
1462 -- When dealing with the deriving clause
1463 -- co1 : N [(b,b)] ~ R1:N (b,b)
1464 -- co2 : R1:N (b,b) ~ Tree (b,b)
1465 -- co : N [(b,b)] ~ Tree (b,b)
1467 genDerivBinds :: SrcSpan -> FixityEnv -> Class -> TyCon -> (LHsBinds RdrName, DerivAuxBinds)
1468 genDerivBinds loc fix_env clas tycon
1469 | className clas `elem` typeableClassNames
1470 = (gen_Typeable_binds loc tycon, [])
1473 = case assocMaybe gen_list (getUnique clas) of
1474 Just gen_fn -> gen_fn loc tycon
1475 Nothing -> pprPanic "genDerivBinds: bad derived class" (ppr clas)
1477 gen_list :: [(Unique, SrcSpan -> TyCon -> (LHsBinds RdrName, DerivAuxBinds))]
1478 gen_list = [(eqClassKey, gen_Eq_binds)
1479 ,(ordClassKey, gen_Ord_binds)
1480 ,(enumClassKey, gen_Enum_binds)
1481 ,(boundedClassKey, gen_Bounded_binds)
1482 ,(ixClassKey, gen_Ix_binds)
1483 ,(showClassKey, gen_Show_binds fix_env)
1484 ,(readClassKey, gen_Read_binds fix_env)
1485 ,(dataClassKey, gen_Data_binds)
1486 ,(functorClassKey, gen_Functor_binds)
1487 ,(foldableClassKey, gen_Foldable_binds)
1488 ,(traversableClassKey, gen_Traversable_binds)
1491 -- Generate the binds for the generic representation
1492 genGenericRepBinds :: Bool -> [LTyClDecl Name]
1493 -> TcM [([(InstInfo RdrName, DerivAuxBinds)]
1494 , MetaTyCons, TyCon)]
1495 genGenericRepBinds isBoot tyclDecls
1496 | isBoot = return []
1498 allTyDecls <- mapM tcLookupTyCon [ tcdName d | L _ d <- tyclDecls
1500 let tyDecls = filter tyConHasGenerics allTyDecls
1501 inst1 <- mapM genGenericRepBind tyDecls
1502 let (_repInsts, metaTyCons, _repTys) = unzip3 inst1
1503 metaInsts <- ASSERT (length tyDecls == length metaTyCons)
1504 mapM genDtMeta (zip tyDecls metaTyCons)
1505 return (ASSERT (length inst1 == length metaInsts)
1507 | ((ri, ms, rt), mi) <- zip inst1 metaInsts ])
1509 genGenericRepBind :: TyCon -> TcM ((InstInfo RdrName, DerivAuxBinds)
1510 , MetaTyCons, TyCon)
1511 genGenericRepBind tc =
1512 do clas <- tcLookupClass rep0ClassName
1513 uniqS <- newUniqueSupply
1514 dfun_name <- new_dfun_name clas tc
1516 -- Uniques for everyone
1517 (uniqD:uniqs) = uniqsFromSupply uniqS
1518 (uniqsC,us) = splitAt (length tc_cons) uniqs
1519 uniqsS :: [[Unique]] -- Unique supply for the S datatypes
1520 uniqsS = mkUniqsS tc_arits us
1522 mkUniqsS (n:t) us = case splitAt n us of
1523 (us1,us2) -> us1 : mkUniqsS t us2
1525 tc_name = tyConName tc
1526 tc_cons = tyConDataCons tc
1527 tc_arits = map dataConSourceArity tc_cons
1529 tc_occ = nameOccName tc_name
1530 d_occ = mkGenD tc_occ
1531 c_occ m = mkGenC tc_occ m
1532 s_occ m n = mkGenS tc_occ m n
1533 mod_name = nameModule (tyConName tc)
1534 d_name = mkExternalName uniqD mod_name d_occ wiredInSrcSpan
1535 c_names = [ mkExternalName u mod_name (c_occ m) wiredInSrcSpan
1536 | (u,m) <- zip uniqsC [0..] ]
1537 s_names = [ [ mkExternalName u mod_name (s_occ m n) wiredInSrcSpan
1538 | (u,n) <- zip us [0..] ] | (us,m) <- zip uniqsS [0..] ]
1539 tvs = tyConTyVars tc
1540 tc_ty = mkTyConApp tc (mkTyVarTys tvs)
1542 mkTyCon name = ASSERT( isExternalName name )
1543 buildAlgTyCon name [] [] mkAbstractTyConRhs
1544 NonRecursive False False NoParentTyCon Nothing
1546 metaDTyCon <- mkTyCon d_name
1547 metaCTyCons <- sequence [ mkTyCon c_name | c_name <- c_names ]
1548 metaSTyCons <- mapM sequence
1550 | s_name <- s_namesC ] | s_namesC <- s_names ]
1552 let metaDts = MetaTyCons metaDTyCon metaCTyCons metaSTyCons
1554 rep0_tycon <- tc_mkRep0TyCon tc metaDts
1557 mkInstRep0 = (InstInfo { iSpec = inst, iBinds = binds }
1558 , [ {- No DerivAuxBinds -} ])
1559 inst = mkLocalInstance dfun NoOverlap
1560 binds = VanillaInst (mkBindsRep0 tc) [] False
1562 dfun = mkDictFunId dfun_name (tyConTyVars tc) [] clas [tc_ty]
1563 return (mkInstRep0, metaDts, rep0_tycon)
1565 genDtMeta :: (TyCon, MetaTyCons) -> TcM [(InstInfo RdrName, DerivAuxBinds)]
1566 genDtMeta (tc,metaDts) =
1567 do dClas <- tcLookupClass datatypeClassName
1568 d_dfun_name <- new_dfun_name dClas tc
1569 cClas <- tcLookupClass constructorClassName
1570 c_dfun_names <- sequence [ new_dfun_name cClas tc | _ <- metaC metaDts ]
1571 sClas <- tcLookupClass selectorClassName
1572 s_dfun_names <- sequence (map sequence [ [ new_dfun_name sClas tc
1574 | x <- metaS metaDts ])
1575 fix_env <- getFixityEnv
1578 (dBinds,cBinds,sBinds) = mkBindsMetaD fix_env tc
1581 d_metaTycon = metaD metaDts
1582 d_inst = mkLocalInstance d_dfun NoOverlap
1583 d_binds = VanillaInst dBinds [] False
1584 d_dfun = mkDictFunId d_dfun_name (tyConTyVars tc) [] dClas
1585 [ mkTyConTy d_metaTycon ]
1586 d_mkInst = (InstInfo { iSpec = d_inst, iBinds = d_binds }, [])
1589 c_metaTycons = metaC metaDts
1590 c_insts = [ mkLocalInstance (c_dfun c ds) NoOverlap
1591 | (c, ds) <- myZip1 c_metaTycons c_dfun_names ]
1592 c_binds = [ VanillaInst c [] False | c <- cBinds ]
1593 c_dfun c dfun_name = mkDictFunId dfun_name (tyConTyVars tc) [] cClas
1595 c_mkInst = [ (InstInfo { iSpec = is, iBinds = bs }, [])
1596 | (is,bs) <- myZip1 c_insts c_binds ]
1599 s_metaTycons = metaS metaDts
1600 s_insts = map (map (\(s,ds) -> mkLocalInstance (s_dfun s ds) NoOverlap))
1601 (myZip2 s_metaTycons s_dfun_names)
1602 s_binds = [ [ VanillaInst s [] False | s <- ss ] | ss <- sBinds ]
1603 s_dfun s dfun_name = mkDictFunId dfun_name (tyConTyVars tc) [] sClas
1605 s_mkInst = map (map (\(is,bs) -> (InstInfo {iSpec=is, iBinds=bs}, [])))
1606 (myZip2 s_insts s_binds)
1608 myZip1 :: [a] -> [b] -> [(a,b)]
1609 myZip1 l1 l2 = ASSERT (length l1 == length l2) zip l1 l2
1611 myZip2 :: [[a]] -> [[b]] -> [[(a,b)]]
1613 ASSERT (and (zipWith (>=) (map length l1) (map length l2)))
1614 [ zip x1 x2 | (x1,x2) <- zip l1 l2 ]
1616 return (d_mkInst : c_mkInst ++ concat s_mkInst)
1620 %************************************************************************
1622 \subsection[TcDeriv-taggery-Names]{What con2tag/tag2con functions are available?}
1624 %************************************************************************
1627 derivingKindErr :: TyCon -> Class -> [Type] -> Kind -> Message
1628 derivingKindErr tc cls cls_tys cls_kind
1629 = hang (ptext (sLit "Cannot derive well-kinded instance of form")
1630 <+> quotes (pprClassPred cls cls_tys <+> parens (ppr tc <+> ptext (sLit "..."))))
1631 2 (ptext (sLit "Class") <+> quotes (ppr cls)
1632 <+> ptext (sLit "expects an argument of kind") <+> quotes (pprKind cls_kind))
1634 derivingEtaErr :: Class -> [Type] -> Type -> Message
1635 derivingEtaErr cls cls_tys inst_ty
1636 = sep [ptext (sLit "Cannot eta-reduce to an instance of form"),
1637 nest 2 (ptext (sLit "instance (...) =>")
1638 <+> pprClassPred cls (cls_tys ++ [inst_ty]))]
1640 typeFamilyPapErr :: TyCon -> Class -> [Type] -> Type -> Message
1641 typeFamilyPapErr tc cls cls_tys inst_ty
1642 = hang (ptext (sLit "Derived instance") <+> quotes (pprClassPred cls (cls_tys ++ [inst_ty])))
1643 2 (ptext (sLit "requires illegal partial application of data type family") <+> ppr tc)
1645 derivingThingErr :: Bool -> Class -> [Type] -> Type -> Message -> Message
1646 derivingThingErr newtype_deriving clas tys ty why
1647 = sep [(hang (ptext (sLit "Can't make a derived instance of"))
1648 2 (quotes (ppr pred))
1649 $$ nest 2 extra) <> colon,
1652 extra | newtype_deriving = ptext (sLit "(even with cunning newtype deriving)")
1654 pred = mkClassPred clas (tys ++ [ty])
1656 derivingHiddenErr :: TyCon -> SDoc
1657 derivingHiddenErr tc
1658 = hang (ptext (sLit "The data constructors of") <+> quotes (ppr tc) <+> ptext (sLit "are not all in scope"))
1659 2 (ptext (sLit "so you cannot derive an instance for it"))
1661 standaloneCtxt :: LHsType Name -> SDoc
1662 standaloneCtxt ty = hang (ptext (sLit "In the stand-alone deriving instance for"))
1665 derivInstCtxt :: PredType -> Message
1667 = ptext (sLit "When deriving the instance for") <+> parens (ppr pred)
1669 badDerivedPred :: PredType -> Message
1671 = vcat [ptext (sLit "Can't derive instances where the instance context mentions"),
1672 ptext (sLit "type variables that are not data type parameters"),
1673 nest 2 (ptext (sLit "Offending constraint:") <+> ppr pred)]