+------------------------------------------------------------------
+deriveStandalone :: LDerivDecl Name -> TcM (Maybe DerivEqn, Maybe InstInfo)
+-- Standalone deriving declarations
+-- e.g. deriving instance show a => Show (T a)
+-- Rather like tcLocalInstDecl
+deriveStandalone (L loc (DerivDecl deriv_ty))
+ = setSrcSpan loc $
+ addErrCtxt (standaloneCtxt deriv_ty) $
+ do { traceTc (text "standalone deriving decl for" <+> ppr deriv_ty)
+ ; (tvs, theta, tau) <- tcHsInstHead deriv_ty
+ ; traceTc (text "standalone deriving;"
+ <+> text "tvs:" <+> ppr tvs
+ <+> text "theta:" <+> ppr theta
+ <+> text "tau:" <+> ppr tau)
+ ; (cls, inst_tys) <- checkValidInstHead tau
+ ; let cls_tys = take (length inst_tys - 1) inst_tys
+ inst_ty = last inst_tys
+
+ ; traceTc (text "standalone deriving;"
+ <+> text "class:" <+> ppr cls
+ <+> text "class types:" <+> ppr cls_tys
+ <+> text "type:" <+> ppr inst_ty)
+ ; mkEqnHelp StandAloneDerivOrigin tvs cls cls_tys inst_ty
+ (Just theta) }
+
+------------------------------------------------------------------
+deriveTyData :: (LHsType Name, LTyClDecl Name) -> TcM (Maybe DerivEqn, Maybe InstInfo)
+deriveTyData (deriv_pred, L loc decl@(TyData { tcdLName = L _ tycon_name,
+ tcdTyVars = tv_names,
+ tcdTyPats = ty_pats }))
+ = setSrcSpan loc $
+ tcAddDeclCtxt decl $
+ do { let hs_ty_args = ty_pats `orElse` map (nlHsTyVar . hsLTyVarName) tv_names
+ hs_app = nlHsTyConApp tycon_name hs_ty_args
+ -- We get kinding info for the tyvars by typechecking (T a b)
+ -- Hence forming a tycon application and then dis-assembling it
+ ; (tvs, tc_app) <- tcHsQuantifiedType tv_names hs_app
+ ; tcExtendTyVarEnv tvs $ -- Deriving preds may (now) mention
+ -- the type variables for the type constructor
+ do { (deriv_tvs, cls, cls_tys) <- tcHsDeriv deriv_pred
+ -- The "deriv_pred" is a LHsType to take account of the fact that for
+ -- newtype deriving we allow deriving (forall a. C [a]).
+ ; mkEqnHelp DerivOrigin (tvs++deriv_tvs) cls cls_tys tc_app Nothing } }
+deriveTyData (deriv_pred, other_decl)
+ = panic "derivTyData" -- Caller ensures that only TyData can happen
+
+------------------------------------------------------------------
+mkEqnHelp :: InstOrigin -> [TyVar] -> Class -> [Type] -> Type
+ -> Maybe DerivRhs
+ -> TcRn (Maybe DerivEqn, Maybe InstInfo)
+mkEqnHelp orig tvs cls cls_tys tc_app mtheta
+ | Just (tycon, tc_args) <- tcSplitTyConApp_maybe tc_app
+ = do { -- Make tc_app saturated, because that's what the
+ -- mkDataTypeEqn things expect
+ -- It might not be saturated in the standalone deriving case
+ -- derive instance Monad (T a)
+ let extra_tvs = dropList tc_args (tyConTyVars tycon)
+ full_tc_args = tc_args ++ mkTyVarTys extra_tvs
+ full_tvs = tvs ++ extra_tvs
+
+ ; (rep_tc, rep_tc_args) <- tcLookupFamInstExact tycon full_tc_args
+
+ ; mayDeriveDataTypeable <- doptM Opt_DeriveDataTypeable
+ ; newtype_deriving <- doptM Opt_GeneralizedNewtypeDeriving
+ ; overlap_flag <- getOverlapFlag
+
+ -- Be careful to test rep_tc here: in the case of families, we want
+ -- to check the instance tycon, not the family tycon
+ ; if isDataTyCon rep_tc then
+ mkDataTypeEqn orig mayDeriveDataTypeable full_tvs cls cls_tys
+ tycon full_tc_args rep_tc rep_tc_args mtheta
+ else
+ mkNewTypeEqn orig mayDeriveDataTypeable newtype_deriving overlap_flag
+ full_tvs cls cls_tys
+ tycon full_tc_args rep_tc rep_tc_args mtheta }
+ | otherwise
+ = baleOut (derivingThingErr cls cls_tys tc_app
+ (ptext SLIT("Last argument of the instance must be a type application")))
+
+baleOut err = addErrTc err >> returnM (Nothing, Nothing)
+\end{code}
+
+Auxiliary lookup wrapper which requires that looked up family instances are
+not type instances.
+
+\begin{code}
+tcLookupFamInstExact :: TyCon -> [Type] -> TcM (TyCon, [Type])
+tcLookupFamInstExact tycon tys
+ = do { result@(rep_tycon, rep_tys) <- tcLookupFamInst tycon tys
+ ; let { tvs = map (Type.getTyVar
+ "TcDeriv.tcLookupFamInstExact")
+ rep_tys
+ ; variable_only_subst = all Type.isTyVarTy rep_tys &&
+ sizeVarSet (mkVarSet tvs) == length tvs
+ -- renaming may have no repetitions
+ }
+ ; unless variable_only_subst $
+ famInstNotFound tycon tys [result]
+ ; return result
+ }
+
+\end{code}
+
+
+%************************************************************************
+%* *
+ Deriving data types
+%* *
+%************************************************************************
+
+\begin{code}
+mkDataTypeEqn :: InstOrigin -> Bool -> [Var] -> Class -> [Type]
+ -> TyCon -> [Type] -> TyCon -> [Type] -> Maybe DerivRhs
+ -> TcRn (Maybe DerivEqn, Maybe InstInfo)
+mkDataTypeEqn orig mayDeriveDataTypeable tvs cls cls_tys
+ tycon tc_args rep_tc rep_tc_args mtheta
+ | Just err <- checkSideConditions mayDeriveDataTypeable cls cls_tys rep_tc
+ -- NB: pass the *representation* tycon to checkSideConditions
+ = baleOut (derivingThingErr cls cls_tys (mkTyConApp tycon tc_args) err)
+
+ | otherwise
+ = ASSERT( null cls_tys )
+ do { loc <- getSrcSpanM
+ ; eqn <- mk_data_eqn loc orig tvs cls tycon tc_args rep_tc
+ rep_tc_args mtheta
+ ; return (Just eqn, Nothing) }
+
+mk_data_eqn :: SrcSpan -> InstOrigin -> [TyVar] -> Class
+ -> TyCon -> [TcType] -> TyCon -> [TcType] -> Maybe DerivRhs
+ -> TcM DerivEqn
+mk_data_eqn loc orig tvs cls tycon tc_args rep_tc rep_tc_args mtheta
+ | cls `hasKey` typeableClassKey
+ = -- The Typeable class is special in several ways
+ -- data T a b = ... deriving( Typeable )
+ -- gives
+ -- instance Typeable2 T where ...
+ -- Notice that:
+ -- 1. There are no constraints in the instance
+ -- 2. There are no type variables either
+ -- 3. The actual class we want to generate isn't necessarily
+ -- Typeable; it depends on the arity of the type
+ do { real_clas <- tcLookupClass (typeableClassNames !! tyConArity tycon)
+ ; dfun_name <- new_dfun_name real_clas tycon
+ ; let theta = fromMaybe [] mtheta
+ ; return (loc, orig, dfun_name, [], real_clas, mkTyConApp tycon [], theta)
+ }
+
+ | otherwise
+ = do { dfun_name <- new_dfun_name cls tycon
+ ; let ordinary_constraints
+ = [ mkClassPred cls [arg_ty]
+ | data_con <- tyConDataCons rep_tc,
+ arg_ty <- ASSERT( isVanillaDataCon data_con )
+ dataConInstOrigArgTys data_con rep_tc_args,
+ not (isUnLiftedType arg_ty) ] -- No constraints for unlifted types?
+ theta = fromMaybe ordinary_constraints mtheta
+
+ tiresome_subst = zipTopTvSubst (tyConTyVars rep_tc) rep_tc_args
+ stupid_constraints = substTheta tiresome_subst (tyConStupidTheta rep_tc)
+ -- see note [Data decl contexts] above
+
+ ; return (loc, orig, dfun_name, tvs, cls, mkTyConApp tycon tc_args,
+ stupid_constraints ++ theta)
+ }
+
+------------------------------------------------------------------
+-- Check side conditions that dis-allow derivability for particular classes
+-- This is *apart* from the newtype-deriving mechanism
+--
+-- Here we get the representation tycon in case of family instances as it has
+-- the data constructors - but we need to be careful to fall back to the
+-- family tycon (with indexes) in error messages.
+
+checkSideConditions :: Bool -> Class -> [TcType] -> TyCon -> Maybe SDoc
+checkSideConditions mayDeriveDataTypeable cls cls_tys rep_tc
+ | notNull cls_tys
+ = Just ty_args_why -- e.g. deriving( Foo s )
+ | otherwise
+ = case [cond | (key,cond) <- sideConditions, key == getUnique cls] of
+ [] -> Just (non_std_why cls)
+ [cond] -> cond (mayDeriveDataTypeable, rep_tc)
+ other -> pprPanic "checkSideConditions" (ppr cls)
+ where
+ ty_args_why = quotes (ppr (mkClassPred cls cls_tys)) <+> ptext SLIT("is not a class")
+
+non_std_why cls = quotes (ppr cls) <+> ptext SLIT("is not a derivable class")
+
+sideConditions :: [(Unique, Condition)]
+sideConditions
+ = [ (eqClassKey, cond_std),
+ (ordClassKey, cond_std),
+ (readClassKey, cond_std),
+ (showClassKey, cond_std),
+ (enumClassKey, cond_std `andCond` cond_isEnumeration),
+ (ixClassKey, cond_std `andCond` (cond_isEnumeration `orCond` cond_isProduct)),
+ (boundedClassKey, cond_std `andCond` (cond_isEnumeration `orCond` cond_isProduct)),
+ (typeableClassKey, cond_mayDeriveDataTypeable `andCond` cond_typeableOK),
+ (dataClassKey, cond_mayDeriveDataTypeable `andCond` cond_std)
+ ]
+
+type Condition = (Bool, TyCon) -> Maybe SDoc
+ -- Bool is whether or not we are allowed to derive Data and Typeable
+ -- TyCon is the *representation* tycon if the
+ -- data type is an indexed one
+ -- Nothing => OK
+
+orCond :: Condition -> Condition -> Condition
+orCond c1 c2 tc
+ = case c1 tc of
+ Nothing -> Nothing -- c1 succeeds
+ Just x -> case c2 tc of -- c1 fails
+ Nothing -> Nothing
+ Just y -> Just (x $$ ptext SLIT(" and") $$ y)
+ -- Both fail
+
+andCond c1 c2 tc = case c1 tc of
+ Nothing -> c2 tc -- c1 succeeds
+ Just x -> Just x -- c1 fails
+
+cond_std :: Condition
+cond_std (_, rep_tc)
+ | any (not . isVanillaDataCon) data_cons = Just existential_why
+ | null data_cons = Just no_cons_why
+ | otherwise = Nothing
+ where
+ data_cons = tyConDataCons rep_tc
+ no_cons_why = quotes (pprSourceTyCon rep_tc) <+>
+ ptext SLIT("has no data constructors")
+ existential_why = quotes (pprSourceTyCon rep_tc) <+>
+ ptext SLIT("has non-Haskell-98 constructor(s)")
+
+cond_isEnumeration :: Condition
+cond_isEnumeration (_, rep_tc)
+ | isEnumerationTyCon rep_tc = Nothing
+ | otherwise = Just why
+ where
+ why = quotes (pprSourceTyCon rep_tc) <+>
+ ptext SLIT("has non-nullary constructors")
+
+cond_isProduct :: Condition
+cond_isProduct (_, rep_tc)
+ | isProductTyCon rep_tc = Nothing
+ | otherwise = Just why
+ where
+ why = quotes (pprSourceTyCon rep_tc) <+>
+ ptext SLIT("has more than one constructor")
+
+cond_typeableOK :: Condition
+-- OK for Typeable class
+-- Currently: (a) args all of kind *
+-- (b) 7 or fewer args
+cond_typeableOK (_, rep_tc)
+ | tyConArity rep_tc > 7 = Just too_many
+ | not (all (isSubArgTypeKind . tyVarKind) (tyConTyVars rep_tc))
+ = Just bad_kind
+ | isFamInstTyCon rep_tc = Just fam_inst -- no Typable for family insts
+ | otherwise = Nothing
+ where
+ too_many = quotes (pprSourceTyCon rep_tc) <+>
+ ptext SLIT("has too many arguments")
+ bad_kind = quotes (pprSourceTyCon rep_tc) <+>
+ ptext SLIT("has arguments of kind other than `*'")
+ fam_inst = quotes (pprSourceTyCon rep_tc) <+>
+ ptext SLIT("is a type family")
+
+cond_mayDeriveDataTypeable :: Condition
+cond_mayDeriveDataTypeable (mayDeriveDataTypeable, _)
+ | mayDeriveDataTypeable = Nothing
+ | otherwise = Just why
+ where
+ why = ptext SLIT("You need -fglasgow-exts to derive an instance for this class")
+
+std_class_via_iso clas -- These standard classes can be derived for a newtype
+ -- using the isomorphism trick *even if no -fglasgow-exts*
+ = classKey clas `elem` [eqClassKey, ordClassKey, ixClassKey, boundedClassKey]
+ -- Not Read/Show because they respect the type
+ -- Not Enum, because newtypes are never in Enum
+
+
+new_dfun_name clas tycon -- Just a simple wrapper
+ = newDFunName clas [mkTyConApp tycon []] (getSrcSpan tycon)
+ -- The type passed to newDFunName is only used to generate
+ -- a suitable string; hence the empty type arg list
+\end{code}
+
+
+%************************************************************************
+%* *
+ Deriving newtypes
+%* *
+%************************************************************************
+
+\begin{code}
+mkNewTypeEqn :: InstOrigin -> Bool -> Bool -> OverlapFlag -> [Var] -> Class
+ -> [Type] -> TyCon -> [Type] -> TyCon -> [Type]
+ -> Maybe DerivRhs
+ -> TcRn (Maybe DerivEqn, Maybe InstInfo)
+mkNewTypeEqn orig mayDeriveDataTypeable newtype_deriving overlap_flag tvs
+ cls cls_tys tycon tc_args rep_tycon rep_tc_args mtheta
+ | can_derive_via_isomorphism && (newtype_deriving || std_class_via_iso cls)
+ = do { traceTc (text "newtype deriving:" <+> ppr tycon <+> ppr rep_tys)
+ ; -- Go ahead and use the isomorphism
+ dfun_name <- new_dfun_name cls tycon
+ ; return (Nothing, Just (InstInfo { iSpec = mk_inst_spec dfun_name,
+ iBinds = NewTypeDerived ntd_info })) }
+
+ | isNothing mb_std_err -- Use the standard H98 method
+ = do { loc <- getSrcSpanM
+ ; eqn <- mk_data_eqn loc orig tvs cls tycon tc_args rep_tycon
+ rep_tc_args mtheta
+ ; return (Just eqn, Nothing) }
+
+ -- Otherwise we can't derive
+ | newtype_deriving = baleOut cant_derive_err -- Too hard
+ | otherwise = baleOut std_err -- Just complain about being a non-std instance
+ where
+ mb_std_err = checkSideConditions mayDeriveDataTypeable cls cls_tys rep_tycon
+ std_err = derivingThingErr cls cls_tys tc_app $
+ vcat [fromJust mb_std_err,
+ ptext SLIT("Try -XGeneralizedNewtypeDeriving for GHC's newtype-deriving extension")]
+