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