X-Git-Url: http://git.megacz.com/?a=blobdiff_plain;f=compiler%2Ftypecheck%2FTcDeriv.lhs;h=0acf31c512b3274c50d445d5f65fe9af50c89ff3;hb=b99310f05faee2abec850da4349fcd5c0498f7ca;hp=7a584cd0e1d5de46ff54ef798f5c42c71a1e53d1;hpb=ed81632e2112e76b88890e9893fb808593d6e4df;p=ghc-hetmet.git diff --git a/compiler/typecheck/TcDeriv.lhs b/compiler/typecheck/TcDeriv.lhs index 7a584cd..0acf31c 100644 --- a/compiler/typecheck/TcDeriv.lhs +++ b/compiler/typecheck/TcDeriv.lhs @@ -47,6 +47,8 @@ import Util import ListSetOps import Outputable import Bag + +import Monad (unless) \end{code} %************************************************************************ @@ -203,16 +205,18 @@ And then translate it to: %************************************************************************ \begin{code} -tcDeriving :: [LTyClDecl Name] -- All type constructors +tcDeriving :: [LTyClDecl Name] -- All type constructors + -> [LInstDecl Name] -- All instance declarations -> [LDerivDecl Name] -- All stand-alone deriving declarations -> TcM ([InstInfo], -- The generated "instance decls" HsValBinds Name) -- Extra generated top-level bindings -tcDeriving tycl_decls deriv_decls +tcDeriving tycl_decls inst_decls deriv_decls = recoverM (returnM ([], emptyValBindsOut)) $ do { -- Fish the "deriving"-related information out of the TcEnv -- and make the necessary "equations". - ; (ordinary_eqns, newtype_inst_info) <- makeDerivEqns tycl_decls deriv_decls + ; (ordinary_eqns, newtype_inst_info) + <- makeDerivEqns tycl_decls inst_decls deriv_decls ; (ordinary_inst_info, deriv_binds) <- extendLocalInstEnv (map iSpec newtype_inst_info) $ @@ -234,10 +238,11 @@ tcDeriving tycl_decls deriv_decls ; gen_binds <- mkGenericBinds tycl_decls -- Rename these extra bindings, discarding warnings about unused bindings etc - -- Set -fglasgow exts so that we can have type signatures in patterns, - -- which is used in the generic binds + -- Type signatures in patterns are used in the generic binds ; rn_binds - <- discardWarnings $ setOptM Opt_GlasgowExts $ do + <- discardWarnings $ + setOptM Opt_PatternSignatures $ + do { (rn_deriv, _dus1) <- rnTopBinds (ValBindsIn deriv_binds []) ; (rn_gen, dus_gen) <- rnTopBinds (ValBindsIn gen_binds []) ; keepAliveSetTc (duDefs dus_gen) -- Mark these guys to @@ -336,17 +341,24 @@ when the dict is constructed in TcInstDcls.tcInstDecl2 \begin{code} makeDerivEqns :: [LTyClDecl Name] + -> [LInstDecl Name] -> [LDerivDecl Name] -> TcM ([DerivEqn], -- Ordinary derivings [InstInfo]) -- Special newtype derivings -makeDerivEqns tycl_decls deriv_decls +makeDerivEqns tycl_decls inst_decls deriv_decls = do { eqns1 <- mapM deriveTyData $ - [ (p,d) | d@(L _ (TyData {tcdDerivs = Just preds})) <- tycl_decls - , p <- preds ] + extractTyDataPreds tycl_decls ++ + [ pd -- traverse assoc data families + | L _ (InstDecl _ _ _ ats) <- inst_decls + , pd <- extractTyDataPreds ats ] ; eqns2 <- mapM deriveStandalone deriv_decls ; return ([eqn | (Just eqn, _) <- eqns1 ++ eqns2], [inst | (_, Just inst) <- eqns1 ++ eqns2]) } + where + extractTyDataPreds decls = + [(p, d) | d@(L _ (TyData {tcdDerivs = Just preds})) <- decls, p <- preds] + ------------------------------------------------------------------ deriveStandalone :: LDerivDecl Name -> TcM (Maybe DerivEqn, Maybe InstInfo) @@ -381,6 +393,8 @@ deriveTyData (deriv_pred, L loc decl@(TyData { tcdLName = L _ tycon_name, -- 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 } } +deriveTyData (deriv_pred, other_decl) + = panic "derivTyData" -- Caller ensures that only TyData can happen ------------------------------------------------------------------ mkEqnHelp orig tvs cls cls_tys tc_app @@ -393,15 +407,20 @@ mkEqnHelp orig tvs cls cls_tys tc_app full_tc_args = tc_args ++ mkTyVarTys extra_tvs full_tvs = tvs ++ extra_tvs - ; (rep_tc, rep_tc_args) <- tcLookupFamInst tycon full_tc_args + ; (rep_tc, rep_tc_args) <- tcLookupFamInstExact tycon full_tc_args - ; gla_exts <- doptM Opt_GlasgowExts + ; mayDeriveDataTypeable <- doptM Opt_DeriveDataTypeable + ; newtype_deriving <- doptM Opt_GeneralizedNewtypeDeriving ; overlap_flag <- getOverlapFlag - ; if isDataTyCon tycon then - mkDataTypeEqn orig gla_exts full_tvs cls cls_tys + + -- 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 else - mkNewTypeEqn orig gla_exts overlap_flag full_tvs cls cls_tys + mkNewTypeEqn orig mayDeriveDataTypeable newtype_deriving overlap_flag + full_tvs cls cls_tys tycon full_tc_args rep_tc rep_tc_args } | otherwise = baleOut (derivingThingErr cls cls_tys tc_app @@ -410,6 +429,27 @@ mkEqnHelp orig tvs cls cls_tys tc_app 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} + %************************************************************************ %* * @@ -418,8 +458,9 @@ baleOut err = addErrTc err >> returnM (Nothing, Nothing) %************************************************************************ \begin{code} -mkDataTypeEqn orig gla_exts tvs cls cls_tys tycon tc_args rep_tc rep_tc_args - | Just err <- checkSideConditions gla_exts cls cls_tys rep_tc +mkDataTypeEqn orig mayDeriveDataTypeable tvs cls cls_tys + tycon tc_args rep_tc rep_tc_args + | 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) @@ -451,7 +492,8 @@ mk_data_eqn loc orig tvs cls tycon tc_args rep_tc rep_tc_args ; let ordinary_constraints = [ mkClassPred cls [arg_ty] | data_con <- tyConDataCons rep_tc, - arg_ty <- dataConInstOrigArgTys data_con rep_tc_args, + arg_ty <- ASSERT( isVanillaDataCon data_con ) + dataConInstOrigArgTys data_con rep_tc_args, not (isUnLiftedType arg_ty) ] -- No constraints for unlifted types? tiresome_subst = zipTopTvSubst (tyConTyVars rep_tc) rep_tc_args @@ -471,13 +513,13 @@ mk_data_eqn loc orig tvs cls tycon tc_args rep_tc rep_tc_args -- family tycon (with indexes) in error messages. checkSideConditions :: Bool -> Class -> [TcType] -> TyCon -> Maybe SDoc -checkSideConditions gla_exts cls cls_tys rep_tc +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 (gla_exts, rep_tc) + [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") @@ -493,12 +535,12 @@ sideConditions (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_glaExts `andCond` cond_typeableOK), - (dataClassKey, cond_glaExts `andCond` cond_std) + (typeableClassKey, cond_mayDeriveDataTypeable `andCond` cond_typeableOK), + (dataClassKey, cond_mayDeriveDataTypeable `andCond` cond_std) ] type Condition = (Bool, TyCon) -> Maybe SDoc - -- Bool is gla-exts flag + -- 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 @@ -517,7 +559,7 @@ andCond c1 c2 tc = case c1 tc of Just x -> Just x -- c1 fails cond_std :: Condition -cond_std (gla_exts, rep_tc) +cond_std (_, rep_tc) | any (not . isVanillaDataCon) data_cons = Just existential_why | null data_cons = Just no_cons_why | otherwise = Nothing @@ -529,7 +571,7 @@ cond_std (gla_exts, rep_tc) ptext SLIT("has non-Haskell-98 constructor(s)") cond_isEnumeration :: Condition -cond_isEnumeration (gla_exts, rep_tc) +cond_isEnumeration (_, rep_tc) | isEnumerationTyCon rep_tc = Nothing | otherwise = Just why where @@ -537,18 +579,18 @@ cond_isEnumeration (gla_exts, rep_tc) ptext SLIT("has non-nullary constructors") cond_isProduct :: Condition -cond_isProduct (gla_exts, rep_tc) +cond_isProduct (_, rep_tc) | isProductTyCon rep_tc = Nothing | otherwise = Just why where - why = (pprSourceTyCon rep_tc) <+> + 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 (gla_exts, rep_tc) +cond_typeableOK (_, rep_tc) | tyConArity rep_tc > 7 = Just too_many | not (all (isSubArgTypeKind . tyVarKind) (tyConTyVars rep_tc)) = Just bad_kind @@ -562,9 +604,10 @@ cond_typeableOK (gla_exts, rep_tc) fam_inst = quotes (pprSourceTyCon rep_tc) <+> ptext SLIT("is a type family") -cond_glaExts :: Condition -cond_glaExts (gla_exts, _rep_tc) | gla_exts = Nothing - | otherwise = Just why +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") @@ -576,7 +619,7 @@ std_class_via_iso clas -- These standard classes can be derived for a newtype new_dfun_name clas tycon -- Just a simple wrapper - = newDFunName clas [mkTyConApp tycon []] (getSrcLoc tycon) + = 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} @@ -589,10 +632,13 @@ new_dfun_name clas tycon -- Just a simple wrapper %************************************************************************ \begin{code} -mkNewTypeEqn orig gla_exts overlap_flag tvs cls cls_tys +mkNewTypeEqn :: InstOrigin -> Bool -> Bool -> OverlapFlag -> [Var] -> Class + -> [Type] -> TyCon -> [Type] -> TyCon -> [Type] + -> TcRn (Maybe DerivEqn, Maybe InstInfo) +mkNewTypeEqn orig mayDeriveDataTypeable newtype_deriving overlap_flag tvs cls cls_tys tycon tc_args rep_tycon rep_tc_args - | can_derive_via_isomorphism && (gla_exts || std_class_via_iso cls) + | 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 @@ -605,13 +651,13 @@ mkNewTypeEqn orig gla_exts overlap_flag tvs cls cls_tys ; return (Just eqn, Nothing) } -- Otherwise we can't derive - | gla_exts = baleOut cant_derive_err -- Too hard + | 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 gla_exts cls cls_tys rep_tycon + 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 -fglasgow-exts for GHC's newtype-deriving extension")] + ptext SLIT("Try -XGeneralizedNewtypeDeriving for GHC's newtype-deriving extension")] -- Here is the plan for newtype derivings. We see -- newtype T a1...an = MkT (t ak+1...an) deriving (.., C s1 .. sm, ...) @@ -838,11 +884,11 @@ solveDerivEqns overlap_flag orig_eqns gen_soln :: DerivEqn -> TcM [PredType] gen_soln (loc, orig, _, tyvars, clas, inst_ty, deriv_rhs) = setSrcSpan loc $ + addErrCtxt (derivInstCtxt clas [inst_ty]) $ do { theta <- tcSimplifyDeriv orig tyvars deriv_rhs - ; addErrCtxt (derivInstCtxt theta clas [inst_ty]) $ - do { checkNoErrs (checkValidInstance tyvars theta clas [inst_ty]) - -- See Note [Deriving context] - -- If this fails, don't continue + -- checkValidInstance tyvars theta clas [inst_ty] + -- Not necessary; see Note [Exotic derived instance contexts] + -- in TcSimplify -- Check for a bizarre corner case, when the derived instance decl should -- have form instance C a b => D (T a) where ... @@ -856,7 +902,7 @@ solveDerivEqns overlap_flag orig_eqns -- Claim: the result instance declaration is guaranteed valid -- Hence no need to call: -- checkValidInstance tyvars theta clas inst_tys - ; return (sortLe (<=) theta) } } -- Canonicalise before returning the solution + ; return (sortLe (<=) theta) } -- Canonicalise before returning the solution ------------------------------------------------------------------ mk_inst_spec :: DerivEqn -> DerivSoln -> Instance @@ -875,25 +921,6 @@ extendLocalInstEnv dfuns thing_inside ; setGblEnv env' thing_inside } \end{code} -Note [Deriving context] -~~~~~~~~~~~~~~~~~~~~~~~ -With -fglasgow-exts, we allow things like (C Int a) in the simplified -context for a derived instance declaration, because at a use of this -instance, we might know that a=Bool, and have an instance for (C Int -Bool) - -We nevertheless insist that each predicate meets the termination -conditions. If not, the deriving mechanism generates larger and larger -constraints. Example: - data Succ a = S a - data Seq a = Cons a (Seq (Succ a)) | Nil deriving Show - -Note the lack of a Show instance for Succ. First we'll generate - instance (Show (Succ a), Show a) => Show (Seq a) -and then - instance (Show (Succ (Succ a)), Show (Succ a), Show a) => Show (Seq a) -and so on. Instead we want to complain of no instance for (Show (Succ a)). - %************************************************************************ %* * @@ -975,7 +1002,7 @@ genInst spec -- In case of a family instance, we need to use the representation -- tycon (after all, it has the data constructors) - ; (tycon, _) <- tcLookupFamInst visible_tycon tyArgs + ; (tycon, _) <- tcLookupFamInstExact visible_tycon tyArgs ; let (meth_binds, aux_binds) = genDerivBinds clas fix_env tycon -- Bring the right type variables into @@ -1109,10 +1136,8 @@ derivingThingErr clas tys ty why standaloneCtxt :: LHsType Name -> SDoc standaloneCtxt ty = ptext SLIT("In the stand-alone deriving instance for") <+> quotes (ppr ty) -derivInstCtxt theta clas inst_tys - = hang (ptext SLIT("In the derived instance:")) - 2 (pprThetaArrow theta <+> pprClassPred clas inst_tys) --- Used for the ...Thetas variants; all top level +derivInstCtxt clas inst_tys + = ptext SLIT("When deriving the instance for") <+> parens (pprClassPred clas inst_tys) badDerivedPred pred = vcat [ptext SLIT("Can't derive instances where the instance context mentions"), @@ -1120,4 +1145,4 @@ badDerivedPred pred nest 2 (ptext SLIT("Offending constraint:") <+> ppr pred)] \end{code} - \ No newline at end of file +