diff --git a/compiler/rustc_ast/src/ast.rs b/compiler/rustc_ast/src/ast.rs index 37f429cce44d7..08d92ea54eac5 100644 --- a/compiler/rustc_ast/src/ast.rs +++ b/compiler/rustc_ast/src/ast.rs @@ -2648,8 +2648,16 @@ pub enum Const { /// For details see the [RFC #2532](https://github.com/rust-lang/rfcs/pull/2532). #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] pub enum Defaultness { + /// `default` Default(Span), - Final, + /// Item is unmarked. Implicitly determined based off of position. + /// For impls, this is `final`; for traits, this is `default`. + /// + /// If you're expanding an item in a built-in macro or parsing an item + /// by hand, you probably want to use this. + Implicit, + /// `final`; per RFC 3678, only trait items may be *explicitly* marked final. + Final(Span), } #[derive(Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)] @@ -3440,7 +3448,7 @@ impl AssocItemKind { | Self::Fn(box Fn { defaultness, .. }) | Self::Type(box TyAlias { defaultness, .. }) => defaultness, Self::MacCall(..) | Self::Delegation(..) | Self::DelegationMac(..) => { - Defaultness::Final + Defaultness::Implicit } } } diff --git a/compiler/rustc_ast/src/mut_visit.rs b/compiler/rustc_ast/src/mut_visit.rs index 104f84f26e0af..ed3815c9f109e 100644 --- a/compiler/rustc_ast/src/mut_visit.rs +++ b/compiler/rustc_ast/src/mut_visit.rs @@ -832,7 +832,8 @@ fn visit_nonterminal(vis: &mut T, nt: &mut token::Nonterminal) { fn visit_defaultness(vis: &mut T, defaultness: &mut Defaultness) { match defaultness { Defaultness::Default(span) => vis.visit_span(span), - Defaultness::Final => {} + Defaultness::Final(span) => vis.visit_span(span), + Defaultness::Implicit => {} } } diff --git a/compiler/rustc_ast_lowering/src/item.rs b/compiler/rustc_ast_lowering/src/item.rs index 7bb3b2fa29095..f54ab393ec6ce 100644 --- a/compiler/rustc_ast_lowering/src/item.rs +++ b/compiler/rustc_ast_lowering/src/item.rs @@ -386,7 +386,8 @@ impl<'hir> LoweringContext<'_, 'hir> { // `defaultness.has_value()` is never called for an `impl`, always `true` in order // to not cause an assertion failure inside the `lower_defaultness` function. let has_val = true; - let (defaultness, defaultness_span) = self.lower_defaultness(*defaultness, has_val); + let (defaultness, defaultness_span) = + self.lower_defaultness(*defaultness, has_val, || hir::Defaultness::Final); let polarity = match polarity { ImplPolarity::Positive => ImplPolarity::Positive, ImplPolarity::Negative(s) => ImplPolarity::Negative(self.lower_span(*s)), @@ -785,7 +786,7 @@ impl<'hir> LoweringContext<'_, 'hir> { self.lower_attrs(hir_id, &i.attrs); let trait_item_def_id = hir_id.expect_owner(); - let (generics, kind, has_default) = match &i.kind { + let (generics, kind, has_value) = match &i.kind { AssocItemKind::Const(box ConstItem { generics, ty, expr, .. }) => { let (generics, kind) = self.lower_generics( generics, @@ -874,13 +875,17 @@ impl<'hir> LoweringContext<'_, 'hir> { } }; + let (defaultness, _) = self.lower_defaultness(i.kind.defaultness(), has_value, || { + hir::Defaultness::Default { has_value } + }); + let item = hir::TraitItem { owner_id: trait_item_def_id, ident: self.lower_ident(i.ident), generics, kind, span: self.lower_span(i.span), - defaultness: hir::Defaultness::Default { has_value: has_default }, + defaultness, }; self.arena.alloc(item) } @@ -920,7 +925,8 @@ impl<'hir> LoweringContext<'_, 'hir> { ) -> &'hir hir::ImplItem<'hir> { // Since `default impl` is not yet implemented, this is always true in impls. let has_value = true; - let (defaultness, _) = self.lower_defaultness(i.kind.defaultness(), has_value); + let (defaultness, _) = + self.lower_defaultness(i.kind.defaultness(), has_value, || hir::Defaultness::Final); let hir_id = self.lower_node_id(i.id); self.lower_attrs(hir_id, &i.attrs); @@ -1044,15 +1050,14 @@ impl<'hir> LoweringContext<'_, 'hir> { &self, d: Defaultness, has_value: bool, + implicit: impl FnOnce() -> hir::Defaultness, ) -> (hir::Defaultness, Option) { match d { + Defaultness::Implicit => (implicit(), None), Defaultness::Default(sp) => { (hir::Defaultness::Default { has_value }, Some(self.lower_span(sp))) } - Defaultness::Final => { - assert!(has_value); - (hir::Defaultness::Final, None) - } + Defaultness::Final(sp) => (hir::Defaultness::Final, Some(sp)), } } diff --git a/compiler/rustc_ast_passes/messages.ftl b/compiler/rustc_ast_passes/messages.ftl index c361c35b723d8..44dc2d3c3198a 100644 --- a/compiler/rustc_ast_passes/messages.ftl +++ b/compiler/rustc_ast_passes/messages.ftl @@ -127,6 +127,14 @@ ast_passes_forbidden_default = `default` is only allowed on items in trait impls .label = `default` because of this +ast_passes_forbidden_final = + `final` is only allowed on associated functions in traits + .label = `final` because of this + +ast_passes_forbidden_final_without_body = + `final` is only allowed on associated functions if they have a body + .label = `final` because of this + ast_passes_forbidden_non_lifetime_param = only lifetime parameters can be used in this context diff --git a/compiler/rustc_ast_passes/src/ast_validation.rs b/compiler/rustc_ast_passes/src/ast_validation.rs index 229d04f8de2fd..594297e6c741e 100644 --- a/compiler/rustc_ast_passes/src/ast_validation.rs +++ b/compiler/rustc_ast_passes/src/ast_validation.rs @@ -62,6 +62,28 @@ impl TraitOrTraitImpl { } } +enum AllowDefault { + Yes, + No, +} + +impl AllowDefault { + fn only_if(b: bool) -> Self { + if b { Self::Yes } else { Self::No } + } +} + +enum AllowFinal { + Yes, + No, +} + +impl AllowFinal { + fn only_if(b: bool) -> Self { + if b { Self::Yes } else { Self::No } + } +} + struct AstValidator<'a> { session: &'a Session, features: &'a Features, @@ -470,10 +492,38 @@ impl<'a> AstValidator<'a> { } } - fn check_defaultness(&self, span: Span, defaultness: Defaultness) { - if let Defaultness::Default(def_span) = defaultness { - let span = self.session.source_map().guess_head_span(span); - self.dcx().emit_err(errors::ForbiddenDefault { span, def_span }); + fn check_defaultness( + &self, + span: Span, + defaultness: Defaultness, + allow_default: AllowDefault, + allow_final: AllowFinal, + ) { + match defaultness { + Defaultness::Implicit => {} + Defaultness::Default(def_span) => match allow_default { + AllowDefault::Yes => {} + AllowDefault::No => { + let span = self.session.source_map().guess_head_span(span); + self.dcx().emit_err(errors::ForbiddenDefault { span, def_span }); + } + }, + Defaultness::Final(def_span) => match allow_final { + AllowFinal::Yes => {} + AllowFinal::No => { + let span = self.session.source_map().guess_head_span(span); + self.dcx().emit_err(errors::ForbiddenFinal { span, def_span }); + } + }, + } + } + + fn check_final_has_body(&self, item: &Item, defaultness: Defaultness) { + if let AssocItemKind::Fn(box Fn { body: None, .. }) = &item.kind + && let Defaultness::Final(def_span) = defaultness + { + let span = self.session.source_map().guess_head_span(item.span); + self.dcx().emit_err(errors::ForbiddenFinalWithoutBody { span, def_span }); } } @@ -1005,7 +1055,7 @@ impl<'a> Visitor<'a> for AstValidator<'a> { return; // Avoid visiting again. } ItemKind::Fn(box Fn { defaultness, sig, generics, body }) => { - self.check_defaultness(item.span, *defaultness); + self.check_defaultness(item.span, *defaultness, AllowDefault::No, AllowFinal::No); if body.is_none() { self.dcx().emit_err(errors::FnWithoutBody { @@ -1152,7 +1202,7 @@ impl<'a> Visitor<'a> for AstValidator<'a> { } } ItemKind::Const(box ConstItem { defaultness, expr, .. }) => { - self.check_defaultness(item.span, *defaultness); + self.check_defaultness(item.span, *defaultness, AllowDefault::No, AllowFinal::No); if expr.is_none() { self.dcx().emit_err(errors::ConstWithoutBody { span: item.span, @@ -1176,7 +1226,7 @@ impl<'a> Visitor<'a> for AstValidator<'a> { ItemKind::TyAlias( ty_alias @ box TyAlias { defaultness, bounds, where_clauses, ty, .. }, ) => { - self.check_defaultness(item.span, *defaultness); + self.check_defaultness(item.span, *defaultness, AllowDefault::No, AllowFinal::No); if ty.is_none() { self.dcx().emit_err(errors::TyAliasWithoutBody { span: item.span, @@ -1205,7 +1255,7 @@ impl<'a> Visitor<'a> for AstValidator<'a> { fn visit_foreign_item(&mut self, fi: &'a ForeignItem) { match &fi.kind { ForeignItemKind::Fn(box Fn { defaultness, sig, body, .. }) => { - self.check_defaultness(fi.span, *defaultness); + self.check_defaultness(fi.span, *defaultness, AllowDefault::No, AllowFinal::No); self.check_foreign_fn_bodyless(fi.ident, body.as_deref()); self.check_foreign_fn_headerless(sig.header); self.check_foreign_item_ascii_only(fi.ident); @@ -1218,7 +1268,7 @@ impl<'a> Visitor<'a> for AstValidator<'a> { ty, .. }) => { - self.check_defaultness(fi.span, *defaultness); + self.check_defaultness(fi.span, *defaultness, AllowDefault::No, AllowFinal::No); self.check_foreign_kind_bodyless(fi.ident, "type", ty.as_ref().map(|b| b.span)); self.check_type_no_bounds(bounds, "`extern` blocks"); self.check_foreign_ty_genericless(generics, where_clauses); @@ -1490,9 +1540,20 @@ impl<'a> Visitor<'a> for AstValidator<'a> { self.check_nomangle_item_asciionly(item.ident, item.span); } - if ctxt == AssocCtxt::Trait || self.outer_trait_or_trait_impl.is_none() { - self.check_defaultness(item.span, item.kind.defaultness()); - } + let defaultness = item.kind.defaultness(); + self.check_defaultness( + item.span, + defaultness, + // `default` is allowed on all associated items in impls. + AllowDefault::only_if(ctxt == AssocCtxt::Impl), + // `final` is allowed on all associated *functions* in traits. + AllowFinal::only_if( + ctxt == AssocCtxt::Trait && matches!(item.kind, AssocItemKind::Fn(..)), + ), + ); + + // + self.check_final_has_body(item, defaultness); if ctxt == AssocCtxt::Impl { match &item.kind { diff --git a/compiler/rustc_ast_passes/src/errors.rs b/compiler/rustc_ast_passes/src/errors.rs index 5cce47ce7bd21..631ede4ece227 100644 --- a/compiler/rustc_ast_passes/src/errors.rs +++ b/compiler/rustc_ast_passes/src/errors.rs @@ -124,6 +124,24 @@ pub(crate) struct ForbiddenDefault { pub def_span: Span, } +#[derive(Diagnostic)] +#[diag(ast_passes_forbidden_final)] +pub(crate) struct ForbiddenFinal { + #[primary_span] + pub span: Span, + #[label] + pub def_span: Span, +} + +#[derive(Diagnostic)] +#[diag(ast_passes_forbidden_final_without_body)] +pub(crate) struct ForbiddenFinalWithoutBody { + #[primary_span] + pub span: Span, + #[label] + pub def_span: Span, +} + #[derive(Diagnostic)] #[diag(ast_passes_assoc_const_without_body)] pub(crate) struct AssocConstWithoutBody { diff --git a/compiler/rustc_ast_passes/src/feature_gate.rs b/compiler/rustc_ast_passes/src/feature_gate.rs index 614a99a6e1960..37fa674ef1fc8 100644 --- a/compiler/rustc_ast_passes/src/feature_gate.rs +++ b/compiler/rustc_ast_passes/src/feature_gate.rs @@ -545,6 +545,7 @@ pub fn check_crate(krate: &ast::Crate, sess: &Session, features: &Features) { gate_all!(mut_ref, "mutable by-reference bindings are experimental"); gate_all!(global_registration, "global registration is experimental"); gate_all!(return_type_notation, "return type notation is experimental"); + gate_all!(final_associated_functions, "`final` on trait functions is experimental"); if !visitor.features.never_patterns { if let Some(spans) = spans.get(&sym::never_patterns) { diff --git a/compiler/rustc_ast_pretty/src/pprust/state/item.rs b/compiler/rustc_ast_pretty/src/pprust/state/item.rs index 8217b6df5b470..2686d9832b6ea 100644 --- a/compiler/rustc_ast_pretty/src/pprust/state/item.rs +++ b/compiler/rustc_ast_pretty/src/pprust/state/item.rs @@ -46,7 +46,7 @@ impl<'a> State<'a> { ty, expr.as_deref(), vis, - ast::Defaultness::Final, + ast::Defaultness::Implicit, ) } ast::ForeignItemKind::TyAlias(box ast::TyAlias { @@ -181,7 +181,7 @@ impl<'a> State<'a> { ty, body.as_deref(), &item.vis, - ast::Defaultness::Final, + ast::Defaultness::Implicit, ); } ast::ItemKind::Const(box ast::ConstItem { defaultness, generics, ty, expr }) => { diff --git a/compiler/rustc_builtin_macros/src/alloc_error_handler.rs b/compiler/rustc_builtin_macros/src/alloc_error_handler.rs index 0caad997b9df1..27bef526bcda8 100644 --- a/compiler/rustc_builtin_macros/src/alloc_error_handler.rs +++ b/compiler/rustc_builtin_macros/src/alloc_error_handler.rs @@ -83,7 +83,7 @@ fn generate_handler(cx: &ExtCtxt<'_>, handler: Ident, span: Span, sig_span: Span let body = Some(cx.block_expr(call)); let kind = ItemKind::Fn(Box::new(Fn { - defaultness: ast::Defaultness::Final, + defaultness: ast::Defaultness::Implicit, sig, generics: Generics::default(), body, diff --git a/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs b/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs index 82baaca9a4641..342824cc85126 100644 --- a/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs +++ b/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs @@ -608,7 +608,7 @@ impl<'a> TraitDef<'a> { }, attrs: ast::AttrVec::new(), kind: ast::AssocItemKind::Type(Box::new(ast::TyAlias { - defaultness: ast::Defaultness::Final, + defaultness: ast::Defaultness::Implicit, generics: Generics::default(), where_clauses: ast::TyAliasWhereClauses::default(), bounds: Vec::new(), @@ -799,7 +799,7 @@ impl<'a> TraitDef<'a> { ast::ItemKind::Impl(Box::new(ast::Impl { safety: ast::Safety::Default, polarity: ast::ImplPolarity::Positive, - defaultness: ast::Defaultness::Final, + defaultness: ast::Defaultness::Implicit, constness: if self.is_const { ast::Const::Yes(DUMMY_SP) } else { ast::Const::No }, generics: trait_generics, of_trait: opt_trait_ref, @@ -1026,7 +1026,7 @@ impl<'a> MethodDef<'a> { let trait_lo_sp = span.shrink_to_lo(); let sig = ast::FnSig { header: ast::FnHeader::default(), decl: fn_decl, span }; - let defaultness = ast::Defaultness::Final; + let defaultness = ast::Defaultness::Implicit; // Create the method. P(ast::AssocItem { diff --git a/compiler/rustc_builtin_macros/src/deriving/smart_ptr.rs b/compiler/rustc_builtin_macros/src/deriving/smart_ptr.rs index 12749e87dcbcc..dc0cde6bb129e 100644 --- a/compiler/rustc_builtin_macros/src/deriving/smart_ptr.rs +++ b/compiler/rustc_builtin_macros/src/deriving/smart_ptr.rs @@ -144,7 +144,7 @@ pub(crate) fn expand_deriving_smart_ptr( ast::ItemKind::Impl(Box::new(ast::Impl { safety: ast::Safety::Default, polarity: ast::ImplPolarity::Positive, - defaultness: ast::Defaultness::Final, + defaultness: ast::Defaultness::Implicit, constness: ast::Const::No, generics, of_trait: Some(trait_ref), diff --git a/compiler/rustc_builtin_macros/src/global_allocator.rs b/compiler/rustc_builtin_macros/src/global_allocator.rs index b4b18409a18eb..792ba1779302a 100644 --- a/compiler/rustc_builtin_macros/src/global_allocator.rs +++ b/compiler/rustc_builtin_macros/src/global_allocator.rs @@ -79,7 +79,7 @@ impl AllocFnFactory<'_, '_> { let sig = FnSig { decl, header, span: self.span }; let body = Some(self.cx.block_expr(result)); let kind = ItemKind::Fn(Box::new(Fn { - defaultness: ast::Defaultness::Final, + defaultness: ast::Defaultness::Implicit, sig, generics: Generics::default(), body, diff --git a/compiler/rustc_builtin_macros/src/test.rs b/compiler/rustc_builtin_macros/src/test.rs index 664e935ee14a3..2f6b9fb223cc0 100644 --- a/compiler/rustc_builtin_macros/src/test.rs +++ b/compiler/rustc_builtin_macros/src/test.rs @@ -260,7 +260,7 @@ pub(crate) fn expand_test_or_bench( // const $ident: test::TestDescAndFn = ast::ItemKind::Const( ast::ConstItem { - defaultness: ast::Defaultness::Final, + defaultness: ast::Defaultness::Implicit, generics: ast::Generics::default(), ty: cx.ty(sp, ast::TyKind::Path(None, test_path("TestDescAndFn"))), // test::TestDescAndFn { diff --git a/compiler/rustc_builtin_macros/src/test_harness.rs b/compiler/rustc_builtin_macros/src/test_harness.rs index 953484533087c..9dc78b1311c34 100644 --- a/compiler/rustc_builtin_macros/src/test_harness.rs +++ b/compiler/rustc_builtin_macros/src/test_harness.rs @@ -341,7 +341,7 @@ fn mk_main(cx: &mut TestCtxt<'_>) -> P { let decl = ecx.fn_decl(ThinVec::new(), ast::FnRetTy::Ty(main_ret_ty)); let sig = ast::FnSig { decl, header: ast::FnHeader::default(), span: sp }; - let defaultness = ast::Defaultness::Final; + let defaultness = ast::Defaultness::Implicit; let main = ast::ItemKind::Fn(Box::new(ast::Fn { defaultness, sig, diff --git a/compiler/rustc_expand/src/build.rs b/compiler/rustc_expand/src/build.rs index b5945759d43a0..d64aa060a6d77 100644 --- a/compiler/rustc_expand/src/build.rs +++ b/compiler/rustc_expand/src/build.rs @@ -642,7 +642,7 @@ impl<'a> ExtCtxt<'a> { ty: P, expr: P, ) -> P { - let defaultness = ast::Defaultness::Final; + let defaultness = ast::Defaultness::Implicit; self.item( span, name, diff --git a/compiler/rustc_feature/src/unstable.rs b/compiler/rustc_feature/src/unstable.rs index 63b4b272f76c9..1fe000510e0f5 100644 --- a/compiler/rustc_feature/src/unstable.rs +++ b/compiler/rustc_feature/src/unstable.rs @@ -467,6 +467,8 @@ declare_features! ( (unstable, ffi_const, "1.45.0", Some(58328)), /// Allows the use of `#[ffi_pure]` on foreign functions. (unstable, ffi_pure, "1.45.0", Some(58329)), + /// Allows marking trait functions as `final` to prevent overriding impls + (unstable, final_associated_functions, "CURRENT_RUSTC_VERSION", Some(1)), /// Controlling the behavior of fmt::Debug (unstable, fmt_debug, "1.82.0", Some(129709)), /// Allows using `#[repr(align(...))]` on function items diff --git a/compiler/rustc_hir_analysis/messages.ftl b/compiler/rustc_hir_analysis/messages.ftl index 09d466339ff6f..12e0476721d86 100644 --- a/compiler/rustc_hir_analysis/messages.ftl +++ b/compiler/rustc_hir_analysis/messages.ftl @@ -374,6 +374,9 @@ hir_analysis_opaque_captures_higher_ranked_lifetime = `impl Trait` cannot captur .label = `impl Trait` implicitly captures all lifetimes in scope .note = lifetime declared here +hir_analysis_overriding_final_trait_function = cannot override `{$name}` because it already has a `final` definition in the trait + .note = `{$name}` is marked final here + hir_analysis_param_in_ty_of_assoc_const_binding = the type of the associated constant `{$assoc_const}` must not depend on {$param_category -> [self] `Self` diff --git a/compiler/rustc_hir_analysis/src/check/check.rs b/compiler/rustc_hir_analysis/src/check/check.rs index d725772a5b369..830a0d6a3eec3 100644 --- a/compiler/rustc_hir_analysis/src/check/check.rs +++ b/compiler/rustc_hir_analysis/src/check/check.rs @@ -881,13 +881,35 @@ pub(super) fn check_specialization_validity<'tcx>( if let Err(parent_impl) = result { // FIXME(effects) the associated type from effects could be specialized if !tcx.is_impl_trait_in_trait(impl_item) && !tcx.is_effects_desugared_assoc_ty(impl_item) { - report_forbidden_specialization(tcx, impl_item, parent_impl); + let span = tcx.def_span(impl_item); + let ident = tcx.item_name(impl_item); + + let err = match tcx.span_of_impl(parent_impl) { + Ok(sp) => errors::ImplNotMarkedDefault::Ok { span, ident, ok_label: sp }, + Err(cname) => errors::ImplNotMarkedDefault::Err { span, ident, cname }, + }; + + tcx.dcx().emit_err(err); } else { tcx.dcx().delayed_bug(format!("parent item: {parent_impl:?} not marked as default")); } } } +fn check_overriding_final_trait_item<'tcx>( + tcx: TyCtxt<'tcx>, + trait_item: ty::AssocItem, + impl_item: ty::AssocItem, +) { + if trait_item.defaultness(tcx).is_final() { + tcx.dcx().emit_err(errors::OverridingFinalTraitFunction { + impl_span: tcx.def_span(impl_item.def_id), + trait_span: tcx.def_span(trait_item.def_id), + name: tcx.item_name(impl_item.def_id), + }); + } +} + fn check_impl_items_against_trait<'tcx>( tcx: TyCtxt<'tcx>, impl_id: LocalDefId, @@ -954,6 +976,11 @@ fn check_impl_items_against_trait<'tcx>( impl_id.to_def_id(), impl_item, ); + + // FIXME(final_associated_functions): This *could* be integrated into + // the specialization check, but that might overly complicate it, and + // make it difficult to remove if we were to tear out specialization. + check_overriding_final_trait_item(tcx, ty_trait_item, ty_impl_item); } if let Ok(ancestors) = trait_def.ancestors(tcx, impl_id.to_def_id()) { diff --git a/compiler/rustc_hir_analysis/src/check/mod.rs b/compiler/rustc_hir_analysis/src/check/mod.rs index d3d88919d8795..bad3210a97478 100644 --- a/compiler/rustc_hir_analysis/src/check/mod.rs +++ b/compiler/rustc_hir_analysis/src/check/mod.rs @@ -197,18 +197,6 @@ fn maybe_check_static_with_link_section(tcx: TyCtxt<'_>, id: LocalDefId) { } } -fn report_forbidden_specialization(tcx: TyCtxt<'_>, impl_item: DefId, parent_impl: DefId) { - let span = tcx.def_span(impl_item); - let ident = tcx.item_name(impl_item); - - let err = match tcx.span_of_impl(parent_impl) { - Ok(sp) => errors::ImplNotMarkedDefault::Ok { span, ident, ok_label: sp }, - Err(cname) => errors::ImplNotMarkedDefault::Err { span, ident, cname }, - }; - - tcx.dcx().emit_err(err); -} - fn missing_items_err( tcx: TyCtxt<'_>, impl_def_id: LocalDefId, diff --git a/compiler/rustc_hir_analysis/src/errors.rs b/compiler/rustc_hir_analysis/src/errors.rs index 4edb68e61999e..eba221f57629a 100644 --- a/compiler/rustc_hir_analysis/src/errors.rs +++ b/compiler/rustc_hir_analysis/src/errors.rs @@ -916,6 +916,16 @@ pub(crate) enum ImplNotMarkedDefault { }, } +#[derive(Diagnostic)] +#[diag(hir_analysis_overriding_final_trait_function)] +pub(crate) struct OverridingFinalTraitFunction { + #[primary_span] + pub impl_span: Span, + #[note] + pub trait_span: Span, + pub name: Symbol, +} + #[derive(Diagnostic)] #[diag(hir_analysis_missing_trait_item, code = E0046)] pub(crate) struct MissingTraitItem { diff --git a/compiler/rustc_parse/messages.ftl b/compiler/rustc_parse/messages.ftl index 6cb851eb8df6b..c3c26cd0150a3 100644 --- a/compiler/rustc_parse/messages.ftl +++ b/compiler/rustc_parse/messages.ftl @@ -309,6 +309,10 @@ parse_inappropriate_default = {$article} {$descr} cannot be `default` .label = `default` because of this .note = only associated `fn`, `const`, and `type` items can be `default` +parse_inappropriate_final = {$article} {$descr} cannot be `final` + .label = `final` because of this + .note = only associated functions in traits can be `final` + parse_inclusive_range_extra_equals = unexpected `=` after inclusive range .suggestion_remove_eq = use `..=` instead .note = inclusive ranges end with a single equals sign (`..=`) diff --git a/compiler/rustc_parse/src/errors.rs b/compiler/rustc_parse/src/errors.rs index 20bcefd4fe1e7..5835e25f0afd8 100644 --- a/compiler/rustc_parse/src/errors.rs +++ b/compiler/rustc_parse/src/errors.rs @@ -2939,6 +2939,17 @@ pub(crate) struct InappropriateDefault { pub descr: &'static str, } +#[derive(Diagnostic)] +#[diag(parse_inappropriate_final)] +#[note] +pub(crate) struct InappropriateFinal { + #[primary_span] + #[label] + pub span: Span, + pub article: &'static str, + pub descr: &'static str, +} + #[derive(Diagnostic)] #[diag(parse_recover_import_as_use)] pub(crate) struct RecoverImportAsUse { diff --git a/compiler/rustc_parse/src/parser/item.rs b/compiler/rustc_parse/src/parser/item.rs index 9fc82d84225cc..ff5a6a3996365 100644 --- a/compiler/rustc_parse/src/parser/item.rs +++ b/compiler/rustc_parse/src/parser/item.rs @@ -168,14 +168,24 @@ impl<'a> Parser<'a> { }) } - /// Error in-case `default` was parsed in an in-appropriate context. + /// Error in-case `default`/`final` was parsed in an in-appropriate context. fn error_on_unconsumed_default(&self, def: Defaultness, kind: &ItemKind) { - if let Defaultness::Default(span) = def { - self.dcx().emit_err(errors::InappropriateDefault { - span, - article: kind.article(), - descr: kind.descr(), - }); + match def { + Defaultness::Default(span) => { + self.dcx().emit_err(errors::InappropriateDefault { + span, + article: kind.article(), + descr: kind.descr(), + }); + } + Defaultness::Final(span) => { + self.dcx().emit_err(errors::InappropriateFinal { + span, + article: kind.article(), + descr: kind.descr(), + }); + } + Defaultness::Implicit => {} } } @@ -190,8 +200,8 @@ impl<'a> Parser<'a> { fn_parse_mode: FnParseMode, case: Case, ) -> PResult<'a, Option> { - let check_pub = def == &Defaultness::Final; - let mut def_ = || mem::replace(def, Defaultness::Final); + let check_pub = def == &Defaultness::Implicit; + let mut def_ = || mem::replace(def, Defaultness::Implicit); let info = if self.eat_keyword_case(kw::Use, case) { self.parse_use_item()? @@ -869,8 +879,11 @@ impl<'a> Parser<'a> { { self.bump(); // `default` Defaultness::Default(self.prev_token.uninterpolated_span()) + } else if self.eat_keyword(kw::Final) { + self.psess.gated_spans.gate(sym::final_associated_functions, self.prev_token.span); + Defaultness::Final(self.prev_token.uninterpolated_span()) } else { - Defaultness::Final + Defaultness::Implicit } } @@ -967,7 +980,7 @@ impl<'a> Parser<'a> { ItemKind::Static(box StaticItem { ty, safety: _, mutability: _, expr }) => { self.dcx().emit_err(errors::AssociatedStaticItemNotAllowed { span }); AssocItemKind::Const(Box::new(ConstItem { - defaultness: Defaultness::Final, + defaultness: Defaultness::Implicit, generics: Generics::default(), ty, expr, diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index 8f226b26befda..b39c14f984f7f 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -897,6 +897,7 @@ symbols! { field_init_shorthand, file, file_options, + final_associated_functions, float, float_to_int_unchecked, floorf128, diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 3d845cf878f4a..49e34eb17c17f 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -1227,11 +1227,17 @@ fn clean_trait_item<'tcx>(trait_item: &hir::TraitItem<'tcx>, cx: &mut DocContext } hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => { let m = clean_function(cx, sig, trait_item.generics, FunctionArgs::Body(body)); - MethodItem(m, None) + MethodItem(m, match trait_item.defaultness { + hir::Defaultness::Default { .. } => Defaultness::Implicit, + hir::Defaultness::Final => Defaultness::Final, + }) } hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Required(names)) => { let m = clean_function(cx, sig, trait_item.generics, FunctionArgs::Names(names)); - TyMethodItem(m) + TyMethodItem(m, match trait_item.defaultness { + hir::Defaultness::Default { .. } => Defaultness::Implicit, + hir::Defaultness::Final => Defaultness::Final, + }) } hir::TraitItemKind::Type(bounds, Some(default)) => { let generics = enter_impl_trait(cx, |cx| clean_generics(trait_item.generics, cx)); @@ -1272,8 +1278,10 @@ pub(crate) fn clean_impl_item<'tcx>( })), hir::ImplItemKind::Fn(ref sig, body) => { let m = clean_function(cx, sig, impl_.generics, FunctionArgs::Body(body)); - let defaultness = cx.tcx.defaultness(impl_.owner_id); - MethodItem(m, Some(defaultness)) + MethodItem(m, match impl_.defaultness { + hir::Defaultness::Default { .. } => Defaultness::Default, + hir::Defaultness::Final => Defaultness::Implicit, + }) } hir::ImplItemKind::Type(hir_ty) => { let type_ = clean_ty(hir_ty, cx); @@ -1352,18 +1360,22 @@ pub(crate) fn clean_middle_assoc_item(assoc_item: &ty::AssocItem, cx: &mut DocCo } } + let defaultness = assoc_item.defaultness(tcx); let provided = match assoc_item.container { ty::ImplContainer => true, - ty::TraitContainer => assoc_item.defaultness(tcx).has_value(), + ty::TraitContainer => defaultness.has_value(), }; + let rendered_defaultness = match (assoc_item.container, defaultness) { + (ty::TraitContainer, hir::Defaultness::Default { .. }) => Defaultness::Implicit, + (ty::TraitContainer, hir::Defaultness::Final) => Defaultness::Final, + (ty::ImplContainer, hir::Defaultness::Final) => Defaultness::Implicit, + (ty::ImplContainer, hir::Defaultness::Default { .. }) => Defaultness::Default, + }; + if provided { - let defaultness = match assoc_item.container { - ty::ImplContainer => Some(assoc_item.defaultness(tcx)), - ty::TraitContainer => None, - }; - MethodItem(item, defaultness) + MethodItem(item, rendered_defaultness) } else { - TyMethodItem(item) + TyMethodItem(item, rendered_defaultness) } } ty::AssocKind::Type => { diff --git a/src/librustdoc/clean/types.rs b/src/librustdoc/clean/types.rs index 31710bc014af4..a43f267d562d7 100644 --- a/src/librustdoc/clean/types.rs +++ b/src/librustdoc/clean/types.rs @@ -64,6 +64,13 @@ pub(crate) enum ItemId { Blanket { impl_id: DefId, for_: DefId }, } +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) enum Defaultness { + Default, + Final, + Implicit, +} + impl ItemId { #[inline] pub(crate) fn is_local(self) -> bool { @@ -617,12 +624,12 @@ impl Item { ItemType::from(self) } - pub(crate) fn is_default(&self) -> bool { + pub(crate) fn defaultness(&self) -> Option { match self.kind { - ItemKind::MethodItem(_, Some(defaultness)) => { - defaultness.has_value() && !defaultness.is_final() + ItemKind::MethodItem(_, defaultness) | ItemKind::TyMethodItem(_, defaultness) => { + Some(defaultness) } - _ => false, + _ => None, } } @@ -667,7 +674,7 @@ impl Item { asyncness: hir::IsAsync::NotAsync, } } - ItemKind::FunctionItem(_) | ItemKind::MethodItem(_, _) | ItemKind::TyMethodItem(_) => { + ItemKind::FunctionItem(_) | ItemKind::MethodItem(..) | ItemKind::TyMethodItem(..) => { let def_id = self.def_id().unwrap(); build_fn_header(def_id, tcx, tcx.asyncness(def_id)) } @@ -841,11 +848,11 @@ pub(crate) enum ItemKind { TraitAliasItem(TraitAlias), ImplItem(Box), /// A required method in a trait declaration meaning it's only a function signature. - TyMethodItem(Box), + TyMethodItem(Box, Defaultness), /// A method in a trait impl or a provided method in a trait declaration. /// /// Compared to [TyMethodItem], it also contains a method body. - MethodItem(Box, Option), + MethodItem(Box, Defaultness), StructFieldItem(Type), VariantItem(Variant), /// `fn`s from an extern block @@ -896,7 +903,7 @@ impl ItemKind { | StaticItem(_) | ConstantItem(_) | TraitAliasItem(_) - | TyMethodItem(_) + | TyMethodItem(..) | MethodItem(_, _) | StructFieldItem(_) | ForeignFunctionItem(_, _) diff --git a/src/librustdoc/fold.rs b/src/librustdoc/fold.rs index c25a4ddb6f369..86767dbaad2ee 100644 --- a/src/librustdoc/fold.rs +++ b/src/librustdoc/fold.rs @@ -80,7 +80,7 @@ pub(crate) trait DocFolder: Sized { | StaticItem(_) | ConstantItem(..) | TraitAliasItem(_) - | TyMethodItem(_) + | TyMethodItem(..) | MethodItem(_, _) | StructFieldItem(_) | ForeignFunctionItem(..) diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs index 2e70a8c080de0..9e974f6e50005 100644 --- a/src/librustdoc/html/format.rs +++ b/src/librustdoc/html/format.rs @@ -1782,10 +1782,6 @@ pub(crate) fn print_abi_with_space(abi: Abi) -> impl Display { }) } -pub(crate) fn print_default_space<'a>(v: bool) -> &'a str { - if v { "default " } else { "" } -} - impl clean::GenericArg { pub(crate) fn print<'a, 'tcx: 'a>( &'a self, diff --git a/src/librustdoc/html/render/mod.rs b/src/librustdoc/html/render/mod.rs index 227df0c5f3930..a3cbcf20d248a 100644 --- a/src/librustdoc/html/render/mod.rs +++ b/src/librustdoc/html/render/mod.rs @@ -62,7 +62,7 @@ use tracing::{debug, info}; pub(crate) use self::context::*; pub(crate) use self::span_map::{LinkFromSrc, collect_spans_and_sources}; pub(crate) use self::write_shared::*; -use crate::clean::{self, ItemId, RenderedLink}; +use crate::clean::{self, Defaultness, ItemId, RenderedLink}; use crate::error::Error; use crate::formats::Impl; use crate::formats::cache::Cache; @@ -70,8 +70,8 @@ use crate::formats::item_type::ItemType; use crate::html::escape::Escape; use crate::html::format::{ Buffer, Ending, HrefError, PrintWithSpace, display_fn, href, join_with_double_colon, - print_abi_with_space, print_constness_with_space, print_default_space, print_generic_bounds, - print_where_clause, visibility_print_with_space, + print_abi_with_space, print_constness_with_space, print_generic_bounds, print_where_clause, + visibility_print_with_space, }; use crate::html::markdown::{ HeadingOffset, IdMap, Markdown, MarkdownItemInfo, MarkdownSummaryLine, @@ -912,7 +912,11 @@ fn assoc_method( let header = meth.fn_header(tcx).expect("Trying to get header from a non-function item"); let name = meth.name.as_ref().unwrap(); let vis = visibility_print_with_space(meth, cx).to_string(); - let defaultness = print_default_space(meth.is_default()); + let defaultness = match meth.defaultness().expect("Expected assoc method to have defaultness") { + Defaultness::Implicit => "", + Defaultness::Final => "final ", + Defaultness::Default => "default ", + }; // FIXME: Once https://github.com/rust-lang/rust/issues/67792 is implemented, we can remove // this condition. let constness = match render_mode { @@ -1075,7 +1079,7 @@ fn render_assoc_item( ) { match &item.kind { clean::StrippedItem(..) => {} - clean::TyMethodItem(m) => { + clean::TyMethodItem(m, _) => { assoc_method(w, item, &m.generics, &m.decl, link, parent, cx, render_mode) } clean::MethodItem(m, _) => { @@ -1384,7 +1388,7 @@ fn render_deref_methods( fn should_render_item(item: &clean::Item, deref_mut_: bool, tcx: TyCtxt<'_>) -> bool { let self_type_opt = match item.kind { clean::MethodItem(ref method, _) => method.decl.receiver_type(), - clean::TyMethodItem(ref method) => method.decl.receiver_type(), + clean::TyMethodItem(ref method, _) => method.decl.receiver_type(), _ => None, }; @@ -1661,7 +1665,7 @@ fn render_impl( write!(w, "
"); } match &item.kind { - clean::MethodItem(..) | clean::TyMethodItem(_) => { + clean::MethodItem(..) | clean::TyMethodItem(..) => { // Only render when the method is not static or we allow static methods if render_method_item { let id = cx.derive_id(format!("{item_type}.{name}")); @@ -1810,7 +1814,7 @@ fn render_impl( if !impl_.is_negative_trait_impl() { for trait_item in &impl_.items { match trait_item.kind { - clean::MethodItem(..) | clean::TyMethodItem(_) => methods.push(trait_item), + clean::MethodItem(..) | clean::TyMethodItem(..) => methods.push(trait_item), clean::TyAssocTypeItem(..) | clean::AssocTypeItem(..) => { assoc_types.push(trait_item) } diff --git a/src/librustdoc/html/render/search_index.rs b/src/librustdoc/html/render/search_index.rs index 660ca3b2594cc..f829f7ddb83ac 100644 --- a/src/librustdoc/html/render/search_index.rs +++ b/src/librustdoc/html/render/search_index.rs @@ -759,7 +759,9 @@ pub(crate) fn get_function_type_for_search<'tcx>( } }); let (mut inputs, mut output, where_clause) = match item.kind { - clean::FunctionItem(ref f) | clean::MethodItem(ref f, _) | clean::TyMethodItem(ref f) => { + clean::FunctionItem(ref f) + | clean::MethodItem(ref f, _) + | clean::TyMethodItem(ref f, _) => { get_fn_inputs_and_outputs(f, tcx, impl_or_trait_generics, cache) } _ => return None, diff --git a/src/librustdoc/json/conversions.rs b/src/librustdoc/json/conversions.rs index b411f9a1a52d0..860209266a9a6 100644 --- a/src/librustdoc/json/conversions.rs +++ b/src/librustdoc/json/conversions.rs @@ -327,7 +327,7 @@ fn from_clean_item(item: clean::Item, tcx: TyCtxt<'_>) -> ItemEnum { TraitItem(t) => ItemEnum::Trait((*t).into_tcx(tcx)), TraitAliasItem(t) => ItemEnum::TraitAlias(t.into_tcx(tcx)), MethodItem(m, _) => ItemEnum::Function(from_function(m, true, header.unwrap(), tcx)), - TyMethodItem(m) => ItemEnum::Function(from_function(m, false, header.unwrap(), tcx)), + TyMethodItem(m, _) => ItemEnum::Function(from_function(m, false, header.unwrap(), tcx)), ImplItem(i) => ItemEnum::Impl((*i).into_tcx(tcx)), StaticItem(s) => ItemEnum::Static(s.into_tcx(tcx)), ForeignStaticItem(s, _) => ItemEnum::Static(s.into_tcx(tcx)), diff --git a/src/librustdoc/visit.rs b/src/librustdoc/visit.rs index 7fb0a32cc9495..0b7e253fd30d3 100644 --- a/src/librustdoc/visit.rs +++ b/src/librustdoc/visit.rs @@ -29,7 +29,7 @@ pub(crate) trait DocVisitor: Sized { | StaticItem(_) | ConstantItem(..) | TraitAliasItem(_) - | TyMethodItem(_) + | TyMethodItem(..) | MethodItem(_, _) | StructFieldItem(_) | ForeignFunctionItem(..) diff --git a/src/tools/clippy/clippy_utils/src/ast_utils.rs b/src/tools/clippy/clippy_utils/src/ast_utils.rs index de8bbb619f8e4..01aed1842bfb6 100644 --- a/src/tools/clippy/clippy_utils/src/ast_utils.rs +++ b/src/tools/clippy/clippy_utils/src/ast_utils.rs @@ -670,7 +670,9 @@ pub fn eq_use_tree_kind(l: &UseTreeKind, r: &UseTreeKind) -> bool { pub fn eq_defaultness(l: Defaultness, r: Defaultness) -> bool { matches!( (l, r), - (Defaultness::Final, Defaultness::Final) | (Defaultness::Default(_), Defaultness::Default(_)) + (Defaultness::Final(_), Defaultness::Final(_)) + | (Defaultness::Default(_), Defaultness::Default(_)) + | (Defaultness::Implicit, Defaultness::Implicit) ) } diff --git a/src/tools/rustfmt/src/items.rs b/src/tools/rustfmt/src/items.rs index fc043a697e039..ac600fa31a47f 100644 --- a/src/tools/rustfmt/src/items.rs +++ b/src/tools/rustfmt/src/items.rs @@ -314,12 +314,13 @@ impl<'a> FnSig<'a> { method_sig: &'a ast::FnSig, generics: &'a ast::Generics, visibility: &'a ast::Visibility, + defaultness: ast::Defaultness, ) -> FnSig<'a> { FnSig { safety: method_sig.header.safety, coroutine_kind: Cow::Borrowed(&method_sig.header.coroutine_kind), constness: method_sig.header.constness, - defaultness: ast::Defaultness::Final, + defaultness, ext: method_sig.header.ext, decl: &*method_sig.decl, generics, @@ -334,9 +335,7 @@ impl<'a> FnSig<'a> { ) -> FnSig<'a> { match *fn_kind { visit::FnKind::Fn(visit::FnCtxt::Assoc(..), _, fn_sig, vis, generics, _) => { - let mut fn_sig = FnSig::from_method_sig(fn_sig, generics, vis); - fn_sig.defaultness = defaultness; - fn_sig + FnSig::from_method_sig(fn_sig, generics, vis, defaultness) } visit::FnKind::Fn(_, _, fn_sig, vis, generics, _) => FnSig { decl, @@ -454,6 +453,7 @@ impl<'a> FmtVisitor<'a> { sig: &ast::FnSig, vis: &ast::Visibility, generics: &ast::Generics, + defaultness: ast::Defaultness, span: Span, ) -> RewriteResult { // Drop semicolon or it will be interpreted as comment. @@ -464,7 +464,7 @@ impl<'a> FmtVisitor<'a> { &context, indent, ident, - &FnSig::from_method_sig(sig, generics, vis), + &FnSig::from_method_sig(sig, generics, vis, defaultness), span, FnBraceStyle::None, )?; @@ -3460,7 +3460,7 @@ impl Rewrite for ast::ForeignItem { context, shape.indent, self.ident, - &FnSig::from_method_sig(sig, generics, &self.vis), + &FnSig::from_method_sig(sig, generics, &self.vis, defaultness), span, FnBraceStyle::None, ) diff --git a/src/tools/rustfmt/src/utils.rs b/src/tools/rustfmt/src/utils.rs index d1cfc6acc49bc..7f595222c0a88 100644 --- a/src/tools/rustfmt/src/utils.rs +++ b/src/tools/rustfmt/src/utils.rs @@ -103,7 +103,8 @@ pub(crate) fn format_constness_right(constness: ast::Const) -> &'static str { pub(crate) fn format_defaultness(defaultness: ast::Defaultness) -> &'static str { match defaultness { ast::Defaultness::Default(..) => "default ", - ast::Defaultness::Final => "", + ast::Defaultness::Final(..) => "final ", + ast::Defaultness::Implicit => "", } } diff --git a/src/tools/rustfmt/src/visitor.rs b/src/tools/rustfmt/src/visitor.rs index 8102fe7ad8f29..3cf175b05cc51 100644 --- a/src/tools/rustfmt/src/visitor.rs +++ b/src/tools/rustfmt/src/visitor.rs @@ -564,7 +564,13 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { let indent = self.block_indent; let rewrite = self .rewrite_required_fn( - indent, item.ident, sig, &item.vis, generics, item.span, + indent, + item.ident, + sig, + &item.vis, + generics, + defaultness, + item.span, ) .ok(); self.push_rewrite(item.span, rewrite); @@ -661,7 +667,15 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { } else { let indent = self.block_indent; let rewrite = self - .rewrite_required_fn(indent, ai.ident, sig, &ai.vis, generics, ai.span) + .rewrite_required_fn( + indent, + ai.ident, + sig, + &ai.vis, + generics, + defaultness, + ai.span, + ) .ok(); self.push_rewrite(ai.span, rewrite); } diff --git a/src/tools/rustfmt/tests/target/final-kw.rs b/src/tools/rustfmt/tests/target/final-kw.rs new file mode 100644 index 0000000000000..d68b6908d76a7 --- /dev/null +++ b/src/tools/rustfmt/tests/target/final-kw.rs @@ -0,0 +1,5 @@ +trait Foo { + final fn final_() {} + + fn not_final() {} +} diff --git a/tests/rustdoc/final-trait-method.rs b/tests/rustdoc/final-trait-method.rs new file mode 100644 index 0000000000000..016578a8b0e74 --- /dev/null +++ b/tests/rustdoc/final-trait-method.rs @@ -0,0 +1,22 @@ +#![feature(final_associated_functions)] + +//@ has final_trait_method/trait.Item.html +pub trait Item { + //@ has - '//*[@id="method.foo"]' 'final fn foo()' + //@ !has - '//*[@id="method.foo"]' 'default fn foo()' + final fn foo() {} + + //@ has - '//*[@id="method.bar"]' 'fn bar()' + //@ !has - '//*[@id="method.bar"]' 'default fn bar()' + //@ !has - '//*[@id="method.bar"]' 'final fn bar()' + fn bar() {} +} + +//@ has final_trait_method/struct.Foo.html +pub struct Foo; +impl Item for Foo { + //@ has - '//*[@id="method.bar"]' 'fn bar()' + //@ !has - '//*[@id="method.bar"]' 'final fn bar()' + //@ !has - '//*[@id="method.bar"]' 'default fn bar()' + fn bar() {} +} diff --git a/tests/ui/coroutine/gen_fn.none.stderr b/tests/ui/coroutine/gen_fn.none.stderr index 590210641aed4..8a5f865413168 100644 --- a/tests/ui/coroutine/gen_fn.none.stderr +++ b/tests/ui/coroutine/gen_fn.none.stderr @@ -1,8 +1,8 @@ -error: expected one of `#`, `async`, `const`, `default`, `extern`, `fn`, `pub`, `safe`, `unsafe`, or `use`, found `gen` +error: expected one of `#`, `async`, `const`, `default`, `extern`, `final`, `fn`, `pub`, `safe`, `unsafe`, or `use`, found `gen` --> $DIR/gen_fn.rs:4:1 | LL | gen fn foo() {} - | ^^^ expected one of 10 possible tokens + | ^^^ expected one of 11 possible tokens error: aborting due to 1 previous error diff --git a/tests/ui/coroutine/gen_fn.rs b/tests/ui/coroutine/gen_fn.rs index d47b7e576d002..5c7e906032224 100644 --- a/tests/ui/coroutine/gen_fn.rs +++ b/tests/ui/coroutine/gen_fn.rs @@ -2,7 +2,7 @@ //@[e2024] compile-flags: --edition 2024 -Zunstable-options gen fn foo() {} -//[none]~^ ERROR: expected one of `#`, `async`, `const`, `default`, `extern`, `fn`, `pub`, `safe`, `unsafe`, or `use`, found `gen` +//[none]~^ ERROR: expected one of `#`, `async`, `const`, `default`, `extern`, `final`, `fn`, `pub`, `safe`, `unsafe`, or `use`, found `gen` //[e2024]~^^ ERROR: gen blocks are experimental fn main() {} diff --git a/tests/ui/feature-gates/feature-gate-final-associated-functions.rs b/tests/ui/feature-gates/feature-gate-final-associated-functions.rs new file mode 100644 index 0000000000000..bdac2710d58e1 --- /dev/null +++ b/tests/ui/feature-gates/feature-gate-final-associated-functions.rs @@ -0,0 +1,6 @@ +trait Foo { + final fn bar() {} + //~^ ERROR `final` on trait functions is experimental +} + +fn main() {} diff --git a/tests/ui/feature-gates/feature-gate-final-associated-functions.stderr b/tests/ui/feature-gates/feature-gate-final-associated-functions.stderr new file mode 100644 index 0000000000000..b3731acd1d905 --- /dev/null +++ b/tests/ui/feature-gates/feature-gate-final-associated-functions.stderr @@ -0,0 +1,13 @@ +error[E0658]: `final` on trait functions is experimental + --> $DIR/feature-gate-final-associated-functions.rs:2:5 + | +LL | final fn bar() {} + | ^^^^^ + | + = note: see issue #1 for more information + = help: add `#![feature(final_associated_functions)]` to the crate attributes to enable + = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0658`. diff --git a/tests/ui/parser/duplicate-visibility.rs b/tests/ui/parser/duplicate-visibility.rs index f0ee60873da01..d35624981c744 100644 --- a/tests/ui/parser/duplicate-visibility.rs +++ b/tests/ui/parser/duplicate-visibility.rs @@ -2,8 +2,8 @@ fn main() {} extern "C" { //~ NOTE while parsing this item list starting here pub pub fn foo(); - //~^ ERROR expected one of `(`, `async`, `const`, `default`, `extern`, `fn`, `safe`, `unsafe`, or `use`, found keyword `pub` - //~| NOTE expected one of 9 possible tokens + //~^ ERROR expected one of `(`, `async`, `const`, `default`, `extern`, `final`, `fn`, `safe`, `unsafe`, or `use`, found keyword `pub` + //~| NOTE expected one of 10 possible tokens //~| HELP there is already a visibility modifier, remove one //~| NOTE explicit visibility first seen here } //~ NOTE the item list ends here diff --git a/tests/ui/parser/duplicate-visibility.stderr b/tests/ui/parser/duplicate-visibility.stderr index 0d1421ee7f4e4..e00ebe6a8cf6d 100644 --- a/tests/ui/parser/duplicate-visibility.stderr +++ b/tests/ui/parser/duplicate-visibility.stderr @@ -1,4 +1,4 @@ -error: expected one of `(`, `async`, `const`, `default`, `extern`, `fn`, `safe`, `unsafe`, or `use`, found keyword `pub` +error: expected one of `(`, `async`, `const`, `default`, `extern`, `final`, `fn`, `safe`, `unsafe`, or `use`, found keyword `pub` --> $DIR/duplicate-visibility.rs:4:9 | LL | extern "C" { @@ -6,7 +6,7 @@ LL | extern "C" { LL | pub pub fn foo(); | ^^^ | | - | expected one of 9 possible tokens + | expected one of 10 possible tokens | help: there is already a visibility modifier, remove one ... LL | } diff --git a/tests/ui/parser/misspelled-keywords/pub-fn.stderr b/tests/ui/parser/misspelled-keywords/pub-fn.stderr index 82ca7105a4965..e94562b94366b 100644 --- a/tests/ui/parser/misspelled-keywords/pub-fn.stderr +++ b/tests/ui/parser/misspelled-keywords/pub-fn.stderr @@ -1,8 +1,8 @@ -error: expected one of `#`, `async`, `auto`, `const`, `default`, `enum`, `extern`, `fn`, `gen`, `impl`, `macro_rules`, `macro`, `mod`, `pub`, `safe`, `static`, `struct`, `trait`, `type`, `unsafe`, or `use`, found `puB` +error: expected one of `#`, `async`, `auto`, `const`, `default`, `enum`, `extern`, `final`, `fn`, `gen`, `impl`, `macro_rules`, `macro`, `mod`, `pub`, `safe`, `static`, `struct`, `trait`, `type`, `unsafe`, or `use`, found `puB` --> $DIR/pub-fn.rs:1:1 | LL | puB fn code() {} - | ^^^ expected one of 21 possible tokens + | ^^^ expected one of 22 possible tokens | help: write keyword `pub` in lowercase | diff --git a/tests/ui/traits/final/final-kw.gated.stderr b/tests/ui/traits/final/final-kw.gated.stderr new file mode 100644 index 0000000000000..a7967ebf08e2a --- /dev/null +++ b/tests/ui/traits/final/final-kw.gated.stderr @@ -0,0 +1,13 @@ +error[E0658]: `final` on trait functions is experimental + --> $DIR/final-kw.rs:5:5 + | +LL | final fn foo() {} + | ^^^^^ + | + = note: see issue #1 for more information + = help: add `#![feature(final_associated_functions)]` to the crate attributes to enable + = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0658`. diff --git a/tests/ui/traits/final/final-kw.rs b/tests/ui/traits/final/final-kw.rs new file mode 100644 index 0000000000000..ed675dea6608d --- /dev/null +++ b/tests/ui/traits/final/final-kw.rs @@ -0,0 +1,9 @@ +//@ revisions: ungated gated + +#[cfg(ungated)] +trait Trait { + final fn foo() {} + //~^ ERROR `final` on trait functions is experimental +} + +fn main() {} diff --git a/tests/ui/traits/final/final-kw.ungated.stderr b/tests/ui/traits/final/final-kw.ungated.stderr new file mode 100644 index 0000000000000..a7967ebf08e2a --- /dev/null +++ b/tests/ui/traits/final/final-kw.ungated.stderr @@ -0,0 +1,13 @@ +error[E0658]: `final` on trait functions is experimental + --> $DIR/final-kw.rs:5:5 + | +LL | final fn foo() {} + | ^^^^^ + | + = note: see issue #1 for more information + = help: add `#![feature(final_associated_functions)]` to the crate attributes to enable + = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0658`. diff --git a/tests/ui/traits/final/final-must-have-body.rs b/tests/ui/traits/final/final-must-have-body.rs new file mode 100644 index 0000000000000..57ed26c3e78db --- /dev/null +++ b/tests/ui/traits/final/final-must-have-body.rs @@ -0,0 +1,8 @@ +#![feature(final_associated_functions)] + +trait Foo { + final fn method(); + //~^ ERROR `final` is only allowed on associated functions if they have a body +} + +fn main() {} diff --git a/tests/ui/traits/final/final-must-have-body.stderr b/tests/ui/traits/final/final-must-have-body.stderr new file mode 100644 index 0000000000000..e4f1ffb701e86 --- /dev/null +++ b/tests/ui/traits/final/final-must-have-body.stderr @@ -0,0 +1,10 @@ +error: `final` is only allowed on associated functions if they have a body + --> $DIR/final-must-have-body.rs:4:5 + | +LL | final fn method(); + | -----^^^^^^^^^^^^^ + | | + | `final` because of this + +error: aborting due to 1 previous error + diff --git a/tests/ui/traits/final/overriding.rs b/tests/ui/traits/final/overriding.rs new file mode 100644 index 0000000000000..f91451852ff06 --- /dev/null +++ b/tests/ui/traits/final/overriding.rs @@ -0,0 +1,12 @@ +#![feature(final_associated_functions)] + +trait Foo { + final fn method() {} +} + +impl Foo for () { + fn method() {} + //~^ ERROR cannot override `method` because it already has a `final` definition in the trait +} + +fn main() {} diff --git a/tests/ui/traits/final/overriding.stderr b/tests/ui/traits/final/overriding.stderr new file mode 100644 index 0000000000000..b5598565072fc --- /dev/null +++ b/tests/ui/traits/final/overriding.stderr @@ -0,0 +1,14 @@ +error: cannot override `method` because it already has a `final` definition in the trait + --> $DIR/overriding.rs:8:5 + | +LL | fn method() {} + | ^^^^^^^^^^^ + | +note: `method` is marked final here + --> $DIR/overriding.rs:4:5 + | +LL | final fn method() {} + | ^^^^^^^^^^^^^^^^^ + +error: aborting due to 1 previous error + diff --git a/tests/ui/traits/final/positions.rs b/tests/ui/traits/final/positions.rs new file mode 100644 index 0000000000000..f9284796f182b --- /dev/null +++ b/tests/ui/traits/final/positions.rs @@ -0,0 +1,72 @@ +#![feature(final_associated_functions)] + +// Just for exercising the syntax positions +#![feature(associated_type_defaults, extern_types, inherent_associated_types)] +#![allow(incomplete_features)] + +final struct Foo {} +//~^ ERROR a struct cannot be `final` + +final trait Trait { +//~^ ERROR a trait cannot be `final` + + final fn method() {} + // OK! + + final type Foo = (); + //~^ ERROR `final` is only allowed on associated functions in traits + + final const FOO: usize = 1; + //~^ ERROR `final` is only allowed on associated functions in traits +} + +final impl Foo { + final fn method() {} + //~^ ERROR `final` is only allowed on associated functions in traits + + final type Foo = (); + //~^ ERROR `final` is only allowed on associated functions in traits + + final const FOO: usize = 1; + //~^ ERROR `final` is only allowed on associated functions in traits +} + +final impl Trait for Foo { + final fn method() {} + //~^ ERROR `final` is only allowed on associated functions in traits + //~| ERROR cannot override `method` because it already has a `final` definition in the trait + + final type Foo = (); + //~^ ERROR `final` is only allowed on associated functions in traits + //~| ERROR cannot override `Foo` because it already has a `final` definition in the trait + + final const FOO: usize = 1; + //~^ ERROR `final` is only allowed on associated functions in traits + //~| ERROR cannot override `FOO` because it already has a `final` definition in the trait +} + + +final fn foo() {} +//~^ ERROR `final` is only allowed on associated functions in traits + +final type FooTy = (); +//~^ ERROR `final` is only allowed on associated functions in traits + +final const FOO: usize = 0; +//~^ ERROR `final` is only allowed on associated functions in traits + +final unsafe extern "C" { +//~^ ERROR an extern block cannot be `final` + + final fn foo_extern(); + //~^ ERROR `final` is only allowed on associated functions in traits + + final type FooExtern; + //~^ ERROR `final` is only allowed on associated functions in traits + + final static FOO_EXTERN: usize = 0; + //~^ ERROR a static item cannot be `final` + //~| ERROR incorrect `static` inside `extern` block +} + +fn main() {} diff --git a/tests/ui/traits/final/positions.stderr b/tests/ui/traits/final/positions.stderr new file mode 100644 index 0000000000000..bcb300e49d1a9 --- /dev/null +++ b/tests/ui/traits/final/positions.stderr @@ -0,0 +1,187 @@ +error: a struct cannot be `final` + --> $DIR/positions.rs:7:1 + | +LL | final struct Foo {} + | ^^^^^ `final` because of this + | + = note: only associated functions in traits can be `final` + +error: a trait cannot be `final` + --> $DIR/positions.rs:10:1 + | +LL | final trait Trait { + | ^^^^^ `final` because of this + | + = note: only associated functions in traits can be `final` + +error: a static item cannot be `final` + --> $DIR/positions.rs:67:5 + | +LL | final static FOO_EXTERN: usize = 0; + | ^^^^^ `final` because of this + | + = note: only associated functions in traits can be `final` + +error: an extern block cannot be `final` + --> $DIR/positions.rs:58:1 + | +LL | final unsafe extern "C" { + | ^^^^^ `final` because of this + | + = note: only associated functions in traits can be `final` + +error: `final` is only allowed on associated functions in traits + --> $DIR/positions.rs:16:5 + | +LL | final type Foo = (); + | -----^^^^^^^^^^^^^^^ + | | + | `final` because of this + +error: `final` is only allowed on associated functions in traits + --> $DIR/positions.rs:19:5 + | +LL | final const FOO: usize = 1; + | -----^^^^^^^^^^^^^^^^^^^^^^ + | | + | `final` because of this + +error: `final` is only allowed on associated functions in traits + --> $DIR/positions.rs:24:5 + | +LL | final fn method() {} + | -----^^^^^^^^^^^^ + | | + | `final` because of this + +error: `final` is only allowed on associated functions in traits + --> $DIR/positions.rs:27:5 + | +LL | final type Foo = (); + | -----^^^^^^^^^^^^^^^ + | | + | `final` because of this + +error: `final` is only allowed on associated functions in traits + --> $DIR/positions.rs:30:5 + | +LL | final const FOO: usize = 1; + | -----^^^^^^^^^^^^^^^^^^^^^^ + | | + | `final` because of this + +error: `final` is only allowed on associated functions in traits + --> $DIR/positions.rs:35:5 + | +LL | final fn method() {} + | -----^^^^^^^^^^^^ + | | + | `final` because of this + +error: `final` is only allowed on associated functions in traits + --> $DIR/positions.rs:39:5 + | +LL | final type Foo = (); + | -----^^^^^^^^^^^^^^^ + | | + | `final` because of this + +error: `final` is only allowed on associated functions in traits + --> $DIR/positions.rs:43:5 + | +LL | final const FOO: usize = 1; + | -----^^^^^^^^^^^^^^^^^^^^^^ + | | + | `final` because of this + +error: `final` is only allowed on associated functions in traits + --> $DIR/positions.rs:49:1 + | +LL | final fn foo() {} + | -----^^^^^^^^^ + | | + | `final` because of this + +error: `final` is only allowed on associated functions in traits + --> $DIR/positions.rs:52:1 + | +LL | final type FooTy = (); + | -----^^^^^^^^^^^^^^^^^ + | | + | `final` because of this + +error: `final` is only allowed on associated functions in traits + --> $DIR/positions.rs:55:1 + | +LL | final const FOO: usize = 0; + | -----^^^^^^^^^^^^^^^^^^^^^^ + | | + | `final` because of this + +error: `final` is only allowed on associated functions in traits + --> $DIR/positions.rs:61:5 + | +LL | final fn foo_extern(); + | -----^^^^^^^^^^^^^^^^^ + | | + | `final` because of this + +error: `final` is only allowed on associated functions in traits + --> $DIR/positions.rs:64:5 + | +LL | final type FooExtern; + | -----^^^^^^^^^^^^^^^^ + | | + | `final` because of this + +error: incorrect `static` inside `extern` block + --> $DIR/positions.rs:67:18 + | +LL | final unsafe extern "C" { + | ----------------------- `extern` blocks define existing foreign statics and statics inside of them cannot have a body +... +LL | final static FOO_EXTERN: usize = 0; + | ^^^^^^^^^^ - the invalid body + | | + | cannot have a body + | + = note: for more information, visit https://doc.rust-lang.org/std/keyword.extern.html + +error: cannot override `method` because it already has a `final` definition in the trait + --> $DIR/positions.rs:35:5 + | +LL | final fn method() {} + | ^^^^^^^^^^^^^^^^^ + | +note: `method` is marked final here + --> $DIR/positions.rs:13:5 + | +LL | final fn method() {} + | ^^^^^^^^^^^^^^^^^ + +error: cannot override `Foo` because it already has a `final` definition in the trait + --> $DIR/positions.rs:39:5 + | +LL | final type Foo = (); + | ^^^^^^^^^^^^^^ + | +note: `Foo` is marked final here + --> $DIR/positions.rs:16:5 + | +LL | final type Foo = (); + | ^^^^^^^^^^^^^^ + +error: cannot override `FOO` because it already has a `final` definition in the trait + --> $DIR/positions.rs:43:5 + | +LL | final const FOO: usize = 1; + | ^^^^^^^^^^^^^^^^^^^^^^ + | +note: `FOO` is marked final here + --> $DIR/positions.rs:19:5 + | +LL | final const FOO: usize = 1; + | ^^^^^^^^^^^^^^^^^^^^^^ + +error: aborting due to 21 previous errors + diff --git a/tests/ui/traits/final/works.rs b/tests/ui/traits/final/works.rs new file mode 100644 index 0000000000000..e756521701a45 --- /dev/null +++ b/tests/ui/traits/final/works.rs @@ -0,0 +1,13 @@ +//@ check-pass + +#![feature(final_associated_functions)] + +trait Foo { + final fn bar(&self) {} +} + +impl Foo for () {} + +fn main() { + ().bar(); +}